Search moodle.org's
Developer Documentation


  • Bug fixes for general core bugs in 2.8.x ended 9 November 2015 (12 months).
  • Bug fixes for security issues in 2.8.x ended 9 May 2016 (18 months).
  • minimum PHP 5.4.4 (always use latest PHP 5.4.x or 5.5.x on Windows - http://windows.php.net/download/), PHP 7 is NOT supported
  • /message/ -> lib.php (source)

    Differences Between: [Versions 28 and 29] [Versions 28 and 30] [Versions 28 and 31] [Versions 28 and 32] [Versions 28 and 33] [Versions 28 and 34] [Versions 28 and 35] [Versions 28 and 36] [Versions 28 and 37]

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

    Search This Site: