externallib.php 40 KB

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