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