PageRenderTime 60ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/message/lib.php

https://bitbucket.org/synergylearning/campusconnect
PHP | 2540 lines | 1557 code | 389 blank | 594 comment | 359 complexity | 8574035bd86cb2b217b9ea7f19ffeedb MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, LGPL-2.1, Apache-2.0, BSD-3-Clause, AGPL-3.0
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Library functions for messaging
  18. *
  19. * @package core_message
  20. * @copyright 2008 Luis Rodrigues
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. */
  23. require_once($CFG->libdir.'/eventslib.php');
  24. define ('MESSAGE_SHORTLENGTH', 300);
  25. define ('MESSAGE_DISCUSSION_WIDTH',600);
  26. define ('MESSAGE_DISCUSSION_HEIGHT',500);
  27. define ('MESSAGE_SHORTVIEW_LIMIT', 8);//the maximum number of messages to show on the short message history
  28. define('MESSAGE_HISTORY_SHORT',0);
  29. define('MESSAGE_HISTORY_ALL',1);
  30. define('MESSAGE_VIEW_UNREAD_MESSAGES','unread');
  31. define('MESSAGE_VIEW_RECENT_CONVERSATIONS','recentconversations');
  32. define('MESSAGE_VIEW_RECENT_NOTIFICATIONS','recentnotifications');
  33. define('MESSAGE_VIEW_CONTACTS','contacts');
  34. define('MESSAGE_VIEW_BLOCKED','blockedusers');
  35. define('MESSAGE_VIEW_COURSE','course_');
  36. define('MESSAGE_VIEW_SEARCH','search');
  37. define('MESSAGE_SEARCH_MAX_RESULTS', 200);
  38. define('MESSAGE_CONTACTS_PER_PAGE',10);
  39. define('MESSAGE_MAX_COURSE_NAME_LENGTH', 30);
  40. /**
  41. * Define contants for messaging default settings population. For unambiguity of
  42. * plugin developer intentions we use 4-bit value (LSB numbering):
  43. * bit 0 - whether to send message when user is loggedin (MESSAGE_DEFAULT_LOGGEDIN)
  44. * bit 1 - whether to send message when user is loggedoff (MESSAGE_DEFAULT_LOGGEDOFF)
  45. * bit 2..3 - messaging permission (MESSAGE_DISALLOWED|MESSAGE_PERMITTED|MESSAGE_FORCED)
  46. *
  47. * MESSAGE_PERMITTED_MASK contains the mask we use to distinguish permission setting
  48. */
  49. define('MESSAGE_DEFAULT_LOGGEDIN', 0x01); // 0001
  50. define('MESSAGE_DEFAULT_LOGGEDOFF', 0x02); // 0010
  51. define('MESSAGE_DISALLOWED', 0x04); // 0100
  52. define('MESSAGE_PERMITTED', 0x08); // 1000
  53. define('MESSAGE_FORCED', 0x0c); // 1100
  54. define('MESSAGE_PERMITTED_MASK', 0x0c); // 1100
  55. /**
  56. * Set default value for default outputs permitted setting
  57. */
  58. define('MESSAGE_DEFAULT_PERMITTED', 'permitted');
  59. /**
  60. * Print the selector that allows the user to view their contacts, course participants, their recent
  61. * conversations etc
  62. *
  63. * @param int $countunreadtotal how many unread messages does the user have?
  64. * @param int $viewing What is the user viewing? ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_SEARCH etc
  65. * @param object $user1 the user whose messages are being viewed
  66. * @param object $user2 the user $user1 is talking to
  67. * @param array $blockedusers an array of users blocked by $user1
  68. * @param array $onlinecontacts an array of $user1's online contacts
  69. * @param array $offlinecontacts an array of $user1's offline contacts
  70. * @param array $strangers an array of users who have messaged $user1 who aren't contacts
  71. * @param bool $showactionlinks show action links (add/remove contact etc)
  72. * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
  73. * @return void
  74. */
  75. function message_print_contact_selector($countunreadtotal, $viewing, $user1, $user2, $blockedusers, $onlinecontacts, $offlinecontacts, $strangers, $showactionlinks, $page=0) {
  76. global $PAGE;
  77. echo html_writer::start_tag('div', array('class' => 'contactselector mdl-align'));
  78. //if 0 unread messages and they've requested unread messages then show contacts
  79. if ($countunreadtotal == 0 && $viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
  80. $viewing = MESSAGE_VIEW_CONTACTS;
  81. }
  82. //if they have no blocked users and they've requested blocked users switch them over to contacts
  83. if (count($blockedusers) == 0 && $viewing == MESSAGE_VIEW_BLOCKED) {
  84. $viewing = MESSAGE_VIEW_CONTACTS;
  85. }
  86. $onlyactivecourses = true;
  87. $courses = enrol_get_users_courses($user1->id, $onlyactivecourses);
  88. $coursecontexts = message_get_course_contexts($courses);//we need one of these again so holding on to them
  89. $strunreadmessages = null;
  90. if ($countunreadtotal>0) { //if there are unread messages
  91. $strunreadmessages = get_string('unreadmessages','message', $countunreadtotal);
  92. }
  93. message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, count($blockedusers), $strunreadmessages, $user1);
  94. if ($viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
  95. message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 1, $showactionlinks,$strunreadmessages, $user2);
  96. } else if ($viewing == MESSAGE_VIEW_CONTACTS || $viewing == MESSAGE_VIEW_SEARCH || $viewing == MESSAGE_VIEW_RECENT_CONVERSATIONS || $viewing == MESSAGE_VIEW_RECENT_NOTIFICATIONS) {
  97. message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 0, $showactionlinks, $strunreadmessages, $user2);
  98. } else if ($viewing == MESSAGE_VIEW_BLOCKED) {
  99. message_print_blocked_users($blockedusers, $PAGE->url, $showactionlinks, null, $user2);
  100. } else if (substr($viewing, 0, 7) == MESSAGE_VIEW_COURSE) {
  101. $courseidtoshow = intval(substr($viewing, 7));
  102. if (!empty($courseidtoshow)
  103. && array_key_exists($courseidtoshow, $coursecontexts)
  104. && has_capability('moodle/course:viewparticipants', $coursecontexts[$courseidtoshow])) {
  105. message_print_participants($coursecontexts[$courseidtoshow], $courseidtoshow, $PAGE->url, $showactionlinks, null, $page, $user2);
  106. } else {
  107. //shouldn't get here. User trying to access a course they're not in perhaps.
  108. add_to_log(SITEID, 'message', 'view', 'index.php', $viewing);
  109. }
  110. }
  111. // Only show the search button if we're viewing our own messages.
  112. // Search isn't currently able to deal with user A wanting to search user B's messages.
  113. if ($showactionlinks) {
  114. echo html_writer::start_tag('form', array('action' => 'index.php','method' => 'GET'));
  115. echo html_writer::start_tag('fieldset');
  116. $managebuttonclass = 'visible';
  117. if ($viewing == MESSAGE_VIEW_SEARCH) {
  118. $managebuttonclass = 'hiddenelement';
  119. }
  120. $strmanagecontacts = get_string('search','message');
  121. echo html_writer::empty_tag('input', array('type' => 'hidden','name' => 'viewing','value' => MESSAGE_VIEW_SEARCH));
  122. echo html_writer::empty_tag('input', array('type' => 'submit','value' => $strmanagecontacts,'class' => $managebuttonclass));
  123. echo html_writer::end_tag('fieldset');
  124. echo html_writer::end_tag('form');
  125. }
  126. echo html_writer::end_tag('div');
  127. }
  128. /**
  129. * Print course participants. Called by message_print_contact_selector()
  130. *
  131. * @param object $context the course context
  132. * @param int $courseid the course ID
  133. * @param string $contactselecturl the url to send the user to when a contact's name is clicked
  134. * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
  135. * @param string $titletodisplay Optionally specify a title to display above the participants
  136. * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
  137. * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of participants
  138. * @return void
  139. */
  140. function message_print_participants($context, $courseid, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $page=0, $user2=null) {
  141. global $DB, $USER, $PAGE, $OUTPUT;
  142. if (empty($titletodisplay)) {
  143. $titletodisplay = get_string('participants');
  144. }
  145. $countparticipants = count_enrolled_users($context);
  146. list($esql, $params) = get_enrolled_sql($context);
  147. $params['mcuserid'] = $USER->id;
  148. $ufields = user_picture::fields('u');
  149. $sql = "SELECT $ufields, mc.id as contactlistid, mc.blocked
  150. FROM {user} u
  151. JOIN ($esql) je ON je.id = u.id
  152. LEFT JOIN {message_contacts} mc ON mc.contactid = u.id AND mc.userid = :mcuserid
  153. WHERE u.deleted = 0";
  154. $participants = $DB->get_records_sql($sql, $params, $page * MESSAGE_CONTACTS_PER_PAGE, MESSAGE_CONTACTS_PER_PAGE);
  155. $pagingbar = new paging_bar($countparticipants, $page, MESSAGE_CONTACTS_PER_PAGE, $PAGE->url, 'page');
  156. echo $OUTPUT->render($pagingbar);
  157. echo html_writer::start_tag('table', array('id' => 'message_participants', 'class' => 'boxaligncenter', 'cellspacing' => '2', 'cellpadding' => '0', 'border' => '0'));
  158. echo html_writer::start_tag('tr');
  159. echo html_writer::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
  160. echo html_writer::end_tag('tr');
  161. foreach ($participants as $participant) {
  162. if ($participant->id != $USER->id) {
  163. $iscontact = false;
  164. $isblocked = false;
  165. if ( $participant->contactlistid ) {
  166. if ($participant->blocked == 0) {
  167. // Is contact. Is not blocked.
  168. $iscontact = true;
  169. $isblocked = false;
  170. } else {
  171. // Is blocked.
  172. $iscontact = false;
  173. $isblocked = true;
  174. }
  175. }
  176. $participant->messagecount = 0;//todo it would be nice if the course participant could report new messages
  177. message_print_contactlist_user($participant, $iscontact, $isblocked, $contactselecturl, $showactionlinks, $user2);
  178. }
  179. }
  180. echo html_writer::end_tag('table');
  181. }
  182. /**
  183. * Retrieve users blocked by $user1
  184. *
  185. * @param object $user1 the user whose messages are being viewed
  186. * @param object $user2 the user $user1 is talking to. If they are being blocked
  187. * they will have a variable called 'isblocked' added to their user object
  188. * @return array the users blocked by $user1
  189. */
  190. function message_get_blocked_users($user1=null, $user2=null) {
  191. global $DB, $USER;
  192. if (empty($user1)) {
  193. $user1 = $USER;
  194. }
  195. if (!empty($user2)) {
  196. $user2->isblocked = false;
  197. }
  198. $blockedusers = array();
  199. $userfields = user_picture::fields('u', array('lastaccess'));
  200. $blockeduserssql = "SELECT $userfields, COUNT(m.id) AS messagecount
  201. FROM {message_contacts} mc
  202. JOIN {user} u ON u.id = mc.contactid
  203. LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = :user1id1
  204. WHERE mc.userid = :user1id2 AND mc.blocked = 1
  205. GROUP BY $userfields
  206. ORDER BY u.firstname ASC";
  207. $rs = $DB->get_recordset_sql($blockeduserssql, array('user1id1' => $user1->id, 'user1id2' => $user1->id));
  208. foreach($rs as $rd) {
  209. $blockedusers[] = $rd;
  210. if (!empty($user2) && $user2->id == $rd->id) {
  211. $user2->isblocked = true;
  212. }
  213. }
  214. $rs->close();
  215. return $blockedusers;
  216. }
  217. /**
  218. * Print users blocked by $user1. Called by message_print_contact_selector()
  219. *
  220. * @param array $blockedusers the users blocked by $user1
  221. * @param string $contactselecturl the url to send the user to when a contact's name is clicked
  222. * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
  223. * @param string $titletodisplay Optionally specify a title to display above the participants
  224. * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of blocked users
  225. * @return void
  226. */
  227. function message_print_blocked_users($blockedusers, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $user2=null) {
  228. global $DB, $USER;
  229. $countblocked = count($blockedusers);
  230. echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
  231. if (!empty($titletodisplay)) {
  232. echo html_writer::start_tag('tr');
  233. echo html_writer::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
  234. echo html_writer::end_tag('tr');
  235. }
  236. if ($countblocked) {
  237. echo html_writer::start_tag('tr');
  238. echo html_writer::tag('td', get_string('blockedusers', 'message', $countblocked), array('colspan' => 3, 'class' => 'heading'));
  239. echo html_writer::end_tag('tr');
  240. $isuserblocked = true;
  241. $isusercontact = false;
  242. foreach ($blockedusers as $blockeduser) {
  243. message_print_contactlist_user($blockeduser, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
  244. }
  245. }
  246. echo html_writer::end_tag('table');
  247. }
  248. /**
  249. * Retrieve $user1's contacts (online, offline and strangers)
  250. *
  251. * @param object $user1 the user whose messages are being viewed
  252. * @param object $user2 the user $user1 is talking to. If they are a contact
  253. * they will have a variable called 'iscontact' added to their user object
  254. * @return array containing 3 arrays. array($onlinecontacts, $offlinecontacts, $strangers)
  255. */
  256. function message_get_contacts($user1=null, $user2=null) {
  257. global $DB, $CFG, $USER;
  258. if (empty($user1)) {
  259. $user1 = $USER;
  260. }
  261. if (!empty($user2)) {
  262. $user2->iscontact = false;
  263. }
  264. $timetoshowusers = 300; //Seconds default
  265. if (isset($CFG->block_online_users_timetosee)) {
  266. $timetoshowusers = $CFG->block_online_users_timetosee * 60;
  267. }
  268. // time which a user is counting as being active since
  269. $timefrom = time()-$timetoshowusers;
  270. // people in our contactlist who are online
  271. $onlinecontacts = array();
  272. // people in our contactlist who are offline
  273. $offlinecontacts = array();
  274. // people who are not in our contactlist but have sent us a message
  275. $strangers = array();
  276. $userfields = user_picture::fields('u', array('lastaccess'));
  277. // get all in our contactlist who are not blocked in our contact list
  278. // and count messages we have waiting from each of them
  279. $contactsql = "SELECT $userfields, COUNT(m.id) AS messagecount
  280. FROM {message_contacts} mc
  281. JOIN {user} u ON u.id = mc.contactid
  282. LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ?
  283. WHERE mc.userid = ? AND mc.blocked = 0
  284. GROUP BY $userfields
  285. ORDER BY u.firstname ASC";
  286. $rs = $DB->get_recordset_sql($contactsql, array($user1->id, $user1->id));
  287. foreach ($rs as $rd) {
  288. if ($rd->lastaccess >= $timefrom) {
  289. // they have been active recently, so are counted online
  290. $onlinecontacts[] = $rd;
  291. } else {
  292. $offlinecontacts[] = $rd;
  293. }
  294. if (!empty($user2) && $user2->id == $rd->id) {
  295. $user2->iscontact = true;
  296. }
  297. }
  298. $rs->close();
  299. // get messages from anyone who isn't in our contact list and count the number
  300. // of messages we have from each of them
  301. $strangersql = "SELECT $userfields, count(m.id) as messagecount
  302. FROM {message} m
  303. JOIN {user} u ON u.id = m.useridfrom
  304. LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
  305. WHERE mc.id IS NULL AND m.useridto = ?
  306. GROUP BY $userfields
  307. ORDER BY u.firstname ASC";
  308. $rs = $DB->get_recordset_sql($strangersql, array($USER->id));
  309. // Add user id as array index, so supportuser and noreply user don't get duplicated (if they are real users).
  310. foreach ($rs as $rd) {
  311. $strangers[$rd->id] = $rd;
  312. }
  313. $rs->close();
  314. // Add noreply user and support user to the list, if they don't exist.
  315. $supportuser = core_user::get_support_user();
  316. if (!isset($strangers[$supportuser->id])) {
  317. $supportuser->messagecount = message_count_unread_messages($USER, $supportuser);
  318. if ($supportuser->messagecount > 0) {
  319. $strangers[$supportuser->id] = $supportuser;
  320. }
  321. }
  322. $noreplyuser = core_user::get_noreply_user();
  323. if (!isset($strangers[$noreplyuser->id])) {
  324. $noreplyuser->messagecount = message_count_unread_messages($USER, $noreplyuser);
  325. if ($noreplyuser->messagecount > 0) {
  326. $strangers[$noreplyuser->id] = $noreplyuser;
  327. }
  328. }
  329. return array($onlinecontacts, $offlinecontacts, $strangers);
  330. }
  331. /**
  332. * Print $user1's contacts. Called by message_print_contact_selector()
  333. *
  334. * @param array $onlinecontacts $user1's contacts which are online
  335. * @param array $offlinecontacts $user1's contacts which are offline
  336. * @param array $strangers users which are not contacts but who have messaged $user1
  337. * @param string $contactselecturl the url to send the user to when a contact's name is clicked
  338. * @param int $minmessages The minimum number of unread messages required from a user for them to be displayed
  339. * Typically 0 (show all contacts) or 1 (only show contacts from whom we have a new message)
  340. * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
  341. * @param string $titletodisplay Optionally specify a title to display above the participants
  342. * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of contacts
  343. * @return void
  344. */
  345. function message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $contactselecturl=null, $minmessages=0, $showactionlinks=true, $titletodisplay=null, $user2=null) {
  346. global $CFG, $PAGE, $OUTPUT;
  347. $countonlinecontacts = count($onlinecontacts);
  348. $countofflinecontacts = count($offlinecontacts);
  349. $countstrangers = count($strangers);
  350. $isuserblocked = null;
  351. if ($countonlinecontacts + $countofflinecontacts == 0) {
  352. echo html_writer::tag('div', get_string('contactlistempty', 'message'), array('class' => 'heading'));
  353. }
  354. echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
  355. if (!empty($titletodisplay)) {
  356. message_print_heading($titletodisplay);
  357. }
  358. if($countonlinecontacts) {
  359. // Print out list of online contacts.
  360. if (empty($titletodisplay)) {
  361. message_print_heading(get_string('onlinecontacts', 'message', $countonlinecontacts));
  362. }
  363. $isuserblocked = false;
  364. $isusercontact = true;
  365. foreach ($onlinecontacts as $contact) {
  366. if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
  367. message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
  368. }
  369. }
  370. }
  371. if ($countofflinecontacts) {
  372. // Print out list of offline contacts.
  373. if (empty($titletodisplay)) {
  374. message_print_heading(get_string('offlinecontacts', 'message', $countofflinecontacts));
  375. }
  376. $isuserblocked = false;
  377. $isusercontact = true;
  378. foreach ($offlinecontacts as $contact) {
  379. if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
  380. message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
  381. }
  382. }
  383. }
  384. // Print out list of incoming contacts.
  385. if ($countstrangers) {
  386. message_print_heading(get_string('incomingcontacts', 'message', $countstrangers));
  387. $isuserblocked = false;
  388. $isusercontact = false;
  389. foreach ($strangers as $stranger) {
  390. if ($minmessages == 0 || $stranger->messagecount >= $minmessages) {
  391. message_print_contactlist_user($stranger, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
  392. }
  393. }
  394. }
  395. echo html_writer::end_tag('table');
  396. if ($countstrangers && ($countonlinecontacts + $countofflinecontacts == 0)) { // Extra help
  397. echo html_writer::tag('div','('.get_string('addsomecontactsincoming', 'message').')',array('class' => 'note'));
  398. }
  399. }
  400. /**
  401. * Print a select box allowing the user to choose to view new messages, course participants etc.
  402. *
  403. * Called by message_print_contact_selector()
  404. * @param int $viewing What page is the user viewing ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_RECENT_CONVERSATIONS etc
  405. * @param array $courses array of course objects. The courses the user is enrolled in.
  406. * @param array $coursecontexts array of course contexts. Keyed on course id.
  407. * @param int $countunreadtotal how many unread messages does the user have?
  408. * @param int $countblocked how many users has the current user blocked?
  409. * @param stdClass $user1 The user whose messages we are viewing.
  410. * @param string $strunreadmessages a preconstructed message about the number of unread messages the user has
  411. * @return void
  412. */
  413. function message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, $countblocked, $strunreadmessages, $user1 = null) {
  414. $options = array();
  415. if ($countunreadtotal>0) { //if there are unread messages
  416. $options[MESSAGE_VIEW_UNREAD_MESSAGES] = $strunreadmessages;
  417. }
  418. $str = get_string('contacts', 'message');
  419. $options[MESSAGE_VIEW_CONTACTS] = $str;
  420. $options[MESSAGE_VIEW_RECENT_CONVERSATIONS] = get_string('mostrecentconversations', 'message');
  421. $options[MESSAGE_VIEW_RECENT_NOTIFICATIONS] = get_string('mostrecentnotifications', 'message');
  422. if (!empty($courses)) {
  423. $courses_options = array();
  424. foreach($courses as $course) {
  425. if (has_capability('moodle/course:viewparticipants', $coursecontexts[$course->id])) {
  426. //Not using short_text() as we want the end of the course name. Not the beginning.
  427. $shortname = format_string($course->shortname, true, array('context' => $coursecontexts[$course->id]));
  428. if (core_text::strlen($shortname) > MESSAGE_MAX_COURSE_NAME_LENGTH) {
  429. $courses_options[MESSAGE_VIEW_COURSE.$course->id] = '...'.core_text::substr($shortname, -MESSAGE_MAX_COURSE_NAME_LENGTH);
  430. } else {
  431. $courses_options[MESSAGE_VIEW_COURSE.$course->id] = $shortname;
  432. }
  433. }
  434. }
  435. if (!empty($courses_options)) {
  436. $options[] = array(get_string('courses') => $courses_options);
  437. }
  438. }
  439. if ($countblocked>0) {
  440. $str = get_string('blockedusers','message', $countblocked);
  441. $options[MESSAGE_VIEW_BLOCKED] = $str;
  442. }
  443. echo html_writer::start_tag('form', array('id' => 'usergroupform','method' => 'get','action' => ''));
  444. echo html_writer::start_tag('fieldset');
  445. if ( !empty($user1) && !empty($user1->id) ) {
  446. echo html_writer::empty_tag('input', array('type' => 'hidden','name' => 'user1','value' => $user1->id));
  447. }
  448. echo html_writer::label(get_string('messagenavigation', 'message'), 'viewing');
  449. echo html_writer::select($options, 'viewing', $viewing, false, array('id' => 'viewing','onchange' => 'this.form.submit()'));
  450. echo html_writer::end_tag('fieldset');
  451. echo html_writer::end_tag('form');
  452. }
  453. /**
  454. * Load the course contexts for all of the users courses
  455. *
  456. * @param array $courses array of course objects. The courses the user is enrolled in.
  457. * @return array of course contexts
  458. */
  459. function message_get_course_contexts($courses) {
  460. $coursecontexts = array();
  461. foreach($courses as $course) {
  462. $coursecontexts[$course->id] = context_course::instance($course->id);
  463. }
  464. return $coursecontexts;
  465. }
  466. /**
  467. * strip off action parameters like 'removecontact'
  468. *
  469. * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
  470. * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
  471. */
  472. function message_remove_url_params($moodleurl) {
  473. $newurl = new moodle_url($moodleurl);
  474. $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
  475. return $newurl->out();
  476. }
  477. /**
  478. * Count the number of messages with a field having a specified value.
  479. * if $field is empty then return count of the whole array
  480. * if $field is non-existent then return 0
  481. *
  482. * @param array $messagearray array of message objects
  483. * @param string $field the field to inspect on the message objects
  484. * @param string $value the value to test the field against
  485. */
  486. function message_count_messages($messagearray, $field='', $value='') {
  487. if (!is_array($messagearray)) return 0;
  488. if ($field == '' or empty($messagearray)) return count($messagearray);
  489. $count = 0;
  490. foreach ($messagearray as $message) {
  491. $count += ($message->$field == $value) ? 1 : 0;
  492. }
  493. return $count;
  494. }
  495. /**
  496. * Returns the count of unread messages for user. Either from a specific user or from all users.
  497. *
  498. * @param object $user1 the first user. Defaults to $USER
  499. * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
  500. * @return int the count of $user1's unread messages
  501. */
  502. function message_count_unread_messages($user1=null, $user2=null) {
  503. global $USER, $DB;
  504. if (empty($user1)) {
  505. $user1 = $USER;
  506. }
  507. if (!empty($user2)) {
  508. return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
  509. array($user1->id, $user2->id), "COUNT('id')");
  510. } else {
  511. return $DB->count_records_select('message', "useridto = ?",
  512. array($user1->id), "COUNT('id')");
  513. }
  514. }
  515. /**
  516. * Count the number of users blocked by $user1
  517. *
  518. * @param object $user1 user object
  519. * @return int the number of blocked users
  520. */
  521. function message_count_blocked_users($user1=null) {
  522. global $USER, $DB;
  523. if (empty($user1)) {
  524. $user1 = $USER;
  525. }
  526. $sql = "SELECT count(mc.id)
  527. FROM {message_contacts} mc
  528. WHERE mc.userid = :userid AND mc.blocked = 1";
  529. $params = array('userid' => $user1->id);
  530. return $DB->count_records_sql($sql, $params);
  531. }
  532. /**
  533. * Print the search form and search results if a search has been performed
  534. *
  535. * @param boolean $advancedsearch show basic or advanced search form
  536. * @param object $user1 the current user
  537. * @return boolean true if a search was performed
  538. */
  539. function message_print_search($advancedsearch = false, $user1=null) {
  540. $frm = data_submitted();
  541. $doingsearch = false;
  542. if ($frm) {
  543. if (confirm_sesskey()) {
  544. $doingsearch = !empty($frm->combinedsubmit) || !empty($frm->keywords) || (!empty($frm->personsubmit) and !empty($frm->name));
  545. } else {
  546. $frm = false;
  547. }
  548. }
  549. if (!empty($frm->combinedsearch)) {
  550. $combinedsearchstring = $frm->combinedsearch;
  551. } else {
  552. //$combinedsearchstring = get_string('searchcombined','message').'...';
  553. $combinedsearchstring = '';
  554. }
  555. if ($doingsearch) {
  556. if ($advancedsearch) {
  557. $messagesearch = '';
  558. if (!empty($frm->keywords)) {
  559. $messagesearch = $frm->keywords;
  560. }
  561. $personsearch = '';
  562. if (!empty($frm->name)) {
  563. $personsearch = $frm->name;
  564. }
  565. include('search_advanced.html');
  566. } else {
  567. include('search.html');
  568. }
  569. $showicontext = false;
  570. message_print_search_results($frm, $showicontext, $user1);
  571. return true;
  572. } else {
  573. if ($advancedsearch) {
  574. $personsearch = $messagesearch = '';
  575. include('search_advanced.html');
  576. } else {
  577. include('search.html');
  578. }
  579. return false;
  580. }
  581. }
  582. /**
  583. * Get the users recent conversations meaning all the people they've recently
  584. * sent or received a message from plus the most recent message sent to or received from each other user
  585. *
  586. * @param object $user the current user
  587. * @param int $limitfrom can be used for paging
  588. * @param int $limitto can be used for paging
  589. * @return array
  590. */
  591. function message_get_recent_conversations($user, $limitfrom=0, $limitto=100) {
  592. global $DB;
  593. $userfields = user_picture::fields('otheruser', array('lastaccess'));
  594. // This query retrieves the most recent message received from or sent to
  595. // seach other user.
  596. //
  597. // If two messages have the same timecreated, we take the one with the
  598. // larger id.
  599. //
  600. // There is a separate query for read and unread messages as they are stored
  601. // in different tables. They were originally retrieved in one query but it
  602. // was so large that it was difficult to be confident in its correctness.
  603. $sql = "SELECT $userfields,
  604. message.id as mid, message.notification, message.smallmessage, message.fullmessage,
  605. message.fullmessagehtml, message.fullmessageformat, message.timecreated,
  606. contact.id as contactlistid, contact.blocked
  607. FROM {message_read} message
  608. JOIN {user} otheruser ON otheruser.id = CASE
  609. WHEN message.useridto = :userid1 THEN message.useridfrom
  610. ELSE message.useridto END
  611. LEFT JOIN {message_contacts} contact ON contact.userid = :userid2 AND contact.contactid = otheruser.id
  612. WHERE otheruser.deleted = 0
  613. AND (message.useridto = :userid3 OR message.useridfrom = :userid4)
  614. AND message.notification = 0
  615. AND NOT EXISTS (
  616. SELECT 1
  617. FROM {message_read} othermessage
  618. WHERE ((othermessage.useridto = :userid5 AND othermessage.useridfrom = otheruser.id) OR
  619. (othermessage.useridfrom = :userid6 AND othermessage.useridto = otheruser.id))
  620. AND (othermessage.timecreated > message.timecreated OR (
  621. othermessage.timecreated = message.timecreated AND othermessage.id > message.id))
  622. )
  623. ORDER BY message.timecreated DESC";
  624. $params = array('userid1' => $user->id, 'userid2' => $user->id, 'userid3' => $user->id,
  625. 'userid4' => $user->id, 'userid5' => $user->id, 'userid6' => $user->id);
  626. $read = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
  627. // We want to get the messages that have not been read. These are stored in the 'message' table. It is the
  628. // exact same query as the one above, except for the table we are querying. So, simply replace references to
  629. // the 'message_read' table with the 'message' table.
  630. $sql = str_replace('{message_read}', '{message}', $sql);
  631. $unread = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
  632. $conversations = array();
  633. // Union the 2 result sets together looking for the message with the most
  634. // recent timecreated for each other user.
  635. // $conversation->id (the array key) is the other user's ID.
  636. $conversation_arrays = array($unread, $read);
  637. foreach ($conversation_arrays as $conversation_array) {
  638. foreach ($conversation_array as $conversation) {
  639. if (empty($conversations[$conversation->id]) || $conversations[$conversation->id]->timecreated < $conversation->timecreated ) {
  640. $conversations[$conversation->id] = $conversation;
  641. }
  642. }
  643. }
  644. // Sort the conversations by $conversation->timecreated, newest to oldest
  645. // There may be multiple conversations with the same timecreated
  646. // The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
  647. $result = core_collator::asort_objects_by_property($conversations, 'timecreated', core_collator::SORT_NUMERIC);
  648. $conversations = array_reverse($conversations);
  649. return $conversations;
  650. }
  651. /**
  652. * Get the users recent event notifications
  653. *
  654. * @param object $user the current user
  655. * @param int $limitfrom can be used for paging
  656. * @param int $limitto can be used for paging
  657. * @return array
  658. */
  659. function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
  660. global $DB;
  661. $userfields = user_picture::fields('u', array('lastaccess'));
  662. $sql = "SELECT mr.id AS message_read_id, $userfields, mr.notification, mr.smallmessage, mr.fullmessage, mr.fullmessagehtml, mr.fullmessageformat, mr.timecreated as timecreated, mr.contexturl, mr.contexturlname
  663. FROM {message_read} mr
  664. JOIN {user} u ON u.id=mr.useridfrom
  665. WHERE mr.useridto = :userid1 AND u.deleted = '0' AND mr.notification = :notification
  666. ORDER BY mr.timecreated DESC";
  667. $params = array('userid1' => $user->id, 'notification' => 1);
  668. $notifications = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
  669. return $notifications;
  670. }
  671. /**
  672. * Print the user's recent conversations
  673. *
  674. * @param stdClass $user the current user
  675. * @param bool $showicontext flag indicating whether or not to show text next to the action icons
  676. */
  677. function message_print_recent_conversations($user1 = null, $showicontext = false, $showactionlinks = true) {
  678. global $USER;
  679. echo html_writer::start_tag('p', array('class' => 'heading'));
  680. echo get_string('mostrecentconversations', 'message');
  681. echo html_writer::end_tag('p');
  682. if (empty($user1)) {
  683. $user1 = $USER;
  684. }
  685. $conversations = message_get_recent_conversations($user1);
  686. // Attach context url information to create the "View this conversation" type links
  687. foreach($conversations as $conversation) {
  688. $conversation->contexturl = new moodle_url("/message/index.php?user1={$user1->id}&user2={$conversation->id}");
  689. $conversation->contexturlname = get_string('thisconversation', 'message');
  690. }
  691. $showotheruser = true;
  692. message_print_recent_messages_table($conversations, $user1, $showotheruser, $showicontext, false, $showactionlinks);
  693. }
  694. /**
  695. * Print the user's recent notifications
  696. *
  697. * @param stdClass $user the current user
  698. */
  699. function message_print_recent_notifications($user=null) {
  700. global $USER;
  701. echo html_writer::start_tag('p', array('class' => 'heading'));
  702. echo get_string('mostrecentnotifications', 'message');
  703. echo html_writer::end_tag('p');
  704. if (empty($user)) {
  705. $user = $USER;
  706. }
  707. $notifications = message_get_recent_notifications($user);
  708. $showicontext = false;
  709. $showotheruser = false;
  710. message_print_recent_messages_table($notifications, $user, $showotheruser, $showicontext, true);
  711. }
  712. /**
  713. * Print a list of recent messages
  714. *
  715. * @access private
  716. *
  717. * @param array $messages the messages to display
  718. * @param stdClass $user the current user
  719. * @param bool $showotheruser display information on the other user?
  720. * @param bool $showicontext show text next to the action icons?
  721. * @param bool $forcetexttohtml Force text to go through @see text_to_html() via @see format_text()
  722. * @param bool $showactionlinks
  723. * @return void
  724. */
  725. function message_print_recent_messages_table($messages, $user = null, $showotheruser = true, $showicontext = false, $forcetexttohtml = false, $showactionlinks = true) {
  726. global $OUTPUT;
  727. static $dateformat;
  728. if (empty($dateformat)) {
  729. $dateformat = get_string('strftimedatetimeshort');
  730. }
  731. echo html_writer::start_tag('div', array('class' => 'messagerecent'));
  732. foreach ($messages as $message) {
  733. echo html_writer::start_tag('div', array('class' => 'singlemessage'));
  734. if ($showotheruser) {
  735. $strcontact = $strblock = $strhistory = null;
  736. if ($showactionlinks) {
  737. if ( $message->contactlistid ) {
  738. if ($message->blocked == 0) { // The other user isn't blocked.
  739. $strcontact = message_contact_link($message->id, 'remove', true, null, $showicontext);
  740. $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
  741. } else { // The other user is blocked.
  742. $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
  743. $strblock = message_contact_link($message->id, 'unblock', true, null, $showicontext);
  744. }
  745. } else {
  746. $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
  747. $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
  748. }
  749. //should we show just the icon or icon and text?
  750. $histicontext = 'icon';
  751. if ($showicontext) {
  752. $histicontext = 'both';
  753. }
  754. $strhistory = message_history_link($user->id, $message->id, true, '', '', $histicontext);
  755. }
  756. echo html_writer::start_tag('span', array('class' => 'otheruser'));
  757. echo html_writer::start_tag('span', array('class' => 'pix'));
  758. echo $OUTPUT->user_picture($message, array('size' => 20, 'courseid' => SITEID));
  759. echo html_writer::end_tag('span');
  760. echo html_writer::start_tag('span', array('class' => 'contact'));
  761. $link = new moodle_url("/message/index.php?user1={$user->id}&user2=$message->id");
  762. $action = null;
  763. echo $OUTPUT->action_link($link, fullname($message), $action, array('title' => get_string('sendmessageto', 'message', fullname($message))));
  764. echo html_writer::end_tag('span');//end contact
  765. if ($showactionlinks) {
  766. echo $strcontact.$strblock.$strhistory;
  767. }
  768. echo html_writer::end_tag('span');//end otheruser
  769. }
  770. $messagetext = message_format_message_text($message, $forcetexttohtml);
  771. echo html_writer::tag('span', userdate($message->timecreated, $dateformat), array('class' => 'messagedate'));
  772. echo html_writer::tag('span', $messagetext, array('class' => 'themessage'));
  773. echo message_format_contexturl($message);
  774. echo html_writer::end_tag('div');//end singlemessage
  775. }
  776. echo html_writer::end_tag('div');//end messagerecent
  777. }
  778. /**
  779. * Try to guess how to convert the message to html.
  780. *
  781. * @access private
  782. *
  783. * @param stdClass $message
  784. * @param bool $forcetexttohtml
  785. * @return string html fragment
  786. */
  787. function message_format_message_text($message, $forcetexttohtml = false) {
  788. // Note: this is a very nasty hack that tries to work around the weird messaging rules and design.
  789. $options = new stdClass();
  790. $options->para = false;
  791. $format = $message->fullmessageformat;
  792. if ($message->smallmessage !== '') {
  793. if ($message->notification == 1) {
  794. if ($message->fullmessagehtml !== '' or $message->fullmessage !== '') {
  795. $format = FORMAT_PLAIN;
  796. }
  797. }
  798. $messagetext = $message->smallmessage;
  799. } else if ($message->fullmessageformat == FORMAT_HTML) {
  800. if ($message->fullmessagehtml !== '') {
  801. $messagetext = $message->fullmessagehtml;
  802. } else {
  803. $messagetext = $message->fullmessage;
  804. $format = FORMAT_MOODLE;
  805. }
  806. } else {
  807. if ($message->fullmessage !== '') {
  808. $messagetext = $message->fullmessage;
  809. } else {
  810. $messagetext = $message->fullmessagehtml;
  811. $format = FORMAT_HTML;
  812. }
  813. }
  814. if ($forcetexttohtml) {
  815. // This is a crazy hack, why not set proper format when creating the notifications?
  816. if ($format === FORMAT_PLAIN) {
  817. $format = FORMAT_MOODLE;
  818. }
  819. }
  820. return format_text($messagetext, $format, $options);
  821. }
  822. /**
  823. * Add the selected user as a contact for the current user
  824. *
  825. * @param int $contactid the ID of the user to add as a contact
  826. * @param int $blocked 1 if you wish to block the contact
  827. * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
  828. * Otherwise returns the result of update_record() or insert_record()
  829. */
  830. function message_add_contact($contactid, $blocked=0) {
  831. global $USER, $DB;
  832. if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
  833. return false;
  834. }
  835. if (($contact = $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid))) !== false) {
  836. // A record already exists. We may be changing blocking status.
  837. if ($contact->blocked !== $blocked) {
  838. // Blocking status has been changed.
  839. $contact->blocked = $blocked;
  840. return $DB->update_record('message_contacts', $contact);
  841. } else {
  842. // No change to blocking status.
  843. return true;
  844. }
  845. } else {
  846. // New contact record.
  847. $contact = new stdClass();
  848. $contact->userid = $USER->id;
  849. $contact->contactid = $contactid;
  850. $contact->blocked = $blocked;
  851. return $DB->insert_record('message_contacts', $contact, false);
  852. }
  853. }
  854. /**
  855. * remove a contact
  856. *
  857. * @param int $contactid the user ID of the contact to remove
  858. * @return bool returns the result of delete_records()
  859. */
  860. function message_remove_contact($contactid) {
  861. global $USER, $DB;
  862. return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
  863. }
  864. /**
  865. * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
  866. *
  867. * @param int $contactid the user ID of the contact to unblock
  868. * @return bool returns the result of delete_records()
  869. */
  870. function message_unblock_contact($contactid) {
  871. global $USER, $DB;
  872. return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
  873. }
  874. /**
  875. * block a user
  876. *
  877. * @param int $contactid the user ID of the user to block
  878. */
  879. function message_block_contact($contactid) {
  880. return message_add_contact($contactid, 1);
  881. }
  882. /**
  883. * Load a user's contact record
  884. *
  885. * @param int $contactid the user ID of the user whose contact record you want
  886. * @return array message contacts
  887. */
  888. function message_get_contact($contactid) {
  889. global $USER, $DB;
  890. return $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
  891. }
  892. /**
  893. * Print the results of a message search
  894. *
  895. * @param mixed $frm submitted form data
  896. * @param bool $showicontext show text next to action icons?
  897. * @param object $currentuser the current user
  898. * @return void
  899. */
  900. function message_print_search_results($frm, $showicontext=false, $currentuser=null) {
  901. global $USER, $DB, $OUTPUT;
  902. if (empty($currentuser)) {
  903. $currentuser = $USER;
  904. }
  905. echo html_writer::start_tag('div', array('class' => 'mdl-left'));
  906. $personsearch = false;
  907. $personsearchstring = null;
  908. if (!empty($frm->personsubmit) and !empty($frm->name)) {
  909. $personsearch = true;
  910. $personsearchstring = $frm->name;
  911. } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
  912. $personsearch = true;
  913. $personsearchstring = $frm->combinedsearch;
  914. }
  915. // Search for person.
  916. if ($personsearch) {
  917. if (optional_param('mycourses', 0, PARAM_BOOL)) {
  918. $users = array();
  919. $mycourses = enrol_get_my_courses('id');
  920. $mycoursesids = array();
  921. foreach ($mycourses as $mycourse) {
  922. $mycoursesids[] = $mycourse->id;
  923. }
  924. $susers = message_search_users($mycoursesids, $personsearchstring);
  925. foreach ($susers as $suser) {
  926. $users[$suser->id] = $suser;
  927. }
  928. } else {
  929. $users = message_search_users(SITEID, $personsearchstring);
  930. }
  931. if (!empty($users)) {
  932. echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
  933. echo get_string('userssearchresults', 'message', count($users));
  934. echo html_writer::end_tag('p');
  935. echo html_writer::start_tag('table', array('class' => 'messagesearchresults'));
  936. foreach ($users as $user) {
  937. if ( $user->contactlistid ) {
  938. if ($user->blocked == 0) { // User is not blocked.
  939. $strcontact = message_contact_link($user->id, 'remove', true, null, $showicontext);
  940. $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
  941. } else { // blocked
  942. $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
  943. $strblock = message_contact_link($user->id, 'unblock', true, null, $showicontext);
  944. }
  945. } else {
  946. $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
  947. $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
  948. }
  949. // Should we show just the icon or icon and text?
  950. $histicontext = 'icon';
  951. if ($showicontext) {
  952. $histicontext = 'both';
  953. }
  954. $strhistory = message_history_link($USER->id, $user->id, true, '', '', $histicontext);
  955. echo html_writer::start_tag('tr');
  956. echo html_writer::start_tag('td', array('class' => 'pix'));
  957. echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
  958. echo html_writer::end_tag('td');
  959. echo html_writer::start_tag('td',array('class' => 'contact'));
  960. $action = null;
  961. $link = new moodle_url("/message/index.php?id=$user->id");
  962. echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
  963. echo html_writer::end_tag('td');
  964. echo html_writer::tag('td', $strcontact, array('class' => 'link'));
  965. echo html_writer::tag('td', $strblock, array('class' => 'link'));
  966. echo html_writer::tag('td', $strhistory, array('class' => 'link'));
  967. echo html_writer::end_tag('tr');
  968. }
  969. echo html_writer::end_tag('table');
  970. } else {
  971. echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
  972. echo get_string('userssearchresults', 'message', 0).'<br /><br />';
  973. echo html_writer::end_tag('p');
  974. }
  975. }
  976. // search messages for keywords
  977. $messagesearch = false;
  978. $messagesearchstring = null;
  979. if (!empty($frm->keywords)) {
  980. $messagesearch = true;
  981. $messagesearchstring = clean_text(trim($frm->keywords));
  982. } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
  983. $messagesearch = true;
  984. $messagesearchstring = clean_text(trim($frm->combinedsearch));
  985. }
  986. if ($messagesearch) {
  987. if ($messagesearchstring) {
  988. $keywords = explode(' ', $messagesearchstring);
  989. } else {
  990. $keywords = array();
  991. }
  992. $tome = false;
  993. $fromme = false;
  994. $courseid = 'none';
  995. if (empty($frm->keywordsoption)) {
  996. $frm->keywordsoption = 'allmine';
  997. }
  998. switch ($frm->keywordsoption) {
  999. case 'tome':
  1000. $tome = true;
  1001. break;
  1002. case 'fromme':
  1003. $fromme = true;
  1004. break;
  1005. case 'allmine':
  1006. $tome = true;
  1007. $fromme = true;
  1008. break;
  1009. case 'allusers':
  1010. $courseid = SITEID;
  1011. break;
  1012. case 'courseusers':
  1013. $courseid = $frm->courseid;
  1014. break;
  1015. default:
  1016. $tome = true;
  1017. $fromme = true;
  1018. }
  1019. if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
  1020. // Get a list of contacts.
  1021. if (($contacts = $DB->get_records('message_contacts', array('userid' => $USER->id), '', 'contactid, blocked') ) === false) {
  1022. $contacts = array();
  1023. }
  1024. // Print heading with number of results.
  1025. echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
  1026. $countresults = count($messages);
  1027. if ($countresults == MESSAGE_SEARCH_MAX_RESULTS) {
  1028. echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
  1029. } else {
  1030. echo get_string('keywordssearchresults', 'message', $countresults);
  1031. }
  1032. echo html_writer::end_tag('p');
  1033. // Print table headings.
  1034. echo html_writer::start_tag('table', array('class' => 'messagesearchresults', 'cellspacing' => '0'));
  1035. $headertdstart = html_writer::start_tag('td', array('class' => 'messagesearchresultscol'));
  1036. $headertdend = html_writer::end_tag('td');
  1037. echo html_writer::start_tag('tr');
  1038. echo $headertdstart.get_string('from').$headertdend;
  1039. echo $headertdstart.get_string('to').$headertdend;
  1040. echo $headertdstart.get_string('message', 'message').$headertdend;
  1041. echo $headertdstart.get_string('timesent', 'message').$headertdend;
  1042. echo html_writer::end_tag('tr');
  1043. $blockedcount = 0;
  1044. $dateformat = get_string('strftimedatetimeshort');
  1045. $strcontext = get_string('context', 'message');
  1046. foreach ($messages as $message) {
  1047. // Ignore messages to and from blocked users unless $frm->includeblocked is set.
  1048. if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
  1049. ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
  1050. ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
  1051. )
  1052. ) {
  1053. $blockedcount ++;
  1054. continue;
  1055. }
  1056. // Load user-to record.
  1057. if ($message->useridto !== $USER->id) {
  1058. $userto = core_user::get_user($message->useridto);
  1059. $tocontact = (array_key_exists($message->useridto, $contacts) and
  1060. ($contacts[$message->useridto]->blocked == 0) );
  1061. $toblocked = (array_key_exists($message->useridto, $contacts) and
  1062. ($contacts[$message->useridto]->blocked == 1) );
  1063. } else {
  1064. $userto = false;
  1065. $tocontact = false;
  1066. $toblocked = false;
  1067. }
  1068. // Load user-from record.
  1069. if ($message->useridfrom !== $USER->id) {
  1070. $userfrom = core_user::get_user($message->useridfrom);
  1071. $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
  1072. ($contacts[$message->useridfrom]->blocked == 0) );
  1073. $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
  1074. ($contacts[$message->useridfrom]->blocked == 1) );
  1075. } else {
  1076. $userfrom = false;
  1077. $fromcontact = false;
  1078. $fromblocked = false;
  1079. }
  1080. // Find date string for this message.
  1081. $date = usergetdate($message->timecreated);
  1082. $datestring = $date['year'].$date['mon'].$date['mday'];
  1083. // Print out message row.
  1084. echo html_writer::start_tag('tr', array('valign' => 'top'));
  1085. echo html_writer::start_tag('td', array('class' => 'contact'));
  1086. message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
  1087. echo html_writer::end_tag('td');
  1088. echo html_writer::start_tag('td', array('class' => 'contact'));
  1089. message_print_user($userto, $tocontact, $toblocked, $showicontext);
  1090. echo html_writer::end_tag('td');
  1091. echo html_writer::start_tag('td', array('class' => 'summary'));
  1092. echo message_get_fragment($message->smallmessage, $keywords);
  1093. echo html_writer::start_tag('div', array('class' => 'link'));
  1094. // If the user clicks the context link display message sender on the left.
  1095. // EXCEPT if the current user is in the conversation. Current user == always on the left.
  1096. $leftsideuserid = $rightsideuserid = null;
  1097. if ($currentuser->id == $message->useridto) {
  1098. $leftsideuserid = $message->useridto;
  1099. $rightsideuserid = $message->useridfrom;
  1100. } else {
  1101. $leftsideuserid = $message->useridfrom;
  1102. $rightsideuserid = $message->useridto;
  1103. }
  1104. message_history_link($leftsideuserid, $rightsideuserid, false,
  1105. $messagesearchstring, 'm'.$message->id, $strcontext);
  1106. echo html_writer::end_tag('div');
  1107. echo html_writer::end_tag('td');
  1108. echo html_writer::tag('td', userdate($message->timecreated, $dateformat), array('class' => 'date'));
  1109. echo html_writer::end_tag('tr');
  1110. }
  1111. if ($blockedcount > 0) {
  1112. echo html_writer::start_tag('tr');
  1113. echo html_writer::tag('td', get_string('blockedmessages', 'message', $blockedcount), array('colspan' => 4, 'align' => 'center'));
  1114. echo html_writer::end_tag('tr');
  1115. }
  1116. echo html_writer::end_tag('table');
  1117. } else {
  1118. echo html_writer::tag('p', get_string('keywordssearchresults', 'message', 0), array('class' => 'heading'));
  1119. }
  1120. }
  1121. if (!$personsearch && !$messagesearch) {
  1122. //they didn't enter any search terms
  1123. echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
  1124. }
  1125. echo html_writer::end_tag('div');
  1126. }
  1127. /**
  1128. * Print information on a user. Used when printing search results.
  1129. *
  1130. * @param object/bool $user the user to display or false if you just want $USER
  1131. * @param bool $iscontact is the user being displayed a contact?
  1132. * @param bool $isblocked is the user being displayed blocked?
  1133. * @param bool $includeicontext include text next to the action icons?
  1134. * @return void
  1135. */
  1136. function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
  1137. global $USER, $OUTPUT;
  1138. $userpictureparams = array('size' => 20, 'courseid' => SITEID);
  1139. if ($user === false) {
  1140. echo $OUTPUT->user_picture($USER, $userpictureparams);
  1141. } else if (core_user::is_real_user($user->id)) { // If not real user, then don't show any links.
  1142. $userpictureparams['link'] = false;
  1143. echo $OUTPUT->user_picture($USER, $userpictureparams);
  1144. echo fullname($user);
  1145. } else {
  1146. echo $OUTPUT->user_picture($user, $userpictureparams);
  1147. $link = new moodle_url("/message/index.php?id=$user->id");
  1148. echo $OUTPUT->action_link($link, fullname($user), null, array('title' =>
  1149. get_string('sendmessageto', 'message', fullname($user))));
  1150. $return = false;
  1151. $script = null;
  1152. if ($iscontact) {
  1153. message_contact_link($user->id, 'remove', $return, $script, $includeicontext);
  1154. } else {
  1155. message_contact_link($user->id, 'add', $return, $script, $includeicontext);
  1156. }
  1157. if ($isblocked) {
  1158. message_contact_link($user->id, 'unblock', $return, $script, $includeicontext);
  1159. } else {
  1160. message_contact_link($user->id, 'block', $return, $script, $includeicontext);
  1161. }
  1162. }
  1163. }
  1164. /**
  1165. * Print a message contact link
  1166. *
  1167. * @param int $userid the ID of the user to apply to action to
  1168. * @param string $linktype can be add, remove, block or unblock
  1169. * @param bool $return if true return the link as a string. If false echo the link.
  1170. * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
  1171. * @param bool $text include text next to the icons?
  1172. * @param bool $icon include a graphical icon?
  1173. * @return string if $return is true otherwise bool
  1174. */
  1175. function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
  1176. global $OUTPUT, $PAGE;
  1177. //hold onto the strings as we're probably creating a bunch of links
  1178. static $str;
  1179. if (empty($script)) {
  1180. //strip off previous action params like 'removecontact'
  1181. $script = message_remove_url_params($PAGE->url);
  1182. }
  1183. if (empty($str->blockcontact)) {
  1184. $str = new stdClass();
  1185. $str->blockcontact = get_string('blockcontact', 'message');
  1186. $str->unblockcontact = get_string('unblockcontact', 'message');
  1187. $str->removecontact = get_string('removecontact', 'message');
  1188. $str->addcontact = get_string('addcontact', 'message');
  1189. }
  1190. $command = $linktype.'contact';
  1191. $string = $str->{$command};
  1192. $safealttext = s($string);
  1193. $safestring = '';
  1194. if (!empty($text)) {
  1195. $safestring = $safealttext;
  1196. }
  1197. $img = '';
  1198. if ($icon) {
  1199. $iconpath = null;
  1200. switch ($linktype) {
  1201. case 'block':
  1202. $iconpath = 't/block';
  1203. break;
  1204. case 'unblock':
  1205. $iconpath = 't/unblock';
  1206. break;
  1207. case 'remove':
  1208. $iconpath = 't/removecontact';
  1209. break;
  1210. case 'add':
  1211. default:
  1212. $iconpath = 't/addcontact';
  1213. }
  1214. $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
  1215. }
  1216. $output = '<span class="'.$linktype.'contact">'.
  1217. '<a href="'.$script.'&amp;'.$command.'='.$userid.
  1218. '&amp;sesskey='.sesskey().'" title="'.$safealttext.'">'.
  1219. $img.
  1220. $safestring.'</a></span>';
  1221. if ($return) {
  1222. return $output;
  1223. } else {
  1224. echo $output;
  1225. return true;
  1226. }
  1227. }
  1228. /**
  1229. * echo or return a link to take the user to the full message history between themselves and another user
  1230. *
  1231. * @param int $userid1 the ID of the user displayed on the left (usually the current user)
  1232. * @param int $userid2 the ID of the other user
  1233. * @param bool $return true to return the link as a string. False to echo the link.
  1234. * @param string $keywords any keywords to highlight in the message history
  1235. * @param string $position anchor name to jump to within the message history
  1236. * @param string $linktext optionally specify the link text
  1237. * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
  1238. */
  1239. function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
  1240. global $OUTPUT, $PAGE;
  1241. static $strmessagehistory;
  1242. if (empty($strmessagehistory)) {
  1243. $strmessagehistory = get_string('messagehistory', 'message');
  1244. }
  1245. if ($position) {
  1246. $position = "#$position";
  1247. }
  1248. if ($keywords) {
  1249. $keywords = "&search=".urlencode($keywords);
  1250. }
  1251. if ($linktext == 'icon') { // Icon only
  1252. $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
  1253. } else if ($linktext == 'both') { // Icon and standard name
  1254. $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="" />';
  1255. $fulllink .= '&nbsp;'.$strmessagehistory;
  1256. } else if ($linktext) { // Custom name
  1257. $fulllink = $linktext;
  1258. } else { // Standard name only
  1259. $fulllink = $strmessagehistory;
  1260. }
  1261. $popupoptions = array(
  1262. 'height' => 500,
  1263. 'width' => 500,
  1264. 'menubar' => false,
  1265. 'location' => false,
  1266. 'status' => true,
  1267. 'scrollbars' => true,
  1268. 'resizable' => true);
  1269. $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user1=$userid1&user2=$userid2$keywords$position");
  1270. if ($PAGE->url && $PAGE->url->get_param('viewing')) {
  1271. $link->param('viewing', $PAGE->url->get_param('viewing'));
  1272. }
  1273. $action = null;
  1274. $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
  1275. $str = '<span class="history">'.$str.'</span>';
  1276. if ($return) {
  1277. return $str;
  1278. } else {
  1279. echo $str;
  1280. return true;
  1281. }
  1282. }
  1283. /**
  1284. * Search through course users.
  1285. *
  1286. * If $courseids contains the site course then this function searches
  1287. * through all undeleted and confirmed users.
  1288. *
  1289. * @param int|array $courseids Course ID or array of course IDs.
  1290. * @param string $searchtext the text to search for.
  1291. * @param string $sort the column name to order by.
  1292. * @param string|array $exceptions comma separated list or array of user IDs to exclude.
  1293. * @return array An array of {@link $USER} records.
  1294. */
  1295. function message_search_users($courseids, $searchtext, $sort='', $exceptions='') {
  1296. global $CFG, $USER, $DB;
  1297. // Basic validation to ensure that the parameter $courseids is not an empty array or an empty value.
  1298. if (!$courseids) {
  1299. $courseids = array(SITEID);
  1300. }
  1301. // Allow an integer to be passed.
  1302. if (!is_array($courseids)) {
  1303. $courseids = array($courseids);
  1304. }
  1305. $fullname = $DB->sql_fullname();
  1306. $ufields = user_picture::fields('u');
  1307. if (!empty($sort)) {
  1308. $order = ' ORDER BY '. $sort;
  1309. } else {
  1310. $order = '';
  1311. }
  1312. $params = array(
  1313. 'userid' => $USER->id,
  1314. 'query' => "%$searchtext%"
  1315. );
  1316. if (empty($exceptions)) {
  1317. $exceptions = array();
  1318. } else if (!empty($exceptions) && is_string($exceptions)) {
  1319. $exceptions = explode(',', $exceptions);
  1320. }
  1321. // Ignore self and guest account.
  1322. $exceptions[] = $USER->id;
  1323. $exceptions[] = $CFG->siteguest;
  1324. // Exclude exceptions from the search result.
  1325. list($except, $params_except) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'param', false);
  1326. $except = ' AND u.id ' . $except;
  1327. $params = array_merge($params_except, $params);
  1328. if (in_array(SITEID, $courseids)) {
  1329. // Search on site level.
  1330. return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
  1331. FROM {user} u
  1332. LEFT JOIN {message_contacts} mc
  1333. ON mc.contactid = u.id AND mc.userid = :userid
  1334. WHERE u.deleted = '0' AND u.confirmed = '1'
  1335. AND (".$DB->sql_like($fullname, ':query', false).")
  1336. $except
  1337. $order", $params);
  1338. } else {
  1339. // Search in courses.
  1340. // Getting the context IDs or each course.
  1341. $contextids = array();
  1342. foreach ($courseids as $courseid) {
  1343. $context = context_course::instance($courseid);
  1344. $contextids = array_merge($contextids, $context->get_parent_context_ids(true));
  1345. }
  1346. list($contextwhere, $contextparams) = $DB->get_in_or_equal(array_unique($contextids), SQL_PARAMS_NAMED, 'context');
  1347. $params = array_merge($params, $contextparams);
  1348. // Everyone who has a role assignment in this course or higher.
  1349. // TODO: add enabled enrolment join here (skodak)
  1350. $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mc.blocked
  1351. FROM {user} u
  1352. JOIN {role_assignments} ra ON ra.userid = u.id
  1353. LEFT JOIN {message_contacts} mc
  1354. ON mc.contactid = u.id AND mc.userid = :userid
  1355. WHERE u.deleted = '0' AND u.confirmed = '1'
  1356. AND (".$DB->sql_like($fullname, ':query', false).")
  1357. AND ra.contextid $contextwhere
  1358. $except
  1359. $order", $params);
  1360. return $users;
  1361. }
  1362. }
  1363. /**
  1364. * Search a user's messages
  1365. *
  1366. * Returns a list of posts found using an array of search terms
  1367. * eg word +word -word
  1368. *
  1369. * @param array $searchterms an array of search terms (strings)
  1370. * @param bool $fromme include messages from the user?
  1371. * @param bool $tome include messages to the user?
  1372. * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
  1373. * @param int $userid the user ID of the current user
  1374. * @return mixed An array of messages or false if no matching messages were found
  1375. */
  1376. function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
  1377. global $CFG, $USER, $DB;
  1378. // If user is searching all messages check they are allowed to before doing anything else.
  1379. if ($courseid == SITEID && !has_capability('moodle/site:readallmessages', context_system::instance())) {
  1380. print_error('accessdenied','admin');
  1381. }
  1382. // If no userid sent then assume current user.
  1383. if ($userid == 0) $userid = $USER->id;
  1384. // Some differences in SQL syntax.
  1385. if ($DB->sql_regex_supported()) {
  1386. $REGEXP = $DB->sql_regex(true);
  1387. $NOTREGEXP = $DB->sql_regex(false);
  1388. }
  1389. $searchcond = array();
  1390. $params = array();
  1391. $i = 0;
  1392. // Preprocess search terms to check whether we have at least 1 eligible search term.
  1393. // If we do we can drop words around it like 'a'.
  1394. $dropshortwords = false;
  1395. foreach ($searchterms as $searchterm) {
  1396. if (strlen($searchterm) >= 2) {
  1397. $dropshortwords = true;
  1398. }
  1399. }
  1400. foreach ($searchterms as $searchterm) {
  1401. $i++;
  1402. $NOT = false; // Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle.
  1403. if ($dropshortwords && strlen($searchterm) < 2) {
  1404. continue;
  1405. }
  1406. // Under Oracle and MSSQL, trim the + and - operators and perform simpler LIKE search.
  1407. if (!$DB->sql_regex_supported()) {
  1408. if (substr($searchterm, 0, 1) == '-') {
  1409. $NOT = true;
  1410. }
  1411. $searchterm = trim($searchterm, '+-');
  1412. }
  1413. if (substr($searchterm,0,1) == "+") {
  1414. $searchterm = substr($searchterm,1);
  1415. $searchterm = preg_quote($searchterm, '|');
  1416. $searchcond[] = "m.fullmessage $REGEXP :ss$i";
  1417. $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
  1418. } else if (substr($searchterm,0,1) == "-") {
  1419. $searchterm = substr($searchterm,1);
  1420. $searchterm = preg_quote($searchterm, '|');
  1421. $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
  1422. $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
  1423. } else {
  1424. $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
  1425. $params['ss'.$i] = "%$searchterm%";
  1426. }
  1427. }
  1428. if (empty($searchcond)) {
  1429. $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
  1430. $params['ss1'] = "%";
  1431. } else {
  1432. $searchcond = implode(" AND ", $searchcond);
  1433. }
  1434. // There are several possibilities
  1435. // 1. courseid = SITEID : The admin is searching messages by all users
  1436. // 2. courseid = ?? : A teacher is searching messages by users in
  1437. // one of their courses - currently disabled
  1438. // 3. courseid = none : User is searching their own messages;
  1439. // a. Messages from user
  1440. // b. Messages to user
  1441. // c. Messages to and from user
  1442. if ($courseid == SITEID) { // Admin is searching all messages.
  1443. $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
  1444. FROM {message_read} m
  1445. WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
  1446. $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
  1447. FROM {message} m
  1448. WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
  1449. } else if ($courseid !== 'none') {
  1450. // This has not been implemented due to security concerns.
  1451. $m_read = array();
  1452. $m_unread = array();
  1453. } else {
  1454. if ($fromme and $tome) {
  1455. $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
  1456. $params['userid1'] = $userid;
  1457. $params['userid2'] = $userid;
  1458. } else if ($fromme) {
  1459. $searchcond .= " AND m.useridfrom=:userid";
  1460. $params['userid'] = $userid;
  1461. } else if ($tome) {
  1462. $searchcond .= " AND m.useridto=:userid";
  1463. $params['userid'] = $userid;
  1464. }
  1465. $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
  1466. FROM {message_read} m
  1467. WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
  1468. $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
  1469. FROM {message} m
  1470. WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
  1471. }
  1472. /// The keys may be duplicated in $m_read and $m_unread so we can't
  1473. /// do a simple concatenation
  1474. $messages = array();
  1475. foreach ($m_read as $m) {
  1476. $messages[] = $m;
  1477. }
  1478. foreach ($m_unread as $m) {
  1479. $messages[] = $m;
  1480. }
  1481. return (empty($messages)) ? false : $messages;
  1482. }
  1483. /**
  1484. * Given a message object that we already know has a long message
  1485. * this function truncates the message nicely to the first
  1486. * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
  1487. *
  1488. * @param string $message the message
  1489. * @param int $minlength the minimum length to trim the message to
  1490. * @return string the shortened message
  1491. */
  1492. function message_shorten_message($message, $minlength = 0) {
  1493. $i = 0;
  1494. $tag = false;
  1495. $length = strlen($message);
  1496. $count = 0;
  1497. $stopzone = false;
  1498. $truncate = 0;
  1499. if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
  1500. for ($i=0; $i<$length; $i++) {
  1501. $char = $message[$i];
  1502. switch ($char) {
  1503. case "<":
  1504. $tag = true;
  1505. break;
  1506. case ">":
  1507. $tag = false;
  1508. break;
  1509. default:
  1510. if (!$tag) {
  1511. if ($stopzone) {
  1512. if ($char == '.' or $char == ' ') {
  1513. $truncate = $i+1;
  1514. break 2;
  1515. }
  1516. }
  1517. $count++;
  1518. }
  1519. break;
  1520. }
  1521. if (!$stopzone) {
  1522. if ($count > $minlength) {
  1523. $stopzone = true;
  1524. }
  1525. }
  1526. }
  1527. if (!$truncate) {
  1528. $truncate = $i;
  1529. }
  1530. return substr($message, 0, $truncate);
  1531. }
  1532. /**
  1533. * Given a string and an array of keywords, this function looks
  1534. * for the first keyword in the string, and then chops out a
  1535. * small section from the text that shows that word in context.
  1536. *
  1537. * @param string $message the text to search
  1538. * @param array $keywords array of keywords to find
  1539. */
  1540. function message_get_fragment($message, $keywords) {
  1541. $fullsize = 160;
  1542. $halfsize = (int)($fullsize/2);
  1543. $message = strip_tags($message);
  1544. foreach ($keywords as $keyword) { // Just get the first one
  1545. if ($keyword !== '') {
  1546. break;
  1547. }
  1548. }
  1549. if (empty($keyword)) { // None found, so just return start of message
  1550. return message_shorten_message($message, 30);
  1551. }
  1552. $leadin = $leadout = '';
  1553. /// Find the start of the fragment
  1554. $start = 0;
  1555. $length = strlen($message);
  1556. $pos = strpos($message, $keyword);
  1557. if ($pos > $halfsize) {
  1558. $start = $pos - $halfsize;
  1559. $leadin = '...';
  1560. }
  1561. /// Find the end of the fragment
  1562. $end = $start + $fullsize;
  1563. if ($end > $length) {
  1564. $end = $length;
  1565. } else {
  1566. $leadout = '...';
  1567. }
  1568. /// Pull out the fragment and format it
  1569. $fragment = substr($message, $start, $end - $start);
  1570. $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
  1571. return $fragment;
  1572. }
  1573. /**
  1574. * Retrieve the messages between two users
  1575. *
  1576. * @param object $user1 the current user
  1577. * @param object $user2 the other user
  1578. * @param int $limitnum the maximum number of messages to retrieve
  1579. * @param bool $viewingnewmessages are we currently viewing new messages?
  1580. */
  1581. function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
  1582. global $DB, $CFG;
  1583. $messages = array();
  1584. //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
  1585. //desc to get the last $limitnum messages then flip the order in php
  1586. $sort = 'asc';
  1587. if ($limitnum>0) {
  1588. $sort = 'desc';
  1589. }
  1590. $notificationswhere = null;
  1591. //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
  1592. if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) {
  1593. $notificationswhere = 'AND notification=0';
  1594. }
  1595. //prevent notifications of your own actions appearing in your own message history
  1596. $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
  1597. if ($messages_read = $DB->get_records_select('message_read', "((useridto = ? AND useridfrom = ?) OR
  1598. (useridto = ? AND useridfrom = ?)) $notificationswhere $ownnotificationwhere",
  1599. array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
  1600. "timecreated $sort", '*', 0, $limitnum)) {
  1601. foreach ($messages_read as $message) {
  1602. $messages[] = $message;
  1603. }
  1604. }
  1605. if ($messages_new = $DB->get_records_select('message', "((useridto = ? AND useridfrom = ?) OR
  1606. (useridto = ? AND useridfrom = ?)) $ownnotificationwhere",
  1607. array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
  1608. "timecreated $sort", '*', 0, $limitnum)) {
  1609. foreach ($messages_new as $message) {
  1610. $messages[] = $message;
  1611. }
  1612. }
  1613. $result = core_collator::asort_objects_by_property($messages, 'timecreated', core_collator::SORT_NUMERIC);
  1614. //if we only want the last $limitnum messages
  1615. $messagecount = count($messages);
  1616. if ($limitnum > 0 && $messagecount > $limitnum) {
  1617. $messages = array_slice($messages, $messagecount - $limitnum, $limitnum, true);
  1618. }
  1619. return $messages;
  1620. }
  1621. /**
  1622. * Print the message history between two users
  1623. *
  1624. * @param object $user1 the current user
  1625. * @param object $user2 the other user
  1626. * @param string $search search terms to highlight
  1627. * @param int $messagelimit maximum number of messages to return
  1628. * @param string $messagehistorylink the html for the message history link or false
  1629. * @param bool $viewingnewmessages are we currently viewing new messages?
  1630. */
  1631. function message_print_message_history($user1, $user2 ,$search = '', $messagelimit = 0, $messagehistorylink = false, $viewingnewmessages = false, $showactionlinks = true) {
  1632. global $CFG, $OUTPUT;
  1633. echo $OUTPUT->box_start('center');
  1634. echo html_writer::start_tag('table', array('cellpadding' => '10', 'class' => 'message_user_pictures'));
  1635. echo html_writer::start_tag('tr');
  1636. echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user1'));
  1637. echo $OUTPUT->user_picture($user1, array('size' => 100, 'courseid' => SITEID));
  1638. echo html_writer::tag('div', fullname($user1), array('class' => 'heading'));
  1639. echo html_writer::end_tag('td');
  1640. echo html_writer::start_tag('td', array('align' => 'center'));
  1641. echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('i/twoway'), 'alt' => ''));
  1642. echo html_writer::end_tag('td');
  1643. echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user2'));
  1644. // Show user picture with link is real user else without link.
  1645. if (core_user::is_real_user($user2->id)) {
  1646. echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID));
  1647. } else {
  1648. echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID, 'link' => false));
  1649. }
  1650. echo html_writer::tag('div', fullname($user2), array('class' => 'heading'));
  1651. if ($showactionlinks && isset($user2->iscontact) && isset($user2->isblocked)) {
  1652. $script = null;
  1653. $text = true;
  1654. $icon = false;
  1655. $strcontact = message_get_contact_add_remove_link($user2->iscontact, $user2->isblocked, $user2, $script, $text, $icon);
  1656. $strblock = message_get_contact_block_link($user2->iscontact, $user2->isblocked, $user2, $script, $text, $icon);
  1657. $useractionlinks = $strcontact.'&nbsp;|'.$strblock;
  1658. echo html_writer::tag('div', $useractionlinks, array('class' => 'useractionlinks'));
  1659. }
  1660. echo html_writer::end_tag('td');
  1661. echo html_writer::end_tag('tr');
  1662. echo html_writer::end_tag('table');
  1663. echo $OUTPUT->box_end();
  1664. if (!empty($messagehistorylink)) {
  1665. echo $messagehistorylink;
  1666. }
  1667. /// Get all the messages and print them
  1668. if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
  1669. $tablecontents = '';
  1670. $current = new stdClass();
  1671. $current->mday = '';
  1672. $current->month = '';
  1673. $current->year = '';
  1674. $messagedate = get_string('strftimetime');
  1675. $blockdate = get_string('strftimedaydate');
  1676. foreach ($messages as $message) {
  1677. if ($message->notification) {
  1678. $notificationclass = ' notification';
  1679. } else {
  1680. $notificationclass = null;
  1681. }
  1682. $date = usergetdate($message->timecreated);
  1683. if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
  1684. $current->mday = $date['mday'];
  1685. $current->month = $date['month'];
  1686. $current->year = $date['year'];
  1687. $datestring = html_writer::empty_tag('a', array('name' => $date['year'].$date['mon'].$date['mday']));
  1688. $tablecontents .= html_writer::tag('div', $datestring, array('class' => 'mdl-align heading'));
  1689. $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'mdl-align');
  1690. }
  1691. $formatted_message = $side = null;
  1692. if ($message->useridfrom == $user1->id) {
  1693. $formatted_message = message_format_message($message, $messagedate, $search, 'me');
  1694. $side = 'left';
  1695. } else {
  1696. $formatted_message = message_format_message($message, $messagedate, $search, 'other');
  1697. $side = 'right';
  1698. }
  1699. $tablecontents .= html_writer::tag('div', $formatted_message, array('class' => "mdl-left $side $notificationclass"));
  1700. }
  1701. echo html_writer::nonempty_tag('div', $tablecontents, array('class' => 'mdl-left messagehistory'));
  1702. } else {
  1703. echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class' => 'mdl-align messagehistory'));
  1704. }
  1705. }
  1706. /**
  1707. * Format a message for display in the message history
  1708. *
  1709. * @param object $message the message object
  1710. * @param string $format optional date format
  1711. * @param string $keywords keywords to highlight
  1712. * @param string $class CSS class to apply to the div around the message
  1713. * @return string the formatted message
  1714. */
  1715. function message_format_message($message, $format='', $keywords='', $class='other') {
  1716. static $dateformat;
  1717. //if we haven't previously set the date format or they've supplied a new one
  1718. if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
  1719. if ($format) {
  1720. $dateformat = $format;
  1721. } else {
  1722. $dateformat = get_string('strftimedatetimeshort');
  1723. }
  1724. }
  1725. $time = userdate($message->timecreated, $dateformat);
  1726. $messagetext = message_format_message_text($message, false);
  1727. if ($keywords) {
  1728. $messagetext = highlight($keywords, $messagetext);
  1729. }
  1730. $messagetext .= message_format_contexturl($message);
  1731. $messagetext = clean_text($messagetext, FORMAT_HTML);
  1732. return <<<TEMPLATE
  1733. <div class='message $class'>
  1734. <a name="m{$message->id}"></a>
  1735. <span class="message-meta"><span class="time">$time</span></span>: <span class="text">$messagetext</span>
  1736. </div>
  1737. TEMPLATE;
  1738. }
  1739. /**
  1740. * Format a the context url and context url name of a message for display
  1741. *
  1742. * @param object $message the message object
  1743. * @return string the formatted string
  1744. */
  1745. function message_format_contexturl($message) {
  1746. $s = null;
  1747. if (!empty($message->contexturl)) {
  1748. $displaytext = null;
  1749. if (!empty($message->contexturlname)) {
  1750. $displaytext= $message->contexturlname;
  1751. } else {
  1752. $displaytext= $message->contexturl;
  1753. }
  1754. $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
  1755. $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
  1756. $s .= html_writer::end_tag('div');
  1757. }
  1758. return $s;
  1759. }
  1760. /**
  1761. * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
  1762. *
  1763. * @param object $userfrom the message sender
  1764. * @param object $userto the message recipient
  1765. * @param string $message the message
  1766. * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
  1767. * @return int|false the ID of the new message or false
  1768. */
  1769. function message_post_message($userfrom, $userto, $message, $format) {
  1770. global $SITE, $CFG, $USER;
  1771. $eventdata = new stdClass();
  1772. $eventdata->component = 'moodle';
  1773. $eventdata->name = 'instantmessage';
  1774. $eventdata->userfrom = $userfrom;
  1775. $eventdata->userto = $userto;
  1776. //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
  1777. $eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
  1778. if ($format == FORMAT_HTML) {
  1779. $eventdata->fullmessagehtml = $message;
  1780. //some message processors may revert to sending plain text even if html is supplied
  1781. //so we keep both plain and html versions if we're intending to send html
  1782. $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
  1783. } else {
  1784. $eventdata->fullmessage = $message;
  1785. $eventdata->fullmessagehtml = '';
  1786. }
  1787. $eventdata->fullmessageformat = $format;
  1788. $eventdata->smallmessage = $message;//store the message unfiltered. Clean up on output.
  1789. $s = new stdClass();
  1790. $s->sitename = format_string($SITE->shortname, true, array('context' => context_course::instance(SITEID)));
  1791. $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id;
  1792. $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
  1793. if (!empty($eventdata->fullmessage)) {
  1794. $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
  1795. }
  1796. if (!empty($eventdata->fullmessagehtml)) {
  1797. $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
  1798. }
  1799. $eventdata->timecreated = time();
  1800. return message_send($eventdata);
  1801. }
  1802. /**
  1803. * Print a row of contactlist displaying user picture, messages waiting and
  1804. * block links etc
  1805. *
  1806. * @param object $contact contact object containing all fields required for $OUTPUT->user_picture()
  1807. * @param bool $incontactlist is the user a contact of ours?
  1808. * @param bool $isblocked is the user blocked?
  1809. * @param string $selectcontacturl the url to send the user to when a contact's name is clicked
  1810. * @param bool $showactionlinks display action links next to the other users (add contact, block user etc)
  1811. * @param object $selecteduser the user the current user is viewing (if any). They will be highlighted.
  1812. * @return void
  1813. */
  1814. function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true, $selecteduser=null) {
  1815. global $OUTPUT, $USER, $COURSE;
  1816. $fullname = fullname($contact);
  1817. $fullnamelink = $fullname;
  1818. $linkclass = '';
  1819. if (!empty($selecteduser) && $contact->id == $selecteduser->id) {
  1820. $linkclass = 'messageselecteduser';
  1821. }
  1822. // Are there any unread messages for this contact?
  1823. if ($contact->messagecount > 0 ){
  1824. $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
  1825. }
  1826. $strcontact = $strblock = $strhistory = null;
  1827. if ($showactionlinks) {
  1828. // Show block and delete links if user is real user.
  1829. if (core_user::is_real_user($contact->id)) {
  1830. $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
  1831. $strblock = message_get_contact_block_link($incontactlist, $isblocked, $contact);
  1832. }
  1833. $strhistory = message_history_link($USER->id, $contact->id, true, '', '', 'icon');
  1834. }
  1835. echo html_writer::start_tag('tr');
  1836. echo html_writer::start_tag('td', array('class' => 'pix'));
  1837. echo $OUTPUT->user_picture($contact, array('size' => 20, 'courseid' => $COURSE->id));
  1838. echo html_writer::end_tag('td');
  1839. echo html_writer::start_tag('td', array('class' => 'contact'));
  1840. $popupoptions = array(
  1841. 'height' => MESSAGE_DISCUSSION_HEIGHT,
  1842. 'width' => MESSAGE_DISCUSSION_WIDTH,
  1843. 'menubar' => false,
  1844. 'location' => false,
  1845. 'status' => true,
  1846. 'scrollbars' => true,
  1847. 'resizable' => true);
  1848. $link = $action = null;
  1849. if (!empty($selectcontacturl)) {
  1850. $link = new moodle_url($selectcontacturl.'&user2='.$contact->id);
  1851. } else {
  1852. //can $selectcontacturl be removed and maybe the be removed and hardcoded?
  1853. $link = new moodle_url("/message/index.php?id=$contact->id");
  1854. $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
  1855. }
  1856. echo $OUTPUT->action_link($link, $fullnamelink, $action, array('class' => $linkclass,'title' => get_string('sendmessageto', 'message', $fullname)));
  1857. echo html_writer::end_tag('td');
  1858. echo html_writer::tag('td', '&nbsp;'.$strcontact.$strblock.'&nbsp;'.$strhistory, array('class' => 'link'));
  1859. echo html_writer::end_tag('tr');
  1860. }
  1861. /**
  1862. * Constructs the add/remove contact link to display next to other users
  1863. *
  1864. * @param bool $incontactlist is the user a contact
  1865. * @param bool $isblocked is the user blocked
  1866. * @param stdClass $contact contact object
  1867. * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
  1868. * @param bool $text include text next to the icons?
  1869. * @param bool $icon include a graphical icon?
  1870. * @return string
  1871. */
  1872. function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
  1873. $strcontact = '';
  1874. if($incontactlist){
  1875. $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
  1876. } else if ($isblocked) {
  1877. $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
  1878. } else{
  1879. $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
  1880. }
  1881. return $strcontact;
  1882. }
  1883. /**
  1884. * Constructs the block contact link to display next to other users
  1885. *
  1886. * @param bool $incontactlist is the user a contact?
  1887. * @param bool $isblocked is the user blocked?
  1888. * @param stdClass $contact contact object
  1889. * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
  1890. * @param bool $text include text next to the icons?
  1891. * @param bool $icon include a graphical icon?
  1892. * @return string
  1893. */
  1894. function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
  1895. $strblock = '';
  1896. //commented out to allow the user to block a contact without having to remove them first
  1897. /*if ($incontactlist) {
  1898. //$strblock = '';
  1899. } else*/
  1900. if ($isblocked) {
  1901. $strblock = '&nbsp;'.message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
  1902. } else{
  1903. $strblock = '&nbsp;'.message_contact_link($contact->id, 'block', true, $script, $text, $icon);
  1904. }
  1905. return $strblock;
  1906. }
  1907. /**
  1908. * Moves messages from a particular user from the message table (unread messages) to message_read
  1909. * This is typically only used when a user is deleted
  1910. *
  1911. * @param object $userid User id
  1912. * @return boolean success
  1913. */
  1914. function message_move_userfrom_unread2read($userid) {
  1915. global $DB;
  1916. // move all unread messages from message table to message_read
  1917. if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
  1918. foreach ($messages as $message) {
  1919. message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
  1920. }
  1921. }
  1922. return true;
  1923. }
  1924. /**
  1925. * marks ALL messages being sent from $fromuserid to $touserid as read
  1926. *
  1927. * @param int $touserid the id of the message recipient
  1928. * @param int $fromuserid the id of the message sender
  1929. * @return void
  1930. */
  1931. function message_mark_messages_read($touserid, $fromuserid){
  1932. global $DB;
  1933. $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
  1934. $messages = $DB->get_recordset_sql($sql, array('useridto' => $touserid,'useridfrom' => $fromuserid));
  1935. foreach ($messages as $message) {
  1936. message_mark_message_read($message, time());
  1937. }
  1938. $messages->close();
  1939. }
  1940. /**
  1941. * Mark a single message as read
  1942. *
  1943. * @param stdClass $message An object with an object property ie $message->id which is an id in the message table
  1944. * @param int $timeread the timestamp for when the message should be marked read. Usually time().
  1945. * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
  1946. * @return int the ID of the message in the message_read table
  1947. */
  1948. function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
  1949. global $DB;
  1950. $message->timeread = $timeread;
  1951. $messageid = $message->id;
  1952. unset($message->id);//unset because it will get a new id on insert into message_read
  1953. //If any processors have pending actions abort them
  1954. if (!$messageworkingempty) {
  1955. $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
  1956. }
  1957. $messagereadid = $DB->insert_record('message_read', $message);
  1958. $DB->delete_records('message', array('id' => $messageid));
  1959. return $messagereadid;
  1960. }
  1961. /**
  1962. * A helper function that prints a formatted heading
  1963. *
  1964. * @param string $title the heading to display
  1965. * @param int $colspan
  1966. * @return void
  1967. */
  1968. function message_print_heading($title, $colspan=3) {
  1969. echo html_writer::start_tag('tr');
  1970. echo html_writer::tag('td', $title, array('colspan' => $colspan, 'class' => 'heading'));
  1971. echo html_writer::end_tag('tr');
  1972. }
  1973. /**
  1974. * Get all message processors, validate corresponding plugin existance and
  1975. * system configuration
  1976. *
  1977. * @param bool $ready only return ready-to-use processors
  1978. * @param bool $reset Reset list of message processors (used in unit tests)
  1979. * @return mixed $processors array of objects containing information on message processors
  1980. */
  1981. function get_message_processors($ready = false, $reset = false) {
  1982. global $DB, $CFG;
  1983. static $processors;
  1984. if ($reset) {
  1985. $processors = array();
  1986. }
  1987. if (empty($processors)) {
  1988. // Get all processors, ensure the name column is the first so it will be the array key
  1989. $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
  1990. foreach ($processors as &$processor){
  1991. $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
  1992. if (is_readable($processorfile)) {
  1993. include_once($processorfile);
  1994. $processclass = 'message_output_' . $processor->name;
  1995. if (class_exists($processclass)) {
  1996. $pclass = new $processclass();
  1997. $processor->object = $pclass;
  1998. $processor->configured = 0;
  1999. if ($pclass->is_system_configured()) {
  2000. $processor->configured = 1;
  2001. }
  2002. $processor->hassettings = 0;
  2003. if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
  2004. $processor->hassettings = 1;
  2005. }
  2006. $processor->available = 1;
  2007. } else {
  2008. print_error('errorcallingprocessor', 'message');
  2009. }
  2010. } else {
  2011. $processor->available = 0;
  2012. }
  2013. }
  2014. }
  2015. if ($ready) {
  2016. // Filter out enabled and system_configured processors
  2017. $readyprocessors = $processors;
  2018. foreach ($readyprocessors as $readyprocessor) {
  2019. if (!($readyprocessor->enabled && $readyprocessor->configured)) {
  2020. unset($readyprocessors[$readyprocessor->name]);
  2021. }
  2022. }
  2023. return $readyprocessors;
  2024. }
  2025. return $processors;
  2026. }
  2027. /**
  2028. * Get all message providers, validate their plugin existance and
  2029. * system configuration
  2030. *
  2031. * @return mixed $processors array of objects containing information on message processors
  2032. */
  2033. function get_message_providers() {
  2034. global $CFG, $DB;
  2035. $pluginman = core_plugin_manager::instance();
  2036. $providers = $DB->get_records('message_providers', null, 'name');
  2037. // Remove all the providers whose plugins are disabled or don't exist
  2038. foreach ($providers as $providerid => $provider) {
  2039. $plugin = $pluginman->get_plugin_info($provider->component);
  2040. if ($plugin) {
  2041. if ($plugin->get_status() === core_plugin_manager::PLUGIN_STATUS_MISSING) {
  2042. unset($providers[$providerid]); // Plugins does not exist
  2043. continue;
  2044. }
  2045. if ($plugin->is_enabled() === false) {
  2046. unset($providers[$providerid]); // Plugin disabled
  2047. continue;
  2048. }
  2049. }
  2050. }
  2051. return $providers;
  2052. }
  2053. /**
  2054. * Get an instance of the message_output class for one of the output plugins.
  2055. * @param string $type the message output type. E.g. 'email' or 'jabber'.
  2056. * @return message_output message_output the requested class.
  2057. */
  2058. function get_message_processor($type) {
  2059. global $CFG;
  2060. // Note, we cannot use the get_message_processors function here, becaues this
  2061. // code is called during install after installing each messaging plugin, and
  2062. // get_message_processors caches the list of installed plugins.
  2063. $processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php";
  2064. if (!is_readable($processorfile)) {
  2065. throw new coding_exception('Unknown message processor type ' . $type);
  2066. }
  2067. include_once($processorfile);
  2068. $processclass = 'message_output_' . $type;
  2069. if (!class_exists($processclass)) {
  2070. throw new coding_exception('Message processor ' . $type .
  2071. ' does not define the right class');
  2072. }
  2073. return new $processclass();
  2074. }
  2075. /**
  2076. * Get messaging outputs default (site) preferences
  2077. *
  2078. * @return object $processors object containing information on message processors
  2079. */
  2080. function get_message_output_default_preferences() {
  2081. return get_config('message');
  2082. }
  2083. /**
  2084. * Translate message default settings from binary value to the array of string
  2085. * representing the settings to be stored. Also validate the provided value and
  2086. * use default if it is malformed.
  2087. *
  2088. * @param int $plugindefault Default setting suggested by plugin
  2089. * @param string $processorname The name of processor
  2090. * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
  2091. */
  2092. function translate_message_default_setting($plugindefault, $processorname) {
  2093. // Preset translation arrays
  2094. $permittedvalues = array(
  2095. 0x04 => 'disallowed',
  2096. 0x08 => 'permitted',
  2097. 0x0c => 'forced',
  2098. );
  2099. $loggedinstatusvalues = array(
  2100. 0x00 => null, // use null if loggedin/loggedoff is not defined
  2101. 0x01 => 'loggedin',
  2102. 0x02 => 'loggedoff',
  2103. );
  2104. // define the default setting
  2105. $processor = get_message_processor($processorname);
  2106. $default = $processor->get_default_messaging_settings();
  2107. // Validate the value. It should not exceed the maximum size
  2108. if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
  2109. debugging(get_string('errortranslatingdefault', 'message'));
  2110. $plugindefault = $default;
  2111. }
  2112. // Use plugin default setting of 'permitted' is 0
  2113. if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
  2114. $plugindefault = $default;
  2115. }
  2116. $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK];
  2117. $loggedin = $loggedoff = null;
  2118. if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) {
  2119. $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN];
  2120. $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF];
  2121. }
  2122. return array($permitted, $loggedin, $loggedoff);
  2123. }
  2124. /**
  2125. * Return a list of page types
  2126. * @param string $pagetype current page type
  2127. * @param stdClass $parentcontext Block's parent context
  2128. * @param stdClass $currentcontext Current context of block
  2129. */
  2130. function message_page_type_list($pagetype, $parentcontext, $currentcontext) {
  2131. return array('messages-*'=>get_string('page-message-x', 'message'));
  2132. }
  2133. /**
  2134. * Is $USER one of the supplied users?
  2135. *
  2136. * $user2 will be null if viewing a user's recent conversations
  2137. *
  2138. * @param stdClass the first user
  2139. * @param stdClass the second user or null
  2140. * @return bool True if the current user is one of either $user1 or $user2
  2141. */
  2142. function message_current_user_is_involved($user1, $user2) {
  2143. global $USER;
  2144. if (empty($user1->id) || (!empty($user2) && empty($user2->id))) {
  2145. throw new coding_exception('Invalid user object detected. Missing id.');
  2146. }
  2147. if ($user1->id != $USER->id && (empty($user2) || $user2->id != $USER->id)) {
  2148. return false;
  2149. }
  2150. return true;
  2151. }