MDL-54687 message: messaging widget styling
[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'
34c2f347
MN
201 ),
202 'userid' => new external_value(PARAM_INT, 'The id of the user we are creating the contacts for, 0 for the
203 current user', VALUE_DEFAULT, 0)
d6731600
FM
204 )
205 );
206 }
207
208 /**
209 * Create contacts.
210 *
211 * @param array $userids array of user IDs.
34c2f347 212 * @param int $userid The id of the user we are creating the contacts for
d6731600 213 * @return external_description
5bcfd504 214 * @since Moodle 2.5
d6731600 215 */
34c2f347 216 public static function create_contacts($userids, $userid = 0) {
436bbf89
DM
217 global $CFG;
218
219 // Check if messaging is enabled.
220 if (!$CFG->messaging) {
221 throw new moodle_exception('disabled', 'message');
222 }
223
34c2f347 224 $params = array('userids' => $userids, 'userid' => $userid);
d6731600
FM
225 $params = self::validate_parameters(self::create_contacts_parameters(), $params);
226
227 $warnings = array();
228 foreach ($params['userids'] as $id) {
34c2f347 229 if (!message_add_contact($id, 0, $userid)) {
d6731600
FM
230 $warnings[] = array(
231 'item' => 'user',
232 'itemid' => $id,
233 'warningcode' => 'contactnotcreated',
234 'message' => 'The contact could not be created'
235 );
236 }
237 }
238 return $warnings;
239 }
240
241 /**
242 * Create contacts return description.
243 *
244 * @return external_description
5bcfd504 245 * @since Moodle 2.5
d6731600
FM
246 */
247 public static function create_contacts_returns() {
248 return new external_warnings();
249 }
250
251 /**
252 * Delete contacts parameters description.
253 *
254 * @return external_function_parameters
5bcfd504 255 * @since Moodle 2.5
d6731600
FM
256 */
257 public static function delete_contacts_parameters() {
258 return new external_function_parameters(
259 array(
260 'userids' => new external_multiple_structure(
261 new external_value(PARAM_INT, 'User ID'),
262 'List of user IDs'
34c2f347
MN
263 ),
264 'userid' => new external_value(PARAM_INT, 'The id of the user we are deleting the contacts for, 0 for the
265 current user', VALUE_DEFAULT, 0)
d6731600
FM
266 )
267 );
268 }
269
270 /**
271 * Delete contacts.
272 *
273 * @param array $userids array of user IDs.
34c2f347 274 * @param int $userid The id of the user we are deleting the contacts for
d6731600 275 * @return null
5bcfd504 276 * @since Moodle 2.5
d6731600 277 */
34c2f347 278 public static function delete_contacts($userids, $userid = 0) {
436bbf89
DM
279 global $CFG;
280
281 // Check if messaging is enabled.
282 if (!$CFG->messaging) {
283 throw new moodle_exception('disabled', 'message');
284 }
285
34c2f347 286 $params = array('userids' => $userids, 'userid' => $userid);
d6731600
FM
287 $params = self::validate_parameters(self::delete_contacts_parameters(), $params);
288
289 foreach ($params['userids'] as $id) {
34c2f347 290 message_remove_contact($id, $userid);
d6731600
FM
291 }
292
293 return null;
294 }
295
296 /**
297 * Delete contacts return description.
298 *
299 * @return external_description
5bcfd504 300 * @since Moodle 2.5
d6731600
FM
301 */
302 public static function delete_contacts_returns() {
303 return null;
304 }
305
306 /**
307 * Block contacts parameters description.
308 *
309 * @return external_function_parameters
5bcfd504 310 * @since Moodle 2.5
d6731600
FM
311 */
312 public static function block_contacts_parameters() {
313 return new external_function_parameters(
314 array(
315 'userids' => new external_multiple_structure(
316 new external_value(PARAM_INT, 'User ID'),
317 'List of user IDs'
34c2f347
MN
318 ),
319 'userid' => new external_value(PARAM_INT, 'The id of the user we are blocking the contacts for, 0 for the
320 current user', VALUE_DEFAULT, 0)
d6731600
FM
321 )
322 );
323 }
324
325 /**
326 * Block contacts.
327 *
328 * @param array $userids array of user IDs.
34c2f347 329 * @param int $userid The id of the user we are blocking the contacts for
d6731600 330 * @return external_description
5bcfd504 331 * @since Moodle 2.5
d6731600 332 */
34c2f347 333 public static function block_contacts($userids, $userid = 0) {
436bbf89
DM
334 global $CFG;
335
336 // Check if messaging is enabled.
337 if (!$CFG->messaging) {
338 throw new moodle_exception('disabled', 'message');
339 }
340
34c2f347 341 $params = array('userids' => $userids, 'userid' => $userid);
d6731600
FM
342 $params = self::validate_parameters(self::block_contacts_parameters(), $params);
343
344 $warnings = array();
345 foreach ($params['userids'] as $id) {
34c2f347 346 if (!message_block_contact($id, $userid)) {
d6731600
FM
347 $warnings[] = array(
348 'item' => 'user',
349 'itemid' => $id,
350 'warningcode' => 'contactnotblocked',
351 'message' => 'The contact could not be blocked'
352 );
353 }
354 }
355 return $warnings;
356 }
357
358 /**
359 * Block contacts return description.
360 *
361 * @return external_description
5bcfd504 362 * @since Moodle 2.5
d6731600
FM
363 */
364 public static function block_contacts_returns() {
365 return new external_warnings();
366 }
367
368 /**
369 * Unblock contacts parameters description.
370 *
371 * @return external_function_parameters
5bcfd504 372 * @since Moodle 2.5
d6731600
FM
373 */
374 public static function unblock_contacts_parameters() {
375 return new external_function_parameters(
376 array(
377 'userids' => new external_multiple_structure(
378 new external_value(PARAM_INT, 'User ID'),
379 'List of user IDs'
34c2f347
MN
380 ),
381 'userid' => new external_value(PARAM_INT, 'The id of the user we are unblocking the contacts for, 0 for the
382 current user', VALUE_DEFAULT, 0)
d6731600
FM
383 )
384 );
385 }
386
387 /**
388 * Unblock contacts.
389 *
390 * @param array $userids array of user IDs.
34c2f347 391 * @param int $userid The id of the user we are unblocking the contacts for
d6731600 392 * @return null
5bcfd504 393 * @since Moodle 2.5
d6731600 394 */
34c2f347 395 public static function unblock_contacts($userids, $userid = 0) {
436bbf89
DM
396 global $CFG;
397
398 // Check if messaging is enabled.
399 if (!$CFG->messaging) {
400 throw new moodle_exception('disabled', 'message');
401 }
402
34c2f347 403 $params = array('userids' => $userids, 'userid' => $userid);
d6731600
FM
404 $params = self::validate_parameters(self::unblock_contacts_parameters(), $params);
405
406 foreach ($params['userids'] as $id) {
34c2f347 407 message_unblock_contact($id, $userid);
d6731600
FM
408 }
409
410 return null;
411 }
412
413 /**
414 * Unblock contacts return description.
415 *
416 * @return external_description
5bcfd504 417 * @since Moodle 2.5
d6731600
FM
418 */
419 public static function unblock_contacts_returns() {
420 return null;
421 }
422
9aa012b5
MN
423 /**
424 * Get messagearea conversations parameters.
425 *
426 * @return external_function_parameters
427 */
428 public static function data_for_messagearea_conversations_parameters() {
429 return new external_function_parameters(
430 array(
431 'userid' => new external_value(PARAM_INT, 'The id of the user who we are viewing conversations for'),
432 'limitfrom' => new external_value(PARAM_INT, 'Limit from', VALUE_DEFAULT, 0),
433 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 0)
434 )
435 );
436 }
437
438 /**
439 * Get messagearea conversations.
440 *
441 * @param int $userid The id of the user who we are viewing conversations for
442 * @param int $limitfrom
443 * @param int $limitnum
444 * @return external_function_parameters
445 */
446 public static function data_for_messagearea_conversations($userid, $limitfrom = 0, $limitnum = 0) {
447 global $CFG, $PAGE;
448
449 // Check if messaging is enabled.
450 if (!$CFG->messaging) {
451 throw new moodle_exception('disabled', 'message');
452 }
453
454 $params = array(
455 'userid' => $userid,
456 'limitfrom' => $limitfrom,
457 'limitnum' => $limitnum
458 );
459 self::validate_parameters(self::data_for_messagearea_conversations_parameters(), $params);
460
461 self::validate_context(context_user::instance($userid));
462
463 $contacts = \core_message\api::get_conversations($userid, 0, $limitfrom, $limitnum);
464
465 $renderer = $PAGE->get_renderer('core_message');
466 return $contacts->export_for_template($renderer);
467 }
468
469 /**
470 * Get messagearea conversations returns.
471 *
472 * @return external_function_parameters
473 */
474 public static function data_for_messagearea_conversations_returns() {
475 return new external_function_parameters(
476 array(
477 'userid' => new external_value(PARAM_INT, 'The id of the user who we are viewing conversations for'),
9aa012b5
MN
478 'contacts' => new external_multiple_structure(
479 new external_single_structure(
480 array(
481 'userid' => new external_value(PARAM_INT, 'The user\'s id'),
482 'fullname' => new external_value(PARAM_NOTAGS, 'The user\'s name'),
483 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL'),
484 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL'),
485 'lastmessage' => new external_value(PARAM_NOTAGS, 'The user\'s last message', VALUE_OPTIONAL),
eda6bc19
RW
486 'isonline' => new external_value(PARAM_BOOL, 'The user\'s online status', VALUE_OPTIONAL),
487 'isread' => new external_value(PARAM_BOOL, 'If the user has read the message', VALUE_OPTIONAL),
9aa012b5
MN
488 )
489 )
490 )
491 )
492 );
493 }
494
495 /**
496 * Get messagearea contacts parameters.
497 *
498 * @return external_function_parameters
499 */
500 public static function data_for_messagearea_contacts_parameters() {
501 return self::data_for_messagearea_conversations_parameters();
502 }
503
504 /**
505 * Get messagearea contacts parameters.
506 *
507 * @param int $userid The id of the user who we are viewing conversations for
508 * @param int $limitfrom
509 * @param int $limitnum
510 * @return external_function_parameters
511 */
512 public static function data_for_messagearea_contacts($userid, $limitfrom = 0, $limitnum = 0) {
513 global $CFG, $PAGE;
514
515 // Check if messaging is enabled.
516 if (!$CFG->messaging) {
517 throw new moodle_exception('disabled', 'message');
518 }
519
520 $params = array(
521 'userid' => $userid,
522 'limitfrom' => $limitfrom,
523 'limitnum' => $limitnum
524 );
525 self::validate_parameters(self::data_for_messagearea_contacts_parameters(), $params);
526
527 self::validate_context(context_user::instance($userid));
528
529 $contacts = \core_message\api::get_contacts($userid, $limitfrom, $limitnum);
530
531 $renderer = $PAGE->get_renderer('core_message');
532 return $contacts->export_for_template($renderer);
533 }
534
535 /**
536 * Get messagearea contacts returns.
537 *
538 * @return external_function_parameters
539 */
540 public static function data_for_messagearea_contacts_returns() {
541 return self::data_for_messagearea_conversations_returns();
542 }
543
3cd13828
MN
544 /**
545 * Get messagearea messages parameters.
546 *
547 * @return external_function_parameters
548 */
549 public static function data_for_messagearea_messages_parameters() {
550 return new external_function_parameters(
551 array(
552 'currentuserid' => new external_value(PARAM_INT, 'The current user\'s id'),
553 'otheruserid' => new external_value(PARAM_INT, 'The other user\'s id'),
554 'limitfrom' => new external_value(PARAM_INT, 'Limit from', VALUE_DEFAULT, 0),
8ec78c48
MN
555 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 0),
556 'newest' => new external_value(PARAM_BOOL, 'Newest first?', VALUE_DEFAULT, false),
3cd13828
MN
557 )
558 );
559 }
560
561 /**
562 * Get messagearea messages.
563 *
564 * @param int $currentuserid The current user's id
565 * @param int $otheruserid The other user's id
566 * @param int $limitfrom
567 * @param int $limitnum
8ec78c48 568 * @param boolean $newest
3cd13828
MN
569 * @return external_description
570 */
8ec78c48 571 public static function data_for_messagearea_messages($currentuserid, $otheruserid, $limitfrom = 0, $limitnum = 0, $newest = false) {
3cd13828
MN
572 global $CFG, $PAGE;
573
574 // Check if messaging is enabled.
575 if (!$CFG->messaging) {
576 throw new moodle_exception('disabled', 'message');
577 }
578
579 $params = array(
580 'currentuserid' => $currentuserid,
581 'otheruserid' => $otheruserid,
582 'limitfrom' => $limitfrom,
8ec78c48
MN
583 'limitnum' => $limitnum,
584 'newest' => $newest
3cd13828
MN
585 );
586 self::validate_parameters(self::data_for_messagearea_messages_parameters(), $params);
587
588 self::validate_context(context_user::instance($currentuserid));
589
8ec78c48
MN
590 if ($newest) {
591 $sort = 'timecreated DESC';
592 } else {
593 $sort = 'timecreated ASC';
594 }
595 $messages = \core_message\api::get_messages($currentuserid, $otheruserid, $limitfrom, $limitnum, $sort);
3cd13828
MN
596
597 $renderer = $PAGE->get_renderer('core_message');
598 return $messages->export_for_template($renderer);
599 }
600
601 /**
602 * Get messagearea messages returns.
603 *
604 * @return external_description
605 */
606 public static function data_for_messagearea_messages_returns() {
607 return new external_function_parameters(
608 array(
609 'iscurrentuser' => new external_value(PARAM_BOOL, 'Is the currently logged in user the user we are viewing the messages on behalf of?'),
610 'currentuserid' => new external_value(PARAM_INT, 'The current user\'s id'),
611 'otheruserid' => new external_value(PARAM_INT, 'The other user\'s id'),
612 'otheruserfullname' => new external_value(PARAM_NOTAGS, 'The other user\'s fullname'),
613 'messages' => new external_multiple_structure(
614 new external_single_structure(
615 array(
3090f52f 616 'id' => new external_value(PARAM_INT, 'The id of the message'),
3cd13828 617 'text' => new external_value(PARAM_RAW, 'The text of the message'),
3090f52f 618 'displayblocktime' => new external_value(PARAM_BOOL, 'Should we display the block time?'),
3cd13828
MN
619 'blocktime' => new external_value(PARAM_NOTAGS, 'The time to display above the message'),
620 'position' => new external_value(PARAM_ALPHA, 'The position of the text'),
621 'timesent' => new external_value(PARAM_NOTAGS, 'The time the message was sent'),
3090f52f 622 'isread' => new external_value(PARAM_INT, 'Determines if the message was read or not'),
3cd13828
MN
623 )
624 )
625 )
626 )
627 );
628 }
629
c060cd49
MN
630 /**
631 * Get the most recent message in a conversation parameters.
632 *
633 * @return external_function_parameters
634 */
635 public static function data_for_messagearea_get_most_recent_message_parameters() {
636 return new external_function_parameters(
637 array(
638 'currentuserid' => new external_value(PARAM_INT, 'The current user\'s id'),
639 'otheruserid' => new external_value(PARAM_INT, 'The other user\'s id'),
640 )
641 );
642 }
643
644 /**
645 * Get the most recent message in a conversation.
646 *
647 * @param int $currentuserid The current user's id
648 * @param int $otheruserid The other user's id
649 * @return external_single_structure
650 */
651 public static function data_for_messagearea_get_most_recent_message($currentuserid, $otheruserid) {
652 global $CFG, $PAGE;
653
654 // Check if messaging is enabled.
655 if (!$CFG->messaging) {
656 throw new moodle_exception('disabled', 'message');
657 }
658
659 $params = array(
660 'currentuserid' => $currentuserid,
661 'otheruserid' => $otheruserid
662 );
663 self::validate_parameters(self::data_for_messagearea_get_most_recent_message_parameters(), $params);
664
665 self::validate_context(context_user::instance($currentuserid));
666
667 $message = \core_message\api::get_most_recent_message($currentuserid, $otheruserid);
668
669 $renderer = $PAGE->get_renderer('core_message');
670 return $message->export_for_template($renderer);
671 }
672
673 /**
674 * Get messagearea get most recent message returns.
675 *
676 * @return external_single_structure
677 */
678 public static function data_for_messagearea_get_most_recent_message_returns() {
679 return new external_single_structure(
680 array(
3090f52f 681 'id' => new external_value(PARAM_INT, 'The id of the message'),
c060cd49 682 'text' => new external_value(PARAM_RAW, 'The text of the message'),
3090f52f 683 'displayblocktime' => new external_value(PARAM_BOOL, 'Should we display the block time?'),
c060cd49
MN
684 'blocktime' => new external_value(PARAM_NOTAGS, 'The time to display above the message'),
685 'position' => new external_value(PARAM_ALPHA, 'The position of the text'),
686 'timesent' => new external_value(PARAM_NOTAGS, 'The time the message was sent'),
3090f52f 687 'isread' => new external_value(PARAM_INT, 'Determines if the message was read or not'),
c060cd49
MN
688 )
689 );
690 }
691
c6e97f54
MN
692 /**
693 * The get profile parameters.
694 *
695 * @return external_function_parameters
696 */
697 public static function data_for_messagearea_get_profile_parameters() {
698 return new external_function_parameters(
699 array(
700 'currentuserid' => new external_value(PARAM_INT, 'The current user\'s id'),
701 'otheruserid' => new external_value(PARAM_INT, 'The id of the user whose profile we want to view'),
702 )
703 );
704 }
705
706 /**
707 * Get the profile information for a contact.
708 *
709 * @param int $currentuserid The current user's id
710 * @param int $otheruserid The id of the user whose profile we are viewing
711 * @return external_single_structure
712 */
713 public static function data_for_messagearea_get_profile($currentuserid, $otheruserid) {
714 global $CFG, $PAGE;
715
716 // Check if messaging is enabled.
717 if (!$CFG->messaging) {
718 throw new moodle_exception('disabled', 'message');
719 }
720
721 $params = array(
722 'currentuserid' => $currentuserid,
723 'otheruserid' => $otheruserid
724 );
725 self::validate_parameters(self::data_for_messagearea_get_profile_parameters(), $params);
726
727 self::validate_context(context_user::instance($otheruserid));
728
729 $profile = \core_message\api::get_profile($currentuserid, $otheruserid);
730
731 $renderer = $PAGE->get_renderer('core_message');
732 return $profile->export_for_template($renderer);
733 }
734
735 /**
736 * Get profile returns.
737 *
738 * @return external_single_structure
739 */
740 public static function data_for_messagearea_get_profile_returns() {
741 return new external_single_structure(
742 array(
743 'iscurrentuser' => new external_value(PARAM_BOOL, 'Is the currently logged in user the user we are viewing the profile on behalf of?'),
744 'currentuserid' => new external_value(PARAM_INT, 'The current user\'s id'),
745 'otheruserid' => new external_value(PARAM_INT, 'The id of the user whose profile we are viewing'),
746 'email' => new external_value(core_user::get_property_type('email'), 'An email address'),
747 'country' => new external_value(core_user::get_property_type('country'), 'Home country code of the user'),
748 'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user'),
749 'fullname' => new external_value(PARAM_NOTAGS, 'The user\'s name'),
750 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL'),
751 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL'),
752 'isblocked' => new external_value(PARAM_BOOL, 'Is the user blocked?'),
753 'iscontact' => new external_value(PARAM_BOOL, 'Is the user a contact?')
754 )
755 );
756 }
757
d6731600
FM
758 /**
759 * Get contacts parameters description.
760 *
761 * @return external_function_parameters
5bcfd504 762 * @since Moodle 2.5
d6731600
FM
763 */
764 public static function get_contacts_parameters() {
765 return new external_function_parameters(array());
766 }
767
768 /**
769 * Get contacts.
770 *
771 * @param array $userids array of user IDs.
772 * @return external_description
5bcfd504 773 * @since Moodle 2.5
d6731600
FM
774 */
775 public static function get_contacts() {
d85bedf7 776 global $CFG, $PAGE;
436bbf89
DM
777
778 // Check if messaging is enabled.
779 if (!$CFG->messaging) {
780 throw new moodle_exception('disabled', 'message');
781 }
782
d6731600
FM
783 require_once($CFG->dirroot . '/user/lib.php');
784
785 list($online, $offline, $strangers) = message_get_contacts();
786 $allcontacts = array('online' => $online, 'offline' => $offline, 'strangers' => $strangers);
787 foreach ($allcontacts as $mode => $contacts) {
788 foreach ($contacts as $key => $contact) {
789 $newcontact = array(
790 'id' => $contact->id,
791 'fullname' => fullname($contact),
792 'unread' => $contact->messagecount
793 );
794
d85bedf7
JL
795 $userpicture = new user_picture($contact);
796 $userpicture->size = 1; // Size f1.
797 $newcontact['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
798 $userpicture->size = 0; // Size f2.
799 $newcontact['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
d6731600
FM
800
801 $allcontacts[$mode][$key] = $newcontact;
802 }
803 }
804 return $allcontacts;
805 }
806
807 /**
808 * Get contacts return description.
809 *
810 * @return external_description
5bcfd504 811 * @since Moodle 2.5
d6731600
FM
812 */
813 public static function get_contacts_returns() {
814 return new external_single_structure(
815 array(
816 'online' => new external_multiple_structure(
817 new external_single_structure(
818 array(
819 'id' => new external_value(PARAM_INT, 'User ID'),
820 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
821 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
822 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL),
823 'unread' => new external_value(PARAM_INT, 'Unread message count')
824 )
825 ),
826 'List of online contacts'
827 ),
828 'offline' => new external_multiple_structure(
829 new external_single_structure(
830 array(
831 'id' => new external_value(PARAM_INT, 'User ID'),
832 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
833 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
834 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL),
835 'unread' => new external_value(PARAM_INT, 'Unread message count')
836 )
837 ),
838 'List of offline contacts'
839 ),
840 'strangers' => new external_multiple_structure(
841 new external_single_structure(
842 array(
843 'id' => new external_value(PARAM_INT, 'User ID'),
844 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
845 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
846 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL),
847 'unread' => new external_value(PARAM_INT, 'Unread message count')
848 )
849 ),
850 'List of users that are not in the user\'s contact list but have sent a message'
851 )
852 )
853 );
854 }
855
856 /**
857 * Search contacts parameters description.
858 *
859 * @return external_function_parameters
5bcfd504 860 * @since Moodle 2.5
d6731600
FM
861 */
862 public static function search_contacts_parameters() {
863 return new external_function_parameters(
864 array(
865 'searchtext' => new external_value(PARAM_CLEAN, 'String the user\'s fullname has to match to be found'),
866 'onlymycourses' => new external_value(PARAM_BOOL, 'Limit search to the user\'s courses',
867 VALUE_DEFAULT, false)
868 )
869 );
870 }
871
872 /**
873 * Search contacts.
874 *
875 * @param string $searchtext query string.
876 * @param bool $onlymycourses limit the search to the user's courses only.
877 * @return external_description
5bcfd504 878 * @since Moodle 2.5
d6731600
FM
879 */
880 public static function search_contacts($searchtext, $onlymycourses = false) {
d85bedf7 881 global $CFG, $USER, $PAGE;
11d83ab3 882 require_once($CFG->dirroot . '/user/lib.php');
436bbf89
DM
883
884 // Check if messaging is enabled.
885 if (!$CFG->messaging) {
886 throw new moodle_exception('disabled', 'message');
887 }
888
d6731600
FM
889 require_once($CFG->libdir . '/enrollib.php');
890
891 $params = array('searchtext' => $searchtext, 'onlymycourses' => $onlymycourses);
892 $params = self::validate_parameters(self::search_contacts_parameters(), $params);
893
894 // Extra validation, we do not allow empty queries.
895 if ($params['searchtext'] === '') {
896 throw new moodle_exception('querystringcannotbeempty');
897 }
898
899 $courseids = array();
900 if ($params['onlymycourses']) {
901 $mycourses = enrol_get_my_courses(array('id'));
902 foreach ($mycourses as $mycourse) {
903 $courseids[] = $mycourse->id;
904 }
905 } else {
906 $courseids[] = SITEID;
907 }
908
909 // Retrieving the users matching the query.
910 $users = message_search_users($courseids, $params['searchtext']);
911 $results = array();
912 foreach ($users as $user) {
913 $results[$user->id] = $user;
914 }
915
916 // Reorganising information.
917 foreach ($results as &$user) {
918 $newuser = array(
919 'id' => $user->id,
920 'fullname' => fullname($user)
921 );
922
923 // Avoid undefined property notice as phone not specified.
924 $user->phone1 = null;
925 $user->phone2 = null;
926
d85bedf7
JL
927 $userpicture = new user_picture($user);
928 $userpicture->size = 1; // Size f1.
929 $newuser['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
930 $userpicture->size = 0; // Size f2.
931 $newuser['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
d6731600
FM
932
933 $user = $newuser;
934 }
935
936 return $results;
937 }
938
939 /**
940 * Search contacts return description.
941 *
942 * @return external_description
5bcfd504 943 * @since Moodle 2.5
d6731600
FM
944 */
945 public static function search_contacts_returns() {
946 return new external_multiple_structure(
947 new external_single_structure(
948 array(
949 'id' => new external_value(PARAM_INT, 'User ID'),
950 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
951 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
952 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL)
953 )
954 ),
955 'List of contacts'
956 );
957 }
aff9da17
JL
958
959 /**
960 * Get messages parameters description.
961 *
962 * @return external_function_parameters
193edf7f 963 * @since 2.8
aff9da17
JL
964 */
965 public static function get_messages_parameters() {
966 return new external_function_parameters(
967 array(
6ff4464b 968 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
127ef540
SH
969 'useridfrom' => new external_value(
970 PARAM_INT, 'the user id who send the message, 0 for any user. -10 or -20 for no-reply or support user',
971 VALUE_DEFAULT, 0),
972 'type' => new external_value(
973 PARAM_ALPHA, 'type of message to return, expected values are: notifications, conversations and both',
974 VALUE_DEFAULT, 'both'),
6ff4464b 975 'read' => new external_value(PARAM_BOOL, 'true for getting read messages, false for unread', VALUE_DEFAULT, true),
127ef540
SH
976 'newestfirst' => new external_value(
977 PARAM_BOOL, 'true for ordering by newest first, false for oldest first',
978 VALUE_DEFAULT, true),
aff9da17 979 'limitfrom' => new external_value(PARAM_INT, 'limit from', VALUE_DEFAULT, 0),
127ef540
SH
980 'limitnum' => new external_value(PARAM_INT, 'limit number', VALUE_DEFAULT, 0)
981 )
aff9da17
JL
982 );
983 }
984
985 /**
986 * Get messages function implementation.
127ef540
SH
987 *
988 * @since 2.8
989 * @throws invalid_parameter_exception
990 * @throws moodle_exception
6ff4464b
JL
991 * @param int $useridto the user id who received the message
992 * @param int $useridfrom the user id who send the message. -10 or -20 for no-reply or support user
193edf7f 993 * @param string $type type of message to return, expected values: notifications, conversations and both
aff9da17 994 * @param bool $read true for retreiving read messages, false for unread
6ff4464b 995 * @param bool $newestfirst true for ordering by newest first, false for oldest first
aff9da17
JL
996 * @param int $limitfrom limit from
997 * @param int $limitnum limit num
998 * @return external_description
aff9da17 999 */
193edf7f 1000 public static function get_messages($useridto, $useridfrom = 0, $type = 'both', $read = true,
aff9da17 1001 $newestfirst = true, $limitfrom = 0, $limitnum = 0) {
127ef540 1002 global $CFG, $USER;
aff9da17
JL
1003
1004 $warnings = array();
1005
1006 $params = array(
1007 'useridto' => $useridto,
6ff4464b 1008 'useridfrom' => $useridfrom,
aff9da17
JL
1009 'type' => $type,
1010 'read' => $read,
aff9da17
JL
1011 'newestfirst' => $newestfirst,
1012 'limitfrom' => $limitfrom,
1013 'limitnum' => $limitnum
1014 );
1015
1016 $params = self::validate_parameters(self::get_messages_parameters(), $params);
1017
1018 $context = context_system::instance();
1019 self::validate_context($context);
1020
1021 $useridto = $params['useridto'];
6ff4464b 1022 $useridfrom = $params['useridfrom'];
aff9da17
JL
1023 $type = $params['type'];
1024 $read = $params['read'];
aff9da17
JL
1025 $newestfirst = $params['newestfirst'];
1026 $limitfrom = $params['limitfrom'];
1027 $limitnum = $params['limitnum'];
1028
1029 $allowedvalues = array('notifications', 'conversations', 'both');
1030 if (!in_array($type, $allowedvalues)) {
1031 throw new invalid_parameter_exception('Invalid value for type parameter (value: ' . $type . '),' .
1032 'allowed values are: ' . implode(',', $allowedvalues));
1033 }
1034
1035 // Check if private messaging between users is allowed.
1036 if (empty($CFG->messaging)) {
1037 // If we are retreiving only conversations, and messaging is disabled, throw an exception.
aff9da17
JL
1038 if ($type == "conversations") {
1039 throw new moodle_exception('disabled', 'message');
1040 }
1041 if ($type == "both") {
1042 $warning = array();
1043 $warning['item'] = 'message';
1044 $warning['itemid'] = $USER->id;
1045 $warning['warningcode'] = '1';
1046 $warning['message'] = 'Private messages (conversations) are not enabled in this site.
1047 Only notifications will be returned';
1048 $warnings[] = $warning;
1049 }
1050 }
1051
1052 if (!empty($useridto)) {
6ff4464b
JL
1053 if (core_user::is_real_user($useridto)) {
1054 $userto = core_user::get_user($useridto, '*', MUST_EXIST);
1055 } else {
1056 throw new moodle_exception('invaliduser');
1057 }
aff9da17
JL
1058 }
1059
1060 if (!empty($useridfrom)) {
1061 // We use get_user here because the from user can be the noreply or support user.
1062 $userfrom = core_user::get_user($useridfrom, '*', MUST_EXIST);
1063 }
1064
1065 // Check if the current user is the sender/receiver or just a privileged user.
1066 if ($useridto != $USER->id and $useridfrom != $USER->id and
1067 !has_capability('moodle/site:readallmessages', $context)) {
1068 throw new moodle_exception('accessdenied', 'admin');
1069 }
1070
127ef540 1071 // Which type of messages to retrieve.
193edf7f 1072 $notifications = -1;
aff9da17 1073 if ($type != 'both') {
193edf7f 1074 $notifications = ($type == 'notifications') ? 1 : 0;
aff9da17
JL
1075 }
1076
aff9da17 1077 $orderdirection = $newestfirst ? 'DESC' : 'ASC';
193edf7f 1078 $sort = "mr.timecreated $orderdirection";
aff9da17 1079
193edf7f 1080 if ($messages = message_get_messages($useridto, $useridfrom, $notifications, $read, $sort, $limitfrom, $limitnum)) {
aff9da17
JL
1081 $canviewfullname = has_capability('moodle/site:viewfullnames', $context);
1082
1083 // In some cases, we don't need to get the to/from user objects from the sql query.
1084 $userfromfullname = '';
1085 $usertofullname = '';
1086
1087 // In this case, the useridto field is not empty, so we can get the user destinatary fullname from there.
1088 if (!empty($useridto)) {
1089 $usertofullname = fullname($userto, $canviewfullname);
1090 // The user from may or may not be filled.
1091 if (!empty($useridfrom)) {
1092 $userfromfullname = fullname($userfrom, $canviewfullname);
1093 }
1094 } else {
1095 // If the useridto field is empty, the useridfrom must be filled.
1096 $userfromfullname = fullname($userfrom, $canviewfullname);
1097 }
aff9da17
JL
1098 foreach ($messages as $mid => $message) {
1099
ea21d637
JL
1100 // Do not return deleted messages.
1101 if (($useridto == $USER->id and $message->timeusertodeleted) or
1102 ($useridfrom == $USER->id and $message->timeuserfromdeleted)) {
1103
1104 unset($messages[$mid]);
1105 continue;
1106 }
1107
aff9da17
JL
1108 // We need to get the user from the query.
1109 if (empty($userfromfullname)) {
6ff4464b
JL
1110 // Check for non-reply and support users.
1111 if (core_user::is_real_user($message->useridfrom)) {
127ef540 1112 $user = new stdClass();
6ff4464b
JL
1113 $user = username_load_fields_from_object($user, $message, 'userfrom');
1114 $message->userfromfullname = fullname($user, $canviewfullname);
1115 } else {
1116 $user = core_user::get_user($message->useridfrom);
1117 $message->userfromfullname = fullname($user, $canviewfullname);
1118 }
aff9da17
JL
1119 } else {
1120 $message->userfromfullname = $userfromfullname;
1121 }
1122
1123 // We need to get the user from the query.
1124 if (empty($usertofullname)) {
127ef540 1125 $user = new stdClass();
aff9da17
JL
1126 $user = username_load_fields_from_object($user, $message, 'userto');
1127 $message->usertofullname = fullname($user, $canviewfullname);
1128 } else {
1129 $message->usertofullname = $usertofullname;
1130 }
1131
193edf7f 1132 // This field is only available in the message_read table.
aff9da17
JL
1133 if (!isset($message->timeread)) {
1134 $message->timeread = 0;
1135 }
1136
aff9da17 1137 $message->text = message_format_message_text($message);
aff9da17
JL
1138 $messages[$mid] = (array) $message;
1139 }
1140 }
1141
1142 $results = array(
1143 'messages' => $messages,
1144 'warnings' => $warnings
1145 );
1146
1147 return $results;
1148 }
1149
1150 /**
1151 * Get messages return description.
1152 *
6ff4464b 1153 * @return external_single_structure
193edf7f 1154 * @since 2.8
aff9da17
JL
1155 */
1156 public static function get_messages_returns() {
1157 return new external_single_structure(
1158 array(
1159 'messages' => new external_multiple_structure(
1160 new external_single_structure(
1161 array(
193edf7f 1162 'id' => new external_value(PARAM_INT, 'Message id'),
aff9da17
JL
1163 'useridfrom' => new external_value(PARAM_INT, 'User from id'),
1164 'useridto' => new external_value(PARAM_INT, 'User to id'),
1165 'subject' => new external_value(PARAM_TEXT, 'The message subject'),
1166 'text' => new external_value(PARAM_RAW, 'The message text formated'),
1167 'fullmessage' => new external_value(PARAM_RAW, 'The message'),
193edf7f 1168 'fullmessageformat' => new external_format_value('fullmessage'),
aff9da17
JL
1169 'fullmessagehtml' => new external_value(PARAM_RAW, 'The message in html'),
1170 'smallmessage' => new external_value(PARAM_RAW, 'The shorten message'),
1171 'notification' => new external_value(PARAM_INT, 'Is a notification?'),
1172 'contexturl' => new external_value(PARAM_RAW, 'Context URL'),
1173 'contexturlname' => new external_value(PARAM_TEXT, 'Context URL link name'),
1174 'timecreated' => new external_value(PARAM_INT, 'Time created'),
1175 'timeread' => new external_value(PARAM_INT, 'Time read'),
1176 'usertofullname' => new external_value(PARAM_TEXT, 'User to full name'),
1177 'userfromfullname' => new external_value(PARAM_TEXT, 'User from full name')
1178 ), 'message'
1179 )
1180 ),
1181 'warnings' => new external_warnings()
1182 )
1183 );
3274d5ca
RW
1184 }
1185
1186 /**
ada7695d 1187 * Get popup notifications parameters description.
3274d5ca
RW
1188 *
1189 * @return external_function_parameters
1190 * @since 3.2
1191 */
ada7695d 1192 public static function get_popup_notifications_parameters() {
3274d5ca
RW
1193 return new external_function_parameters(
1194 array(
1195 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
3274d5ca
RW
1196 'status' => new external_value(
1197 PARAM_ALPHA, 'filter the results to just "read" or "unread" notifications',
1198 VALUE_DEFAULT, ''),
c5dd16a1
RW
1199 'embedpreference' => new external_value(
1200 PARAM_BOOL, 'true for returning user\'s preference for the notification',
1201 VALUE_DEFAULT, false),
3274d5ca
RW
1202 'embeduserto' => new external_value(
1203 PARAM_BOOL, 'true for returning user details for the recipient in each notification',
1204 VALUE_DEFAULT, false),
1205 'embeduserfrom' => new external_value(
1206 PARAM_BOOL, 'true for returning user details for the sender in each notification',
1207 VALUE_DEFAULT, false),
1208 'newestfirst' => new external_value(
1209 PARAM_BOOL, 'true for ordering by newest first, false for oldest first',
1210 VALUE_DEFAULT, true),
1211 'markasread' => new external_value(
1212 PARAM_BOOL, 'mark notifications as read when they are returned by this function',
1213 VALUE_DEFAULT, false),
1214 'limit' => new external_value(PARAM_INT, 'the number of results to return', VALUE_DEFAULT, 0),
1215 'offset' => new external_value(PARAM_INT, 'offset the result set by a given amount', VALUE_DEFAULT, 0)
1216 )
1217 );
1218 }
1219
1220 /**
1221 * Get notifications function.
1222 *
1223 * @since 3.2
1224 * @throws invalid_parameter_exception
1225 * @throws moodle_exception
c5dd16a1 1226 * @param int $useridto the user id who received the message
c5dd16a1
RW
1227 * @param string $status filter the results to only read or unread notifications
1228 * @param bool $embedpreference true to embed the recipient user details in the record for each notification
1229 * @param bool $embeduserto true to embed the recipient user details in the record for each notification
1230 * @param bool $embeduserfrom true to embed the send user details in the record for each notification
1231 * @param bool $newestfirst true for ordering by newest first, false for oldest first
1232 * @param bool $markasread mark notifications as read when they are returned by this function
1233 * @param int $limit the number of results to return
1234 * @param int $offset offset the result set by a given amount
3274d5ca
RW
1235 * @return external_description
1236 */
ada7695d 1237 public static function get_popup_notifications($useridto, $status, $embedpreference,
c5dd16a1 1238 $embeduserto, $embeduserfrom, $newestfirst, $markasread, $limit, $offset) {
24a76780 1239 global $CFG, $USER, $PAGE;
3274d5ca
RW
1240
1241 $params = self::validate_parameters(
ada7695d 1242 self::get_popup_notifications_parameters(),
3274d5ca
RW
1243 array(
1244 'useridto' => $useridto,
3274d5ca 1245 'status' => $status,
c5dd16a1 1246 'embedpreference' => $embedpreference,
3274d5ca
RW
1247 'embeduserto' => $embeduserto,
1248 'embeduserfrom' => $embeduserfrom,
1249 'newestfirst' => $newestfirst,
1250 'markasread' => $markasread,
1251 'limit' => $limit,
1252 'offset' => $offset,
1253 )
1254 );
1255
1256 $context = context_system::instance();
1257 self::validate_context($context);
1258
1259 $useridto = $params['useridto'];
3274d5ca 1260 $status = $params['status'];
c5dd16a1 1261 $embedpreference = $params['embedpreference'];
3274d5ca
RW
1262 $embeduserto = $params['embeduserto'];
1263 $embeduserfrom = $params['embeduserfrom'];
1264 $newestfirst = $params['newestfirst'];
1265 $markasread = $params['markasread'];
1266 $limit = $params['limit'];
1267 $offset = $params['offset'];
c5dd16a1 1268 $issuperuser = has_capability('moodle/site:readallmessages', $context);
24a76780 1269 $renderer = $PAGE->get_renderer('core_message');
3274d5ca
RW
1270
1271 if (!empty($useridto)) {
1272 if (core_user::is_real_user($useridto)) {
1273 if ($embeduserto) {
1274 $userto = core_user::get_user($useridto, '*', MUST_EXIST);
1275 }
1276 } else {
1277 throw new moodle_exception('invaliduser');
1278 }
1279 }
1280
3274d5ca 1281 // Check if the current user is the sender/receiver or just a privileged user.
ada7695d 1282 if ($useridto != $USER->id and !$issuperuser) {
3274d5ca
RW
1283 throw new moodle_exception('accessdenied', 'admin');
1284 }
1285
1286 $sort = $newestfirst ? 'DESC' : 'ASC';
ada7695d 1287 $notifications = message_get_popup_notifications($useridto, $status, $embeduserto, $embeduserfrom, $sort, $limit, $offset);
24a76780 1288 $notificationcontexts = [];
3274d5ca
RW
1289
1290 if ($notifications) {
ada7695d 1291 // In some cases, we don't need to get the to user objects from the sql query.
3274d5ca
RW
1292 $usertofullname = '';
1293
1294 // In this case, the useridto field is not empty, so we can get the user destinatary fullname from there.
1295 if (!empty($useridto) && $embeduserto) {
1296 $usertofullname = fullname($userto);
3274d5ca
RW
1297 }
1298
1299 foreach ($notifications as $notification) {
1300
24a76780
RW
1301 $notificationoutput = new \core_message\output\popup_notification($notification, $embeduserto,
1302 $embeduserfrom, $embedpreference, $usertofullname);
3274d5ca 1303
24a76780
RW
1304 $notificationcontext = $notificationoutput->export_for_template($renderer);
1305 $notificationcontexts[] = $notificationcontext;
c5dd16a1 1306
24a76780
RW
1307 if ($markasread && !$notificationcontext->read) {
1308 message_mark_message_read($notification, time());
3274d5ca
RW
1309 }
1310 }
1311 }
1312
1313 return array(
24a76780 1314 'notifications' => $notificationcontexts,
ada7695d 1315 'unreadcount' => message_count_unread_popup_notifications($useridto),
3274d5ca
RW
1316 );
1317 }
1318
1319 /**
1320 * Get notifications return description.
1321 *
1322 * @return external_single_structure
1323 * @since 3.2
1324 */
ada7695d 1325 public static function get_popup_notifications_returns() {
3274d5ca
RW
1326 return new external_single_structure(
1327 array(
1328 'notifications' => new external_multiple_structure(
1329 new external_single_structure(
1330 array(
1331 'id' => new external_value(PARAM_INT, 'Notification id (this is not guaranteed to be unique within this result set)'),
1332 'useridfrom' => new external_value(PARAM_INT, 'User from id'),
1333 'useridto' => new external_value(PARAM_INT, 'User to id'),
1334 'subject' => new external_value(PARAM_TEXT, 'The notification subject'),
1335 'text' => new external_value(PARAM_RAW, 'The message text formated'),
1336 'fullmessage' => new external_value(PARAM_RAW, 'The message'),
1337 'fullmessageformat' => new external_format_value('fullmessage'),
1338 'fullmessagehtml' => new external_value(PARAM_RAW, 'The message in html'),
1339 'smallmessage' => new external_value(PARAM_RAW, 'The shorten message'),
1340 'contexturl' => new external_value(PARAM_RAW, 'Context URL'),
1341 'contexturlname' => new external_value(PARAM_TEXT, 'Context URL link name'),
1342 'timecreated' => new external_value(PARAM_INT, 'Time created'),
1343 'timecreatedpretty' => new external_value(PARAM_TEXT, 'Time created in a pretty format'),
1344 'timeread' => new external_value(PARAM_INT, 'Time read'),
1345 'usertofullname' => new external_value(PARAM_TEXT, 'User to full name', VALUE_OPTIONAL),
1346 'userfromfullname' => new external_value(PARAM_TEXT, 'User from full name', VALUE_OPTIONAL),
1347 'userfromprofileurl' => new external_value(PARAM_URL, 'User from profile url', VALUE_OPTIONAL),
1348 'read' => new external_value(PARAM_BOOL, 'notification read status'),
1349 'deleted' => new external_value(PARAM_BOOL, 'notification deletion status'),
1350 'iconurl' => new external_value(PARAM_URL, 'URL for notification icon'),
1351 'component' => new external_value(PARAM_TEXT, 'The component that generated the notification', VALUE_OPTIONAL),
1352 'eventtype' => new external_value(PARAM_TEXT, 'The type of notification', VALUE_OPTIONAL),
c5dd16a1
RW
1353 'preference' => new external_single_structure(
1354 array (
1355 'key' => new external_value(PARAM_TEXT, 'The preference key'),
1356 'loggedin' => new external_value(PARAM_TEXT, 'The logged in preference setting'),
1357 'loggedoff' => new external_value(PARAM_TEXT, 'The logged off preference setting'),
1358 ),
1359 'The preference configuration',
1360 VALUE_OPTIONAL
1361 ),
3274d5ca
RW
1362 ), 'message'
1363 )
1364 ),
1365 'unreadcount' => new external_value(PARAM_INT, 'the user whose blocked users we want to retrieve'),
1366 )
1367 );
1368 }
1369
1370 /**
1371 * Mark all notifications as read parameters description.
1372 *
1373 * @return external_function_parameters
1374 * @since 3.2
1375 */
1376 public static function mark_all_notifications_as_read_parameters() {
1377 return new external_function_parameters(
1378 array(
1379 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
1380 'useridfrom' => new external_value(
1381 PARAM_INT, 'the user id who send the message, 0 for any user. -10 or -20 for no-reply or support user',
1382 VALUE_DEFAULT, 0),
1383 )
1384 );
1385 }
1386
1387 /**
1388 * Mark all notifications as read function.
1389 *
1390 * @since 3.2
1391 * @throws invalid_parameter_exception
1392 * @throws moodle_exception
1393 * @param int $useridto the user id who received the message
1394 * @param int $useridfrom the user id who send the message. -10 or -20 for no-reply or support user
1395 * @return external_description
1396 */
1397 public static function mark_all_notifications_as_read($useridto, $useridfrom) {
1398 global $CFG, $USER;
1399
1400 $params = self::validate_parameters(
1401 self::mark_all_notifications_as_read_parameters(),
1402 array(
1403 'useridto' => $useridto,
1404 'useridfrom' => $useridfrom,
1405 )
1406 );
1407
1408 $context = context_system::instance();
1409 self::validate_context($context);
1410
1411 $useridto = $params['useridto'];
1412 $useridfrom = $params['useridfrom'];
1413
1414 if (!empty($useridto)) {
1415 if (core_user::is_real_user($useridto)) {
1416 $userto = core_user::get_user($useridto, '*', MUST_EXIST);
1417 } else {
1418 throw new moodle_exception('invaliduser');
1419 }
1420 }
1421
1422 if (!empty($useridfrom)) {
1423 // We use get_user here because the from user can be the noreply or support user.
1424 $userfrom = core_user::get_user($useridfrom, '*', MUST_EXIST);
1425 }
1426
1427 // Check if the current user is the sender/receiver or just a privileged user.
1428 if ($useridto != $USER->id and $useridfrom != $USER->id and
1429 // deleteanymessage seems more reasonable here than readallmessages.
1430 !has_capability('moodle/site:deleteanymessage', $context)) {
1431 throw new moodle_exception('accessdenied', 'admin');
1432 }
1433
8c55bd6c 1434 message_mark_all_read_for_user($useridto, $useridfrom, MESSAGE_TYPE_NOTIFICATION);
3274d5ca
RW
1435
1436 return true;
1437 }
1438
1439 /**
1440 * Mark all notifications as read return description.
1441 *
1442 * @return external_single_structure
1443 * @since 3.2
1444 */
1445 public static function mark_all_notifications_as_read_returns() {
1446 return new external_value(PARAM_BOOL, 'True if the messages were marked read, false otherwise');
1447 }
1448
1449 /**
1450 * Get unread notification count parameters description.
1451 *
1452 * @return external_function_parameters
1453 * @since 3.2
1454 */
ada7695d 1455 public static function get_unread_popup_notification_count_parameters() {
3274d5ca
RW
1456 return new external_function_parameters(
1457 array(
1458 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
3274d5ca
RW
1459 )
1460 );
1461 }
1462
1463 /**
1464 * Get unread notification count function.
1465 *
1466 * @since 3.2
1467 * @throws invalid_parameter_exception
1468 * @throws moodle_exception
1469 * @param int $useridto the user id who received the message
3274d5ca
RW
1470 * @return external_description
1471 */
ada7695d 1472 public static function get_unread_popup_notification_count($useridto) {
3274d5ca
RW
1473 global $CFG, $USER;
1474
1475 $params = self::validate_parameters(
ada7695d
RW
1476 self::get_unread_popup_notification_count_parameters(),
1477 array('useridto' => $useridto)
3274d5ca
RW
1478 );
1479
1480 $context = context_system::instance();
1481 self::validate_context($context);
1482
1483 $useridto = $params['useridto'];
3274d5ca
RW
1484
1485 if (!empty($useridto)) {
1486 if (core_user::is_real_user($useridto)) {
1487 $userto = core_user::get_user($useridto, '*', MUST_EXIST);
1488 } else {
1489 throw new moodle_exception('invaliduser');
1490 }
1491 }
1492
3274d5ca 1493 // Check if the current user is the sender/receiver or just a privileged user.
ada7695d 1494 if ($useridto != $USER->id and !has_capability('moodle/site:readallmessages', $context)) {
3274d5ca
RW
1495 throw new moodle_exception('accessdenied', 'admin');
1496 }
1497
ada7695d 1498 return message_count_unread_popup_notifications($useridto);
3274d5ca
RW
1499 }
1500
1501 /**
ada7695d 1502 * Get unread popup notification count return description.
3274d5ca
RW
1503 *
1504 * @return external_single_structure
1505 * @since 3.2
1506 */
ada7695d 1507 public static function get_unread_popup_notification_count_returns() {
8c55bd6c
RW
1508 return new external_value(PARAM_INT, 'The count of unread popup notifications');
1509 }
1510
1511 /**
1512 * Get unread conversations count parameters description.
1513 *
1514 * @return external_function_parameters
1515 * @since 3.2
1516 */
1517 public static function get_unread_conversations_count_parameters() {
1518 return new external_function_parameters(
1519 array(
1520 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
1521 )
1522 );
1523 }
1524
1525 /**
1526 * Get unread messages count function.
1527 *
1528 * @since 3.2
1529 * @throws invalid_parameter_exception
1530 * @throws moodle_exception
1531 * @param int $useridto the user id who received the message
1532 * @return external_description
1533 */
1534 public static function get_unread_conversations_count($useridto) {
1535 global $USER;
1536
1537 $params = self::validate_parameters(
1538 self::get_unread_conversations_count_parameters(),
1539 array('useridto' => $useridto)
1540 );
1541
1542 $context = context_system::instance();
1543 self::validate_context($context);
1544
1545 $useridto = $params['useridto'];
1546
1547 if (!empty($useridto)) {
1548 if (core_user::is_real_user($useridto)) {
1549 $userto = core_user::get_user($useridto, '*', MUST_EXIST);
1550 } else {
1551 throw new moodle_exception('invaliduser');
1552 }
1553 } else {
1554 $useridto = $USER->id;
1555 }
1556
1557 // Check if the current user is the receiver or just a privileged user.
1558 if ($useridto != $USER->id and !has_capability('moodle/site:readallmessages', $context)) {
1559 throw new moodle_exception('accessdenied', 'admin');
1560 }
1561
1562 return message_count_unread_conversations($userto);
1563 }
1564
1565 /**
1566 * Get unread conversations count return description.
1567 *
1568 * @return external_single_structure
1569 * @since 3.2
1570 */
1571 public static function get_unread_conversations_count_returns() {
1572 return new external_value(PARAM_INT, 'The count of unread messages for the user');
aff9da17
JL
1573 }
1574
60ab2e1b
JL
1575 /**
1576 * Get blocked users parameters description.
1577 *
1578 * @return external_function_parameters
1579 * @since 2.9
1580 */
1581 public static function get_blocked_users_parameters() {
1582 return new external_function_parameters(
1583 array(
1584 'userid' => new external_value(PARAM_INT,
1585 'the user whose blocked users we want to retrieve',
1586 VALUE_REQUIRED),
1587 )
1588 );
1589 }
1590
1591 /**
1592 * Retrieve a list of users blocked
1593 *
1594 * @param int $userid the user whose blocked users we want to retrieve
1595 * @return external_description
1596 * @since 2.9
1597 */
1598 public static function get_blocked_users($userid) {
d85bedf7 1599 global $CFG, $USER, $PAGE;
60ab2e1b
JL
1600
1601 // Warnings array, it can be empty at the end but is mandatory.
1602 $warnings = array();
1603
1604 // Validate params.
1605 $params = array(
1606 'userid' => $userid
1607 );
1608 $params = self::validate_parameters(self::get_blocked_users_parameters(), $params);
1609 $userid = $params['userid'];
1610
1611 // Validate context.
1612 $context = context_system::instance();
1613 self::validate_context($context);
1614
1615 // Check if private messaging between users is allowed.
1616 if (empty($CFG->messaging)) {
1617 throw new moodle_exception('disabled', 'message');
1618 }
1619
4485f7c5
JL
1620 $user = core_user::get_user($userid, '*', MUST_EXIST);
1621 core_user::require_active_user($user);
60ab2e1b
JL
1622
1623 // Check if we have permissions for retrieve the information.
1624 if ($userid != $USER->id and !has_capability('moodle/site:readallmessages', $context)) {
1625 throw new moodle_exception('accessdenied', 'admin');
1626 }
1627
1628 // Now, we can get safely all the blocked users.
1629 $users = message_get_blocked_users($user);
1630
1631 $blockedusers = array();
1632 foreach ($users as $user) {
1633 $newuser = array(
1634 'id' => $user->id,
1635 'fullname' => fullname($user),
1636 );
0b074e88 1637
d85bedf7
JL
1638 $userpicture = new user_picture($user);
1639 $userpicture->size = 1; // Size f1.
1640 $newuser['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
60ab2e1b
JL
1641
1642 $blockedusers[] = $newuser;
1643 }
1644
1645 $results = array(
1646 'users' => $blockedusers,
1647 'warnings' => $warnings
1648 );
1649 return $results;
1650 }
1651
1652 /**
1653 * Get blocked users return description.
1654 *
1655 * @return external_single_structure
1656 * @since 2.9
1657 */
1658 public static function get_blocked_users_returns() {
1659 return new external_single_structure(
1660 array(
1661 'users' => new external_multiple_structure(
1662 new external_single_structure(
1663 array(
1664 'id' => new external_value(PARAM_INT, 'User ID'),
1665 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
1666 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL)
1667 )
1668 ),
1669 'List of blocked users'
1670 ),
1671 'warnings' => new external_warnings()
1672 )
1673 );
1674 }
1675
31c474da
JL
1676 /**
1677 * Returns description of method parameters
1678 *
1679 * @return external_function_parameters
1680 * @since 2.9
1681 */
1682 public static function mark_message_read_parameters() {
1683 return new external_function_parameters(
1684 array(
1685 'messageid' => new external_value(PARAM_INT, 'id of the message (in the message table)'),
1686 'timeread' => new external_value(PARAM_INT, 'timestamp for when the message should be marked read')
1687 )
1688 );
1689 }
1690
1691 /**
1692 * Mark a single message as read, trigger message_viewed event
1693 *
1694 * @param int $messageid id of the message (in the message table)
1695 * @param int $timeread timestamp for when the message should be marked read
1696 * @return external_description
1697 * @throws invalid_parameter_exception
1698 * @throws moodle_exception
1699 * @since 2.9
1700 */
1701 public static function mark_message_read($messageid, $timeread) {
1702 global $CFG, $DB, $USER;
31c474da
JL
1703
1704 // Check if private messaging between users is allowed.
1705 if (empty($CFG->messaging)) {
1706 throw new moodle_exception('disabled', 'message');
1707 }
1708
1709 // Warnings array, it can be empty at the end but is mandatory.
1710 $warnings = array();
1711
1712 // Validate params.
1713 $params = array(
1714 'messageid' => $messageid,
1715 'timeread' => $timeread
1716 );
1717 $params = self::validate_parameters(self::mark_message_read_parameters(), $params);
1718
1719 // Validate context.
1720 $context = context_system::instance();
1721 self::validate_context($context);
1722
1723 $message = $DB->get_record('message', array('id' => $params['messageid']), '*', MUST_EXIST);
1724
1725 if ($message->useridto != $USER->id) {
1726 throw new invalid_parameter_exception('Invalid messageid, you don\'t have permissions to mark this message as read');
1727 }
1728
1729 $messageid = message_mark_message_read($message, $params['timeread']);
1730
1731 $results = array(
1732 'messageid' => $messageid,
1733 'warnings' => $warnings
1734 );
1735 return $results;
1736 }
1737
1738 /**
1739 * Returns description of method result value
1740 *
1741 * @return external_description
1742 * @since 2.9
1743 */
1744 public static function mark_message_read_returns() {
1745 return new external_single_structure(
1746 array(
1747 'messageid' => new external_value(PARAM_INT, 'the id of the message in the message_read table'),
1748 'warnings' => new external_warnings()
1749 )
1750 );
1751 }
1752
8c55bd6c
RW
1753 /**
1754 * Mark all messages as read parameters description.
1755 *
1756 * @return external_function_parameters
1757 * @since 3.2
1758 */
1759 public static function mark_all_messages_as_read_parameters() {
1760 return new external_function_parameters(
1761 array(
1762 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
1763 'useridfrom' => new external_value(
1764 PARAM_INT, 'the user id who send the message, 0 for any user. -10 or -20 for no-reply or support user',
1765 VALUE_DEFAULT, 0),
1766 )
1767 );
1768 }
1769
1770 /**
1771 * Mark all notifications as read function.
1772 *
1773 * @since 3.2
1774 * @throws invalid_parameter_exception
1775 * @throws moodle_exception
1776 * @param int $useridto the user id who received the message
1777 * @param int $useridfrom the user id who send the message. -10 or -20 for no-reply or support user
1778 * @return external_description
1779 */
1780 public static function mark_all_messages_as_read($useridto, $useridfrom) {
1781 global $CFG, $USER;
1782
1783 $params = self::validate_parameters(
1784 self::mark_all_messages_as_read_parameters(),
1785 array(
1786 'useridto' => $useridto,
1787 'useridfrom' => $useridfrom,
1788 )
1789 );
1790
1791 $context = context_system::instance();
1792 self::validate_context($context);
1793
1794 $useridto = $params['useridto'];
1795 $useridfrom = $params['useridfrom'];
1796
1797 if (!empty($useridto)) {
1798 if (core_user::is_real_user($useridto)) {
1799 $userto = core_user::get_user($useridto, '*', MUST_EXIST);
1800 } else {
1801 throw new moodle_exception('invaliduser');
1802 }
1803 }
1804
1805 if (!empty($useridfrom)) {
1806 // We use get_user here because the from user can be the noreply or support user.
1807 $userfrom = core_user::get_user($useridfrom, '*', MUST_EXIST);
1808 }
1809
1810 // Check if the current user is the sender/receiver or just a privileged user.
1811 if ($useridto != $USER->id and $useridfrom != $USER->id and
1812 // deleteanymessage seems more reasonable here than readallmessages.
1813 !has_capability('moodle/site:deleteanymessage', $context)) {
1814 throw new moodle_exception('accessdenied', 'admin');
1815 }
1816
1817 message_mark_all_read_for_user($useridto, $useridfrom, MESSAGE_TYPE_MESSAGE);
1818
1819 return true;
1820 }
1821
1822 /**
1823 * Mark all notifications as read return description.
1824 *
1825 * @return external_single_structure
1826 * @since 3.2
1827 */
1828 public static function mark_all_messages_as_read_returns() {
1829 return new external_value(PARAM_BOOL, 'True if the messages were marked read, false otherwise');
1830 }
1831
dec0cd99
MN
1832 /**
1833 * Returns description of method parameters.
1834 *
1835 * @return external_function_parameters
1836 * @since 3.2
1837 */
1838 public static function delete_conversation_parameters() {
1839 return new external_function_parameters(
1840 array(
1841 'userid' => new external_value(PARAM_INT, 'The user id of who we want to delete the conversation for'),
1842 'otheruserid' => new external_value(PARAM_INT, 'The user id of the other user in the conversation'),
1843 )
1844 );
1845 }
1846
1847 /**
1848 * Deletes a conversation.
1849 *
1850 * @param int $userid The user id of who we want to delete the conversation for
1851 * @param int $otheruserid The user id of the other user in the conversation
1852 * @return array
1853 * @throws moodle_exception
1854 * @since 3.2
1855 */
1856 public static function delete_conversation($userid, $otheruserid) {
1857 global $CFG;
1858
1859 // Check if private messaging between users is allowed.
1860 if (empty($CFG->messaging)) {
1861 throw new moodle_exception('disabled', 'message');
1862 }
1863
1864 // Warnings array, it can be empty at the end but is mandatory.
1865 $warnings = array();
1866
1867 // Validate params.
1868 $params = array(
1869 'userid' => $userid,
1870 'otheruserid' => $otheruserid,
1871 );
1872 $params = self::validate_parameters(self::delete_conversation_parameters(), $params);
1873
1874 // Validate context.
1875 $context = context_system::instance();
1876 self::validate_context($context);
1877
1878 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1879 core_user::require_active_user($user);
1880
1881 if (\core_message\api::can_delete_conversation($user->id)) {
1882 $status = \core_message\api::delete_conversation($user->id, $otheruserid);
1883 } else {
1884 throw new moodle_exception('You do not have permission to delete messages');
1885 }
1886
1887 $results = array(
1888 'status' => $status,
1889 'warnings' => $warnings
1890 );
1891
1892 return $results;
1893 }
1894
1895 /**
1896 * Returns description of method result value.
1897 *
1898 * @return external_description
1899 * @since 3.2
1900 */
1901 public static function delete_conversation_returns() {
1902 return new external_single_structure(
1903 array(
1904 'status' => new external_value(PARAM_BOOL, 'True if the conversation was deleted, false otherwise'),
1905 'warnings' => new external_warnings()
1906 )
1907 );
1908 }
1909
419b1128
JL
1910 /**
1911 * Returns description of method parameters
1912 *
1913 * @return external_function_parameters
1914 * @since 3.1
1915 */
1916 public static function delete_message_parameters() {
1917 return new external_function_parameters(
1918 array(
1919 'messageid' => new external_value(PARAM_INT, 'The message id'),
1920 'userid' => new external_value(PARAM_INT, 'The user id of who we want to delete the message for'),
1921 'read' => new external_value(PARAM_BOOL, 'If is a message read', VALUE_DEFAULT, true)
1922 )
1923 );
1924 }
1925
1926 /**
1927 * Deletes a message
1928 *
1929 * @param int $messageid the message id
1930 * @param int $userid the user id of who we want to delete the message for
1931 * @param bool $read if is a message read (default to true)
1932 * @return external_description
1933 * @throws moodle_exception
1934 * @since 3.1
1935 */
1936 public static function delete_message($messageid, $userid, $read = true) {
1937 global $CFG, $DB;
419b1128
JL
1938
1939 // Check if private messaging between users is allowed.
1940 if (empty($CFG->messaging)) {
1941 throw new moodle_exception('disabled', 'message');
1942 }
1943
1944 // Warnings array, it can be empty at the end but is mandatory.
1945 $warnings = array();
1946
1947 // Validate params.
1948 $params = array(
1949 'messageid' => $messageid,
1950 'userid' => $userid,
1951 'read' => $read
1952 );
1953 $params = self::validate_parameters(self::delete_message_parameters(), $params);
1954
1955 // Validate context.
1956 $context = context_system::instance();
1957 self::validate_context($context);
1958
1959 $messagestable = $params['read'] ? 'message_read' : 'message';
1960 $message = $DB->get_record($messagestable, array('id' => $params['messageid']), '*', MUST_EXIST);
1961
1962 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1963 core_user::require_active_user($user);
1964
1965 $status = false;
1966 if (message_can_delete_message($message, $user->id)) {
1967 $status = message_delete_message($message, $user->id);;
1968 } else {
1969 throw new moodle_exception('You do not have permission to delete this message');
1970 }
1971
1972 $results = array(
1973 'status' => $status,
1974 'warnings' => $warnings
1975 );
1976 return $results;
1977 }
1978
1979 /**
1980 * Returns description of method result value
1981 *
1982 * @return external_description
1983 * @since 3.1
1984 */
1985 public static function delete_message_returns() {
1986 return new external_single_structure(
1987 array(
1988 'status' => new external_value(PARAM_BOOL, 'True if the message was deleted, false otherwise'),
1989 'warnings' => new external_warnings()
1990 )
1991 );
1992 }
1993
a0eabdd3
RW
1994 /**
1995 * Returns description of method parameters
1996 *
1997 * @return external_function_parameters
1998 * @since 3.2
1999 */
2000 public static function message_processor_config_form_parameters() {
2001 return new external_function_parameters(
2002 array(
2003 'userid' => new external_value(PARAM_INT, 'id of the user, 0 for current user', VALUE_REQUIRED),
2004 'name' => new external_value(PARAM_TEXT, 'The name of the message processor'),
2005 'formvalues' => new external_multiple_structure(
2006 new external_single_structure(
2007 array(
2008 'name' => new external_value(PARAM_TEXT, 'name of the form element', VALUE_REQUIRED),
2009 'value' => new external_value(PARAM_RAW, 'value of the form element', VALUE_REQUIRED),
2010 )
2011 ),
2012 'Config form values',
2013 VALUE_REQUIRED
2014 ),
2015 )
2016 );
2017 }
2018
2019 /**
2020 * Processes a message processor config form.
2021 *
2022 * @param int $userid the user id
2023 * @param string $name the name of the processor
2024 * @param array $formvalues the form values
2025 * @return external_description
2026 * @throws moodle_exception
2027 * @since 3.2
2028 */
2029 public static function message_processor_config_form($userid, $name, $formvalues) {
2030 $params = self::validate_parameters(
2031 self::message_processor_config_form_parameters(),
2032 array(
2033 'userid' => $userid,
2034 'name' => $name,
2035 'formvalues' => $formvalues,
2036 )
2037 );
2038
2039 if (empty($params['userid'])) {
2040 $params['userid'] = $USER->id;
2041 }
2042
2043 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
2044 core_user::require_active_user($user);
2045
2046 $processor = get_message_processor($name);
2047 $preferences = [];
2048 $form = new stdClass();
2049
2050 foreach ($formvalues as $formvalue) {
2051 $form->$formvalue['name'] = $formvalue['value'];
2052 }
2053
2054 $processor->process_form($form, $preferences);
2055
2056 if (!empty($preferences)) {
2057 set_user_preferences($preferences, $userid);
2058 }
2059 }
2060
2061 /**
2062 * Returns description of method result value
2063 *
2064 * @return external_description
2065 * @since 3.2
2066 */
2067 public static function message_processor_config_form_returns() {
2068 return null;
2069 }
a623b6b8 2070}