MDL-54687 core_message: added ability to toggle between tabs
[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 27require_once("$CFG->libdir/externallib.php");
705afe6f 28require_once($CFG->dirroot . "/message/lib.php");
a623b6b8 29
5d1017e1 30/**
4615817d 31 * Message external functions
6fbd60ef
AD
32 *
33 * @package core_message
4615817d
JM
34 * @category external
35 * @copyright 2011 Jerome Mouneyrac
75e4f98c 36 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4615817d 37 * @since Moodle 2.2
5d1017e1
JM
38 */
39class core_message_external extends external_api {
a623b6b8
JM
40
41 /**
42 * Returns description of method parameters
4615817d 43 *
a623b6b8 44 * @return external_function_parameters
4615817d 45 * @since Moodle 2.2
a623b6b8 46 */
5d1017e1 47 public static function send_instant_messages_parameters() {
a623b6b8
JM
48 return new external_function_parameters(
49 array(
50 'messages' => new external_multiple_structure(
51 new external_single_structure(
52 array(
53 'touserid' => new external_value(PARAM_INT, 'id of the user to send the private message'),
93ce0e82
JM
54 'text' => new external_value(PARAM_RAW, 'the text of the message'),
55 'textformat' => new external_format_value('text', VALUE_DEFAULT),
a623b6b8
JM
56 '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),
57 )
58 )
59 )
60 )
61 );
62 }
63
64 /**
65 * Send private messages from the current USER to other users
66 *
4615817d
JM
67 * @param array $messages An array of message to send.
68 * @return array
69 * @since Moodle 2.2
a623b6b8 70 */
5d1017e1 71 public static function send_instant_messages($messages = array()) {
a623b6b8 72 global $CFG, $USER, $DB;
a623b6b8 73
436bbf89 74 // Check if messaging is enabled.
a623b6b8
JM
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;
126a4bc4
CS
140 $errormessage = get_string('userisblockingyounoncontact', 'message',
141 fullname(core_user::get_user($message['touserid'])));
a623b6b8
JM
142 }
143
144 //now we can send the message (at least try)
145 if ($success) {
4615817d 146 //TODO MDL-31118 performance improvement - edit the function so we can pass an array instead one touser object
93ce0e82
JM
147 $success = message_post_message($USER, $tousers[$message['touserid']],
148 $message['text'], external_validate_format($message['textformat']));
a623b6b8
JM
149 }
150
151 //build the resultmsg
152 if (isset($message['clientmsgid'])) {
78736e5d 153 $resultmsg['clientmsgid'] = $message['clientmsgid'];
a623b6b8
JM
154 }
155 if ($success) {
156 $resultmsg['msgid'] = $success;
157 } else {
93ce0e82
JM
158 // WARNINGS: for backward compatibility we return this errormessage.
159 // We should have thrown exceptions as these errors prevent results to be returned.
160 // See http://docs.moodle.org/dev/Errors_handling_in_web_services#When_to_send_a_warning_on_the_server_side .
a623b6b8
JM
161 $resultmsg['msgid'] = -1;
162 $resultmsg['errormessage'] = $errormessage;
163 }
164
165 $resultmessages[] = $resultmsg;
166 }
167
168 return $resultmessages;
169 }
170
171 /**
172 * Returns description of method result value
4615817d 173 *
a623b6b8 174 * @return external_description
4615817d 175 * @since Moodle 2.2
a623b6b8 176 */
5d1017e1 177 public static function send_instant_messages_returns() {
a623b6b8
JM
178 return new external_multiple_structure(
179 new external_single_structure(
180 array(
78736e5d 181 '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 182 'clientmsgid' => new external_value(PARAM_ALPHANUMEXT, 'your own id for the message', VALUE_OPTIONAL),
78736e5d 183 'errormessage' => new external_value(PARAM_TEXT, 'error message - if it failed', VALUE_OPTIONAL)
a623b6b8
JM
184 )
185 )
186 );
187 }
188
d6731600
FM
189 /**
190 * Create contacts parameters description.
191 *
192 * @return external_function_parameters
5bcfd504 193 * @since Moodle 2.5
d6731600
FM
194 */
195 public static function create_contacts_parameters() {
196 return new external_function_parameters(
197 array(
198 'userids' => new external_multiple_structure(
199 new external_value(PARAM_INT, 'User ID'),
200 'List of user IDs'
201 )
202 )
203 );
204 }
205
206 /**
207 * Create contacts.
208 *
209 * @param array $userids array of user IDs.
210 * @return external_description
5bcfd504 211 * @since Moodle 2.5
d6731600
FM
212 */
213 public static function create_contacts($userids) {
436bbf89
DM
214 global $CFG;
215
216 // Check if messaging is enabled.
217 if (!$CFG->messaging) {
218 throw new moodle_exception('disabled', 'message');
219 }
220
d6731600
FM
221 $params = array('userids' => $userids);
222 $params = self::validate_parameters(self::create_contacts_parameters(), $params);
223
224 $warnings = array();
225 foreach ($params['userids'] as $id) {
226 if (!message_add_contact($id)) {
227 $warnings[] = array(
228 'item' => 'user',
229 'itemid' => $id,
230 'warningcode' => 'contactnotcreated',
231 'message' => 'The contact could not be created'
232 );
233 }
234 }
235 return $warnings;
236 }
237
238 /**
239 * Create contacts return description.
240 *
241 * @return external_description
5bcfd504 242 * @since Moodle 2.5
d6731600
FM
243 */
244 public static function create_contacts_returns() {
245 return new external_warnings();
246 }
247
248 /**
249 * Delete contacts parameters description.
250 *
251 * @return external_function_parameters
5bcfd504 252 * @since Moodle 2.5
d6731600
FM
253 */
254 public static function delete_contacts_parameters() {
255 return new external_function_parameters(
256 array(
257 'userids' => new external_multiple_structure(
258 new external_value(PARAM_INT, 'User ID'),
259 'List of user IDs'
260 )
261 )
262 );
263 }
264
265 /**
266 * Delete contacts.
267 *
268 * @param array $userids array of user IDs.
269 * @return null
5bcfd504 270 * @since Moodle 2.5
d6731600
FM
271 */
272 public static function delete_contacts($userids) {
436bbf89
DM
273 global $CFG;
274
275 // Check if messaging is enabled.
276 if (!$CFG->messaging) {
277 throw new moodle_exception('disabled', 'message');
278 }
279
d6731600
FM
280 $params = array('userids' => $userids);
281 $params = self::validate_parameters(self::delete_contacts_parameters(), $params);
282
283 foreach ($params['userids'] as $id) {
284 message_remove_contact($id);
285 }
286
287 return null;
288 }
289
290 /**
291 * Delete contacts return description.
292 *
293 * @return external_description
5bcfd504 294 * @since Moodle 2.5
d6731600
FM
295 */
296 public static function delete_contacts_returns() {
297 return null;
298 }
299
300 /**
301 * Block contacts parameters description.
302 *
303 * @return external_function_parameters
5bcfd504 304 * @since Moodle 2.5
d6731600
FM
305 */
306 public static function block_contacts_parameters() {
307 return new external_function_parameters(
308 array(
309 'userids' => new external_multiple_structure(
310 new external_value(PARAM_INT, 'User ID'),
311 'List of user IDs'
312 )
313 )
314 );
315 }
316
317 /**
318 * Block contacts.
319 *
320 * @param array $userids array of user IDs.
321 * @return external_description
5bcfd504 322 * @since Moodle 2.5
d6731600
FM
323 */
324 public static function block_contacts($userids) {
436bbf89
DM
325 global $CFG;
326
327 // Check if messaging is enabled.
328 if (!$CFG->messaging) {
329 throw new moodle_exception('disabled', 'message');
330 }
331
d6731600
FM
332 $params = array('userids' => $userids);
333 $params = self::validate_parameters(self::block_contacts_parameters(), $params);
334
335 $warnings = array();
336 foreach ($params['userids'] as $id) {
337 if (!message_block_contact($id)) {
338 $warnings[] = array(
339 'item' => 'user',
340 'itemid' => $id,
341 'warningcode' => 'contactnotblocked',
342 'message' => 'The contact could not be blocked'
343 );
344 }
345 }
346 return $warnings;
347 }
348
349 /**
350 * Block contacts return description.
351 *
352 * @return external_description
5bcfd504 353 * @since Moodle 2.5
d6731600
FM
354 */
355 public static function block_contacts_returns() {
356 return new external_warnings();
357 }
358
359 /**
360 * Unblock contacts parameters description.
361 *
362 * @return external_function_parameters
5bcfd504 363 * @since Moodle 2.5
d6731600
FM
364 */
365 public static function unblock_contacts_parameters() {
366 return new external_function_parameters(
367 array(
368 'userids' => new external_multiple_structure(
369 new external_value(PARAM_INT, 'User ID'),
370 'List of user IDs'
371 )
372 )
373 );
374 }
375
376 /**
377 * Unblock contacts.
378 *
379 * @param array $userids array of user IDs.
380 * @return null
5bcfd504 381 * @since Moodle 2.5
d6731600
FM
382 */
383 public static function unblock_contacts($userids) {
436bbf89
DM
384 global $CFG;
385
386 // Check if messaging is enabled.
387 if (!$CFG->messaging) {
388 throw new moodle_exception('disabled', 'message');
389 }
390
d6731600
FM
391 $params = array('userids' => $userids);
392 $params = self::validate_parameters(self::unblock_contacts_parameters(), $params);
393
394 foreach ($params['userids'] as $id) {
395 message_unblock_contact($id);
396 }
397
398 return null;
399 }
400
401 /**
402 * Unblock contacts return description.
403 *
404 * @return external_description
5bcfd504 405 * @since Moodle 2.5
d6731600
FM
406 */
407 public static function unblock_contacts_returns() {
408 return null;
409 }
410
9aa012b5
MN
411 /**
412 * Get messagearea conversations parameters.
413 *
414 * @return external_function_parameters
415 */
416 public static function data_for_messagearea_conversations_parameters() {
417 return new external_function_parameters(
418 array(
419 'userid' => new external_value(PARAM_INT, 'The id of the user who we are viewing conversations for'),
420 'limitfrom' => new external_value(PARAM_INT, 'Limit from', VALUE_DEFAULT, 0),
421 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 0)
422 )
423 );
424 }
425
426 /**
427 * Get messagearea conversations.
428 *
429 * @param int $userid The id of the user who we are viewing conversations for
430 * @param int $limitfrom
431 * @param int $limitnum
432 * @return external_function_parameters
433 */
434 public static function data_for_messagearea_conversations($userid, $limitfrom = 0, $limitnum = 0) {
435 global $CFG, $PAGE;
436
437 // Check if messaging is enabled.
438 if (!$CFG->messaging) {
439 throw new moodle_exception('disabled', 'message');
440 }
441
442 $params = array(
443 'userid' => $userid,
444 'limitfrom' => $limitfrom,
445 'limitnum' => $limitnum
446 );
447 self::validate_parameters(self::data_for_messagearea_conversations_parameters(), $params);
448
449 self::validate_context(context_user::instance($userid));
450
451 $contacts = \core_message\api::get_conversations($userid, 0, $limitfrom, $limitnum);
452
453 $renderer = $PAGE->get_renderer('core_message');
454 return $contacts->export_for_template($renderer);
455 }
456
457 /**
458 * Get messagearea conversations returns.
459 *
460 * @return external_function_parameters
461 */
462 public static function data_for_messagearea_conversations_returns() {
463 return new external_function_parameters(
464 array(
465 'userid' => new external_value(PARAM_INT, 'The id of the user who we are viewing conversations for'),
466 'conversationsselected' => new external_value(PARAM_BOOL, 'Determines if conversations were selected,
467 otherwise contacts were'),
468 'contacts' => new external_multiple_structure(
469 new external_single_structure(
470 array(
471 'userid' => new external_value(PARAM_INT, 'The user\'s id'),
472 'fullname' => new external_value(PARAM_NOTAGS, 'The user\'s name'),
473 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL'),
474 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL'),
475 'lastmessage' => new external_value(PARAM_NOTAGS, 'The user\'s last message', VALUE_OPTIONAL),
476 'isonline' => new external_value(PARAM_BOOL, 'The user\'s online status', VALUE_OPTIONAL)
477 )
478 )
479 )
480 )
481 );
482 }
483
484 /**
485 * Get messagearea contacts parameters.
486 *
487 * @return external_function_parameters
488 */
489 public static function data_for_messagearea_contacts_parameters() {
490 return self::data_for_messagearea_conversations_parameters();
491 }
492
493 /**
494 * Get messagearea contacts parameters.
495 *
496 * @param int $userid The id of the user who we are viewing conversations for
497 * @param int $limitfrom
498 * @param int $limitnum
499 * @return external_function_parameters
500 */
501 public static function data_for_messagearea_contacts($userid, $limitfrom = 0, $limitnum = 0) {
502 global $CFG, $PAGE;
503
504 // Check if messaging is enabled.
505 if (!$CFG->messaging) {
506 throw new moodle_exception('disabled', 'message');
507 }
508
509 $params = array(
510 'userid' => $userid,
511 'limitfrom' => $limitfrom,
512 'limitnum' => $limitnum
513 );
514 self::validate_parameters(self::data_for_messagearea_contacts_parameters(), $params);
515
516 self::validate_context(context_user::instance($userid));
517
518 $contacts = \core_message\api::get_contacts($userid, $limitfrom, $limitnum);
519
520 $renderer = $PAGE->get_renderer('core_message');
521 return $contacts->export_for_template($renderer);
522 }
523
524 /**
525 * Get messagearea contacts returns.
526 *
527 * @return external_function_parameters
528 */
529 public static function data_for_messagearea_contacts_returns() {
530 return self::data_for_messagearea_conversations_returns();
531 }
532
d6731600
FM
533 /**
534 * Get contacts parameters description.
535 *
536 * @return external_function_parameters
5bcfd504 537 * @since Moodle 2.5
d6731600
FM
538 */
539 public static function get_contacts_parameters() {
540 return new external_function_parameters(array());
541 }
542
543 /**
544 * Get contacts.
545 *
546 * @param array $userids array of user IDs.
547 * @return external_description
5bcfd504 548 * @since Moodle 2.5
d6731600
FM
549 */
550 public static function get_contacts() {
d85bedf7 551 global $CFG, $PAGE;
436bbf89
DM
552
553 // Check if messaging is enabled.
554 if (!$CFG->messaging) {
555 throw new moodle_exception('disabled', 'message');
556 }
557
d6731600
FM
558 require_once($CFG->dirroot . '/user/lib.php');
559
560 list($online, $offline, $strangers) = message_get_contacts();
561 $allcontacts = array('online' => $online, 'offline' => $offline, 'strangers' => $strangers);
562 foreach ($allcontacts as $mode => $contacts) {
563 foreach ($contacts as $key => $contact) {
564 $newcontact = array(
565 'id' => $contact->id,
566 'fullname' => fullname($contact),
567 'unread' => $contact->messagecount
568 );
569
d85bedf7
JL
570 $userpicture = new user_picture($contact);
571 $userpicture->size = 1; // Size f1.
572 $newcontact['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
573 $userpicture->size = 0; // Size f2.
574 $newcontact['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
d6731600
FM
575
576 $allcontacts[$mode][$key] = $newcontact;
577 }
578 }
579 return $allcontacts;
580 }
581
582 /**
583 * Get contacts return description.
584 *
585 * @return external_description
5bcfd504 586 * @since Moodle 2.5
d6731600
FM
587 */
588 public static function get_contacts_returns() {
589 return new external_single_structure(
590 array(
591 'online' => new external_multiple_structure(
592 new external_single_structure(
593 array(
594 'id' => new external_value(PARAM_INT, 'User ID'),
595 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
596 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
597 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL),
598 'unread' => new external_value(PARAM_INT, 'Unread message count')
599 )
600 ),
601 'List of online contacts'
602 ),
603 'offline' => new external_multiple_structure(
604 new external_single_structure(
605 array(
606 'id' => new external_value(PARAM_INT, 'User ID'),
607 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
608 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
609 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL),
610 'unread' => new external_value(PARAM_INT, 'Unread message count')
611 )
612 ),
613 'List of offline contacts'
614 ),
615 'strangers' => new external_multiple_structure(
616 new external_single_structure(
617 array(
618 'id' => new external_value(PARAM_INT, 'User ID'),
619 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
620 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
621 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL),
622 'unread' => new external_value(PARAM_INT, 'Unread message count')
623 )
624 ),
625 'List of users that are not in the user\'s contact list but have sent a message'
626 )
627 )
628 );
629 }
630
631 /**
632 * Search contacts parameters description.
633 *
634 * @return external_function_parameters
5bcfd504 635 * @since Moodle 2.5
d6731600
FM
636 */
637 public static function search_contacts_parameters() {
638 return new external_function_parameters(
639 array(
640 'searchtext' => new external_value(PARAM_CLEAN, 'String the user\'s fullname has to match to be found'),
641 'onlymycourses' => new external_value(PARAM_BOOL, 'Limit search to the user\'s courses',
642 VALUE_DEFAULT, false)
643 )
644 );
645 }
646
647 /**
648 * Search contacts.
649 *
650 * @param string $searchtext query string.
651 * @param bool $onlymycourses limit the search to the user's courses only.
652 * @return external_description
5bcfd504 653 * @since Moodle 2.5
d6731600
FM
654 */
655 public static function search_contacts($searchtext, $onlymycourses = false) {
d85bedf7 656 global $CFG, $USER, $PAGE;
11d83ab3 657 require_once($CFG->dirroot . '/user/lib.php');
436bbf89
DM
658
659 // Check if messaging is enabled.
660 if (!$CFG->messaging) {
661 throw new moodle_exception('disabled', 'message');
662 }
663
d6731600
FM
664 require_once($CFG->libdir . '/enrollib.php');
665
666 $params = array('searchtext' => $searchtext, 'onlymycourses' => $onlymycourses);
667 $params = self::validate_parameters(self::search_contacts_parameters(), $params);
668
669 // Extra validation, we do not allow empty queries.
670 if ($params['searchtext'] === '') {
671 throw new moodle_exception('querystringcannotbeempty');
672 }
673
674 $courseids = array();
675 if ($params['onlymycourses']) {
676 $mycourses = enrol_get_my_courses(array('id'));
677 foreach ($mycourses as $mycourse) {
678 $courseids[] = $mycourse->id;
679 }
680 } else {
681 $courseids[] = SITEID;
682 }
683
684 // Retrieving the users matching the query.
685 $users = message_search_users($courseids, $params['searchtext']);
686 $results = array();
687 foreach ($users as $user) {
688 $results[$user->id] = $user;
689 }
690
691 // Reorganising information.
692 foreach ($results as &$user) {
693 $newuser = array(
694 'id' => $user->id,
695 'fullname' => fullname($user)
696 );
697
698 // Avoid undefined property notice as phone not specified.
699 $user->phone1 = null;
700 $user->phone2 = null;
701
d85bedf7
JL
702 $userpicture = new user_picture($user);
703 $userpicture->size = 1; // Size f1.
704 $newuser['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
705 $userpicture->size = 0; // Size f2.
706 $newuser['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
d6731600
FM
707
708 $user = $newuser;
709 }
710
711 return $results;
712 }
713
714 /**
715 * Search contacts return description.
716 *
717 * @return external_description
5bcfd504 718 * @since Moodle 2.5
d6731600
FM
719 */
720 public static function search_contacts_returns() {
721 return new external_multiple_structure(
722 new external_single_structure(
723 array(
724 'id' => new external_value(PARAM_INT, 'User ID'),
725 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
726 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
727 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL)
728 )
729 ),
730 'List of contacts'
731 );
732 }
aff9da17
JL
733
734 /**
735 * Get messages parameters description.
736 *
737 * @return external_function_parameters
193edf7f 738 * @since 2.8
aff9da17
JL
739 */
740 public static function get_messages_parameters() {
741 return new external_function_parameters(
742 array(
6ff4464b 743 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
127ef540
SH
744 'useridfrom' => new external_value(
745 PARAM_INT, 'the user id who send the message, 0 for any user. -10 or -20 for no-reply or support user',
746 VALUE_DEFAULT, 0),
747 'type' => new external_value(
748 PARAM_ALPHA, 'type of message to return, expected values are: notifications, conversations and both',
749 VALUE_DEFAULT, 'both'),
6ff4464b 750 'read' => new external_value(PARAM_BOOL, 'true for getting read messages, false for unread', VALUE_DEFAULT, true),
127ef540
SH
751 'newestfirst' => new external_value(
752 PARAM_BOOL, 'true for ordering by newest first, false for oldest first',
753 VALUE_DEFAULT, true),
aff9da17 754 'limitfrom' => new external_value(PARAM_INT, 'limit from', VALUE_DEFAULT, 0),
127ef540
SH
755 'limitnum' => new external_value(PARAM_INT, 'limit number', VALUE_DEFAULT, 0)
756 )
aff9da17
JL
757 );
758 }
759
760 /**
761 * Get messages function implementation.
127ef540
SH
762 *
763 * @since 2.8
764 * @throws invalid_parameter_exception
765 * @throws moodle_exception
6ff4464b
JL
766 * @param int $useridto the user id who received the message
767 * @param int $useridfrom the user id who send the message. -10 or -20 for no-reply or support user
193edf7f 768 * @param string $type type of message to return, expected values: notifications, conversations and both
aff9da17 769 * @param bool $read true for retreiving read messages, false for unread
6ff4464b 770 * @param bool $newestfirst true for ordering by newest first, false for oldest first
aff9da17
JL
771 * @param int $limitfrom limit from
772 * @param int $limitnum limit num
773 * @return external_description
aff9da17 774 */
193edf7f 775 public static function get_messages($useridto, $useridfrom = 0, $type = 'both', $read = true,
aff9da17 776 $newestfirst = true, $limitfrom = 0, $limitnum = 0) {
127ef540 777 global $CFG, $USER;
aff9da17
JL
778
779 $warnings = array();
780
781 $params = array(
782 'useridto' => $useridto,
6ff4464b 783 'useridfrom' => $useridfrom,
aff9da17
JL
784 'type' => $type,
785 'read' => $read,
aff9da17
JL
786 'newestfirst' => $newestfirst,
787 'limitfrom' => $limitfrom,
788 'limitnum' => $limitnum
789 );
790
791 $params = self::validate_parameters(self::get_messages_parameters(), $params);
792
793 $context = context_system::instance();
794 self::validate_context($context);
795
796 $useridto = $params['useridto'];
6ff4464b 797 $useridfrom = $params['useridfrom'];
aff9da17
JL
798 $type = $params['type'];
799 $read = $params['read'];
aff9da17
JL
800 $newestfirst = $params['newestfirst'];
801 $limitfrom = $params['limitfrom'];
802 $limitnum = $params['limitnum'];
803
804 $allowedvalues = array('notifications', 'conversations', 'both');
805 if (!in_array($type, $allowedvalues)) {
806 throw new invalid_parameter_exception('Invalid value for type parameter (value: ' . $type . '),' .
807 'allowed values are: ' . implode(',', $allowedvalues));
808 }
809
810 // Check if private messaging between users is allowed.
811 if (empty($CFG->messaging)) {
812 // If we are retreiving only conversations, and messaging is disabled, throw an exception.
aff9da17
JL
813 if ($type == "conversations") {
814 throw new moodle_exception('disabled', 'message');
815 }
816 if ($type == "both") {
817 $warning = array();
818 $warning['item'] = 'message';
819 $warning['itemid'] = $USER->id;
820 $warning['warningcode'] = '1';
821 $warning['message'] = 'Private messages (conversations) are not enabled in this site.
822 Only notifications will be returned';
823 $warnings[] = $warning;
824 }
825 }
826
827 if (!empty($useridto)) {
6ff4464b
JL
828 if (core_user::is_real_user($useridto)) {
829 $userto = core_user::get_user($useridto, '*', MUST_EXIST);
830 } else {
831 throw new moodle_exception('invaliduser');
832 }
aff9da17
JL
833 }
834
835 if (!empty($useridfrom)) {
836 // We use get_user here because the from user can be the noreply or support user.
837 $userfrom = core_user::get_user($useridfrom, '*', MUST_EXIST);
838 }
839
840 // Check if the current user is the sender/receiver or just a privileged user.
841 if ($useridto != $USER->id and $useridfrom != $USER->id and
842 !has_capability('moodle/site:readallmessages', $context)) {
843 throw new moodle_exception('accessdenied', 'admin');
844 }
845
127ef540 846 // Which type of messages to retrieve.
193edf7f 847 $notifications = -1;
aff9da17 848 if ($type != 'both') {
193edf7f 849 $notifications = ($type == 'notifications') ? 1 : 0;
aff9da17
JL
850 }
851
aff9da17 852 $orderdirection = $newestfirst ? 'DESC' : 'ASC';
193edf7f 853 $sort = "mr.timecreated $orderdirection";
aff9da17 854
193edf7f 855 if ($messages = message_get_messages($useridto, $useridfrom, $notifications, $read, $sort, $limitfrom, $limitnum)) {
aff9da17
JL
856 $canviewfullname = has_capability('moodle/site:viewfullnames', $context);
857
858 // In some cases, we don't need to get the to/from user objects from the sql query.
859 $userfromfullname = '';
860 $usertofullname = '';
861
862 // In this case, the useridto field is not empty, so we can get the user destinatary fullname from there.
863 if (!empty($useridto)) {
864 $usertofullname = fullname($userto, $canviewfullname);
865 // The user from may or may not be filled.
866 if (!empty($useridfrom)) {
867 $userfromfullname = fullname($userfrom, $canviewfullname);
868 }
869 } else {
870 // If the useridto field is empty, the useridfrom must be filled.
871 $userfromfullname = fullname($userfrom, $canviewfullname);
872 }
aff9da17
JL
873 foreach ($messages as $mid => $message) {
874
ea21d637
JL
875 // Do not return deleted messages.
876 if (($useridto == $USER->id and $message->timeusertodeleted) or
877 ($useridfrom == $USER->id and $message->timeuserfromdeleted)) {
878
879 unset($messages[$mid]);
880 continue;
881 }
882
aff9da17
JL
883 // We need to get the user from the query.
884 if (empty($userfromfullname)) {
6ff4464b
JL
885 // Check for non-reply and support users.
886 if (core_user::is_real_user($message->useridfrom)) {
127ef540 887 $user = new stdClass();
6ff4464b
JL
888 $user = username_load_fields_from_object($user, $message, 'userfrom');
889 $message->userfromfullname = fullname($user, $canviewfullname);
890 } else {
891 $user = core_user::get_user($message->useridfrom);
892 $message->userfromfullname = fullname($user, $canviewfullname);
893 }
aff9da17
JL
894 } else {
895 $message->userfromfullname = $userfromfullname;
896 }
897
898 // We need to get the user from the query.
899 if (empty($usertofullname)) {
127ef540 900 $user = new stdClass();
aff9da17
JL
901 $user = username_load_fields_from_object($user, $message, 'userto');
902 $message->usertofullname = fullname($user, $canviewfullname);
903 } else {
904 $message->usertofullname = $usertofullname;
905 }
906
193edf7f 907 // This field is only available in the message_read table.
aff9da17
JL
908 if (!isset($message->timeread)) {
909 $message->timeread = 0;
910 }
911
aff9da17 912 $message->text = message_format_message_text($message);
aff9da17
JL
913 $messages[$mid] = (array) $message;
914 }
915 }
916
917 $results = array(
918 'messages' => $messages,
919 'warnings' => $warnings
920 );
921
922 return $results;
923 }
924
925 /**
926 * Get messages return description.
927 *
6ff4464b 928 * @return external_single_structure
193edf7f 929 * @since 2.8
aff9da17
JL
930 */
931 public static function get_messages_returns() {
932 return new external_single_structure(
933 array(
934 'messages' => new external_multiple_structure(
935 new external_single_structure(
936 array(
193edf7f 937 'id' => new external_value(PARAM_INT, 'Message id'),
aff9da17
JL
938 'useridfrom' => new external_value(PARAM_INT, 'User from id'),
939 'useridto' => new external_value(PARAM_INT, 'User to id'),
940 'subject' => new external_value(PARAM_TEXT, 'The message subject'),
941 'text' => new external_value(PARAM_RAW, 'The message text formated'),
942 'fullmessage' => new external_value(PARAM_RAW, 'The message'),
193edf7f 943 'fullmessageformat' => new external_format_value('fullmessage'),
aff9da17
JL
944 'fullmessagehtml' => new external_value(PARAM_RAW, 'The message in html'),
945 'smallmessage' => new external_value(PARAM_RAW, 'The shorten message'),
946 'notification' => new external_value(PARAM_INT, 'Is a notification?'),
947 'contexturl' => new external_value(PARAM_RAW, 'Context URL'),
948 'contexturlname' => new external_value(PARAM_TEXT, 'Context URL link name'),
949 'timecreated' => new external_value(PARAM_INT, 'Time created'),
950 'timeread' => new external_value(PARAM_INT, 'Time read'),
951 'usertofullname' => new external_value(PARAM_TEXT, 'User to full name'),
952 'userfromfullname' => new external_value(PARAM_TEXT, 'User from full name')
953 ), 'message'
954 )
955 ),
956 'warnings' => new external_warnings()
957 )
958 );
959 }
960
60ab2e1b
JL
961 /**
962 * Get blocked users parameters description.
963 *
964 * @return external_function_parameters
965 * @since 2.9
966 */
967 public static function get_blocked_users_parameters() {
968 return new external_function_parameters(
969 array(
970 'userid' => new external_value(PARAM_INT,
971 'the user whose blocked users we want to retrieve',
972 VALUE_REQUIRED),
973 )
974 );
975 }
976
977 /**
978 * Retrieve a list of users blocked
979 *
980 * @param int $userid the user whose blocked users we want to retrieve
981 * @return external_description
982 * @since 2.9
983 */
984 public static function get_blocked_users($userid) {
d85bedf7 985 global $CFG, $USER, $PAGE;
60ab2e1b
JL
986
987 // Warnings array, it can be empty at the end but is mandatory.
988 $warnings = array();
989
990 // Validate params.
991 $params = array(
992 'userid' => $userid
993 );
994 $params = self::validate_parameters(self::get_blocked_users_parameters(), $params);
995 $userid = $params['userid'];
996
997 // Validate context.
998 $context = context_system::instance();
999 self::validate_context($context);
1000
1001 // Check if private messaging between users is allowed.
1002 if (empty($CFG->messaging)) {
1003 throw new moodle_exception('disabled', 'message');
1004 }
1005
4485f7c5
JL
1006 $user = core_user::get_user($userid, '*', MUST_EXIST);
1007 core_user::require_active_user($user);
60ab2e1b
JL
1008
1009 // Check if we have permissions for retrieve the information.
1010 if ($userid != $USER->id and !has_capability('moodle/site:readallmessages', $context)) {
1011 throw new moodle_exception('accessdenied', 'admin');
1012 }
1013
1014 // Now, we can get safely all the blocked users.
1015 $users = message_get_blocked_users($user);
1016
1017 $blockedusers = array();
1018 foreach ($users as $user) {
1019 $newuser = array(
1020 'id' => $user->id,
1021 'fullname' => fullname($user),
1022 );
0b074e88 1023
d85bedf7
JL
1024 $userpicture = new user_picture($user);
1025 $userpicture->size = 1; // Size f1.
1026 $newuser['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
60ab2e1b
JL
1027
1028 $blockedusers[] = $newuser;
1029 }
1030
1031 $results = array(
1032 'users' => $blockedusers,
1033 'warnings' => $warnings
1034 );
1035 return $results;
1036 }
1037
1038 /**
1039 * Get blocked users return description.
1040 *
1041 * @return external_single_structure
1042 * @since 2.9
1043 */
1044 public static function get_blocked_users_returns() {
1045 return new external_single_structure(
1046 array(
1047 'users' => new external_multiple_structure(
1048 new external_single_structure(
1049 array(
1050 'id' => new external_value(PARAM_INT, 'User ID'),
1051 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
1052 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL)
1053 )
1054 ),
1055 'List of blocked users'
1056 ),
1057 'warnings' => new external_warnings()
1058 )
1059 );
1060 }
1061
31c474da
JL
1062 /**
1063 * Returns description of method parameters
1064 *
1065 * @return external_function_parameters
1066 * @since 2.9
1067 */
1068 public static function mark_message_read_parameters() {
1069 return new external_function_parameters(
1070 array(
1071 'messageid' => new external_value(PARAM_INT, 'id of the message (in the message table)'),
1072 'timeread' => new external_value(PARAM_INT, 'timestamp for when the message should be marked read')
1073 )
1074 );
1075 }
1076
1077 /**
1078 * Mark a single message as read, trigger message_viewed event
1079 *
1080 * @param int $messageid id of the message (in the message table)
1081 * @param int $timeread timestamp for when the message should be marked read
1082 * @return external_description
1083 * @throws invalid_parameter_exception
1084 * @throws moodle_exception
1085 * @since 2.9
1086 */
1087 public static function mark_message_read($messageid, $timeread) {
1088 global $CFG, $DB, $USER;
31c474da
JL
1089
1090 // Check if private messaging between users is allowed.
1091 if (empty($CFG->messaging)) {
1092 throw new moodle_exception('disabled', 'message');
1093 }
1094
1095 // Warnings array, it can be empty at the end but is mandatory.
1096 $warnings = array();
1097
1098 // Validate params.
1099 $params = array(
1100 'messageid' => $messageid,
1101 'timeread' => $timeread
1102 );
1103 $params = self::validate_parameters(self::mark_message_read_parameters(), $params);
1104
1105 // Validate context.
1106 $context = context_system::instance();
1107 self::validate_context($context);
1108
1109 $message = $DB->get_record('message', array('id' => $params['messageid']), '*', MUST_EXIST);
1110
1111 if ($message->useridto != $USER->id) {
1112 throw new invalid_parameter_exception('Invalid messageid, you don\'t have permissions to mark this message as read');
1113 }
1114
1115 $messageid = message_mark_message_read($message, $params['timeread']);
1116
1117 $results = array(
1118 'messageid' => $messageid,
1119 'warnings' => $warnings
1120 );
1121 return $results;
1122 }
1123
1124 /**
1125 * Returns description of method result value
1126 *
1127 * @return external_description
1128 * @since 2.9
1129 */
1130 public static function mark_message_read_returns() {
1131 return new external_single_structure(
1132 array(
1133 'messageid' => new external_value(PARAM_INT, 'the id of the message in the message_read table'),
1134 'warnings' => new external_warnings()
1135 )
1136 );
1137 }
1138
419b1128
JL
1139 /**
1140 * Returns description of method parameters
1141 *
1142 * @return external_function_parameters
1143 * @since 3.1
1144 */
1145 public static function delete_message_parameters() {
1146 return new external_function_parameters(
1147 array(
1148 'messageid' => new external_value(PARAM_INT, 'The message id'),
1149 'userid' => new external_value(PARAM_INT, 'The user id of who we want to delete the message for'),
1150 'read' => new external_value(PARAM_BOOL, 'If is a message read', VALUE_DEFAULT, true)
1151 )
1152 );
1153 }
1154
1155 /**
1156 * Deletes a message
1157 *
1158 * @param int $messageid the message id
1159 * @param int $userid the user id of who we want to delete the message for
1160 * @param bool $read if is a message read (default to true)
1161 * @return external_description
1162 * @throws moodle_exception
1163 * @since 3.1
1164 */
1165 public static function delete_message($messageid, $userid, $read = true) {
1166 global $CFG, $DB;
419b1128
JL
1167
1168 // Check if private messaging between users is allowed.
1169 if (empty($CFG->messaging)) {
1170 throw new moodle_exception('disabled', 'message');
1171 }
1172
1173 // Warnings array, it can be empty at the end but is mandatory.
1174 $warnings = array();
1175
1176 // Validate params.
1177 $params = array(
1178 'messageid' => $messageid,
1179 'userid' => $userid,
1180 'read' => $read
1181 );
1182 $params = self::validate_parameters(self::delete_message_parameters(), $params);
1183
1184 // Validate context.
1185 $context = context_system::instance();
1186 self::validate_context($context);
1187
1188 $messagestable = $params['read'] ? 'message_read' : 'message';
1189 $message = $DB->get_record($messagestable, array('id' => $params['messageid']), '*', MUST_EXIST);
1190
1191 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1192 core_user::require_active_user($user);
1193
1194 $status = false;
1195 if (message_can_delete_message($message, $user->id)) {
1196 $status = message_delete_message($message, $user->id);;
1197 } else {
1198 throw new moodle_exception('You do not have permission to delete this message');
1199 }
1200
1201 $results = array(
1202 'status' => $status,
1203 'warnings' => $warnings
1204 );
1205 return $results;
1206 }
1207
1208 /**
1209 * Returns description of method result value
1210 *
1211 * @return external_description
1212 * @since 3.1
1213 */
1214 public static function delete_message_returns() {
1215 return new external_single_structure(
1216 array(
1217 'status' => new external_value(PARAM_BOOL, 'True if the message was deleted, false otherwise'),
1218 'warnings' => new external_warnings()
1219 )
1220 );
1221 }
1222
a623b6b8 1223}