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