[ Index ]

PHP Cross Reference of moodle-2.8

title

Body

[close]

/message/ -> lib.php (source)

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


Generated: Fri Nov 28 20:29:05 2014 Cross-referenced by PHPXref 0.7.1