PageRenderTime 52ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/mod/forum/externallib.php

https://bitbucket.org/moodle/moodle
PHP | 2540 lines | 1720 code | 309 blank | 511 comment | 120 complexity | 4e4714f81b512a39a82e1714bdefd54c MD5 | raw file
Possible License(s): Apache-2.0, LGPL-2.1, BSD-3-Clause, MIT, GPL-3.0

Large files files are truncated, but you can click here to view the full file

  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 forum API
  18. *
  19. * @package mod_forum
  20. * @copyright 2012 Mark Nelson <markn@moodle.com>
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. */
  23. defined('MOODLE_INTERNAL') || die;
  24. require_once("$CFG->libdir/externallib.php");
  25. use mod_forum\local\exporters\post as post_exporter;
  26. use mod_forum\local\exporters\discussion as discussion_exporter;
  27. class mod_forum_external extends external_api {
  28. /**
  29. * Describes the parameters for get_forum.
  30. *
  31. * @return external_function_parameters
  32. * @since Moodle 2.5
  33. */
  34. public static function get_forums_by_courses_parameters() {
  35. return new external_function_parameters (
  36. array(
  37. 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID',
  38. VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of Course IDs', VALUE_DEFAULT, array()),
  39. )
  40. );
  41. }
  42. /**
  43. * Returns a list of forums in a provided list of courses,
  44. * if no list is provided all forums that the user can view
  45. * will be returned.
  46. *
  47. * @param array $courseids the course ids
  48. * @return array the forum details
  49. * @since Moodle 2.5
  50. */
  51. public static function get_forums_by_courses($courseids = array()) {
  52. global $CFG;
  53. require_once($CFG->dirroot . "/mod/forum/lib.php");
  54. $params = self::validate_parameters(self::get_forums_by_courses_parameters(), array('courseids' => $courseids));
  55. $courses = array();
  56. if (empty($params['courseids'])) {
  57. $courses = enrol_get_my_courses();
  58. $params['courseids'] = array_keys($courses);
  59. }
  60. // Array to store the forums to return.
  61. $arrforums = array();
  62. $warnings = array();
  63. // Ensure there are courseids to loop through.
  64. if (!empty($params['courseids'])) {
  65. list($courses, $warnings) = external_util::validate_courses($params['courseids'], $courses);
  66. // Get the forums in this course. This function checks users visibility permissions.
  67. $forums = get_all_instances_in_courses("forum", $courses);
  68. foreach ($forums as $forum) {
  69. $course = $courses[$forum->course];
  70. $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id);
  71. $context = context_module::instance($cm->id);
  72. // Skip forums we are not allowed to see discussions.
  73. if (!has_capability('mod/forum:viewdiscussion', $context)) {
  74. continue;
  75. }
  76. $forum->name = external_format_string($forum->name, $context->id);
  77. // Format the intro before being returning using the format setting.
  78. $options = array('noclean' => true);
  79. list($forum->intro, $forum->introformat) =
  80. external_format_text($forum->intro, $forum->introformat, $context->id, 'mod_forum', 'intro', null, $options);
  81. $forum->introfiles = external_util::get_area_files($context->id, 'mod_forum', 'intro', false, false);
  82. // Discussions count. This function does static request cache.
  83. $forum->numdiscussions = forum_count_discussions($forum, $cm, $course);
  84. $forum->cmid = $forum->coursemodule;
  85. $forum->cancreatediscussions = forum_user_can_post_discussion($forum, null, -1, $cm, $context);
  86. $forum->istracked = forum_tp_is_tracked($forum);
  87. if ($forum->istracked) {
  88. $forum->unreadpostscount = forum_tp_count_forum_unread_posts($cm, $course);
  89. }
  90. // Add the forum to the array to return.
  91. $arrforums[$forum->id] = $forum;
  92. }
  93. }
  94. return $arrforums;
  95. }
  96. /**
  97. * Describes the get_forum return value.
  98. *
  99. * @return external_single_structure
  100. * @since Moodle 2.5
  101. */
  102. public static function get_forums_by_courses_returns() {
  103. return new external_multiple_structure(
  104. new external_single_structure(
  105. array(
  106. 'id' => new external_value(PARAM_INT, 'Forum id'),
  107. 'course' => new external_value(PARAM_INT, 'Course id'),
  108. 'type' => new external_value(PARAM_TEXT, 'The forum type'),
  109. 'name' => new external_value(PARAM_RAW, 'Forum name'),
  110. 'intro' => new external_value(PARAM_RAW, 'The forum intro'),
  111. 'introformat' => new external_format_value('intro'),
  112. 'introfiles' => new external_files('Files in the introduction text', VALUE_OPTIONAL),
  113. 'duedate' => new external_value(PARAM_INT, 'duedate for the user', VALUE_OPTIONAL),
  114. 'cutoffdate' => new external_value(PARAM_INT, 'cutoffdate for the user', VALUE_OPTIONAL),
  115. 'assessed' => new external_value(PARAM_INT, 'Aggregate type'),
  116. 'assesstimestart' => new external_value(PARAM_INT, 'Assess start time'),
  117. 'assesstimefinish' => new external_value(PARAM_INT, 'Assess finish time'),
  118. 'scale' => new external_value(PARAM_INT, 'Scale'),
  119. 'grade_forum' => new external_value(PARAM_INT, 'Whole forum grade'),
  120. 'grade_forum_notify' => new external_value(PARAM_INT, 'Whether to send notifications to students upon grading by default'),
  121. 'maxbytes' => new external_value(PARAM_INT, 'Maximum attachment size'),
  122. 'maxattachments' => new external_value(PARAM_INT, 'Maximum number of attachments'),
  123. 'forcesubscribe' => new external_value(PARAM_INT, 'Force users to subscribe'),
  124. 'trackingtype' => new external_value(PARAM_INT, 'Subscription mode'),
  125. 'rsstype' => new external_value(PARAM_INT, 'RSS feed for this activity'),
  126. 'rssarticles' => new external_value(PARAM_INT, 'Number of RSS recent articles'),
  127. 'timemodified' => new external_value(PARAM_INT, 'Time modified'),
  128. 'warnafter' => new external_value(PARAM_INT, 'Post threshold for warning'),
  129. 'blockafter' => new external_value(PARAM_INT, 'Post threshold for blocking'),
  130. 'blockperiod' => new external_value(PARAM_INT, 'Time period for blocking'),
  131. 'completiondiscussions' => new external_value(PARAM_INT, 'Student must create discussions'),
  132. 'completionreplies' => new external_value(PARAM_INT, 'Student must post replies'),
  133. 'completionposts' => new external_value(PARAM_INT, 'Student must post discussions or replies'),
  134. 'cmid' => new external_value(PARAM_INT, 'Course module id'),
  135. 'numdiscussions' => new external_value(PARAM_INT, 'Number of discussions in the forum', VALUE_OPTIONAL),
  136. 'cancreatediscussions' => new external_value(PARAM_BOOL, 'If the user can create discussions', VALUE_OPTIONAL),
  137. 'lockdiscussionafter' => new external_value(PARAM_INT, 'After what period a discussion is locked', VALUE_OPTIONAL),
  138. 'istracked' => new external_value(PARAM_BOOL, 'If the user is tracking the forum', VALUE_OPTIONAL),
  139. 'unreadpostscount' => new external_value(PARAM_INT, 'The number of unread posts for tracked forums',
  140. VALUE_OPTIONAL),
  141. ), 'forum'
  142. )
  143. );
  144. }
  145. /**
  146. * Get the forum posts in the specified discussion.
  147. *
  148. * @param int $discussionid
  149. * @param string $sortby
  150. * @param string $sortdirection
  151. * @param bool $includeinlineattachments Whether inline attachments should be included or not.
  152. * @return array
  153. */
  154. public static function get_discussion_posts(int $discussionid, ?string $sortby, ?string $sortdirection, bool $includeinlineattachments = false) {
  155. global $USER;
  156. // Validate the parameter.
  157. $params = self::validate_parameters(self::get_discussion_posts_parameters(), [
  158. 'discussionid' => $discussionid,
  159. 'sortby' => $sortby,
  160. 'sortdirection' => $sortdirection,
  161. ]);
  162. $warnings = [];
  163. $vaultfactory = mod_forum\local\container::get_vault_factory();
  164. $discussionvault = $vaultfactory->get_discussion_vault();
  165. $discussion = $discussionvault->get_from_id($params['discussionid']);
  166. $forumvault = $vaultfactory->get_forum_vault();
  167. $forum = $forumvault->get_from_id($discussion->get_forum_id());
  168. $context = $forum->get_context();
  169. self::validate_context($context);
  170. $sortby = $params['sortby'];
  171. $sortdirection = $params['sortdirection'];
  172. $sortallowedvalues = ['id', 'created', 'modified'];
  173. $directionallowedvalues = ['ASC', 'DESC'];
  174. if (!in_array(strtolower($sortby), $sortallowedvalues)) {
  175. throw new invalid_parameter_exception('Invalid value for sortby parameter (value: ' . $sortby . '),' .
  176. 'allowed values are: ' . implode(', ', $sortallowedvalues));
  177. }
  178. $sortdirection = strtoupper($sortdirection);
  179. if (!in_array($sortdirection, $directionallowedvalues)) {
  180. throw new invalid_parameter_exception('Invalid value for sortdirection parameter (value: ' . $sortdirection . '),' .
  181. 'allowed values are: ' . implode(',', $directionallowedvalues));
  182. }
  183. $managerfactory = mod_forum\local\container::get_manager_factory();
  184. $capabilitymanager = $managerfactory->get_capability_manager($forum);
  185. $postvault = $vaultfactory->get_post_vault();
  186. $posts = $postvault->get_from_discussion_id(
  187. $USER,
  188. $discussion->get_id(),
  189. $capabilitymanager->can_view_any_private_reply($USER),
  190. "{$sortby} {$sortdirection}"
  191. );
  192. $builderfactory = mod_forum\local\container::get_builder_factory();
  193. $postbuilder = $builderfactory->get_exported_posts_builder();
  194. $legacydatamapper = mod_forum\local\container::get_legacy_data_mapper_factory();
  195. return [
  196. 'posts' => $postbuilder->build($USER, [$forum], [$discussion], $posts, $includeinlineattachments),
  197. 'forumid' => $discussion->get_forum_id(),
  198. 'courseid' => $discussion->get_course_id(),
  199. 'ratinginfo' => \core_rating\external\util::get_rating_info(
  200. $legacydatamapper->get_forum_data_mapper()->to_legacy_object($forum),
  201. $forum->get_context(),
  202. 'mod_forum',
  203. 'post',
  204. $legacydatamapper->get_post_data_mapper()->to_legacy_objects($posts)
  205. ),
  206. 'warnings' => $warnings,
  207. ];
  208. }
  209. /**
  210. * Describe the post parameters.
  211. *
  212. * @return external_function_parameters
  213. */
  214. public static function get_discussion_posts_parameters() {
  215. return new external_function_parameters ([
  216. 'discussionid' => new external_value(PARAM_INT, 'The ID of the discussion from which to fetch posts.', VALUE_REQUIRED),
  217. 'sortby' => new external_value(PARAM_ALPHA, 'Sort by this element: id, created or modified', VALUE_DEFAULT, 'created'),
  218. 'sortdirection' => new external_value(PARAM_ALPHA, 'Sort direction: ASC or DESC', VALUE_DEFAULT, 'DESC'),
  219. 'includeinlineattachments' => new external_value(PARAM_BOOL, 'Whether inline attachments should be included or not', VALUE_DEFAULT,
  220. false),
  221. ]);
  222. }
  223. /**
  224. * Describe the post return format.
  225. *
  226. * @return external_single_structure
  227. */
  228. public static function get_discussion_posts_returns() {
  229. return new external_single_structure([
  230. 'posts' => new external_multiple_structure(\mod_forum\local\exporters\post::get_read_structure()),
  231. 'forumid' => new external_value(PARAM_INT, 'The forum id'),
  232. 'courseid' => new external_value(PARAM_INT, 'The forum course id'),
  233. 'ratinginfo' => \core_rating\external\util::external_ratings_structure(),
  234. 'warnings' => new external_warnings()
  235. ]);
  236. }
  237. /**
  238. * Mark the get_forum_discussions_paginated web service as deprecated.
  239. *
  240. * @return bool
  241. */
  242. public static function get_forum_discussions_paginated_is_deprecated() {
  243. return true;
  244. }
  245. /**
  246. * Describes the parameters for get_forum_discussions_paginated.
  247. *
  248. * @deprecated since 3.7
  249. * @return external_function_parameters
  250. * @since Moodle 2.8
  251. */
  252. public static function get_forum_discussions_paginated_parameters() {
  253. return new external_function_parameters (
  254. array(
  255. 'forumid' => new external_value(PARAM_INT, 'forum instance id', VALUE_REQUIRED),
  256. 'sortby' => new external_value(PARAM_ALPHA,
  257. 'sort by this element: id, timemodified, timestart or timeend', VALUE_DEFAULT, 'timemodified'),
  258. 'sortdirection' => new external_value(PARAM_ALPHA, 'sort direction: ASC or DESC', VALUE_DEFAULT, 'DESC'),
  259. 'page' => new external_value(PARAM_INT, 'current page', VALUE_DEFAULT, -1),
  260. 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
  261. )
  262. );
  263. }
  264. /**
  265. * Returns a list of forum discussions optionally sorted and paginated.
  266. *
  267. * @deprecated since 3.7
  268. * @param int $forumid the forum instance id
  269. * @param string $sortby sort by this element (id, timemodified, timestart or timeend)
  270. * @param string $sortdirection sort direction: ASC or DESC
  271. * @param int $page page number
  272. * @param int $perpage items per page
  273. *
  274. * @return array the forum discussion details including warnings
  275. * @since Moodle 2.8
  276. */
  277. public static function get_forum_discussions_paginated($forumid, $sortby = 'timemodified', $sortdirection = 'DESC',
  278. $page = -1, $perpage = 0) {
  279. global $CFG, $DB, $USER, $PAGE;
  280. require_once($CFG->dirroot . "/mod/forum/lib.php");
  281. $warnings = array();
  282. $discussions = array();
  283. $params = self::validate_parameters(self::get_forum_discussions_paginated_parameters(),
  284. array(
  285. 'forumid' => $forumid,
  286. 'sortby' => $sortby,
  287. 'sortdirection' => $sortdirection,
  288. 'page' => $page,
  289. 'perpage' => $perpage
  290. )
  291. );
  292. // Compact/extract functions are not recommended.
  293. $forumid = $params['forumid'];
  294. $sortby = $params['sortby'];
  295. $sortdirection = $params['sortdirection'];
  296. $page = $params['page'];
  297. $perpage = $params['perpage'];
  298. $sortallowedvalues = array('id', 'timemodified', 'timestart', 'timeend');
  299. if (!in_array($sortby, $sortallowedvalues)) {
  300. throw new invalid_parameter_exception('Invalid value for sortby parameter (value: ' . $sortby . '),' .
  301. 'allowed values are: ' . implode(',', $sortallowedvalues));
  302. }
  303. $sortdirection = strtoupper($sortdirection);
  304. $directionallowedvalues = array('ASC', 'DESC');
  305. if (!in_array($sortdirection, $directionallowedvalues)) {
  306. throw new invalid_parameter_exception('Invalid value for sortdirection parameter (value: ' . $sortdirection . '),' .
  307. 'allowed values are: ' . implode(',', $directionallowedvalues));
  308. }
  309. $forum = $DB->get_record('forum', array('id' => $forumid), '*', MUST_EXIST);
  310. $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
  311. $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id, false, MUST_EXIST);
  312. // Validate the module context. It checks everything that affects the module visibility (including groupings, etc..).
  313. $modcontext = context_module::instance($cm->id);
  314. self::validate_context($modcontext);
  315. // Check they have the view forum capability.
  316. require_capability('mod/forum:viewdiscussion', $modcontext, null, true, 'noviewdiscussionspermission', 'forum');
  317. $sort = 'd.pinned DESC, d.' . $sortby . ' ' . $sortdirection;
  318. $alldiscussions = forum_get_discussions($cm, $sort, true, -1, -1, true, $page, $perpage, FORUM_POSTS_ALL_USER_GROUPS);
  319. if ($alldiscussions) {
  320. $canviewfullname = has_capability('moodle/site:viewfullnames', $modcontext);
  321. // Get the unreads array, this takes a forum id and returns data for all discussions.
  322. $unreads = array();
  323. if ($cantrack = forum_tp_can_track_forums($forum)) {
  324. if ($forumtracked = forum_tp_is_tracked($forum)) {
  325. $unreads = forum_get_discussions_unread($cm);
  326. }
  327. }
  328. // The forum function returns the replies for all the discussions in a given forum.
  329. $canseeprivatereplies = has_capability('mod/forum:readprivatereplies', $modcontext);
  330. $canlock = has_capability('moodle/course:manageactivities', $modcontext, $USER);
  331. $replies = forum_count_discussion_replies($forumid, $sort, -1, $page, $perpage, $canseeprivatereplies);
  332. foreach ($alldiscussions as $discussion) {
  333. // This function checks for qanda forums.
  334. // Note that the forum_get_discussions returns as id the post id, not the discussion id so we need to do this.
  335. $discussionrec = clone $discussion;
  336. $discussionrec->id = $discussion->discussion;
  337. if (!forum_user_can_see_discussion($forum, $discussionrec, $modcontext)) {
  338. $warning = array();
  339. // Function forum_get_discussions returns forum_posts ids not forum_discussions ones.
  340. $warning['item'] = 'post';
  341. $warning['itemid'] = $discussion->id;
  342. $warning['warningcode'] = '1';
  343. $warning['message'] = 'You can\'t see this discussion';
  344. $warnings[] = $warning;
  345. continue;
  346. }
  347. $discussion->numunread = 0;
  348. if ($cantrack && $forumtracked) {
  349. if (isset($unreads[$discussion->discussion])) {
  350. $discussion->numunread = (int) $unreads[$discussion->discussion];
  351. }
  352. }
  353. $discussion->numreplies = 0;
  354. if (!empty($replies[$discussion->discussion])) {
  355. $discussion->numreplies = (int) $replies[$discussion->discussion]->replies;
  356. }
  357. $discussion->name = external_format_string($discussion->name, $modcontext->id);
  358. $discussion->subject = external_format_string($discussion->subject, $modcontext->id);
  359. // Rewrite embedded images URLs.
  360. $options = array('trusted' => $discussion->messagetrust);
  361. list($discussion->message, $discussion->messageformat) =
  362. external_format_text($discussion->message, $discussion->messageformat,
  363. $modcontext->id, 'mod_forum', 'post', $discussion->id, $options);
  364. // List attachments.
  365. if (!empty($discussion->attachment)) {
  366. $discussion->attachments = external_util::get_area_files($modcontext->id, 'mod_forum', 'attachment',
  367. $discussion->id);
  368. }
  369. $messageinlinefiles = external_util::get_area_files($modcontext->id, 'mod_forum', 'post', $discussion->id);
  370. if (!empty($messageinlinefiles)) {
  371. $discussion->messageinlinefiles = $messageinlinefiles;
  372. }
  373. $discussion->locked = forum_discussion_is_locked($forum, $discussion);
  374. $discussion->canlock = $canlock;
  375. $discussion->canreply = forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext);
  376. if (forum_is_author_hidden($discussion, $forum)) {
  377. $discussion->userid = null;
  378. $discussion->userfullname = null;
  379. $discussion->userpictureurl = null;
  380. $discussion->usermodified = null;
  381. $discussion->usermodifiedfullname = null;
  382. $discussion->usermodifiedpictureurl = null;
  383. } else {
  384. $picturefields = explode(',', implode(',', \core_user\fields::get_picture_fields()));
  385. // Load user objects from the results of the query.
  386. $user = new stdclass();
  387. $user->id = $discussion->userid;
  388. $user = username_load_fields_from_object($user, $discussion, null, $picturefields);
  389. // Preserve the id, it can be modified by username_load_fields_from_object.
  390. $user->id = $discussion->userid;
  391. $discussion->userfullname = fullname($user, $canviewfullname);
  392. $userpicture = new user_picture($user);
  393. $userpicture->size = 1; // Size f1.
  394. $discussion->userpictureurl = $userpicture->get_url($PAGE)->out(false);
  395. $usermodified = new stdclass();
  396. $usermodified->id = $discussion->usermodified;
  397. $usermodified = username_load_fields_from_object($usermodified, $discussion, 'um', $picturefields);
  398. // Preserve the id (it can be overwritten due to the prefixed $picturefields).
  399. $usermodified->id = $discussion->usermodified;
  400. $discussion->usermodifiedfullname = fullname($usermodified, $canviewfullname);
  401. $userpicture = new user_picture($usermodified);
  402. $userpicture->size = 1; // Size f1.
  403. $discussion->usermodifiedpictureurl = $userpicture->get_url($PAGE)->out(false);
  404. }
  405. $discussions[] = $discussion;
  406. }
  407. }
  408. $result = array();
  409. $result['discussions'] = $discussions;
  410. $result['warnings'] = $warnings;
  411. return $result;
  412. }
  413. /**
  414. * Describes the get_forum_discussions_paginated return value.
  415. *
  416. * @deprecated since 3.7
  417. * @return external_single_structure
  418. * @since Moodle 2.8
  419. */
  420. public static function get_forum_discussions_paginated_returns() {
  421. return new external_single_structure(
  422. array(
  423. 'discussions' => new external_multiple_structure(
  424. new external_single_structure(
  425. array(
  426. 'id' => new external_value(PARAM_INT, 'Post id'),
  427. 'name' => new external_value(PARAM_RAW, 'Discussion name'),
  428. 'groupid' => new external_value(PARAM_INT, 'Group id'),
  429. 'timemodified' => new external_value(PARAM_INT, 'Time modified'),
  430. 'usermodified' => new external_value(PARAM_INT, 'The id of the user who last modified'),
  431. 'timestart' => new external_value(PARAM_INT, 'Time discussion can start'),
  432. 'timeend' => new external_value(PARAM_INT, 'Time discussion ends'),
  433. 'discussion' => new external_value(PARAM_INT, 'Discussion id'),
  434. 'parent' => new external_value(PARAM_INT, 'Parent id'),
  435. 'userid' => new external_value(PARAM_INT, 'User who started the discussion id'),
  436. 'created' => new external_value(PARAM_INT, 'Creation time'),
  437. 'modified' => new external_value(PARAM_INT, 'Time modified'),
  438. 'mailed' => new external_value(PARAM_INT, 'Mailed?'),
  439. 'subject' => new external_value(PARAM_RAW, 'The post subject'),
  440. 'message' => new external_value(PARAM_RAW, 'The post message'),
  441. 'messageformat' => new external_format_value('message'),
  442. 'messagetrust' => new external_value(PARAM_INT, 'Can we trust?'),
  443. 'messageinlinefiles' => new external_files('post message inline files', VALUE_OPTIONAL),
  444. 'attachment' => new external_value(PARAM_RAW, 'Has attachments?'),
  445. 'attachments' => new external_files('attachments', VALUE_OPTIONAL),
  446. 'totalscore' => new external_value(PARAM_INT, 'The post message total score'),
  447. 'mailnow' => new external_value(PARAM_INT, 'Mail now?'),
  448. 'userfullname' => new external_value(PARAM_TEXT, 'Post author full name'),
  449. 'usermodifiedfullname' => new external_value(PARAM_TEXT, 'Post modifier full name'),
  450. 'userpictureurl' => new external_value(PARAM_URL, 'Post author picture.'),
  451. 'usermodifiedpictureurl' => new external_value(PARAM_URL, 'Post modifier picture.'),
  452. 'numreplies' => new external_value(PARAM_INT, 'The number of replies in the discussion'),
  453. 'numunread' => new external_value(PARAM_INT, 'The number of unread discussions.'),
  454. 'pinned' => new external_value(PARAM_BOOL, 'Is the discussion pinned'),
  455. 'locked' => new external_value(PARAM_BOOL, 'Is the discussion locked'),
  456. 'canreply' => new external_value(PARAM_BOOL, 'Can the user reply to the discussion'),
  457. 'canlock' => new external_value(PARAM_BOOL, 'Can the user lock the discussion'),
  458. ), 'post'
  459. )
  460. ),
  461. 'warnings' => new external_warnings()
  462. )
  463. );
  464. }
  465. /**
  466. * Describes the parameters for get_forum_discussions.
  467. *
  468. * @return external_function_parameters
  469. * @since Moodle 3.7
  470. */
  471. public static function get_forum_discussions_parameters() {
  472. return new external_function_parameters (
  473. array(
  474. 'forumid' => new external_value(PARAM_INT, 'forum instance id', VALUE_REQUIRED),
  475. 'sortorder' => new external_value(PARAM_INT,
  476. 'sort by this element: numreplies, , created or timemodified', VALUE_DEFAULT, -1),
  477. 'page' => new external_value(PARAM_INT, 'current page', VALUE_DEFAULT, -1),
  478. 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
  479. 'groupid' => new external_value(PARAM_INT, 'group id', VALUE_DEFAULT, 0),
  480. )
  481. );
  482. }
  483. /**
  484. * Returns a list of forum discussions optionally sorted and paginated.
  485. *
  486. * @param int $forumid the forum instance id
  487. * @param int $sortorder The sort order
  488. * @param int $page page number
  489. * @param int $perpage items per page
  490. * @param int $groupid the user course group
  491. *
  492. *
  493. * @return array the forum discussion details including warnings
  494. * @since Moodle 3.7
  495. */
  496. public static function get_forum_discussions(int $forumid, ?int $sortorder = -1, ?int $page = -1,
  497. ?int $perpage = 0, ?int $groupid = 0) {
  498. global $CFG, $DB, $USER;
  499. require_once($CFG->dirroot . "/mod/forum/lib.php");
  500. $warnings = array();
  501. $discussions = array();
  502. $params = self::validate_parameters(self::get_forum_discussions_parameters(),
  503. array(
  504. 'forumid' => $forumid,
  505. 'sortorder' => $sortorder,
  506. 'page' => $page,
  507. 'perpage' => $perpage,
  508. 'groupid' => $groupid
  509. )
  510. );
  511. // Compact/extract functions are not recommended.
  512. $forumid = $params['forumid'];
  513. $sortorder = $params['sortorder'];
  514. $page = $params['page'];
  515. $perpage = $params['perpage'];
  516. $groupid = $params['groupid'];
  517. $vaultfactory = \mod_forum\local\container::get_vault_factory();
  518. $discussionlistvault = $vaultfactory->get_discussions_in_forum_vault();
  519. $sortallowedvalues = array(
  520. $discussionlistvault::SORTORDER_LASTPOST_DESC,
  521. $discussionlistvault::SORTORDER_LASTPOST_ASC,
  522. $discussionlistvault::SORTORDER_CREATED_DESC,
  523. $discussionlistvault::SORTORDER_CREATED_ASC,
  524. $discussionlistvault::SORTORDER_REPLIES_DESC,
  525. $discussionlistvault::SORTORDER_REPLIES_ASC
  526. );
  527. // If sortorder not defined set a default one.
  528. if ($sortorder == -1) {
  529. $sortorder = $discussionlistvault::SORTORDER_LASTPOST_DESC;
  530. }
  531. if (!in_array($sortorder, $sortallowedvalues)) {
  532. throw new invalid_parameter_exception('Invalid value for sortorder parameter (value: ' . $sortorder . '),' .
  533. ' allowed values are: ' . implode(',', $sortallowedvalues));
  534. }
  535. $managerfactory = \mod_forum\local\container::get_manager_factory();
  536. $urlfactory = \mod_forum\local\container::get_url_factory();
  537. $legacydatamapperfactory = mod_forum\local\container::get_legacy_data_mapper_factory();
  538. $forumvault = $vaultfactory->get_forum_vault();
  539. $forum = $forumvault->get_from_id($forumid);
  540. if (!$forum) {
  541. throw new \moodle_exception("Unable to find forum with id {$forumid}");
  542. }
  543. $forumdatamapper = $legacydatamapperfactory->get_forum_data_mapper();
  544. $forumrecord = $forumdatamapper->to_legacy_object($forum);
  545. $capabilitymanager = $managerfactory->get_capability_manager($forum);
  546. $course = $DB->get_record('course', array('id' => $forum->get_course_id()), '*', MUST_EXIST);
  547. $cm = get_coursemodule_from_instance('forum', $forum->get_id(), $course->id, false, MUST_EXIST);
  548. // Validate the module context. It checks everything that affects the module visibility (including groupings, etc..).
  549. $modcontext = context_module::instance($cm->id);
  550. self::validate_context($modcontext);
  551. $canseeanyprivatereply = $capabilitymanager->can_view_any_private_reply($USER);
  552. // Check they have the view forum capability.
  553. if (!$capabilitymanager->can_view_discussions($USER)) {
  554. throw new moodle_exception('noviewdiscussionspermission', 'forum');
  555. }
  556. $alldiscussions = mod_forum_get_discussion_summaries($forum, $USER, $groupid, $sortorder, $page, $perpage);
  557. if ($alldiscussions) {
  558. $discussionids = array_keys($alldiscussions);
  559. $postvault = $vaultfactory->get_post_vault();
  560. $postdatamapper = $legacydatamapperfactory->get_post_data_mapper();
  561. // Return the reply count for each discussion in a given forum.
  562. $replies = $postvault->get_reply_count_for_discussion_ids($USER, $discussionids, $canseeanyprivatereply);
  563. // Return the first post for each discussion in a given forum.
  564. $firstposts = $postvault->get_first_post_for_discussion_ids($discussionids);
  565. // Get the unreads array, this takes a forum id and returns data for all discussions.
  566. $unreads = array();
  567. if ($cantrack = forum_tp_can_track_forums($forumrecord)) {
  568. if ($forumtracked = forum_tp_is_tracked($forumrecord)) {
  569. $unreads = $postvault->get_unread_count_for_discussion_ids($USER, $discussionids, $canseeanyprivatereply);
  570. }
  571. }
  572. $canlock = $capabilitymanager->can_manage_forum($USER);
  573. $usercontext = context_user::instance($USER->id);
  574. $ufservice = core_favourites\service_factory::get_service_for_user_context($usercontext);
  575. $canfavourite = has_capability('mod/forum:cantogglefavourite', $modcontext, $USER);
  576. foreach ($alldiscussions as $discussionsummary) {
  577. $discussion = $discussionsummary->get_discussion();
  578. $firstpostauthor = $discussionsummary->get_first_post_author();
  579. $latestpostauthor = $discussionsummary->get_latest_post_author();
  580. // This function checks for qanda forums.
  581. $canviewdiscussion = $capabilitymanager->can_view_discussion($USER, $discussion);
  582. if (!$canviewdiscussion) {
  583. $warning = array();
  584. // Function forum_get_discussions returns forum_posts ids not forum_discussions ones.
  585. $warning['item'] = 'post';
  586. $warning['itemid'] = $discussion->get_id();
  587. $warning['warningcode'] = '1';
  588. $warning['message'] = 'You can\'t see this discussion';
  589. $warnings[] = $warning;
  590. continue;
  591. }
  592. $firstpost = $firstposts[$discussion->get_first_post_id()];
  593. $discussionobject = $postdatamapper->to_legacy_object($firstpost);
  594. // Fix up the types for these properties.
  595. $discussionobject->mailed = $discussionobject->mailed ? 1 : 0;
  596. $discussionobject->messagetrust = $discussionobject->messagetrust ? 1 : 0;
  597. $discussionobject->mailnow = $discussionobject->mailnow ? 1 : 0;
  598. $discussionobject->groupid = $discussion->get_group_id();
  599. $discussionobject->timemodified = $discussion->get_time_modified();
  600. $discussionobject->usermodified = $discussion->get_user_modified();
  601. $discussionobject->timestart = $discussion->get_time_start();
  602. $discussionobject->timeend = $discussion->get_time_end();
  603. $discussionobject->pinned = $discussion->is_pinned();
  604. $discussionobject->numunread = 0;
  605. if ($cantrack && $forumtracked) {
  606. if (isset($unreads[$discussion->get_id()])) {
  607. $discussionobject->numunread = (int) $unreads[$discussion->get_id()];
  608. }
  609. }
  610. $discussionobject->numreplies = 0;
  611. if (!empty($replies[$discussion->get_id()])) {
  612. $discussionobject->numreplies = (int) $replies[$discussion->get_id()];
  613. }
  614. $discussionobject->name = external_format_string($discussion->get_name(), $modcontext->id);
  615. $discussionobject->subject = external_format_string($discussionobject->subject, $modcontext->id);
  616. // Rewrite embedded images URLs.
  617. $options = array('trusted' => $discussionobject->messagetrust);
  618. list($discussionobject->message, $discussionobject->messageformat) =
  619. external_format_text($discussionobject->message, $discussionobject->messageformat,
  620. $modcontext->id, 'mod_forum', 'post', $discussionobject->id, $options);
  621. // List attachments.
  622. if (!empty($discussionobject->attachment)) {
  623. $discussionobject->attachments = external_util::get_area_files($modcontext->id, 'mod_forum',
  624. 'attachment', $discussionobject->id);
  625. }
  626. $messageinlinefiles = external_util::get_area_files($modcontext->id, 'mod_forum', 'post',
  627. $discussionobject->id);
  628. if (!empty($messageinlinefiles)) {
  629. $discussionobject->messageinlinefiles = $messageinlinefiles;
  630. }
  631. $discussionobject->locked = $forum->is_discussion_locked($discussion);
  632. $discussionobject->canlock = $canlock;
  633. $discussionobject->starred = !empty($ufservice) ? $ufservice->favourite_exists('mod_forum', 'discussions',
  634. $discussion->get_id(), $modcontext) : false;
  635. $discussionobject->canreply = $capabilitymanager->can_post_in_discussion($USER, $discussion);
  636. $discussionobject->canfavourite = $canfavourite;
  637. if (forum_is_author_hidden($discussionobject, $forumrecord)) {
  638. $discussionobject->userid = null;
  639. $discussionobject->userfullname = null;
  640. $discussionobject->userpictureurl = null;
  641. $discussionobject->usermodified = null;
  642. $discussionobject->usermodifiedfullname = null;
  643. $discussionobject->usermodifiedpictureurl = null;
  644. } else {
  645. $discussionobject->userfullname = $firstpostauthor->get_full_name();
  646. $discussionobject->userpictureurl = $urlfactory->get_author_profile_image_url($firstpostauthor, null, 2)
  647. ->out(false);
  648. $discussionobject->usermodifiedfullname = $latestpostauthor->get_full_name();
  649. $discussionobject->usermodifiedpictureurl = $urlfactory->get_author_profile_image_url(
  650. $latestpostauthor, null, 2)->out(false);
  651. }
  652. $discussions[] = (array) $discussionobject;
  653. }
  654. }
  655. $result = array();
  656. $result['discussions'] = $discussions;
  657. $result['warnings'] = $warnings;
  658. return $result;
  659. }
  660. /**
  661. * Describes the get_forum_discussions return value.
  662. *
  663. * @return external_single_structure
  664. * @since Moodle 3.7
  665. */
  666. public static function get_forum_discussions_returns() {
  667. return new external_single_structure(
  668. array(
  669. 'discussions' => new external_multiple_structure(
  670. new external_single_structure(
  671. array(
  672. 'id' => new external_value(PARAM_INT, 'Post id'),
  673. 'name' => new external_value(PARAM_RAW, 'Discussion name'),
  674. 'groupid' => new external_value(PARAM_INT, 'Group id'),
  675. 'timemodified' => new external_value(PARAM_INT, 'Time modified'),
  676. 'usermodified' => new external_value(PARAM_INT, 'The id of the user who last modified'),
  677. 'timestart' => new external_value(PARAM_INT, 'Time discussion can start'),
  678. 'timeend' => new external_value(PARAM_INT, 'Time discussion ends'),
  679. 'discussion' => new external_value(PARAM_INT, 'Discussion id'),
  680. 'parent' => new external_value(PARAM_INT, 'Parent id'),
  681. 'userid' => new external_value(PARAM_INT, 'User who started the discussion id'),
  682. 'created' => new external_value(PARAM_INT, 'Creation time'),
  683. 'modified' => new external_value(PARAM_INT, 'Time modified'),
  684. 'mailed' => new external_value(PARAM_INT, 'Mailed?'),
  685. 'subject' => new external_value(PARAM_RAW, 'The post subject'),
  686. 'message' => new external_value(PARAM_RAW, 'The post message'),
  687. 'messageformat' => new external_format_value('message'),
  688. 'messagetrust' => new external_value(PARAM_INT, 'Can we trust?'),
  689. 'messageinlinefiles' => new external_files('post message inline files', VALUE_OPTIONAL),
  690. 'attachment' => new external_value(PARAM_RAW, 'Has attachments?'),
  691. 'attachments' => new external_files('attachments', VALUE_OPTIONAL),
  692. 'totalscore' => new external_value(PARAM_INT, 'The post message total score'),
  693. 'mailnow' => new external_value(PARAM_INT, 'Mail now?'),
  694. 'userfullname' => new external_value(PARAM_TEXT, 'Post author full name'),
  695. 'usermodifiedfullname' => new external_value(PARAM_TEXT, 'Post modifier full name'),
  696. 'userpictureurl' => new external_value(PARAM_URL, 'Post author picture.'),
  697. 'usermodifiedpictureurl' => new external_value(PARAM_URL, 'Post modifier picture.'),
  698. 'numreplies' => new external_value(PARAM_INT, 'The number of replies in the discussion'),
  699. 'numunread' => new external_value(PARAM_INT, 'The number of unread discussions.'),
  700. 'pinned' => new external_value(PARAM_BOOL, 'Is the discussion pinned'),
  701. 'locked' => new external_value(PARAM_BOOL, 'Is the discussion locked'),
  702. 'starred' => new external_value(PARAM_BOOL, 'Is the discussion starred'),
  703. 'canreply' => new external_value(PARAM_BOOL, 'Can the user reply to the discussion'),
  704. 'canlock' => new external_value(PARAM_BOOL, 'Can the user lock the discussion'),
  705. 'canfavourite' => new external_value(PARAM_BOOL, 'Can the user star the discussion'),
  706. ), 'post'
  707. )
  708. ),
  709. 'warnings' => new external_warnings()
  710. )
  711. );
  712. }
  713. /**
  714. * Returns description of method parameters
  715. *
  716. * @return external_function_parameters
  717. * @since Moodle 2.9
  718. */
  719. public static function view_forum_parameters() {
  720. return new external_function_parameters(
  721. array(
  722. 'forumid' => new external_value(PARAM_INT, 'forum instance id')
  723. )
  724. );
  725. }
  726. /**
  727. * Trigger the course module viewed event and update the module completion status.
  728. *
  729. * @param int $forumid the forum instance id
  730. * @return array of warnings and status result
  731. * @since Moodle 2.9
  732. * @throws moodle_exception
  733. */
  734. public static function view_forum($forumid) {
  735. global $DB, $CFG;
  736. require_once($CFG->dirroot . "/mod/forum/lib.php");
  737. $params = self::validate_parameters(self::view_forum_parameters(),
  738. array(
  739. 'forumid' => $forumid
  740. ));
  741. $warnings = array();
  742. // Request and permission validation.
  743. $forum = $DB->get_record('forum', array('id' => $params['forumid']), '*', MUST_EXIST);
  744. list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
  745. $context = context_module::instance($cm->id);
  746. self::validate_context($context);
  747. require_capability('mod/forum:viewdiscussion', $context, null, true, 'noviewdiscussionspermission', 'forum');
  748. // Call the forum/lib API.
  749. forum_view($forum, $course, $cm, $context);
  750. $result = array();
  751. $result['status'] = true;
  752. $result['warnings'] = $warnings;
  753. return $result;
  754. }
  755. /**
  756. * Returns description of method result value
  757. *
  758. * @return external_description
  759. * @since Moodle 2.9
  760. */
  761. public static function view_forum_returns() {
  762. return new external_single_structure(
  763. array(
  764. 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
  765. 'warnings' => new external_warnings()
  766. )
  767. );
  768. }
  769. /**
  770. * Returns description of method parameters
  771. *
  772. * @return external_function_parameters
  773. * @since Moodle 2.9
  774. */
  775. public static function view_forum_discussion_parameters() {
  776. return new external_function_parameters(
  777. array(
  778. 'discussionid' => new external_value(PARAM_INT, 'discussion id')
  779. )
  780. );
  781. }
  782. /**
  783. * Trigger the discussion viewed event.
  784. *
  785. * @param int $discussionid the discussion id
  786. * @return array of warnings and status result
  787. * @since Moodle 2.9
  788. * @throws moodle_exception
  789. */
  790. public static function view_forum_discussion($discussionid) {
  791. global $DB, $CFG, $USER;
  792. require_once($CFG->dirroot . "/mod/forum/lib.php");
  793. $params = self::validate_parameters(self::view_forum_discussion_parameters(),
  794. array(
  795. 'discussionid' => $discussionid
  796. ));
  797. $warnings = array();
  798. $discussion = $DB->get_record('forum_discussions', array('id' => $params['discussionid']), '*', MUST_EXIST);
  799. $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST);
  800. list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
  801. // Validate the module context. It checks everything that affects the module visibility (including groupings, etc..).
  802. $modcontext = context_module::instance($cm->id);
  803. self::validate_context($modcontext);
  804. require_capability('mod/forum:viewdiscussion', $modcontext, null, true, 'noviewdiscussionspermission', 'forum');
  805. // Call the forum/lib API.
  806. forum_discussion_view($modcontext, $forum, $discussion);
  807. // Mark as read if required.
  808. if (!$CFG->forum_usermarksread && forum_tp_is_tracked($forum)) {
  809. forum_tp_mark_discussion_read($USER, $discussion->id);
  810. }
  811. $result = array();
  812. $result['status'] = true;
  813. $result['warnings'] = $warnings;
  814. return $result;
  815. }
  816. /**
  817. * Returns description of method result value
  818. *
  819. * @return external_description
  820. * @since Moodle 2.9
  821. */
  822. public static function view_forum_discussion_returns() {
  823. return new external_single_structure(
  824. array(
  825. 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
  826. 'warnings' => new external_warnings()
  827. )
  828. );
  829. }
  830. /**
  831. * Returns description of method parameters
  832. *
  833. * @return external_function_parameters
  834. * @since Moodle 3.0
  835. */
  836. public static function add_discussion_post_parameters() {
  837. return new external_function_parameters(
  838. array(
  839. 'postid' => new external_value(PARAM_INT, 'the post id we are going to reply to
  840. (can be the initial discussion post'),
  841. 'subject' => new external_value(PARAM_TEXT, 'new post subject'),
  842. 'message' => new external_value(PARAM_RAW, 'new post message (html assumed if messageformat is not provided)'),
  843. 'options' => new external_multiple_structure (
  844. new external_single_structure(
  845. array(
  846. 'name' => new external_value(PARAM_ALPHANUM,
  847. 'The allowed keys (value format) are:
  848. discussionsubscribe (bool); subscribe to the discussion?, default to true
  849. private (bool); make this reply private to the author of the parent post, default to false.
  850. inlineattachmentsid (int); the draft file area id for inline attachments
  851. attachmentsid (int); the draft file area id for attachments
  852. topreferredformat (bool); convert the message & messageformat to FORMAT_HTML, defaults to false
  853. '),
  854. 'value' => new external_value(PARAM_RAW, 'the value of the option,
  855. this param is validated in the external function.'
  856. )
  857. )
  858. ), 'Options', VALUE_DEFAULT, array()),
  859. 'messageformat' => new external_format_value('message', VALUE_DEFAULT)
  860. )
  861. );
  862. }
  863. /**
  864. * Create new posts into an existing discussion.
  865. *
  866. * @param int $postid the post id we are going to reply to
  867. * @param string $subject new post subject
  868. * @param string $message new post message (html assumed if messageformat is not provided)
  869. * @param array $options optional settings
  870. * @param string $messageformat The format of the message, defaults to FORMAT_HTML for BC
  871. * @return array of warnings and the new post id
  872. * @since Moodle 3.0
  873. * @throws moodle_exception
  874. */
  875. public static function

Large files files are truncated, but you can click here to view the full file