Search moodle.org's
Developer Documentation

   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  /**
  19   * External message API
  20   *
  21   * @package    core_message
  22   * @category   external
  23   * @copyright  2011 Jerome Mouneyrac
  24   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  25   */
  26  
  27  require_once("$CFG->libdir/externallib.php");
  28  
  29  /**
  30   * Message external functions
  31   *
  32   * @package    core_message
  33   * @category   external
  34   * @copyright  2011 Jerome Mouneyrac
  35   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  36   * @since Moodle 2.2
  37   */
  38  class core_message_external extends external_api {
  39  
  40      /**
  41       * Returns description of method parameters
  42       *
  43       * @return external_function_parameters
  44       * @since Moodle 2.2
  45       */
  46      public static function send_instant_messages_parameters() {
  47          return new external_function_parameters(
  48              array(
  49                  'messages' => new external_multiple_structure(
  50                      new external_single_structure(
  51                          array(
  52                              'touserid' => new external_value(PARAM_INT, 'id of the user to send the private message'),
  53                              'text' => new external_value(PARAM_RAW, 'the text of the message'),
  54                              'textformat' => new external_format_value('text', VALUE_DEFAULT),
  55                              'clientmsgid' => new external_value(PARAM_ALPHANUMEXT, 'your own client id for the message. If this id is provided, the fail message id will be returned to you', VALUE_OPTIONAL),
  56                          )
  57                      )
  58                  )
  59              )
  60          );
  61      }
  62  
  63      /**
  64       * Send private messages from the current USER to other users
  65       *
  66       * @param array $messages An array of message to send.
  67       * @return array
  68       * @since Moodle 2.2
  69       */
  70      public static function send_instant_messages($messages = array()) {
  71          global $CFG, $USER, $DB;
  72          require_once($CFG->dirroot . "/message/lib.php");
  73  
  74          // Check if messaging is enabled.
  75          if (!$CFG->messaging) {
  76              throw new moodle_exception('disabled', 'message');
  77          }
  78  
  79          // Ensure the current user is allowed to run this function
  80          $context = context_system::instance();
  81          self::validate_context($context);
  82          require_capability('moodle/site:sendmessage', $context);
  83  
  84          $params = self::validate_parameters(self::send_instant_messages_parameters(), array('messages' => $messages));
  85  
  86          //retrieve all tousers of the messages
  87          $receivers = array();
  88          foreach($params['messages'] as $message) {
  89              $receivers[] = $message['touserid'];
  90          }
  91          list($sqluserids, $sqlparams) = $DB->get_in_or_equal($receivers, SQL_PARAMS_NAMED, 'userid_');
  92          $tousers = $DB->get_records_select("user", "id " . $sqluserids . " AND deleted = 0", $sqlparams);
  93          $blocklist   = array();
  94          $contactlist = array();
  95          $sqlparams['contactid'] = $USER->id;
  96          $rs = $DB->get_recordset_sql("SELECT *
  97                                          FROM {message_contacts}
  98                                         WHERE userid $sqluserids
  99                                               AND contactid = :contactid", $sqlparams);
 100          foreach ($rs as $record) {
 101              if ($record->blocked) {
 102                  // $record->userid is blocking current user
 103                  $blocklist[$record->userid] = true;
 104              } else {
 105                  // $record->userid have current user as contact
 106                  $contactlist[$record->userid] = true;
 107              }
 108          }
 109          $rs->close();
 110  
 111          $canreadallmessages = has_capability('moodle/site:readallmessages', $context);
 112  
 113          $resultmessages = array();
 114          foreach ($params['messages'] as $message) {
 115              $resultmsg = array(); //the infos about the success of the operation
 116  
 117              //we are going to do some checking
 118              //code should match /messages/index.php checks
 119              $success = true;
 120  
 121              //check the user exists
 122              if (empty($tousers[$message['touserid']])) {
 123                  $success = false;
 124                  $errormessage = get_string('touserdoesntexist', 'message', $message['touserid']);
 125              }
 126  
 127              //check that the touser is not blocking the current user
 128              if ($success and !empty($blocklist[$message['touserid']]) and !$canreadallmessages) {
 129                  $success = false;
 130                  $errormessage = get_string('userisblockingyou', 'message');
 131              }
 132  
 133              // Check if the user is a contact
 134              //TODO MDL-31118 performance improvement - edit the function so we can pass an array instead userid
 135              $blocknoncontacts = get_user_preferences('message_blocknoncontacts', NULL, $message['touserid']);
 136              // message_blocknoncontacts option is on and current user is not in contact list
 137              if ($success && empty($contactlist[$message['touserid']]) && !empty($blocknoncontacts)) {
 138                  // The user isn't a contact and they have selected to block non contacts so this message won't be sent.
 139                  $success = false;
 140                  $errormessage = get_string('userisblockingyounoncontact', 'message');
 141              }
 142  
 143              //now we can send the message (at least try)
 144              if ($success) {
 145                  //TODO MDL-31118 performance improvement - edit the function so we can pass an array instead one touser object
 146                  $success = message_post_message($USER, $tousers[$message['touserid']],
 147                          $message['text'], external_validate_format($message['textformat']));
 148              }
 149  
 150              //build the resultmsg
 151              if (isset($message['clientmsgid'])) {
 152                  $resultmsg['clientmsgid'] = $message['clientmsgid'];
 153              }
 154              if ($success) {
 155                  $resultmsg['msgid'] = $success;
 156              } else {
 157                  // WARNINGS: for backward compatibility we return this errormessage.
 158                  //          We should have thrown exceptions as these errors prevent results to be returned.
 159                  // See http://docs.moodle.org/dev/Errors_handling_in_web_services#When_to_send_a_warning_on_the_server_side .
 160                  $resultmsg['msgid'] = -1;
 161                  $resultmsg['errormessage'] = $errormessage;
 162              }
 163  
 164              $resultmessages[] = $resultmsg;
 165          }
 166  
 167          return $resultmessages;
 168      }
 169  
 170      /**
 171       * Returns description of method result value
 172       *
 173       * @return external_description
 174       * @since Moodle 2.2
 175       */
 176      public static function send_instant_messages_returns() {
 177          return new external_multiple_structure(
 178              new external_single_structure(
 179                  array(
 180                      'msgid' => new external_value(PARAM_INT, 'test this to know if it succeeds:  id of the created message if it succeeded, -1 when failed'),
 181                      'clientmsgid' => new external_value(PARAM_ALPHANUMEXT, 'your own id for the message', VALUE_OPTIONAL),
 182                      'errormessage' => new external_value(PARAM_TEXT, 'error message - if it failed', VALUE_OPTIONAL)
 183                  )
 184              )
 185          );
 186      }
 187  
 188      /**
 189       * Create contacts parameters description.
 190       *
 191       * @return external_function_parameters
 192       * @since Moodle 2.5
 193       */
 194      public static function create_contacts_parameters() {
 195          return new external_function_parameters(
 196              array(
 197                  'userids' => new external_multiple_structure(
 198                      new external_value(PARAM_INT, 'User ID'),
 199                      'List of user IDs'
 200                  )
 201              )
 202          );
 203      }
 204  
 205      /**
 206       * Create contacts.
 207       *
 208       * @param array $userids array of user IDs.
 209       * @return external_description
 210       * @since Moodle 2.5
 211       */
 212      public static function create_contacts($userids) {
 213          global $CFG;
 214  
 215          // Check if messaging is enabled.
 216          if (!$CFG->messaging) {
 217              throw new moodle_exception('disabled', 'message');
 218          }
 219  
 220          $params = array('userids' => $userids);
 221          $params = self::validate_parameters(self::create_contacts_parameters(), $params);
 222  
 223          $warnings = array();
 224          foreach ($params['userids'] as $id) {
 225              if (!message_add_contact($id)) {
 226                  $warnings[] = array(
 227                      'item' => 'user',
 228                      'itemid' => $id,
 229                      'warningcode' => 'contactnotcreated',
 230                      'message' => 'The contact could not be created'
 231                  );
 232              }
 233          }
 234          return $warnings;
 235      }
 236  
 237      /**
 238       * Create contacts return description.
 239       *
 240       * @return external_description
 241       * @since Moodle 2.5
 242       */
 243      public static function create_contacts_returns() {
 244          return new external_warnings();
 245      }
 246  
 247      /**
 248       * Delete contacts parameters description.
 249       *
 250       * @return external_function_parameters
 251       * @since Moodle 2.5
 252       */
 253      public static function delete_contacts_parameters() {
 254          return new external_function_parameters(
 255              array(
 256                  'userids' => new external_multiple_structure(
 257                      new external_value(PARAM_INT, 'User ID'),
 258                      'List of user IDs'
 259                  )
 260              )
 261          );
 262      }
 263  
 264      /**
 265       * Delete contacts.
 266       *
 267       * @param array $userids array of user IDs.
 268       * @return null
 269       * @since Moodle 2.5
 270       */
 271      public static function delete_contacts($userids) {
 272          global $CFG;
 273  
 274          // Check if messaging is enabled.
 275          if (!$CFG->messaging) {
 276              throw new moodle_exception('disabled', 'message');
 277          }
 278  
 279          $params = array('userids' => $userids);
 280          $params = self::validate_parameters(self::delete_contacts_parameters(), $params);
 281  
 282          foreach ($params['userids'] as $id) {
 283              message_remove_contact($id);
 284          }
 285  
 286          return null;
 287      }
 288  
 289      /**
 290       * Delete contacts return description.
 291       *
 292       * @return external_description
 293       * @since Moodle 2.5
 294       */
 295      public static function delete_contacts_returns() {
 296          return null;
 297      }
 298  
 299      /**
 300       * Block contacts parameters description.
 301       *
 302       * @return external_function_parameters
 303       * @since Moodle 2.5
 304       */
 305      public static function block_contacts_parameters() {
 306          return new external_function_parameters(
 307              array(
 308                  'userids' => new external_multiple_structure(
 309                      new external_value(PARAM_INT, 'User ID'),
 310                      'List of user IDs'
 311                  )
 312              )
 313          );
 314      }
 315  
 316      /**
 317       * Block contacts.
 318       *
 319       * @param array $userids array of user IDs.
 320       * @return external_description
 321       * @since Moodle 2.5
 322       */
 323      public static function block_contacts($userids) {
 324          global $CFG;
 325  
 326          // Check if messaging is enabled.
 327          if (!$CFG->messaging) {
 328              throw new moodle_exception('disabled', 'message');
 329          }
 330  
 331          $params = array('userids' => $userids);
 332          $params = self::validate_parameters(self::block_contacts_parameters(), $params);
 333  
 334          $warnings = array();
 335          foreach ($params['userids'] as $id) {
 336              if (!message_block_contact($id)) {
 337                  $warnings[] = array(
 338                      'item' => 'user',
 339                      'itemid' => $id,
 340                      'warningcode' => 'contactnotblocked',
 341                      'message' => 'The contact could not be blocked'
 342                  );
 343              }
 344          }
 345          return $warnings;
 346      }
 347  
 348      /**
 349       * Block contacts return description.
 350       *
 351       * @return external_description
 352       * @since Moodle 2.5
 353       */
 354      public static function block_contacts_returns() {
 355          return new external_warnings();
 356      }
 357  
 358      /**
 359       * Unblock contacts parameters description.
 360       *
 361       * @return external_function_parameters
 362       * @since Moodle 2.5
 363       */
 364      public static function unblock_contacts_parameters() {
 365          return new external_function_parameters(
 366              array(
 367                  'userids' => new external_multiple_structure(
 368                      new external_value(PARAM_INT, 'User ID'),
 369                      'List of user IDs'
 370                  )
 371              )
 372          );
 373      }
 374  
 375      /**
 376       * Unblock contacts.
 377       *
 378       * @param array $userids array of user IDs.
 379       * @return null
 380       * @since Moodle 2.5
 381       */
 382      public static function unblock_contacts($userids) {
 383          global $CFG;
 384  
 385          // Check if messaging is enabled.
 386          if (!$CFG->messaging) {
 387              throw new moodle_exception('disabled', 'message');
 388          }
 389  
 390          $params = array('userids' => $userids);
 391          $params = self::validate_parameters(self::unblock_contacts_parameters(), $params);
 392  
 393          foreach ($params['userids'] as $id) {
 394              message_unblock_contact($id);
 395          }
 396  
 397          return null;
 398      }
 399  
 400      /**
 401       * Unblock contacts return description.
 402       *
 403       * @return external_description
 404       * @since Moodle 2.5
 405       */
 406      public static function unblock_contacts_returns() {
 407          return null;
 408      }
 409  
 410      /**
 411       * Get contacts parameters description.
 412       *
 413       * @return external_function_parameters
 414       * @since Moodle 2.5
 415       */
 416      public static function get_contacts_parameters() {
 417          return new external_function_parameters(array());
 418      }
 419  
 420      /**
 421       * Get contacts.
 422       *
 423       * @param array $userids array of user IDs.
 424       * @return external_description
 425       * @since Moodle 2.5
 426       */
 427      public static function get_contacts() {
 428          global $CFG;
 429  
 430          // Check if messaging is enabled.
 431          if (!$CFG->messaging) {
 432              throw new moodle_exception('disabled', 'message');
 433          }
 434  
 435          require_once($CFG->dirroot . '/user/lib.php');
 436  
 437          list($online, $offline, $strangers) = message_get_contacts();
 438          $allcontacts = array('online' => $online, 'offline' => $offline, 'strangers' => $strangers);
 439          foreach ($allcontacts as $mode => $contacts) {
 440              foreach ($contacts as $key => $contact) {
 441                  $newcontact = array(
 442                      'id' => $contact->id,
 443                      'fullname' => fullname($contact),
 444                      'unread' => $contact->messagecount
 445                  );
 446  
 447                  $usercontext = context_user::instance($contact->id, IGNORE_MISSING);
 448                  if ($usercontext) {
 449                      $newcontact['profileimageurl'] = moodle_url::make_webservice_pluginfile_url(
 450                                                          $usercontext->id, 'user', 'icon', null, '/', 'f1')->out(false);
 451                      $newcontact['profileimageurlsmall'] = moodle_url::make_webservice_pluginfile_url(
 452                                                              $usercontext->id, 'user', 'icon', null, '/', 'f2')->out(false);
 453                  } else {
 454                      $newcontact['profileimageurl'] = '';
 455                      $newcontact['profileimageurlsmall'] = '';
 456                  }
 457  
 458                  $allcontacts[$mode][$key] = $newcontact;
 459              }
 460          }
 461          return $allcontacts;
 462      }
 463  
 464      /**
 465       * Get contacts return description.
 466       *
 467       * @return external_description
 468       * @since Moodle 2.5
 469       */
 470      public static function get_contacts_returns() {
 471          return new external_single_structure(
 472              array(
 473                  'online' => new external_multiple_structure(
 474                      new external_single_structure(
 475                          array(
 476                              'id' => new external_value(PARAM_INT, 'User ID'),
 477                              'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
 478                              'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
 479                              'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL),
 480                              'unread' => new external_value(PARAM_INT, 'Unread message count')
 481                          )
 482                      ),
 483                      'List of online contacts'
 484                  ),
 485                  'offline' => new external_multiple_structure(
 486                      new external_single_structure(
 487                          array(
 488                              'id' => new external_value(PARAM_INT, 'User ID'),
 489                              'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
 490                              'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
 491                              'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL),
 492                              'unread' => new external_value(PARAM_INT, 'Unread message count')
 493                          )
 494                      ),
 495                      'List of offline contacts'
 496                  ),
 497                  'strangers' => new external_multiple_structure(
 498                      new external_single_structure(
 499                          array(
 500                              'id' => new external_value(PARAM_INT, 'User ID'),
 501                              'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
 502                              'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
 503                              'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL),
 504                              'unread' => new external_value(PARAM_INT, 'Unread message count')
 505                          )
 506                      ),
 507                      'List of users that are not in the user\'s contact list but have sent a message'
 508                  )
 509              )
 510          );
 511      }
 512  
 513      /**
 514       * Search contacts parameters description.
 515       *
 516       * @return external_function_parameters
 517       * @since Moodle 2.5
 518       */
 519      public static function search_contacts_parameters() {
 520          return new external_function_parameters(
 521              array(
 522                  'searchtext' => new external_value(PARAM_CLEAN, 'String the user\'s fullname has to match to be found'),
 523                  'onlymycourses' => new external_value(PARAM_BOOL, 'Limit search to the user\'s courses',
 524                      VALUE_DEFAULT, false)
 525              )
 526          );
 527      }
 528  
 529      /**
 530       * Search contacts.
 531       *
 532       * @param string $searchtext query string.
 533       * @param bool $onlymycourses limit the search to the user's courses only.
 534       * @return external_description
 535       * @since Moodle 2.5
 536       */
 537      public static function search_contacts($searchtext, $onlymycourses = false) {
 538          global $CFG, $USER;
 539          require_once($CFG->dirroot . '/user/lib.php');
 540  
 541          // Check if messaging is enabled.
 542          if (!$CFG->messaging) {
 543              throw new moodle_exception('disabled', 'message');
 544          }
 545  
 546          require_once($CFG->libdir . '/enrollib.php');
 547  
 548          $params = array('searchtext' => $searchtext, 'onlymycourses' => $onlymycourses);
 549          $params = self::validate_parameters(self::search_contacts_parameters(), $params);
 550  
 551          // Extra validation, we do not allow empty queries.
 552          if ($params['searchtext'] === '') {
 553              throw new moodle_exception('querystringcannotbeempty');
 554          }
 555  
 556          $courseids = array();
 557          if ($params['onlymycourses']) {
 558              $mycourses = enrol_get_my_courses(array('id'));
 559              foreach ($mycourses as $mycourse) {
 560                  $courseids[] = $mycourse->id;
 561              }
 562          } else {
 563              $courseids[] = SITEID;
 564          }
 565  
 566          // Retrieving the users matching the query.
 567          $users = message_search_users($courseids, $params['searchtext']);
 568          $results = array();
 569          foreach ($users as $user) {
 570              $results[$user->id] = $user;
 571          }
 572  
 573          // Reorganising information.
 574          foreach ($results as &$user) {
 575              $newuser = array(
 576                  'id' => $user->id,
 577                  'fullname' => fullname($user)
 578              );
 579  
 580              // Avoid undefined property notice as phone not specified.
 581              $user->phone1 = null;
 582              $user->phone2 = null;
 583  
 584              $usercontext = context_user::instance($user->id, IGNORE_MISSING);
 585  
 586              if ($usercontext) {
 587                  $newuser['profileimageurl'] = moodle_url::make_webservice_pluginfile_url(
 588                                                      $usercontext->id, 'user', 'icon', null, '/', 'f1')->out(false);
 589                  $newuser['profileimageurlsmall'] = moodle_url::make_webservice_pluginfile_url(
 590                                                          $usercontext->id, 'user', 'icon', null, '/', 'f2')->out(false);
 591              } else {
 592                  $newuser['profileimageurl'] = '';
 593                  $newuser['profileimageurlsmall'] = '';
 594              }
 595  
 596              $user = $newuser;
 597          }
 598  
 599          return $results;
 600      }
 601  
 602      /**
 603       * Search contacts return description.
 604       *
 605       * @return external_description
 606       * @since Moodle 2.5
 607       */
 608      public static function search_contacts_returns() {
 609          return new external_multiple_structure(
 610              new external_single_structure(
 611                  array(
 612                      'id' => new external_value(PARAM_INT, 'User ID'),
 613                      'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
 614                      'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
 615                      'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL)
 616                  )
 617              ),
 618              'List of contacts'
 619          );
 620      }
 621  
 622      /**
 623       * Get messages parameters description.
 624       *
 625       * @return external_function_parameters
 626       * @since 2.8
 627       */
 628      public static function get_messages_parameters() {
 629          return new external_function_parameters(
 630              array(
 631                  'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
 632                  'useridfrom' => new external_value(
 633                      PARAM_INT, 'the user id who send the message, 0 for any user. -10 or -20 for no-reply or support user',
 634                      VALUE_DEFAULT, 0),
 635                  'type' => new external_value(
 636                      PARAM_ALPHA, 'type of message to return, expected values are: notifications, conversations and both',
 637                      VALUE_DEFAULT, 'both'),
 638                  'read' => new external_value(PARAM_BOOL, 'true for getting read messages, false for unread', VALUE_DEFAULT, true),
 639                  'newestfirst' => new external_value(
 640                      PARAM_BOOL, 'true for ordering by newest first, false for oldest first',
 641                      VALUE_DEFAULT, true),
 642                  'limitfrom' => new external_value(PARAM_INT, 'limit from', VALUE_DEFAULT, 0),
 643                  'limitnum' => new external_value(PARAM_INT, 'limit number', VALUE_DEFAULT, 0)
 644              )
 645          );
 646      }
 647  
 648      /**
 649       * Get messages function implementation.
 650       *
 651       * @since  2.8
 652       * @throws invalid_parameter_exception
 653       * @throws moodle_exception
 654       * @param  int      $useridto       the user id who received the message
 655       * @param  int      $useridfrom     the user id who send the message. -10 or -20 for no-reply or support user
 656       * @param  string   $type           type of message to return, expected values: notifications, conversations and both
 657       * @param  bool     $read           true for retreiving read messages, false for unread
 658       * @param  bool     $newestfirst    true for ordering by newest first, false for oldest first
 659       * @param  int      $limitfrom      limit from
 660       * @param  int      $limitnum       limit num
 661       * @return external_description
 662       */
 663      public static function get_messages($useridto, $useridfrom = 0, $type = 'both', $read = true,
 664                                          $newestfirst = true, $limitfrom = 0, $limitnum = 0) {
 665          global $CFG, $USER;
 666          require_once($CFG->dirroot . "/message/lib.php");
 667  
 668          $warnings = array();
 669  
 670          $params = array(
 671              'useridto' => $useridto,
 672              'useridfrom' => $useridfrom,
 673              'type' => $type,
 674              'read' => $read,
 675              'newestfirst' => $newestfirst,
 676              'limitfrom' => $limitfrom,
 677              'limitnum' => $limitnum
 678          );
 679  
 680          $params = self::validate_parameters(self::get_messages_parameters(), $params);
 681  
 682          $context = context_system::instance();
 683          self::validate_context($context);
 684  
 685          $useridto = $params['useridto'];
 686          $useridfrom = $params['useridfrom'];
 687          $type = $params['type'];
 688          $read = $params['read'];
 689          $newestfirst = $params['newestfirst'];
 690          $limitfrom = $params['limitfrom'];
 691          $limitnum = $params['limitnum'];
 692  
 693          $allowedvalues = array('notifications', 'conversations', 'both');
 694          if (!in_array($type, $allowedvalues)) {
 695              throw new invalid_parameter_exception('Invalid value for type parameter (value: ' . $type . '),' .
 696                  'allowed values are: ' . implode(',', $allowedvalues));
 697          }
 698  
 699          // Check if private messaging between users is allowed.
 700          if (empty($CFG->messaging)) {
 701              // If we are retreiving only conversations, and messaging is disabled, throw an exception.
 702              if ($type == "conversations") {
 703                  throw new moodle_exception('disabled', 'message');
 704              }
 705              if ($type == "both") {
 706                  $warning = array();
 707                  $warning['item'] = 'message';
 708                  $warning['itemid'] = $USER->id;
 709                  $warning['warningcode'] = '1';
 710                  $warning['message'] = 'Private messages (conversations) are not enabled in this site.
 711                      Only notifications will be returned';
 712                  $warnings[] = $warning;
 713              }
 714          }
 715  
 716          if (!empty($useridto)) {
 717              if (core_user::is_real_user($useridto)) {
 718                  $userto = core_user::get_user($useridto, '*', MUST_EXIST);
 719              } else {
 720                  throw new moodle_exception('invaliduser');
 721              }
 722          }
 723  
 724          if (!empty($useridfrom)) {
 725              // We use get_user here because the from user can be the noreply or support user.
 726              $userfrom = core_user::get_user($useridfrom, '*', MUST_EXIST);
 727          }
 728  
 729          // Check if the current user is the sender/receiver or just a privileged user.
 730          if ($useridto != $USER->id and $useridfrom != $USER->id and
 731               !has_capability('moodle/site:readallmessages', $context)) {
 732              throw new moodle_exception('accessdenied', 'admin');
 733          }
 734  
 735          // Which type of messages to retrieve.
 736          $notifications = -1;
 737          if ($type != 'both') {
 738              $notifications = ($type == 'notifications') ? 1 : 0;
 739          }
 740  
 741          $orderdirection = $newestfirst ? 'DESC' : 'ASC';
 742          $sort = "mr.timecreated $orderdirection";
 743  
 744          if ($messages = message_get_messages($useridto, $useridfrom, $notifications, $read, $sort, $limitfrom, $limitnum)) {
 745              $canviewfullname = has_capability('moodle/site:viewfullnames', $context);
 746  
 747              // In some cases, we don't need to get the to/from user objects from the sql query.
 748              $userfromfullname = '';
 749              $usertofullname = '';
 750  
 751              // In this case, the useridto field is not empty, so we can get the user destinatary fullname from there.
 752              if (!empty($useridto)) {
 753                  $usertofullname = fullname($userto, $canviewfullname);
 754                  // The user from may or may not be filled.
 755                  if (!empty($useridfrom)) {
 756                      $userfromfullname = fullname($userfrom, $canviewfullname);
 757                  }
 758              } else {
 759                  // If the useridto field is empty, the useridfrom must be filled.
 760                  $userfromfullname = fullname($userfrom, $canviewfullname);
 761              }
 762              foreach ($messages as $mid => $message) {
 763  
 764                  // We need to get the user from the query.
 765                  if (empty($userfromfullname)) {
 766                      // Check for non-reply and support users.
 767                      if (core_user::is_real_user($message->useridfrom)) {
 768                          $user = new stdClass();
 769                          $user = username_load_fields_from_object($user, $message, 'userfrom');
 770                          $message->userfromfullname = fullname($user, $canviewfullname);
 771                      } else {
 772                          $user = core_user::get_user($message->useridfrom);
 773                          $message->userfromfullname = fullname($user, $canviewfullname);
 774                      }
 775                  } else {
 776                      $message->userfromfullname = $userfromfullname;
 777                  }
 778  
 779                  // We need to get the user from the query.
 780                  if (empty($usertofullname)) {
 781                      $user = new stdClass();
 782                      $user = username_load_fields_from_object($user, $message, 'userto');
 783                      $message->usertofullname = fullname($user, $canviewfullname);
 784                  } else {
 785                      $message->usertofullname = $usertofullname;
 786                  }
 787  
 788                  // This field is only available in the message_read table.
 789                  if (!isset($message->timeread)) {
 790                      $message->timeread = 0;
 791                  }
 792  
 793                  $message->text = message_format_message_text($message);
 794                  $messages[$mid] = (array) $message;
 795              }
 796          }
 797  
 798          $results = array(
 799              'messages' => $messages,
 800              'warnings' => $warnings
 801          );
 802  
 803          return $results;
 804      }
 805  
 806      /**
 807       * Get messages return description.
 808       *
 809       * @return external_single_structure
 810       * @since 2.8
 811       */
 812      public static function get_messages_returns() {
 813          return new external_single_structure(
 814              array(
 815                  'messages' => new external_multiple_structure(
 816                      new external_single_structure(
 817                          array(
 818                              'id' => new external_value(PARAM_INT, 'Message id'),
 819                              'useridfrom' => new external_value(PARAM_INT, 'User from id'),
 820                              'useridto' => new external_value(PARAM_INT, 'User to id'),
 821                              'subject' => new external_value(PARAM_TEXT, 'The message subject'),
 822                              'text' => new external_value(PARAM_RAW, 'The message text formated'),
 823                              'fullmessage' => new external_value(PARAM_RAW, 'The message'),
 824                              'fullmessageformat' => new external_format_value('fullmessage'),
 825                              'fullmessagehtml' => new external_value(PARAM_RAW, 'The message in html'),
 826                              'smallmessage' => new external_value(PARAM_RAW, 'The shorten message'),
 827                              'notification' => new external_value(PARAM_INT, 'Is a notification?'),
 828                              'contexturl' => new external_value(PARAM_RAW, 'Context URL'),
 829                              'contexturlname' => new external_value(PARAM_TEXT, 'Context URL link name'),
 830                              'timecreated' => new external_value(PARAM_INT, 'Time created'),
 831                              'timeread' => new external_value(PARAM_INT, 'Time read'),
 832                              'usertofullname' => new external_value(PARAM_TEXT, 'User to full name'),
 833                              'userfromfullname' => new external_value(PARAM_TEXT, 'User from full name')
 834                          ), 'message'
 835                      )
 836                  ),
 837                  'warnings' => new external_warnings()
 838              )
 839          );
 840      }
 841  
 842  }
 843  
 844  /**
 845   * Deprecated message external functions
 846   *
 847   * @package    core_message
 848   * @copyright  2011 Jerome Mouneyrac
 849   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 850   * @since Moodle 2.1
 851   * @deprecated Moodle 2.2 MDL-29106 - Please do not use this class any more.
 852   * @see core_notes_external
 853   */
 854  class moodle_message_external extends external_api {
 855  
 856      /**
 857       * Returns description of method parameters
 858       *
 859       * @return external_function_parameters
 860       * @since Moodle 2.1
 861       * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
 862       * @see core_message_external::send_instant_messages_parameters()
 863       */
 864      public static function send_instantmessages_parameters() {
 865          return core_message_external::send_instant_messages_parameters();
 866      }
 867  
 868      /**
 869       * Send private messages from the current USER to other users
 870       *
 871       * @param array $messages An array of message to send.
 872       * @return array
 873       * @since Moodle 2.1
 874       * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
 875       * @see core_message_external::send_instant_messages()
 876       */
 877      public static function send_instantmessages($messages = array()) {
 878          return core_message_external::send_instant_messages($messages);
 879      }
 880  
 881      /**
 882       * Returns description of method result value
 883       *
 884       * @return external_description
 885       * @since Moodle 2.1
 886       * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
 887       * @see core_message_external::send_instant_messages_returns()
 888       */
 889      public static function send_instantmessages_returns() {
 890          return core_message_external::send_instant_messages_returns();
 891      }
 892  
 893  }

Search This Site: