5e903acbee59a8e2061a8301d8ba578246b384a4
[moodle.git] / mod / forum / tests / externallib_test.php
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/>.
17 /**
18  * The module forums external functions unit tests
19  *
20  * @package    mod_forum
21  * @category   external
22  * @copyright  2012 Mark Nelson <markn@moodle.com>
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
26 defined('MOODLE_INTERNAL') || die();
28 global $CFG;
30 require_once($CFG->dirroot . '/webservice/tests/helpers.php');
31 require_once($CFG->dirroot . '/mod/forum/lib.php');
33 class mod_forum_external_testcase extends externallib_advanced_testcase {
35     /**
36      * Tests set up
37      */
38     protected function setUp() {
39         global $CFG;
41         // We must clear the subscription caches. This has to be done both before each test, and after in case of other
42         // tests using these functions.
43         \mod_forum\subscriptions::reset_forum_cache();
45         require_once($CFG->dirroot . '/mod/forum/externallib.php');
46     }
48     public function tearDown() {
49         // We must clear the subscription caches. This has to be done both before each test, and after in case of other
50         // tests using these functions.
51         \mod_forum\subscriptions::reset_forum_cache();
52     }
54     /**
55      * Test get forums
56      */
57     public function test_mod_forum_get_forums_by_courses() {
58         global $USER, $CFG, $DB;
60         $this->resetAfterTest(true);
62         // Create a user.
63         $user = self::getDataGenerator()->create_user(array('trackforums' => 1));
65         // Set to the user.
66         self::setUser($user);
68         // Create courses to add the modules.
69         $course1 = self::getDataGenerator()->create_course();
70         $course2 = self::getDataGenerator()->create_course();
72         // First forum.
73         $record = new stdClass();
74         $record->introformat = FORMAT_HTML;
75         $record->course = $course1->id;
76         $record->trackingtype = FORUM_TRACKING_FORCED;
77         $forum1 = self::getDataGenerator()->create_module('forum', $record);
79         // Second forum.
80         $record = new stdClass();
81         $record->introformat = FORMAT_HTML;
82         $record->course = $course2->id;
83         $record->trackingtype = FORUM_TRACKING_OFF;
84         $forum2 = self::getDataGenerator()->create_module('forum', $record);
85         $forum2->introfiles = [];
87         // Add discussions to the forums.
88         $record = new stdClass();
89         $record->course = $course1->id;
90         $record->userid = $user->id;
91         $record->forum = $forum1->id;
92         $discussion1 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
93         // Expect one discussion.
94         $forum1->numdiscussions = 1;
95         $forum1->cancreatediscussions = true;
96         $forum1->istracked = true;
97         $forum1->unreadpostscount = 0;
98         $forum1->introfiles = [];
100         $record = new stdClass();
101         $record->course = $course2->id;
102         $record->userid = $user->id;
103         $record->forum = $forum2->id;
104         $discussion2 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
105         $discussion3 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
106         // Expect two discussions.
107         $forum2->numdiscussions = 2;
108         // Default limited role, no create discussion capability enabled.
109         $forum2->cancreatediscussions = false;
110         $forum2->istracked = false;
112         // Check the forum was correctly created.
113         $this->assertEquals(2, $DB->count_records_select('forum', 'id = :forum1 OR id = :forum2',
114                 array('forum1' => $forum1->id, 'forum2' => $forum2->id)));
116         // Enrol the user in two courses.
117         // DataGenerator->enrol_user automatically sets a role for the user with the permission mod/form:viewdiscussion.
118         $this->getDataGenerator()->enrol_user($user->id, $course1->id, null, 'manual');
119         // Execute real Moodle enrolment as we'll call unenrol() method on the instance later.
120         $enrol = enrol_get_plugin('manual');
121         $enrolinstances = enrol_get_instances($course2->id, true);
122         foreach ($enrolinstances as $courseenrolinstance) {
123             if ($courseenrolinstance->enrol == "manual") {
124                 $instance2 = $courseenrolinstance;
125                 break;
126             }
127         }
128         $enrol->enrol_user($instance2, $user->id);
130         // Assign capabilities to view forums for forum 2.
131         $cm2 = get_coursemodule_from_id('forum', $forum2->cmid, 0, false, MUST_EXIST);
132         $context2 = context_module::instance($cm2->id);
133         $newrole = create_role('Role 2', 'role2', 'Role 2 description');
134         $roleid2 = $this->assignUserCapability('mod/forum:viewdiscussion', $context2->id, $newrole);
136         // Create what we expect to be returned when querying the two courses.
137         unset($forum1->displaywordcount);
138         unset($forum2->displaywordcount);
140         $expectedforums = array();
141         $expectedforums[$forum1->id] = (array) $forum1;
142         $expectedforums[$forum2->id] = (array) $forum2;
144         // Call the external function passing course ids.
145         $forums = mod_forum_external::get_forums_by_courses(array($course1->id, $course2->id));
146         $forums = external_api::clean_returnvalue(mod_forum_external::get_forums_by_courses_returns(), $forums);
147         $this->assertCount(2, $forums);
148         foreach ($forums as $forum) {
149             $this->assertEquals($expectedforums[$forum['id']], $forum);
150         }
152         // Call the external function without passing course id.
153         $forums = mod_forum_external::get_forums_by_courses();
154         $forums = external_api::clean_returnvalue(mod_forum_external::get_forums_by_courses_returns(), $forums);
155         $this->assertCount(2, $forums);
156         foreach ($forums as $forum) {
157             $this->assertEquals($expectedforums[$forum['id']], $forum);
158         }
160         // Unenrol user from second course and alter expected forums.
161         $enrol->unenrol_user($instance2, $user->id);
162         unset($expectedforums[$forum2->id]);
164         // Call the external function without passing course id.
165         $forums = mod_forum_external::get_forums_by_courses();
166         $forums = external_api::clean_returnvalue(mod_forum_external::get_forums_by_courses_returns(), $forums);
167         $this->assertCount(1, $forums);
168         $this->assertEquals($expectedforums[$forum1->id], $forums[0]);
169         $this->assertTrue($forums[0]['cancreatediscussions']);
171         // Change the type of the forum, the user shouldn't be able to add discussions.
172         $DB->set_field('forum', 'type', 'news', array('id' => $forum1->id));
173         $forums = mod_forum_external::get_forums_by_courses();
174         $forums = external_api::clean_returnvalue(mod_forum_external::get_forums_by_courses_returns(), $forums);
175         $this->assertFalse($forums[0]['cancreatediscussions']);
177         // Call for the second course we unenrolled the user from.
178         $forums = mod_forum_external::get_forums_by_courses(array($course2->id));
179         $forums = external_api::clean_returnvalue(mod_forum_external::get_forums_by_courses_returns(), $forums);
180         $this->assertCount(0, $forums);
181     }
183     /**
184      * Test the toggle favourite state
185      */
186     public function test_mod_forum_toggle_favourite_state() {
187         global $USER, $CFG, $DB;
189         $this->resetAfterTest(true);
191         // Create a user.
192         $user = self::getDataGenerator()->create_user(array('trackforums' => 1));
194         // Set to the user.
195         self::setUser($user);
197         // Create courses to add the modules.
198         $course1 = self::getDataGenerator()->create_course();
199         $this->getDataGenerator()->enrol_user($user->id, $course1->id);
201         $record = new stdClass();
202         $record->introformat = FORMAT_HTML;
203         $record->course = $course1->id;
204         $record->trackingtype = FORUM_TRACKING_OFF;
205         $forum1 = self::getDataGenerator()->create_module('forum', $record);
206         $forum1->introfiles = [];
208         // Add discussions to the forums.
209         $record = new stdClass();
210         $record->course = $course1->id;
211         $record->userid = $user->id;
212         $record->forum = $forum1->id;
213         $discussion1 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
215         $response = mod_forum_external::toggle_favourite_state($discussion1->id, 1);
216         $response = external_api::clean_returnvalue(mod_forum_external::toggle_favourite_state_returns(), $response);
217         $this->assertTrue($response['userstate']['favourited']);
219         $response = mod_forum_external::toggle_favourite_state($discussion1->id, 0);
220         $response = external_api::clean_returnvalue(mod_forum_external::toggle_favourite_state_returns(), $response);
221         $this->assertFalse($response['userstate']['favourited']);
223         $this->setUser(0);
224         try {
225             $response = mod_forum_external::toggle_favourite_state($discussion1->id, 0);
226         } catch (moodle_exception $e) {
227             $this->assertEquals('requireloginerror', $e->errorcode);
228         }
229     }
231     /**
232      * Test the toggle pin state
233      */
234     public function test_mod_forum_set_pin_state() {
235         $this->resetAfterTest(true);
237         // Create a user.
238         $user = self::getDataGenerator()->create_user(array('trackforums' => 1));
240         // Set to the user.
241         self::setUser($user);
243         // Create courses to add the modules.
244         $course1 = self::getDataGenerator()->create_course();
245         $this->getDataGenerator()->enrol_user($user->id, $course1->id);
247         $record = new stdClass();
248         $record->introformat = FORMAT_HTML;
249         $record->course = $course1->id;
250         $record->trackingtype = FORUM_TRACKING_OFF;
251         $forum1 = self::getDataGenerator()->create_module('forum', $record);
252         $forum1->introfiles = [];
254         // Add discussions to the forums.
255         $record = new stdClass();
256         $record->course = $course1->id;
257         $record->userid = $user->id;
258         $record->forum = $forum1->id;
259         $discussion1 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
261         try {
262             $response = mod_forum_external::set_pin_state($discussion1->id, 1);
263         } catch (Exception $e) {
264             $this->assertEquals('cannotpindiscussions', $e->errorcode);
265         }
267         self::setAdminUser();
268         $response = mod_forum_external::set_pin_state($discussion1->id, 1);
269         $response = external_api::clean_returnvalue(mod_forum_external::set_pin_state_returns(), $response);
270         $this->assertTrue($response['pinned']);
272         $response = mod_forum_external::set_pin_state($discussion1->id, 0);
273         $response = external_api::clean_returnvalue(mod_forum_external::set_pin_state_returns(), $response);
274         $this->assertFalse($response['pinned']);
275     }
277     /**
278      * Test get forum posts
279      */
280     public function test_mod_forum_get_forum_discussion_posts() {
281         global $CFG, $PAGE;
283         $this->resetAfterTest(true);
285         // Set the CFG variable to allow track forums.
286         $CFG->forum_trackreadposts = true;
288         // Create a user who can track forums.
289         $record = new stdClass();
290         $record->trackforums = true;
291         $user1 = self::getDataGenerator()->create_user($record);
292         // Create a bunch of other users to post.
293         $user2 = self::getDataGenerator()->create_user();
294         $user3 = self::getDataGenerator()->create_user();
296         // Set the first created user to the test user.
297         self::setUser($user1);
299         // Create course to add the module.
300         $course1 = self::getDataGenerator()->create_course();
302         // Forum with tracking off.
303         $record = new stdClass();
304         $record->course = $course1->id;
305         $record->trackingtype = FORUM_TRACKING_OFF;
306         $forum1 = self::getDataGenerator()->create_module('forum', $record);
307         $forum1context = context_module::instance($forum1->cmid);
309         // Forum with tracking enabled.
310         $record = new stdClass();
311         $record->course = $course1->id;
312         $forum2 = self::getDataGenerator()->create_module('forum', $record);
313         $forum2cm = get_coursemodule_from_id('forum', $forum2->cmid);
314         $forum2context = context_module::instance($forum2->cmid);
316         // Add discussions to the forums.
317         $record = new stdClass();
318         $record->course = $course1->id;
319         $record->userid = $user1->id;
320         $record->forum = $forum1->id;
321         $discussion1 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
323         $record = new stdClass();
324         $record->course = $course1->id;
325         $record->userid = $user2->id;
326         $record->forum = $forum1->id;
327         $discussion2 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
329         $record = new stdClass();
330         $record->course = $course1->id;
331         $record->userid = $user2->id;
332         $record->forum = $forum2->id;
333         $discussion3 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
335         // Add 2 replies to the discussion 1 from different users.
336         $record = new stdClass();
337         $record->discussion = $discussion1->id;
338         $record->parent = $discussion1->firstpost;
339         $record->userid = $user2->id;
340         $discussion1reply1 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_post($record);
341         $filename = 'shouldbeanimage.jpg';
342         // Add a fake inline image to the post.
343         $filerecordinline = array(
344             'contextid' => $forum1context->id,
345             'component' => 'mod_forum',
346             'filearea'  => 'post',
347             'itemid'    => $discussion1reply1->id,
348             'filepath'  => '/',
349             'filename'  => $filename,
350         );
351         $fs = get_file_storage();
352         $timepost = time();
353         $fs->create_file_from_string($filerecordinline, 'image contents (not really)');
355         $record->parent = $discussion1reply1->id;
356         $record->userid = $user3->id;
357         $record->tags = array('Cats', 'Dogs');
358         $discussion1reply2 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_post($record);
360         // Enrol the user in the  course.
361         $enrol = enrol_get_plugin('manual');
362         // Following line enrol and assign default role id to the user.
363         // So the user automatically gets mod/forum:viewdiscussion on all forums of the course.
364         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
365         $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
367         // Delete one user, to test that we still receive posts by this user.
368         delete_user($user3);
370         // Create what we expect to be returned when querying the discussion.
371         $expectedposts = array(
372             'posts' => array(),
373             'ratinginfo' => array(
374                 'contextid' => $forum1context->id,
375                 'component' => 'mod_forum',
376                 'ratingarea' => 'post',
377                 'canviewall' => null,
378                 'canviewany' => null,
379                 'scales' => array(),
380                 'ratings' => array(),
381             ),
382             'warnings' => array(),
383         );
385         // User pictures are initially empty, we should get the links once the external function is called.
386         $expectedposts['posts'][] = array(
387             'id' => $discussion1reply2->id,
388             'discussion' => $discussion1reply2->discussion,
389             'parent' => $discussion1reply2->parent,
390             'userid' => (int) $discussion1reply2->userid,
391             'created' => $discussion1reply2->created,
392             'modified' => $discussion1reply2->modified,
393             'mailed' => $discussion1reply2->mailed,
394             'subject' => $discussion1reply2->subject,
395             'message' => file_rewrite_pluginfile_urls($discussion1reply2->message, 'pluginfile.php',
396                     $forum1context->id, 'mod_forum', 'post', $discussion1reply2->id),
397             'messageformat' => 1,   // This value is usually changed by external_format_text() function.
398             'messagetrust' => $discussion1reply2->messagetrust,
399             'attachment' => $discussion1reply2->attachment,
400             'totalscore' => $discussion1reply2->totalscore,
401             'mailnow' => $discussion1reply2->mailnow,
402             'children' => array(),
403             'canreply' => true,
404             'postread' => false,
405             'userfullname' => fullname($user3),
406             'userpictureurl' => '',
407             'deleted' => false,
408             'isprivatereply' => false,
409             'tags' => \core_tag\external\util::get_item_tags('mod_forum', 'forum_posts', $discussion1reply2->id),
410         );
411         // Cast to expected.
412         $this->assertCount(2, $expectedposts['posts'][0]['tags']);
413         $expectedposts['posts'][0]['tags'][0]['isstandard'] = (bool) $expectedposts['posts'][0]['tags'][0]['isstandard'];
414         $expectedposts['posts'][0]['tags'][1]['isstandard'] = (bool) $expectedposts['posts'][0]['tags'][1]['isstandard'];
416         $expectedposts['posts'][] = array(
417             'id' => $discussion1reply1->id,
418             'discussion' => $discussion1reply1->discussion,
419             'parent' => $discussion1reply1->parent,
420             'userid' => (int) $discussion1reply1->userid,
421             'created' => $discussion1reply1->created,
422             'modified' => $discussion1reply1->modified,
423             'mailed' => $discussion1reply1->mailed,
424             'subject' => $discussion1reply1->subject,
425             'message' => file_rewrite_pluginfile_urls($discussion1reply1->message, 'pluginfile.php',
426                     $forum1context->id, 'mod_forum', 'post', $discussion1reply1->id),
427             'messageformat' => 1,   // This value is usually changed by external_format_text() function.
428             'messagetrust' => $discussion1reply1->messagetrust,
429             'attachment' => $discussion1reply1->attachment,
430             'messageinlinefiles' => array(
431                 array(
432                     'filename' => $filename,
433                     'filepath' => '/',
434                     'filesize' => '27',
435                     'fileurl' => moodle_url::make_webservice_pluginfile_url($forum1context->id, 'mod_forum', 'post',
436                                     $discussion1reply1->id, '/', $filename),
437                     'timemodified' => $timepost,
438                     'mimetype' => 'image/jpeg',
439                     'isexternalfile' => false,
440                 )
441             ),
442             'totalscore' => $discussion1reply1->totalscore,
443             'mailnow' => $discussion1reply1->mailnow,
444             'children' => array($discussion1reply2->id),
445             'canreply' => true,
446             'postread' => false,
447             'userfullname' => fullname($user2),
448             'userpictureurl' => '',
449             'deleted' => false,
450             'isprivatereply' => false,
451             'tags' => array(),
452         );
454         // Test a discussion with two additional posts (total 3 posts).
455         $posts = mod_forum_external::get_forum_discussion_posts($discussion1->id, 'modified', 'DESC');
456         $posts = external_api::clean_returnvalue(mod_forum_external::get_forum_discussion_posts_returns(), $posts);
457         $this->assertEquals(3, count($posts['posts']));
459         // Generate here the pictures because we need to wait to the external function to init the theme.
460         $userpicture = new user_picture($user3);
461         $userpicture->size = 1; // Size f1.
462         $expectedposts['posts'][0]['userpictureurl'] = $userpicture->get_url($PAGE)->out(false);
464         $userpicture = new user_picture($user2);
465         $userpicture->size = 1; // Size f1.
466         $expectedposts['posts'][1]['userpictureurl'] = $userpicture->get_url($PAGE)->out(false);
468         // Unset the initial discussion post.
469         array_pop($posts['posts']);
470         $this->assertEquals($expectedposts, $posts);
472         // Check we receive the unread count correctly on tracked forum.
473         forum_tp_count_forum_unread_posts($forum2cm, $course1, true);    // Reset static cache.
474         $result = mod_forum_external::get_forums_by_courses(array($course1->id));
475         $result = external_api::clean_returnvalue(mod_forum_external::get_forums_by_courses_returns(), $result);
476         foreach ($result as $f) {
477             if ($f['id'] == $forum2->id) {
478                 $this->assertEquals(1, $f['unreadpostscount']);
479             }
480         }
482         // Test discussion without additional posts. There should be only one post (the one created by the discussion).
483         $posts = mod_forum_external::get_forum_discussion_posts($discussion2->id, 'modified', 'DESC');
484         $posts = external_api::clean_returnvalue(mod_forum_external::get_forum_discussion_posts_returns(), $posts);
485         $this->assertEquals(1, count($posts['posts']));
487         // Test discussion tracking on not tracked forum.
488         $result = mod_forum_external::view_forum_discussion($discussion1->id);
489         $result = external_api::clean_returnvalue(mod_forum_external::view_forum_discussion_returns(), $result);
490         $this->assertTrue($result['status']);
491         $this->assertEmpty($result['warnings']);
493         // Test posts have not been marked as read.
494         $posts = mod_forum_external::get_forum_discussion_posts($discussion1->id, 'modified', 'DESC');
495         $posts = external_api::clean_returnvalue(mod_forum_external::get_forum_discussion_posts_returns(), $posts);
496         foreach ($posts['posts'] as $post) {
497             $this->assertFalse($post['postread']);
498         }
500         // Test discussion tracking on tracked forum.
501         $result = mod_forum_external::view_forum_discussion($discussion3->id);
502         $result = external_api::clean_returnvalue(mod_forum_external::view_forum_discussion_returns(), $result);
503         $this->assertTrue($result['status']);
504         $this->assertEmpty($result['warnings']);
506         // Test posts have been marked as read.
507         $posts = mod_forum_external::get_forum_discussion_posts($discussion3->id, 'modified', 'DESC');
508         $posts = external_api::clean_returnvalue(mod_forum_external::get_forum_discussion_posts_returns(), $posts);
509         foreach ($posts['posts'] as $post) {
510             $this->assertTrue($post['postread']);
511         }
513         // Check we receive 0 unread posts.
514         forum_tp_count_forum_unread_posts($forum2cm, $course1, true);    // Reset static cache.
515         $result = mod_forum_external::get_forums_by_courses(array($course1->id));
516         $result = external_api::clean_returnvalue(mod_forum_external::get_forums_by_courses_returns(), $result);
517         foreach ($result as $f) {
518             if ($f['id'] == $forum2->id) {
519                 $this->assertEquals(0, $f['unreadpostscount']);
520             }
521         }
522     }
524     /**
525      * Test get forum posts
526      *
527      * Tests is similar to the get_forum_discussion_posts only utilizing the new return structure and entities
528      */
529     public function test_mod_forum_get_discussion_posts() {
530         global $CFG, $PAGE;
532         $this->resetAfterTest(true);
534         // Set the CFG variable to allow track forums.
535         $CFG->forum_trackreadposts = true;
537         $urlfactory = mod_forum\local\container::get_url_factory();
538         $legacyfactory = mod_forum\local\container::get_legacy_data_mapper_factory();
539         $entityfactory = mod_forum\local\container::get_entity_factory();
541         // Create a user who can track forums.
542         $record = new stdClass();
543         $record->trackforums = true;
544         $user1 = self::getDataGenerator()->create_user($record);
545         // Create a bunch of other users to post.
546         $user2 = self::getDataGenerator()->create_user();
547         $user2entity = $entityfactory->get_author_from_stdclass($user2);
548         $exporteduser2 = [
549             'id' => (int) $user2->id,
550             'fullname' => fullname($user2),
551             'groups' => [],
552             'urls' => [
553                 'profile' => $urlfactory->get_author_profile_url($user2entity),
554                 'profileimage' => $urlfactory->get_author_profile_image_url($user2entity),
555             ]
556         ];
557         $user2->fullname = $exporteduser2['fullname'];
559         $user3 = self::getDataGenerator()->create_user(['fullname' => "Mr Pants 1"]);
560         $user3entity = $entityfactory->get_author_from_stdclass($user3);
561         $exporteduser3 = [
562             'id' => (int) $user3->id,
563             'fullname' => fullname($user3),
564             'groups' => [],
565             'urls' => [
566                 'profile' => $urlfactory->get_author_profile_url($user3entity),
567                 'profileimage' => $urlfactory->get_author_profile_image_url($user3entity),
568             ]
569         ];
570         $user3->fullname = $exporteduser3['fullname'];
571         $forumgenerator = self::getDataGenerator()->get_plugin_generator('mod_forum');
573         // Set the first created user to the test user.
574         self::setUser($user1);
576         // Create course to add the module.
577         $course1 = self::getDataGenerator()->create_course();
579         // Forum with tracking off.
580         $record = new stdClass();
581         $record->course = $course1->id;
582         $record->trackingtype = FORUM_TRACKING_OFF;
583         $forum1 = self::getDataGenerator()->create_module('forum', $record);
584         $forum1context = context_module::instance($forum1->cmid);
586         // Forum with tracking enabled.
587         $record = new stdClass();
588         $record->course = $course1->id;
589         $forum2 = self::getDataGenerator()->create_module('forum', $record);
590         $forum2cm = get_coursemodule_from_id('forum', $forum2->cmid);
591         $forum2context = context_module::instance($forum2->cmid);
593         // Add discussions to the forums.
594         $record = new stdClass();
595         $record->course = $course1->id;
596         $record->userid = $user1->id;
597         $record->forum = $forum1->id;
598         $discussion1 = $forumgenerator->create_discussion($record);
600         $record = new stdClass();
601         $record->course = $course1->id;
602         $record->userid = $user2->id;
603         $record->forum = $forum1->id;
604         $discussion2 = $forumgenerator->create_discussion($record);
606         $record = new stdClass();
607         $record->course = $course1->id;
608         $record->userid = $user2->id;
609         $record->forum = $forum2->id;
610         $discussion3 = $forumgenerator->create_discussion($record);
612         // Add 2 replies to the discussion 1 from different users.
613         $record = new stdClass();
614         $record->discussion = $discussion1->id;
615         $record->parent = $discussion1->firstpost;
616         $record->userid = $user2->id;
617         $discussion1reply1 = $forumgenerator->create_post($record);
618         $filename = 'shouldbeanimage.jpg';
619         // Add a fake inline image to the post.
620         $filerecordinline = array(
621             'contextid' => $forum1context->id,
622             'component' => 'mod_forum',
623             'filearea'  => 'post',
624             'itemid'    => $discussion1reply1->id,
625             'filepath'  => '/',
626             'filename'  => $filename,
627         );
628         $fs = get_file_storage();
629         $timepost = time();
630         $fs->create_file_from_string($filerecordinline, 'image contents (not really)');
632         $record->parent = $discussion1reply1->id;
633         $record->userid = $user3->id;
634         $discussion1reply2 = $forumgenerator->create_post($record);
636         // Enrol the user in the  course.
637         $enrol = enrol_get_plugin('manual');
638         // Following line enrol and assign default role id to the user.
639         // So the user automatically gets mod/forum:viewdiscussion on all forums of the course.
640         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
641         $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
643         // Delete one user, to test that we still receive posts by this user.
644         delete_user($user3);
646         // Create what we expect to be returned when querying the discussion.
647         $expectedposts = array(
648             'posts' => array(),
649             'ratinginfo' => array(
650                 'contextid' => $forum1context->id,
651                 'component' => 'mod_forum',
652                 'ratingarea' => 'post',
653                 'canviewall' => null,
654                 'canviewany' => null,
655                 'scales' => array(),
656                 'ratings' => array(),
657             ),
658             'warnings' => array(),
659         );
661         // User pictures are initially empty, we should get the links once the external function is called.
662         $isolatedurl = $urlfactory->get_discussion_view_url_from_discussion_id($discussion1reply2->discussion);
663         $isolatedurl->params(['parent' => $discussion1reply2->id]);
664         $expectedposts['posts'][] = array(
665             'id' => $discussion1reply2->id,
666             'discussionid' => $discussion1reply2->discussion,
667             'parentid' => $discussion1reply2->parent,
668             'hasparent' => true,
669             'timecreated' => $discussion1reply2->created,
670             'subject' => $discussion1reply2->subject,
671             'message' => file_rewrite_pluginfile_urls($discussion1reply2->message, 'pluginfile.php',
672                     $forum1context->id, 'mod_forum', 'post', $discussion1reply2->id),
673             'messageformat' => 1,   // This value is usually changed by external_format_text() function.
674             'unread' => null,
675             'isdeleted' => false,
676             'isprivatereply' => false,
677             'haswordcount' => false,
678             'wordcount' => null,
679             'author'=> $exporteduser3,
680             'attachments' => [],
681             'tags' => [],
682             'html' => [
683                 'rating' => null,
684                 'taglist' => null,
685                 'authorsubheading' => $forumgenerator->get_author_subheading_html((object)$exporteduser3, $discussion1reply2->created)
686             ],
687             'capabilities' => [
688                 'view' => 1,
689                 'edit' => 0,
690                 'delete' => 0,
691                 'split' => 0,
692                 'reply' => 1,
693                 'export' => 0,
694                 'controlreadstatus' => 0,
695                 'canreplyprivately' => 0
696             ],
697             'urls' => [
698                 'view' => $urlfactory->get_view_post_url_from_post_id($discussion1reply2->discussion, $discussion1reply2->id),
699                 'viewisolated' => $isolatedurl->out(false),
700                 'viewparent' => $urlfactory->get_view_post_url_from_post_id($discussion1reply2->discussion, $discussion1reply2->parent),
701                 'edit' => null,
702                 'delete' =>null,
703                 'split' => null,
704                 'reply' => (new moodle_url('/mod/forum/post.php#mformforum', [
705                     'reply' => $discussion1reply2->id
706                 ]))->out(false),
707                 'export' => null,
708                 'markasread' => null,
709                 'markasunread' => null,
710                 'discuss' => $urlfactory->get_discussion_view_url_from_discussion_id($discussion1reply2->discussion),
711             ],
712         );
715         $isolatedurl = $urlfactory->get_discussion_view_url_from_discussion_id($discussion1reply1->discussion);
716         $isolatedurl->params(['parent' => $discussion1reply1->id]);
717         $expectedposts['posts'][] = array(
718             'id' => $discussion1reply1->id,
719             'discussionid' => $discussion1reply1->discussion,
720             'parentid' => $discussion1reply1->parent,
721             'hasparent' => true,
722             'timecreated' => $discussion1reply1->created,
723             'subject' => $discussion1reply1->subject,
724             'message' => file_rewrite_pluginfile_urls($discussion1reply1->message, 'pluginfile.php',
725                     $forum1context->id, 'mod_forum', 'post', $discussion1reply1->id),
726             'messageformat' => 1,   // This value is usually changed by external_format_text() function.
727             'unread' => null,
728             'isdeleted' => false,
729             'isprivatereply' => false,
730             'haswordcount' => false,
731             'wordcount' => null,
732             'author'=> $exporteduser2,
733             'attachments' => [],
734             'tags' => [],
735             'html' => [
736                 'rating' => null,
737                 'taglist' => null,
738                 'authorsubheading' => $forumgenerator->get_author_subheading_html((object)$exporteduser2, $discussion1reply1->created)
739             ],
740             'capabilities' => [
741                 'view' => 1,
742                 'edit' => 0,
743                 'delete' => 0,
744                 'split' => 0,
745                 'reply' => 1,
746                 'export' => 0,
747                 'controlreadstatus' => 0,
748                 'canreplyprivately' => 0
749             ],
750             'urls' => [
751                 'view' => $urlfactory->get_view_post_url_from_post_id($discussion1reply1->discussion, $discussion1reply1->id),
752                 'viewisolated' => $isolatedurl->out(false),
753                 'viewparent' => $urlfactory->get_view_post_url_from_post_id($discussion1reply1->discussion, $discussion1reply1->parent),
754                 'edit' => null,
755                 'delete' =>null,
756                 'split' => null,
757                 'reply' => (new moodle_url('/mod/forum/post.php#mformforum', [
758                     'reply' => $discussion1reply1->id
759                 ]))->out(false),
760                 'export' => null,
761                 'markasread' => null,
762                 'markasunread' => null,
763                 'discuss' => $urlfactory->get_discussion_view_url_from_discussion_id($discussion1reply1->discussion),
764             ],
765         );
767         // Test a discussion with two additional posts (total 3 posts).
768         $posts = mod_forum_external::get_discussion_posts($discussion1->id, 'modified', 'DESC');
769         $posts = external_api::clean_returnvalue(mod_forum_external::get_discussion_posts_returns(), $posts);
770         $this->assertEquals(3, count($posts['posts']));
772         // Unset the initial discussion post.
773         array_pop($posts['posts']);
774         $this->assertEquals($expectedposts, $posts);
776         // Check we receive the unread count correctly on tracked forum.
777         forum_tp_count_forum_unread_posts($forum2cm, $course1, true);    // Reset static cache.
778         $result = mod_forum_external::get_forums_by_courses(array($course1->id));
779         $result = external_api::clean_returnvalue(mod_forum_external::get_forums_by_courses_returns(), $result);
780         foreach ($result as $f) {
781             if ($f['id'] == $forum2->id) {
782                 $this->assertEquals(1, $f['unreadpostscount']);
783             }
784         }
786         // Test discussion without additional posts. There should be only one post (the one created by the discussion).
787         $posts = mod_forum_external::get_discussion_posts($discussion2->id, 'modified', 'DESC');
788         $posts = external_api::clean_returnvalue(mod_forum_external::get_discussion_posts_returns(), $posts);
789         $this->assertEquals(1, count($posts['posts']));
791         // Test discussion tracking on not tracked forum.
792         $result = mod_forum_external::view_forum_discussion($discussion1->id);
793         $result = external_api::clean_returnvalue(mod_forum_external::view_forum_discussion_returns(), $result);
794         $this->assertTrue($result['status']);
795         $this->assertEmpty($result['warnings']);
797         // Test posts have not been marked as read.
798         $posts = mod_forum_external::get_discussion_posts($discussion1->id, 'modified', 'DESC');
799         $posts = external_api::clean_returnvalue(mod_forum_external::get_discussion_posts_returns(), $posts);
800         foreach ($posts['posts'] as $post) {
801             $this->assertNull($post['unread']);
802         }
804         // Test discussion tracking on tracked forum.
805         $result = mod_forum_external::view_forum_discussion($discussion3->id);
806         $result = external_api::clean_returnvalue(mod_forum_external::view_forum_discussion_returns(), $result);
807         $this->assertTrue($result['status']);
808         $this->assertEmpty($result['warnings']);
810         // Test posts have been marked as read.
811         $posts = mod_forum_external::get_discussion_posts($discussion3->id, 'modified', 'DESC');
812         $posts = external_api::clean_returnvalue(mod_forum_external::get_discussion_posts_returns(), $posts);
813         foreach ($posts['posts'] as $post) {
814             $this->assertFalse($post['unread']);
815         }
817         // Check we receive 0 unread posts.
818         forum_tp_count_forum_unread_posts($forum2cm, $course1, true);    // Reset static cache.
819         $result = mod_forum_external::get_forums_by_courses(array($course1->id));
820         $result = external_api::clean_returnvalue(mod_forum_external::get_forums_by_courses_returns(), $result);
821         foreach ($result as $f) {
822             if ($f['id'] == $forum2->id) {
823                 $this->assertEquals(0, $f['unreadpostscount']);
824             }
825         }
826     }
828     /**
829      * Test get forum posts
830      */
831     public function test_mod_forum_get_forum_discussion_posts_deleted() {
832         global $CFG, $PAGE;
834         $this->resetAfterTest(true);
835         $generator = self::getDataGenerator()->get_plugin_generator('mod_forum');
837         // Create a course and enrol some users in it.
838         $course1 = self::getDataGenerator()->create_course();
840         // Create users.
841         $user1 = self::getDataGenerator()->create_user();
842         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
843         $user2 = self::getDataGenerator()->create_user();
844         $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
846         // Set the first created user to the test user.
847         self::setUser($user1);
849         // Create test data.
850         $forum1 = self::getDataGenerator()->create_module('forum', (object) [
851                 'course' => $course1->id,
852             ]);
853         $forum1context = context_module::instance($forum1->cmid);
855         // Add discussions to the forum.
856         $discussion = $generator->create_discussion((object) [
857                 'course' => $course1->id,
858                 'userid' => $user1->id,
859                 'forum' => $forum1->id,
860             ]);
862         $discussion2 = $generator->create_discussion((object) [
863                 'course' => $course1->id,
864                 'userid' => $user2->id,
865                 'forum' => $forum1->id,
866             ]);
868         // Add replies to the discussion.
869         $discussionreply1 = $generator->create_post((object) [
870                 'discussion' => $discussion->id,
871                 'parent' => $discussion->firstpost,
872                 'userid' => $user2->id,
873             ]);
874         $discussionreply2 = $generator->create_post((object) [
875                 'discussion' => $discussion->id,
876                 'parent' => $discussionreply1->id,
877                 'userid' => $user2->id,
878                 'subject' => '',
879                 'message' => '',
880                 'messageformat' => FORMAT_PLAIN,
881                 'deleted' => 1,
882             ]);
883         $discussionreply3 = $generator->create_post((object) [
884                 'discussion' => $discussion->id,
885                 'parent' => $discussion->firstpost,
886                 'userid' => $user2->id,
887             ]);
889         // Test where some posts have been marked as deleted.
890         $posts = mod_forum_external::get_forum_discussion_posts($discussion->id, 'modified', 'DESC');
891         $posts = external_api::clean_returnvalue(mod_forum_external::get_forum_discussion_posts_returns(), $posts);
892         $deletedsubject = get_string('privacy:request:delete:post:subject', 'mod_forum');
893         $deletedmessage = get_string('privacy:request:delete:post:message', 'mod_forum');
895         foreach ($posts['posts'] as $post) {
896             if ($post['id'] == $discussionreply2->id) {
897                 $this->assertTrue($post['deleted']);
898                 $this->assertEquals($deletedsubject, $post['subject']);
899                 $this->assertEquals($deletedmessage, $post['message']);
900             } else {
901                 $this->assertFalse($post['deleted']);
902                 $this->assertNotEquals($deletedsubject, $post['subject']);
903                 $this->assertNotEquals($deletedmessage, $post['message']);
904             }
905         }
906     }
908     /**
909      * Test get forum posts (qanda forum)
910      */
911     public function test_mod_forum_get_forum_discussion_posts_qanda() {
912         global $CFG, $DB;
914         $this->resetAfterTest(true);
916         $record = new stdClass();
917         $user1 = self::getDataGenerator()->create_user($record);
918         $user2 = self::getDataGenerator()->create_user();
920         // Set the first created user to the test user.
921         self::setUser($user1);
923         // Create course to add the module.
924         $course1 = self::getDataGenerator()->create_course();
925         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
926         $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
928         // Forum with tracking off.
929         $record = new stdClass();
930         $record->course = $course1->id;
931         $record->type = 'qanda';
932         $forum1 = self::getDataGenerator()->create_module('forum', $record);
933         $forum1context = context_module::instance($forum1->cmid);
935         // Add discussions to the forums.
936         $record = new stdClass();
937         $record->course = $course1->id;
938         $record->userid = $user2->id;
939         $record->forum = $forum1->id;
940         $discussion1 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
942         // Add 1 reply (not the actual user).
943         $record = new stdClass();
944         $record->discussion = $discussion1->id;
945         $record->parent = $discussion1->firstpost;
946         $record->userid = $user2->id;
947         $discussion1reply1 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_post($record);
949         // We still see only the original post.
950         $posts = mod_forum_external::get_forum_discussion_posts($discussion1->id, 'modified', 'DESC');
951         $posts = external_api::clean_returnvalue(mod_forum_external::get_forum_discussion_posts_returns(), $posts);
952         $this->assertEquals(1, count($posts['posts']));
954         // Add a new reply, the user is going to be able to see only the original post and their new post.
955         $record = new stdClass();
956         $record->discussion = $discussion1->id;
957         $record->parent = $discussion1->firstpost;
958         $record->userid = $user1->id;
959         $discussion1reply2 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_post($record);
961         $posts = mod_forum_external::get_forum_discussion_posts($discussion1->id, 'modified', 'DESC');
962         $posts = external_api::clean_returnvalue(mod_forum_external::get_forum_discussion_posts_returns(), $posts);
963         $this->assertEquals(2, count($posts['posts']));
965         // Now, we can fake the time of the user post, so he can se the rest of the discussion posts.
966         $discussion1reply2->created -= $CFG->maxeditingtime * 2;
967         $DB->update_record('forum_posts', $discussion1reply2);
969         $posts = mod_forum_external::get_forum_discussion_posts($discussion1->id, 'modified', 'DESC');
970         $posts = external_api::clean_returnvalue(mod_forum_external::get_forum_discussion_posts_returns(), $posts);
971         $this->assertEquals(3, count($posts['posts']));
972     }
974     /**
975      * Test get forum discussions paginated
976      */
977     public function test_mod_forum_get_forum_discussions_paginated() {
978         global $USER, $CFG, $DB, $PAGE;
980         $this->resetAfterTest(true);
982         // Set the CFG variable to allow track forums.
983         $CFG->forum_trackreadposts = true;
985         // Create a user who can track forums.
986         $record = new stdClass();
987         $record->trackforums = true;
988         $user1 = self::getDataGenerator()->create_user($record);
989         // Create a bunch of other users to post.
990         $user2 = self::getDataGenerator()->create_user();
991         $user3 = self::getDataGenerator()->create_user();
992         $user4 = self::getDataGenerator()->create_user();
994         // Set the first created user to the test user.
995         self::setUser($user1);
997         // Create courses to add the modules.
998         $course1 = self::getDataGenerator()->create_course();
1000         // First forum with tracking off.
1001         $record = new stdClass();
1002         $record->course = $course1->id;
1003         $record->trackingtype = FORUM_TRACKING_OFF;
1004         $forum1 = self::getDataGenerator()->create_module('forum', $record);
1006         // Add discussions to the forums.
1007         $record = new stdClass();
1008         $record->course = $course1->id;
1009         $record->userid = $user1->id;
1010         $record->forum = $forum1->id;
1011         $discussion1 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
1013         // Add three replies to the discussion 1 from different users.
1014         $record = new stdClass();
1015         $record->discussion = $discussion1->id;
1016         $record->parent = $discussion1->firstpost;
1017         $record->userid = $user2->id;
1018         $discussion1reply1 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_post($record);
1020         $record->parent = $discussion1reply1->id;
1021         $record->userid = $user3->id;
1022         $discussion1reply2 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_post($record);
1024         $record->userid = $user4->id;
1025         $discussion1reply3 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_post($record);
1027         // Enrol the user in the first course.
1028         $enrol = enrol_get_plugin('manual');
1030         // We don't use the dataGenerator as we need to get the $instance2 to unenrol later.
1031         $enrolinstances = enrol_get_instances($course1->id, true);
1032         foreach ($enrolinstances as $courseenrolinstance) {
1033             if ($courseenrolinstance->enrol == "manual") {
1034                 $instance1 = $courseenrolinstance;
1035                 break;
1036             }
1037         }
1038         $enrol->enrol_user($instance1, $user1->id);
1040         // Delete one user.
1041         delete_user($user4);
1043         // Assign capabilities to view discussions for forum 1.
1044         $cm = get_coursemodule_from_id('forum', $forum1->cmid, 0, false, MUST_EXIST);
1045         $context = context_module::instance($cm->id);
1046         $newrole = create_role('Role 2', 'role2', 'Role 2 description');
1047         $this->assignUserCapability('mod/forum:viewdiscussion', $context->id, $newrole);
1049         // Create what we expect to be returned when querying the forums.
1051         $post1 = $DB->get_record('forum_posts', array('id' => $discussion1->firstpost), '*', MUST_EXIST);
1053         // User pictures are initially empty, we should get the links once the external function is called.
1054         $expecteddiscussions = array(
1055                 'id' => $discussion1->firstpost,
1056                 'name' => $discussion1->name,
1057                 'groupid' => (int) $discussion1->groupid,
1058                 'timemodified' => $discussion1reply3->created,
1059                 'usermodified' => (int) $discussion1reply3->userid,
1060                 'timestart' => (int) $discussion1->timestart,
1061                 'timeend' => (int) $discussion1->timeend,
1062                 'discussion' => $discussion1->id,
1063                 'parent' => 0,
1064                 'userid' => (int) $discussion1->userid,
1065                 'created' => (int) $post1->created,
1066                 'modified' => (int) $post1->modified,
1067                 'mailed' => (int) $post1->mailed,
1068                 'subject' => $post1->subject,
1069                 'message' => $post1->message,
1070                 'messageformat' => (int) $post1->messageformat,
1071                 'messagetrust' => (int) $post1->messagetrust,
1072                 'attachment' => $post1->attachment,
1073                 'totalscore' => (int) $post1->totalscore,
1074                 'mailnow' => (int) $post1->mailnow,
1075                 'userfullname' => fullname($user1),
1076                 'usermodifiedfullname' => fullname($user4),
1077                 'userpictureurl' => '',
1078                 'usermodifiedpictureurl' => '',
1079                 'numreplies' => 3,
1080                 'numunread' => 0,
1081                 'pinned' => (bool) FORUM_DISCUSSION_UNPINNED,
1082                 'locked' => false,
1083                 'canreply' => false,
1084                 'canlock' => false
1085             );
1087         // Call the external function passing forum id.
1088         $discussions = mod_forum_external::get_forum_discussions_paginated($forum1->id);
1089         $discussions = external_api::clean_returnvalue(mod_forum_external::get_forum_discussions_paginated_returns(), $discussions);
1090         $expectedreturn = array(
1091             'discussions' => array($expecteddiscussions),
1092             'warnings' => array()
1093         );
1095         // Wait the theme to be loaded (the external_api call does that) to generate the user profiles.
1096         $userpicture = new user_picture($user1);
1097         $userpicture->size = 1; // Size f1.
1098         $expectedreturn['discussions'][0]['userpictureurl'] = $userpicture->get_url($PAGE)->out(false);
1100         $userpicture = new user_picture($user4);
1101         $userpicture->size = 1; // Size f1.
1102         $expectedreturn['discussions'][0]['usermodifiedpictureurl'] = $userpicture->get_url($PAGE)->out(false);
1104         $this->assertEquals($expectedreturn, $discussions);
1106         // Call without required view discussion capability.
1107         $this->unassignUserCapability('mod/forum:viewdiscussion', $context->id, $newrole);
1108         try {
1109             mod_forum_external::get_forum_discussions_paginated($forum1->id);
1110             $this->fail('Exception expected due to missing capability.');
1111         } catch (moodle_exception $e) {
1112             $this->assertEquals('noviewdiscussionspermission', $e->errorcode);
1113         }
1115         // Unenrol user from second course.
1116         $enrol->unenrol_user($instance1, $user1->id);
1118         // Call for the second course we unenrolled the user from, make sure exception thrown.
1119         try {
1120             mod_forum_external::get_forum_discussions_paginated($forum1->id);
1121             $this->fail('Exception expected due to being unenrolled from the course.');
1122         } catch (moodle_exception $e) {
1123             $this->assertEquals('requireloginerror', $e->errorcode);
1124         }
1126         $this->setAdminUser();
1127         $discussions = mod_forum_external::get_forum_discussions_paginated($forum1->id);
1128         $discussions = external_api::clean_returnvalue(mod_forum_external::get_forum_discussions_paginated_returns(), $discussions);
1129         $this->assertTrue($discussions['discussions'][0]['canlock']);
1130     }
1132     /**
1133      * Test get forum discussions paginated (qanda forums)
1134      */
1135     public function test_mod_forum_get_forum_discussions_paginated_qanda() {
1137         $this->resetAfterTest(true);
1139         // Create courses to add the modules.
1140         $course = self::getDataGenerator()->create_course();
1142         $user1 = self::getDataGenerator()->create_user();
1143         $user2 = self::getDataGenerator()->create_user();
1145         // First forum with tracking off.
1146         $record = new stdClass();
1147         $record->course = $course->id;
1148         $record->type = 'qanda';
1149         $forum = self::getDataGenerator()->create_module('forum', $record);
1151         // Add discussions to the forums.
1152         $discussionrecord = new stdClass();
1153         $discussionrecord->course = $course->id;
1154         $discussionrecord->userid = $user2->id;
1155         $discussionrecord->forum = $forum->id;
1156         $discussion = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($discussionrecord);
1158         self::setAdminUser();
1159         $discussions = mod_forum_external::get_forum_discussions_paginated($forum->id);
1160         $discussions = external_api::clean_returnvalue(mod_forum_external::get_forum_discussions_paginated_returns(), $discussions);
1162         $this->assertCount(1, $discussions['discussions']);
1163         $this->assertCount(0, $discussions['warnings']);
1165         self::setUser($user1);
1166         $this->getDataGenerator()->enrol_user($user1->id, $course->id);
1168         $discussions = mod_forum_external::get_forum_discussions_paginated($forum->id);
1169         $discussions = external_api::clean_returnvalue(mod_forum_external::get_forum_discussions_paginated_returns(), $discussions);
1171         $this->assertCount(1, $discussions['discussions']);
1172         $this->assertCount(0, $discussions['warnings']);
1174     }
1176     /**
1177      * Test get forum discussions
1178      */
1179     public function test_mod_forum_get_forum_discussions() {
1180         global $CFG, $DB, $PAGE;
1182         $this->resetAfterTest(true);
1184         // Set the CFG variable to allow track forums.
1185         $CFG->forum_trackreadposts = true;
1187         // Create a user who can track forums.
1188         $record = new stdClass();
1189         $record->trackforums = true;
1190         $user1 = self::getDataGenerator()->create_user($record);
1191         // Create a bunch of other users to post.
1192         $user2 = self::getDataGenerator()->create_user();
1193         $user3 = self::getDataGenerator()->create_user();
1194         $user4 = self::getDataGenerator()->create_user();
1196         // Set the first created user to the test user.
1197         self::setUser($user1);
1199         // Create courses to add the modules.
1200         $course1 = self::getDataGenerator()->create_course();
1202         // First forum with tracking off.
1203         $record = new stdClass();
1204         $record->course = $course1->id;
1205         $record->trackingtype = FORUM_TRACKING_OFF;
1206         $forum1 = self::getDataGenerator()->create_module('forum', $record);
1208         // Add discussions to the forums.
1209         $record = new stdClass();
1210         $record->course = $course1->id;
1211         $record->userid = $user1->id;
1212         $record->forum = $forum1->id;
1213         $discussion1 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
1215         // Add three replies to the discussion 1 from different users.
1216         $record = new stdClass();
1217         $record->discussion = $discussion1->id;
1218         $record->parent = $discussion1->firstpost;
1219         $record->userid = $user2->id;
1220         $discussion1reply1 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_post($record);
1222         $record->parent = $discussion1reply1->id;
1223         $record->userid = $user3->id;
1224         $discussion1reply2 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_post($record);
1226         $record->userid = $user4->id;
1227         $discussion1reply3 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_post($record);
1229         // Enrol the user in the first course.
1230         $enrol = enrol_get_plugin('manual');
1232         // We don't use the dataGenerator as we need to get the $instance2 to unenrol later.
1233         $enrolinstances = enrol_get_instances($course1->id, true);
1234         foreach ($enrolinstances as $courseenrolinstance) {
1235             if ($courseenrolinstance->enrol == "manual") {
1236                 $instance1 = $courseenrolinstance;
1237                 break;
1238             }
1239         }
1240         $enrol->enrol_user($instance1, $user1->id);
1242         // Delete one user.
1243         delete_user($user4);
1245         // Assign capabilities to view discussions for forum 1.
1246         $cm = get_coursemodule_from_id('forum', $forum1->cmid, 0, false, MUST_EXIST);
1247         $context = context_module::instance($cm->id);
1248         $newrole = create_role('Role 2', 'role2', 'Role 2 description');
1249         $this->assignUserCapability('mod/forum:viewdiscussion', $context->id, $newrole);
1251         // Create what we expect to be returned when querying the forums.
1253         $post1 = $DB->get_record('forum_posts', array('id' => $discussion1->firstpost), '*', MUST_EXIST);
1255         // User pictures are initially empty, we should get the links once the external function is called.
1256         $expecteddiscussions = array(
1257             'id' => $discussion1->firstpost,
1258             'name' => $discussion1->name,
1259             'groupid' => (int) $discussion1->groupid,
1260             'timemodified' => (int) $discussion1reply3->created,
1261             'usermodified' => (int) $discussion1reply3->userid,
1262             'timestart' => (int) $discussion1->timestart,
1263             'timeend' => (int) $discussion1->timeend,
1264             'discussion' => (int) $discussion1->id,
1265             'parent' => 0,
1266             'userid' => (int) $discussion1->userid,
1267             'created' => (int) $post1->created,
1268             'modified' => (int) $post1->modified,
1269             'mailed' => (int) $post1->mailed,
1270             'subject' => $post1->subject,
1271             'message' => $post1->message,
1272             'messageformat' => (int) $post1->messageformat,
1273             'messagetrust' => (int) $post1->messagetrust,
1274             'attachment' => $post1->attachment,
1275             'totalscore' => (int) $post1->totalscore,
1276             'mailnow' => (int) $post1->mailnow,
1277             'userfullname' => fullname($user1),
1278             'usermodifiedfullname' => fullname($user4),
1279             'userpictureurl' => '',
1280             'usermodifiedpictureurl' => '',
1281             'numreplies' => 3,
1282             'numunread' => 0,
1283             'pinned' => (bool) FORUM_DISCUSSION_UNPINNED,
1284             'locked' => false,
1285             'canreply' => false,
1286             'canlock' => false,
1287             'starred' => false,
1288             'canfavourite' => true
1289         );
1291         // Call the external function passing forum id.
1292         $discussions = mod_forum_external::get_forum_discussions($forum1->id);
1293         $discussions = external_api::clean_returnvalue(mod_forum_external::get_forum_discussions_returns(), $discussions);
1294         $expectedreturn = array(
1295             'discussions' => array($expecteddiscussions),
1296             'warnings' => array()
1297         );
1299         // Wait the theme to be loaded (the external_api call does that) to generate the user profiles.
1300         $userpicture = new user_picture($user1);
1301         $userpicture->size = 2; // Size f2.
1302         $expectedreturn['discussions'][0]['userpictureurl'] = $userpicture->get_url($PAGE)->out(false);
1304         $userpicture = new user_picture($user4);
1305         $userpicture->size = 2; // Size f2.
1306         $expectedreturn['discussions'][0]['usermodifiedpictureurl'] = $userpicture->get_url($PAGE)->out(false);
1308         $this->assertEquals($expectedreturn, $discussions);
1310         // Test the starring functionality return.
1311         $t = mod_forum_external::toggle_favourite_state($discussion1->id, 1);
1312         $expectedreturn['discussions'][0]['starred'] = true;
1313         $discussions = mod_forum_external::get_forum_discussions($forum1->id);
1314         $discussions = external_api::clean_returnvalue(mod_forum_external::get_forum_discussions_returns(), $discussions);
1315         $this->assertEquals($expectedreturn, $discussions);
1317         // Call without required view discussion capability.
1318         $this->unassignUserCapability('mod/forum:viewdiscussion', $context->id, $newrole);
1319         try {
1320             mod_forum_external::get_forum_discussions($forum1->id);
1321             $this->fail('Exception expected due to missing capability.');
1322         } catch (moodle_exception $e) {
1323             $this->assertEquals('noviewdiscussionspermission', $e->errorcode);
1324         }
1326         // Unenrol user from second course.
1327         $enrol->unenrol_user($instance1, $user1->id);
1329         // Call for the second course we unenrolled the user from, make sure exception thrown.
1330         try {
1331             mod_forum_external::get_forum_discussions($forum1->id);
1332             $this->fail('Exception expected due to being unenrolled from the course.');
1333         } catch (moodle_exception $e) {
1334             $this->assertEquals('requireloginerror', $e->errorcode);
1335         }
1337         $this->setAdminUser();
1338         $discussions = mod_forum_external::get_forum_discussions($forum1->id);
1339         $discussions = external_api::clean_returnvalue(mod_forum_external::get_forum_discussions_returns(), $discussions);
1340         $this->assertTrue($discussions['discussions'][0]['canlock']);
1341     }
1343     /**
1344      * Test the sorting in get forum discussions
1345      */
1346     public function test_mod_forum_get_forum_discussions_sorting() {
1347         global $CFG, $DB, $PAGE;
1349         $this->resetAfterTest(true);
1351         // Set the CFG variable to allow track forums.
1352         $CFG->forum_trackreadposts = true;
1354         // Create a user who can track forums.
1355         $record = new stdClass();
1356         $record->trackforums = true;
1357         $user1 = self::getDataGenerator()->create_user($record);
1358         // Create a bunch of other users to post.
1359         $user2 = self::getDataGenerator()->create_user();
1360         $user3 = self::getDataGenerator()->create_user();
1361         $user4 = self::getDataGenerator()->create_user();
1363         // Set the first created user to the test user.
1364         self::setUser($user1);
1366         // Create courses to add the modules.
1367         $course1 = self::getDataGenerator()->create_course();
1369         // Enrol the user in the first course.
1370         $enrol = enrol_get_plugin('manual');
1372         // We don't use the dataGenerator as we need to get the $instance2 to unenrol later.
1373         $enrolinstances = enrol_get_instances($course1->id, true);
1374         foreach ($enrolinstances as $courseenrolinstance) {
1375             if ($courseenrolinstance->enrol == "manual") {
1376                 $instance1 = $courseenrolinstance;
1377                 break;
1378             }
1379         }
1380         $enrol->enrol_user($instance1, $user1->id);
1382         // First forum with tracking off.
1383         $record = new stdClass();
1384         $record->course = $course1->id;
1385         $record->trackingtype = FORUM_TRACKING_OFF;
1386         $forum1 = self::getDataGenerator()->create_module('forum', $record);
1388         // Assign capabilities to view discussions for forum 1.
1389         $cm = get_coursemodule_from_id('forum', $forum1->cmid, 0, false, MUST_EXIST);
1390         $context = context_module::instance($cm->id);
1391         $newrole = create_role('Role 2', 'role2', 'Role 2 description');
1392         $this->assignUserCapability('mod/forum:viewdiscussion', $context->id, $newrole);
1394         // Add discussions to the forums.
1395         $record = new stdClass();
1396         $record->course = $course1->id;
1397         $record->userid = $user1->id;
1398         $record->forum = $forum1->id;
1399         $discussion1 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
1400         sleep(1);
1402         // Add three replies to the discussion 1 from different users.
1403         $record = new stdClass();
1404         $record->discussion = $discussion1->id;
1405         $record->parent = $discussion1->firstpost;
1406         $record->userid = $user2->id;
1407         $discussion1reply1 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_post($record);
1408         sleep(1);
1410         $record->parent = $discussion1reply1->id;
1411         $record->userid = $user3->id;
1412         $discussion1reply2 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_post($record);
1413         sleep(1);
1415         $record->userid = $user4->id;
1416         $discussion1reply3 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_post($record);
1417         sleep(1);
1419         // Create discussion2.
1420         $record2 = new stdClass();
1421         $record2->course = $course1->id;
1422         $record2->userid = $user1->id;
1423         $record2->forum = $forum1->id;
1424         $discussion2 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record2);
1425         sleep(1);
1427         // Add one reply to the discussion 2.
1428         $record2 = new stdClass();
1429         $record2->discussion = $discussion2->id;
1430         $record2->parent = $discussion2->firstpost;
1431         $record2->userid = $user2->id;
1432         $discussion2reply1 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_post($record2);
1433         sleep(1);
1435         // Create discussion 3.
1436         $record3 = new stdClass();
1437         $record3->course = $course1->id;
1438         $record3->userid = $user1->id;
1439         $record3->forum = $forum1->id;
1440         $discussion3 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record3);
1441         sleep(1);
1443         // Add two replies to the discussion 3.
1444         $record3 = new stdClass();
1445         $record3->discussion = $discussion3->id;
1446         $record3->parent = $discussion3->firstpost;
1447         $record3->userid = $user2->id;
1448         $discussion3reply1 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_post($record3);
1449         sleep(1);
1451         $record3->parent = $discussion3reply1->id;
1452         $record3->userid = $user3->id;
1453         $discussion3reply2 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_post($record3);
1455         // Call the external function passing forum id.
1456         $discussions = mod_forum_external::get_forum_discussions($forum1->id);
1457         $discussions = external_api::clean_returnvalue(mod_forum_external::get_forum_discussions_returns(), $discussions);
1458         // Discussions should be ordered by last post date in descending order by default.
1459         $this->assertEquals($discussions['discussions'][0]['discussion'], $discussion3->id);
1460         $this->assertEquals($discussions['discussions'][1]['discussion'], $discussion2->id);
1461         $this->assertEquals($discussions['discussions'][2]['discussion'], $discussion1->id);
1463         $vaultfactory = \mod_forum\local\container::get_vault_factory();
1464         $discussionlistvault = $vaultfactory->get_discussions_in_forum_vault();
1466         // Call the external function passing forum id and sort order parameter.
1467         $discussions = mod_forum_external::get_forum_discussions($forum1->id, $discussionlistvault::SORTORDER_LASTPOST_ASC);
1468         $discussions = external_api::clean_returnvalue(mod_forum_external::get_forum_discussions_returns(), $discussions);
1469         // Discussions should be ordered by last post date in ascending order.
1470         $this->assertEquals($discussions['discussions'][0]['discussion'], $discussion1->id);
1471         $this->assertEquals($discussions['discussions'][1]['discussion'], $discussion2->id);
1472         $this->assertEquals($discussions['discussions'][2]['discussion'], $discussion3->id);
1474         // Call the external function passing forum id and sort order parameter.
1475         $discussions = mod_forum_external::get_forum_discussions($forum1->id, $discussionlistvault::SORTORDER_CREATED_DESC);
1476         $discussions = external_api::clean_returnvalue(mod_forum_external::get_forum_discussions_returns(), $discussions);
1477         // Discussions should be ordered by discussion creation date in descending order.
1478         $this->assertEquals($discussions['discussions'][0]['discussion'], $discussion3->id);
1479         $this->assertEquals($discussions['discussions'][1]['discussion'], $discussion2->id);
1480         $this->assertEquals($discussions['discussions'][2]['discussion'], $discussion1->id);
1482         // Call the external function passing forum id and sort order parameter.
1483         $discussions = mod_forum_external::get_forum_discussions($forum1->id, $discussionlistvault::SORTORDER_CREATED_ASC);
1484         $discussions = external_api::clean_returnvalue(mod_forum_external::get_forum_discussions_returns(), $discussions);
1485         // Discussions should be ordered by discussion creation date in ascending order.
1486         $this->assertEquals($discussions['discussions'][0]['discussion'], $discussion1->id);
1487         $this->assertEquals($discussions['discussions'][1]['discussion'], $discussion2->id);
1488         $this->assertEquals($discussions['discussions'][2]['discussion'], $discussion3->id);
1490         // Call the external function passing forum id and sort order parameter.
1491         $discussions = mod_forum_external::get_forum_discussions($forum1->id, $discussionlistvault::SORTORDER_REPLIES_DESC);
1492         $discussions = external_api::clean_returnvalue(mod_forum_external::get_forum_discussions_returns(), $discussions);
1493         // Discussions should be ordered by the number of replies in descending order.
1494         $this->assertEquals($discussions['discussions'][0]['discussion'], $discussion1->id);
1495         $this->assertEquals($discussions['discussions'][1]['discussion'], $discussion3->id);
1496         $this->assertEquals($discussions['discussions'][2]['discussion'], $discussion2->id);
1498         // Call the external function passing forum id and sort order parameter.
1499         $discussions = mod_forum_external::get_forum_discussions($forum1->id, $discussionlistvault::SORTORDER_REPLIES_ASC);
1500         $discussions = external_api::clean_returnvalue(mod_forum_external::get_forum_discussions_returns(), $discussions);
1501         // Discussions should be ordered by the number of replies in ascending order.
1502         $this->assertEquals($discussions['discussions'][0]['discussion'], $discussion2->id);
1503         $this->assertEquals($discussions['discussions'][1]['discussion'], $discussion3->id);
1504         $this->assertEquals($discussions['discussions'][2]['discussion'], $discussion1->id);
1506         // Pin discussion2.
1507         $DB->update_record('forum_discussions',
1508             (object) array('id' => $discussion2->id, 'pinned' => FORUM_DISCUSSION_PINNED));
1510         // Call the external function passing forum id.
1511         $discussions = mod_forum_external::get_forum_discussions($forum1->id);
1512         $discussions = external_api::clean_returnvalue(mod_forum_external::get_forum_discussions_returns(), $discussions);
1513         // Discussions should be ordered by last post date in descending order by default.
1514         // Pinned discussions should be at the top of the list.
1515         $this->assertEquals($discussions['discussions'][0]['discussion'], $discussion2->id);
1516         $this->assertEquals($discussions['discussions'][1]['discussion'], $discussion3->id);
1517         $this->assertEquals($discussions['discussions'][2]['discussion'], $discussion1->id);
1519         // Call the external function passing forum id and sort order parameter.
1520         $discussions = mod_forum_external::get_forum_discussions($forum1->id, $discussionlistvault::SORTORDER_LASTPOST_ASC);
1521         $discussions = external_api::clean_returnvalue(mod_forum_external::get_forum_discussions_returns(), $discussions);
1522         // Discussions should be ordered by last post date in ascending order.
1523         // Pinned discussions should be at the top of the list.
1524         $this->assertEquals($discussions['discussions'][0]['discussion'], $discussion2->id);
1525         $this->assertEquals($discussions['discussions'][1]['discussion'], $discussion1->id);
1526         $this->assertEquals($discussions['discussions'][2]['discussion'], $discussion3->id);
1527     }
1529     /**
1530      * Test add_discussion_post
1531      */
1532     public function test_add_discussion_post() {
1533         global $CFG;
1535         $this->resetAfterTest(true);
1537         $user = self::getDataGenerator()->create_user();
1538         $otheruser = self::getDataGenerator()->create_user();
1540         self::setAdminUser();
1542         // Create course to add the module.
1543         $course = self::getDataGenerator()->create_course(array('groupmode' => VISIBLEGROUPS, 'groupmodeforce' => 0));
1545         // Forum with tracking off.
1546         $record = new stdClass();
1547         $record->course = $course->id;
1548         $forum = self::getDataGenerator()->create_module('forum', $record);
1549         $cm = get_coursemodule_from_id('forum', $forum->cmid, 0, false, MUST_EXIST);
1550         $forumcontext = context_module::instance($forum->cmid);
1552         // Add discussions to the forums.
1553         $record = new stdClass();
1554         $record->course = $course->id;
1555         $record->userid = $user->id;
1556         $record->forum = $forum->id;
1557         $discussion = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
1559         // Try to post (user not enrolled).
1560         self::setUser($user);
1561         try {
1562             mod_forum_external::add_discussion_post($discussion->firstpost, 'some subject', 'some text here...');
1563             $this->fail('Exception expected due to being unenrolled from the course.');
1564         } catch (moodle_exception $e) {
1565             $this->assertEquals('requireloginerror', $e->errorcode);
1566         }
1568         $this->getDataGenerator()->enrol_user($user->id, $course->id);
1569         $this->getDataGenerator()->enrol_user($otheruser->id, $course->id);
1571         $createdpost = mod_forum_external::add_discussion_post($discussion->firstpost, 'some subject', 'some text here...');
1572         $createdpost = external_api::clean_returnvalue(mod_forum_external::add_discussion_post_returns(), $createdpost);
1574         $posts = mod_forum_external::get_forum_discussion_posts($discussion->id);
1575         $posts = external_api::clean_returnvalue(mod_forum_external::get_forum_discussion_posts_returns(), $posts);
1576         // We receive the discussion and the post.
1577         $this->assertEquals(2, count($posts['posts']));
1579         $tested = false;
1580         foreach ($posts['posts'] as $thispost) {
1581             if ($createdpost['postid'] == $thispost['id']) {
1582                 $this->assertEquals('some subject', $thispost['subject']);
1583                 $this->assertEquals('some text here...', $thispost['message']);
1584                 $this->assertEquals(FORMAT_HTML, $thispost['messageformat']); // This is the default if format was not specified.
1585                 $tested = true;
1586             }
1587         }
1588         $this->assertTrue($tested);
1590         // Let's simulate a call with any other format, it should be stored that way.
1591         global $DB; // Yes, we are going to use DB facilities too, because cannot rely on other functions for checking
1592                     // the format. They eat it completely (going back to FORMAT_HTML. So we only can trust DB for further
1593                     // processing.
1594         $formats = [FORMAT_PLAIN, FORMAT_MOODLE, FORMAT_MARKDOWN, FORMAT_HTML];
1595         $options = [];
1596         foreach ($formats as $format) {
1597             $createdpost = mod_forum_external::add_discussion_post($discussion->firstpost,
1598                 'with some format', 'some formatted here...', $options, $format);
1599             $createdpost = external_api::clean_returnvalue(mod_forum_external::add_discussion_post_returns(), $createdpost);
1600             $dbformat = $DB->get_field('forum_posts', 'messageformat', ['id' => $createdpost['postid']]);
1601             $this->assertEquals($format, $dbformat);
1602         }
1604         // Now let's try the 'topreferredformat' option. That should end with the content
1605         // transformed and the format being FORMAT_HTML (when, like in this case,  user preferred
1606         // format is HTML, inferred from editor in preferences).
1607         $options = [['name' => 'topreferredformat', 'value' => true]];
1608         $createdpost = mod_forum_external::add_discussion_post($discussion->firstpost,
1609             'interesting subject', 'with some https://example.com link', $options, FORMAT_MOODLE);
1610         $createdpost = external_api::clean_returnvalue(mod_forum_external::add_discussion_post_returns(), $createdpost);
1611         $dbpost = $DB->get_record('forum_posts', ['id' => $createdpost['postid']]);
1612         // Format HTML and content converted, we should get.
1613         $this->assertEquals(FORMAT_HTML, $dbpost->messageformat);
1614         $this->assertEquals('<div class="text_to_html">with some https://example.com link</div>', $dbpost->message);
1616         // Test inline and regular attachment in post
1617         // Create a file in a draft area for inline attachments.
1618         $draftidinlineattach = file_get_unused_draft_itemid();
1619         $draftidattach = file_get_unused_draft_itemid();
1620         self::setUser($user);
1621         $usercontext = context_user::instance($user->id);
1622         $filepath = '/';
1623         $filearea = 'draft';
1624         $component = 'user';
1625         $filenameimg = 'shouldbeanimage.txt';
1626         $filerecordinline = array(
1627             'contextid' => $usercontext->id,
1628             'component' => $component,
1629             'filearea'  => $filearea,
1630             'itemid'    => $draftidinlineattach,
1631             'filepath'  => $filepath,
1632             'filename'  => $filenameimg,
1633         );
1634         $fs = get_file_storage();
1636         // Create a file in a draft area for regular attachments.
1637         $filerecordattach = $filerecordinline;
1638         $attachfilename = 'attachment.txt';
1639         $filerecordattach['filename'] = $attachfilename;
1640         $filerecordattach['itemid'] = $draftidattach;
1641         $fs->create_file_from_string($filerecordinline, 'image contents (not really)');
1642         $fs->create_file_from_string($filerecordattach, 'simple text attachment');
1644         $options = array(array('name' => 'inlineattachmentsid', 'value' => $draftidinlineattach),
1645                          array('name' => 'attachmentsid', 'value' => $draftidattach));
1646         $dummytext = 'Here is an inline image: <img src="' . $CFG->wwwroot
1647                      . "/draftfile.php/{$usercontext->id}/user/draft/{$draftidinlineattach}/{$filenameimg}"
1648                      . '" alt="inlineimage">.';
1649         $createdpost = mod_forum_external::add_discussion_post($discussion->firstpost, 'new post inline attachment',
1650                                                                $dummytext, $options);
1651         $createdpost = external_api::clean_returnvalue(mod_forum_external::add_discussion_post_returns(), $createdpost);
1653         $posts = mod_forum_external::get_forum_discussion_posts($discussion->id);
1654         $posts = external_api::clean_returnvalue(mod_forum_external::get_forum_discussion_posts_returns(), $posts);
1655         // We receive the discussion and the post.
1656         // Can't guarantee order of posts during tests.
1657         $postfound = false;
1658         foreach ($posts['posts'] as $thispost) {
1659             if ($createdpost['postid'] == $thispost['id']) {
1660                 $this->assertEquals($createdpost['postid'], $thispost['id']);
1661                 $this->assertEquals($thispost['attachment'], 1, "There should be a non-inline attachment");
1662                 $this->assertCount(1, $thispost['attachments'], "There should be 1 attachment");
1663                 $this->assertEquals($thispost['attachments'][0]['filename'], $attachfilename, "There should be 1 attachment");
1664                 $this->assertContains('pluginfile.php', $thispost['message']);
1665                 $postfound = true;
1666                 break;
1667             }
1668         }
1670         $this->assertTrue($postfound);
1672         // Check not posting in groups the user is not member of.
1673         $group = $this->getDataGenerator()->create_group(array('courseid' => $course->id));
1674         groups_add_member($group->id, $otheruser->id);
1676         $forum = self::getDataGenerator()->create_module('forum', $record, array('groupmode' => SEPARATEGROUPS));
1677         $record->forum = $forum->id;
1678         $record->userid = $otheruser->id;
1679         $record->groupid = $group->id;
1680         $discussion = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
1682         try {
1683             mod_forum_external::add_discussion_post($discussion->firstpost, 'some subject', 'some text here...');
1684             $this->fail('Exception expected due to invalid permissions for posting.');
1685         } catch (moodle_exception $e) {
1686             $this->assertEquals('nopostforum', $e->errorcode);
1687         }
1688     }
1690     /*
1691      * Test add_discussion. A basic test since all the API functions are already covered by unit tests.
1692      */
1693     public function test_add_discussion() {
1694         global $CFG, $USER;
1695         $this->resetAfterTest(true);
1697         // Create courses to add the modules.
1698         $course = self::getDataGenerator()->create_course();
1700         $user1 = self::getDataGenerator()->create_user();
1701         $user2 = self::getDataGenerator()->create_user();
1703         // First forum with tracking off.
1704         $record = new stdClass();
1705         $record->course = $course->id;
1706         $record->type = 'news';
1707         $forum = self::getDataGenerator()->create_module('forum', $record);
1709         self::setUser($user1);
1710         $this->getDataGenerator()->enrol_user($user1->id, $course->id);
1712         try {
1713             mod_forum_external::add_discussion($forum->id, 'the subject', 'some text here...');
1714             $this->fail('Exception expected due to invalid permissions.');
1715         } catch (moodle_exception $e) {
1716             $this->assertEquals('cannotcreatediscussion', $e->errorcode);
1717         }
1719         self::setAdminUser();
1720         $createddiscussion = mod_forum_external::add_discussion($forum->id, 'the subject', 'some text here...');
1721         $createddiscussion = external_api::clean_returnvalue(mod_forum_external::add_discussion_returns(), $createddiscussion);
1723         $discussions = mod_forum_external::get_forum_discussions_paginated($forum->id);
1724         $discussions = external_api::clean_returnvalue(mod_forum_external::get_forum_discussions_paginated_returns(), $discussions);
1726         $this->assertCount(1, $discussions['discussions']);
1727         $this->assertCount(0, $discussions['warnings']);
1729         $this->assertEquals($createddiscussion['discussionid'], $discussions['discussions'][0]['discussion']);
1730         $this->assertEquals(-1, $discussions['discussions'][0]['groupid']);
1731         $this->assertEquals('the subject', $discussions['discussions'][0]['subject']);
1732         $this->assertEquals('some text here...', $discussions['discussions'][0]['message']);
1734         $discussion2pinned = mod_forum_external::add_discussion($forum->id, 'the pinned subject', 'some 2 text here...', -1,
1735                                                                 array('options' => array('name' => 'discussionpinned',
1736                                                                                          'value' => true)));
1737         $discussion3 = mod_forum_external::add_discussion($forum->id, 'the non pinnedsubject', 'some 3 text here...');
1738         $discussions = mod_forum_external::get_forum_discussions_paginated($forum->id);
1739         $discussions = external_api::clean_returnvalue(mod_forum_external::get_forum_discussions_paginated_returns(), $discussions);
1740         $this->assertCount(3, $discussions['discussions']);
1741         $this->assertEquals($discussion2pinned['discussionid'], $discussions['discussions'][0]['discussion']);
1743         // Test inline and regular attachment in new discussion
1744         // Create a file in a draft area for inline attachments.
1746         $fs = get_file_storage();
1748         $draftidinlineattach = file_get_unused_draft_itemid();
1749         $draftidattach = file_get_unused_draft_itemid();
1751         $usercontext = context_user::instance($USER->id);
1752         $filepath = '/';
1753         $filearea = 'draft';
1754         $component = 'user';
1755         $filenameimg = 'shouldbeanimage.txt';
1756         $filerecord = array(
1757             'contextid' => $usercontext->id,
1758             'component' => $component,
1759             'filearea'  => $filearea,
1760             'itemid'    => $draftidinlineattach,
1761             'filepath'  => $filepath,
1762             'filename'  => $filenameimg,
1763         );
1765         // Create a file in a draft area for regular attachments.
1766         $filerecordattach = $filerecord;
1767         $attachfilename = 'attachment.txt';
1768         $filerecordattach['filename'] = $attachfilename;
1769         $filerecordattach['itemid'] = $draftidattach;
1770         $fs->create_file_from_string($filerecord, 'image contents (not really)');
1771         $fs->create_file_from_string($filerecordattach, 'simple text attachment');
1773         $dummytext = 'Here is an inline image: <img src="' . $CFG->wwwroot .
1774                     "/draftfile.php/{$usercontext->id}/user/draft/{$draftidinlineattach}/{$filenameimg}" .
1775                     '" alt="inlineimage">.';
1777         $options = array(array('name' => 'inlineattachmentsid', 'value' => $draftidinlineattach),
1778                          array('name' => 'attachmentsid', 'value' => $draftidattach));
1779         $createddiscussion = mod_forum_external::add_discussion($forum->id, 'the inline attachment subject',
1780                                                                 $dummytext, -1, $options);
1781         $createddiscussion = external_api::clean_returnvalue(mod_forum_external::add_discussion_returns(), $createddiscussion);
1783         $discussions = mod_forum_external::get_forum_discussions_paginated($forum->id);
1784         $discussions = external_api::clean_returnvalue(mod_forum_external::get_forum_discussions_paginated_returns(), $discussions);
1786         $this->assertCount(4, $discussions['discussions']);
1787         $this->assertCount(0, $createddiscussion['warnings']);
1788         // Can't guarantee order of posts during tests.
1789         $postfound = false;
1790         foreach ($discussions['discussions'] as $thisdiscussion) {
1791             if ($createddiscussion['discussionid'] == $thisdiscussion['discussion']) {
1792                 $this->assertEquals($thisdiscussion['attachment'], 1, "There should be a non-inline attachment");
1793                 $this->assertCount(1, $thisdiscussion['attachments'], "There should be 1 attachment");
1794                 $this->assertEquals($thisdiscussion['attachments'][0]['filename'], $attachfilename, "There should be 1 attachment");
1795                 $this->assertNotContains('draftfile.php', $thisdiscussion['message']);
1796                 $this->assertContains('pluginfile.php', $thisdiscussion['message']);
1797                 $postfound = true;
1798                 break;
1799             }
1800         }
1802         $this->assertTrue($postfound);
1803     }
1805     /**
1806      * Test adding discussions in a course with gorups
1807      */
1808     public function test_add_discussion_in_course_with_groups() {
1809         global $CFG;
1811         $this->resetAfterTest(true);
1813         // Create course to add the module.
1814         $course = self::getDataGenerator()->create_course(array('groupmode' => VISIBLEGROUPS, 'groupmodeforce' => 0));
1815         $user = self::getDataGenerator()->create_user();
1816         $this->getDataGenerator()->enrol_user($user->id, $course->id);
1818         // Forum forcing separate gropus.
1819         $record = new stdClass();
1820         $record->course = $course->id;
1821         $forum = self::getDataGenerator()->create_module('forum', $record, array('groupmode' => SEPARATEGROUPS));
1823         // Try to post (user not enrolled).
1824         self::setUser($user);
1826         // The user is not enroled in any group, try to post in a forum with separate groups.
1827         try {
1828             mod_forum_external::add_discussion($forum->id, 'the subject', 'some text here...');
1829             $this->fail('Exception expected due to invalid group permissions.');
1830         } catch (moodle_exception $e) {
1831             $this->assertEquals('cannotcreatediscussion', $e->errorcode);
1832         }
1834         try {
1835             mod_forum_external::add_discussion($forum->id, 'the subject', 'some text here...', 0);
1836             $this->fail('Exception expected due to invalid group permissions.');
1837         } catch (moodle_exception $e) {
1838             $this->assertEquals('cannotcreatediscussion', $e->errorcode);
1839         }
1841         // Create a group.
1842         $group = $this->getDataGenerator()->create_group(array('courseid' => $course->id));
1844         // Try to post in a group the user is not enrolled.
1845         try {
1846             mod_forum_external::add_discussion($forum->id, 'the subject', 'some text here...', $group->id);
1847             $this->fail('Exception expected due to invalid group permissions.');
1848         } catch (moodle_exception $e) {
1849             $this->assertEquals('cannotcreatediscussion', $e->errorcode);
1850         }
1852         // Add the user to a group.
1853         groups_add_member($group->id, $user->id);
1855         // Try to post in a group the user is not enrolled.
1856         try {
1857             mod_forum_external::add_discussion($forum->id, 'the subject', 'some text here...', $group->id + 1);
1858             $this->fail('Exception expected due to invalid group.');
1859         } catch (moodle_exception $e) {
1860             $this->assertEquals('cannotcreatediscussion', $e->errorcode);
1861         }
1863         // Nost add the discussion using a valid group.
1864         $discussion = mod_forum_external::add_discussion($forum->id, 'the subject', 'some text here...', $group->id);
1865         $discussion = external_api::clean_returnvalue(mod_forum_external::add_discussion_returns(), $discussion);
1867         $discussions = mod_forum_external::get_forum_discussions_paginated($forum->id);
1868         $discussions = external_api::clean_returnvalue(mod_forum_external::get_forum_discussions_paginated_returns(), $discussions);
1870         $this->assertCount(1, $discussions['discussions']);
1871         $this->assertCount(0, $discussions['warnings']);
1872         $this->assertEquals($discussion['discussionid'], $discussions['discussions'][0]['discussion']);
1873         $this->assertEquals($group->id, $discussions['discussions'][0]['groupid']);
1875         // Now add a discussions without indicating a group. The function should guess the correct group.
1876         $discussion = mod_forum_external::add_discussion($forum->id, 'the subject', 'some text here...');
1877         $discussion = external_api::clean_returnvalue(mod_forum_external::add_discussion_returns(), $discussion);
1879         $discussions = mod_forum_external::get_forum_discussions_paginated($forum->id);
1880         $discussions = external_api::clean_returnvalue(mod_forum_external::get_forum_discussions_paginated_returns(), $discussions);
1882         $this->assertCount(2, $discussions['discussions']);
1883         $this->assertCount(0, $discussions['warnings']);
1884         $this->assertEquals($group->id, $discussions['discussions'][0]['groupid']);
1885         $this->assertEquals($group->id, $discussions['discussions'][1]['groupid']);
1887         // Enrol the same user in other group.
1888         $group2 = $this->getDataGenerator()->create_group(array('courseid' => $course->id));
1889         groups_add_member($group2->id, $user->id);
1891         // Now add a discussions without indicating a group. The function should guess the correct group (the first one).
1892         $discussion = mod_forum_external::add_discussion($forum->id, 'the subject', 'some text here...');
1893         $discussion = external_api::clean_returnvalue(mod_forum_external::add_discussion_returns(), $discussion);
1895         $discussions = mod_forum_external::get_forum_discussions_paginated($forum->id);
1896         $discussions = external_api::clean_returnvalue(mod_forum_external::get_forum_discussions_paginated_returns(), $discussions);
1898         $this->assertCount(3, $discussions['discussions']);
1899         $this->assertCount(0, $discussions['warnings']);
1900         $this->assertEquals($group->id, $discussions['discussions'][0]['groupid']);
1901         $this->assertEquals($group->id, $discussions['discussions'][1]['groupid']);
1902         $this->assertEquals($group->id, $discussions['discussions'][2]['groupid']);
1904     }
1906     /*
1907      * Test set_lock_state.
1908      */
1909     public function test_set_lock_state() {
1910         global $DB;
1911         $this->resetAfterTest(true);
1913         // Create courses to add the modules.
1914         $course = self::getDataGenerator()->create_course();
1915         $user = self::getDataGenerator()->create_user();
1916         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
1918         // First forum with tracking off.
1919         $record = new stdClass();
1920         $record->course = $course->id;
1921         $record->type = 'news';
1922         $forum = self::getDataGenerator()->create_module('forum', $record);
1924         $record = new stdClass();
1925         $record->course = $course->id;
1926         $record->userid = $user->id;
1927         $record->forum = $forum->id;
1928         $discussion = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
1930         // User who is a student.
1931         self::setUser($user);
1932         $this->getDataGenerator()->enrol_user($user->id, $course->id, $studentrole->id, 'manual');
1934         // Only a teacher should be able to lock a discussion.
1935         try {
1936             $result = mod_forum_external::set_lock_state($forum->id, $discussion->id, 0);
1937             $this->fail('Exception expected due to missing capability.');
1938         } catch (moodle_exception $e) {
1939             $this->assertEquals('errorcannotlock', $e->errorcode);
1940         }
1942         // Set the lock.
1943         self::setAdminUser();
1944         $result = mod_forum_external::set_lock_state($forum->id, $discussion->id, 0);
1945         $result = external_api::clean_returnvalue(mod_forum_external::set_lock_state_returns(), $result);
1946         $this->assertTrue($result['locked']);
1947         $this->assertNotEquals(0, $result['times']['locked']);
1949         // Unset the lock.
1950         $result = mod_forum_external::set_lock_state($forum->id, $discussion->id, time());
1951         $result = external_api::clean_returnvalue(mod_forum_external::set_lock_state_returns(), $result);
1952         $this->assertFalse($result['locked']);
1953         $this->assertEquals('0', $result['times']['locked']);
1954     }
1956     /*
1957      * Test can_add_discussion. A basic test since all the API functions are already covered by unit tests.
1958      */
1959     public function test_can_add_discussion() {
1960         global $DB;
1961         $this->resetAfterTest(true);
1963         // Create courses to add the modules.
1964         $course = self::getDataGenerator()->create_course();
1966         $user = self::getDataGenerator()->create_user();
1968         // First forum with tracking off.
1969         $record = new stdClass();
1970         $record->course = $course->id;
1971         $record->type = 'news';
1972         $forum = self::getDataGenerator()->create_module('forum', $record);
1974         // User with no permissions to add in a news forum.
1975         self::setUser($user);
1976         $this->getDataGenerator()->enrol_user($user->id, $course->id);
1978         $result = mod_forum_external::can_add_discussion($forum->id);
1979         $result = external_api::clean_returnvalue(mod_forum_external::can_add_discussion_returns(), $result);
1980         $this->assertFalse($result['status']);
1981         $this->assertFalse($result['canpindiscussions']);
1982         $this->assertTrue($result['cancreateattachment']);
1984         // Disable attachments.
1985         $DB->set_field('forum', 'maxattachments', 0, array('id' => $forum->id));
1986         $result = mod_forum_external::can_add_discussion($forum->id);
1987         $result = external_api::clean_returnvalue(mod_forum_external::can_add_discussion_returns(), $result);
1988         $this->assertFalse($result['status']);
1989         $this->assertFalse($result['canpindiscussions']);
1990         $this->assertFalse($result['cancreateattachment']);
1991         $DB->set_field('forum', 'maxattachments', 1, array('id' => $forum->id));    // Enable attachments again.
1993         self::setAdminUser();
1994         $result = mod_forum_external::can_add_discussion($forum->id);
1995         $result = external_api::clean_returnvalue(mod_forum_external::can_add_discussion_returns(), $result);
1996         $this->assertTrue($result['status']);
1997         $this->assertTrue($result['canpindiscussions']);
1998         $this->assertTrue($result['cancreateattachment']);
1999     }
2001     /*
2002      * A basic test to make sure users cannot post to forum after the cutoff date.
2003      */
2004     public function test_can_add_discussion_after_cutoff() {
2005         $this->resetAfterTest(true);
2007         // Create courses to add the modules.
2008         $course = self::getDataGenerator()->create_course();
2010         $user = self::getDataGenerator()->create_user();
2012         // Create a forum with cutoff date set to a past date.
2013         $forum = self::getDataGenerator()->create_module('forum', ['course' => $course->id, 'cutoffdate' => time() - 1]);
2015         // User with no mod/forum:canoverridecutoff capability.
2016         self::setUser($user);
2017         $this->getDataGenerator()->enrol_user($user->id, $course->id);
2019         $result = mod_forum_external::can_add_discussion($forum->id);
2020         $result = external_api::clean_returnvalue(mod_forum_external::can_add_discussion_returns(), $result);
2021         $this->assertFalse($result['status']);
2023         self::setAdminUser();
2024         $result = mod_forum_external::can_add_discussion($forum->id);
2025         $result = external_api::clean_returnvalue(mod_forum_external::can_add_discussion_returns(), $result);
2026         $this->assertTrue($result['status']);
2027     }
2029     /**
2030      * Test get forum posts discussions including rating information.
2031      */
2032     public function test_mod_forum_get_forum_discussion_rating_information() {
2033         global $DB, $CFG;
2034         require_once($CFG->dirroot . '/rating/lib.php');
2036         $this->resetAfterTest(true);
2038         $user1 = self::getDataGenerator()->create_user();
2039         $user2 = self::getDataGenerator()->create_user();
2040         $user3 = self::getDataGenerator()->create_user();
2041         $teacher = self::getDataGenerator()->create_user();
2043         // Create course to add the module.
2044         $course = self::getDataGenerator()->create_course();
2046         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
2047         $teacherrole = $DB->get_record('role', array('shortname' => 'editingteacher'));
2048         $this->getDataGenerator()->enrol_user($user1->id, $course->id, $studentrole->id, 'manual');
2049         $this->getDataGenerator()->enrol_user($user2->id, $course->id, $studentrole->id, 'manual');
2050         $this->getDataGenerator()->enrol_user($user3->id, $course->id, $studentrole->id, 'manual');
2051         $this->getDataGenerator()->enrol_user($teacher->id, $course->id, $teacherrole->id, 'manual');
2053         // Create the forum.
2054         $record = new stdClass();
2055         $record->course = $course->id;
2056         // Set Aggregate type = Average of ratings.
2057         $record->assessed = RATING_AGGREGATE_AVERAGE;
2058         $record->scale = 100;
2059         $forum = self::getDataGenerator()->create_module('forum', $record);
2060         $context = context_module::instance($forum->cmid);
2062         // Add discussion to the forum.
2063         $record = new stdClass();
2064         $record->course = $course->id;
2065         $record->userid = $user1->id;
2066         $record->forum = $forum->id;
2067         $discussion = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
2069         // Retrieve the first post.
2070         $post = $DB->get_record('forum_posts', array('discussion' => $discussion->id));
2072         // Rate the discussion as user2.
2073         $rating1 = new stdClass();
2074         $rating1->contextid = $context->id;
2075         $rating1->component = 'mod_forum';
2076         $rating1->ratingarea = 'post';
2077         $rating1->itemid = $post->id;
2078         $rating1->rating = 50;
2079         $rating1->scaleid = 100;
2080         $rating1->userid = $user2->id;
2081         $rating1->timecreated = time();
2082         $rating1->timemodified = time();
2083         $rating1->id = $DB->insert_record('rating', $rating1);
2085         // Rate the discussion as user3.
2086         $rating2 = new stdClass();
2087         $rating2->contextid = $context->id;
2088         $rating2->component = 'mod_forum';
2089         $rating2->ratingarea = 'post';
2090         $rating2->itemid = $post->id;
2091         $rating2->rating = 100;
2092         $rating2->scaleid = 100;
2093         $rating2->userid = $user3->id;
2094         $rating2->timecreated = time() + 1;
2095         $rating2->timemodified = time() + 1;
2096         $rating2->id = $DB->insert_record('rating', $rating2);
2098         // Retrieve the rating for the post as student.
2099         $this->setUser($user1);
2100         $posts = mod_forum_external::get_forum_discussion_posts($discussion->id);
2101         $posts = external_api::clean_returnvalue(mod_forum_external::get_forum_discussion_posts_returns(), $posts);
2102         $this->assertCount(1, $posts['ratinginfo']['ratings']);
2103         $this->assertTrue($posts['ratinginfo']['ratings'][0]['canviewaggregate']);
2104         $this->assertFalse($posts['ratinginfo']['canviewall']);
2105         $this->assertFalse($posts['ratinginfo']['ratings'][0]['canrate']);
2106         $this->assertEquals(2, $posts['ratinginfo']['ratings'][0]['count']);
2107         $this->assertEquals(($rating1->rating + $rating2->rating) / 2, $posts['ratinginfo']['ratings'][0]['aggregate']);
2109         // Retrieve the rating for the post as teacher.
2110         $this->setUser($teacher);
2111         $posts = mod_forum_external::get_forum_discussion_posts($discussion->id);
2112         $posts = external_api::clean_returnvalue(mod_forum_external::get_forum_discussion_posts_returns(), $posts);
2113         $this->assertCount(1, $posts['ratinginfo']['ratings']);
2114         $this->assertTrue($posts['ratinginfo']['ratings'][0]['canviewaggregate']);
2115         $this->assertTrue($posts['ratinginfo']['canviewall']);
2116         $this->assertTrue($posts['ratinginfo']['ratings'][0]['canrate']);
2117         $this->assertEquals(2, $posts['ratinginfo']['ratings'][0]['count']);
2118         $this->assertEquals(($rating1->rating + $rating2->rating) / 2, $posts['ratinginfo']['ratings'][0]['aggregate']);
2119     }
2121     /**
2122      * Test mod_forum_get_forum_access_information.
2123      */
2124     public function test_mod_forum_get_forum_access_information() {
2125         global $DB;
2127         $this->resetAfterTest(true);
2129         $student = self::getDataGenerator()->create_user();
2130         $course = self::getDataGenerator()->create_course();
2131         // Create the forum.
2132         $record = new stdClass();
2133         $record->course = $course->id;
2134         $forum = self::getDataGenerator()->create_module('forum', $record);
2136         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
2137         $this->getDataGenerator()->enrol_user($student->id, $course->id, $studentrole->id, 'manual');
2139         self::setUser($student);
2140         $result = mod_forum_external::get_forum_access_information($forum->id);
2141         $result = external_api::clean_returnvalue(mod_forum_external::get_forum_access_information_returns(), $result);
2143         // Check default values for capabilities.
2144         $enabledcaps = array('canviewdiscussion', 'canstartdiscussion', 'canreplypost', 'canviewrating', 'cancreateattachment',
2145             'canexportownpost', 'cancantogglefavourite', 'candeleteownpost', 'canallowforcesubscribe');
2147         unset($result['warnings']);
2148         foreach ($result as $capname => $capvalue) {
2149             if (in_array($capname, $enabledcaps)) {
2150                 $this->assertTrue($capvalue);
2151             } else {
2152                 $this->assertFalse($capvalue);
2153             }
2154         }
2155         // Now, unassign some capabilities.
2156         unassign_capability('mod/forum:deleteownpost', $studentrole->id);
2157         unassign_capability('mod/forum:allowforcesubscribe', $studentrole->id);
2158         array_pop($enabledcaps);
2159         array_pop($enabledcaps);
2160         accesslib_clear_all_caches_for_unit_testing();
2162         $result = mod_forum_external::get_forum_access_information($forum->id);
2163         $result = external_api::clean_returnvalue(mod_forum_external::get_forum_access_information_returns(), $result);
2164         unset($result['warnings']);
2165         foreach ($result as $capname => $capvalue) {
2166             if (in_array($capname, $enabledcaps)) {
2167                 $this->assertTrue($capvalue);
2168             } else {
2169                 $this->assertFalse($capvalue);
2170             }
2171         }
2172     }
2174     /**
2175      * Test add_discussion_post
2176      */
2177     public function test_add_discussion_post_private() {
2178         global $DB;
2180         $this->resetAfterTest(true);
2182         self::setAdminUser();
2184         // Create course to add the module.
2185         $course = self::getDataGenerator()->create_course();
2187         // Standard forum.
2188         $record = new stdClass();
2189         $record->course = $course->id;
2190         $forum = self::getDataGenerator()->create_module('forum', $record);
2191         $cm = get_coursemodule_from_id('forum', $forum->cmid, 0, false, MUST_EXIST);
2192         $forumcontext = context_module::instance($forum->cmid);
2193         $generator = self::getDataGenerator()->get_plugin_generator('mod_forum');
2195         // Create an enrol users.
2196         $student1 = self::getDataGenerator()->create_user();
2197         $this->getDataGenerator()->enrol_user($student1->id, $course->id, 'student');
2198         $student2 = self::getDataGenerator()->create_user();
2199         $this->getDataGenerator()->enrol_user($student2->id, $course->id, 'student');
2200         $teacher1 = self::getDataGenerator()->create_user();
2201         $this->getDataGenerator()->enrol_user($teacher1->id, $course->id, 'editingteacher');
2202         $teacher2 = self::getDataGenerator()->create_user();
2203         $this->getDataGenerator()->enrol_user($teacher2->id, $course->id, 'editingteacher');
2205         // Add a new discussion to the forum.
2206         self::setUser($student1);
2207         $record = new stdClass();
2208         $record->course = $course->id;
2209         $record->userid = $student1->id;
2210         $record->forum = $forum->id;
2211         $discussion = $generator->create_discussion($record);
2213         // Have the teacher reply privately.
2214         self::setUser($teacher1);
2215         $post = mod_forum_external::add_discussion_post($discussion->firstpost, 'some subject', 'some text here...', [
2216                 [
2217                     'name' => 'private',
2218                     'value' => true,
2219                 ],
2220             ]);
2221         $post = external_api::clean_returnvalue(mod_forum_external::add_discussion_post_returns(), $post);
2222         $privatereply = $DB->get_record('forum_posts', array('id' => $post['postid']));
2223         $this->assertEquals($student1->id, $privatereply->privatereplyto);
2224         // Bump the time of the private reply to ensure order.
2225         $privatereply->created++;
2226         $privatereply->modified = $privatereply->created;
2227         $DB->update_record('forum_posts', $privatereply);
2229         // The teacher will receive their private reply.
2230         self::setUser($teacher1);
2231         $posts = mod_forum_external::get_forum_discussion_posts($discussion->id);
2232         $posts = external_api::clean_returnvalue(mod_forum_external::get_forum_discussion_posts_returns(), $posts);
2233         $this->assertEquals(2, count($posts['posts']));
2234         $this->assertTrue($posts['posts'][0]['isprivatereply']);
2236         // Another teacher on the course will also receive the private reply.
2237         self::setUser($teacher2);
2238         $posts = mod_forum_external::get_forum_discussion_posts($discussion->id);
2239         $posts = external_api::clean_returnvalue(mod_forum_external::get_forum_discussion_posts_returns(), $posts);
2240         $this->assertEquals(2, count($posts['posts']));
2241         $this->assertTrue($posts['posts'][0]['isprivatereply']);
2243         // The student will receive the private reply.
2244         self::setUser($student1);
2245         $posts = mod_forum_external::get_forum_discussion_posts($discussion->id);
2246         $posts = external_api::clean_returnvalue(mod_forum_external::get_forum_discussion_posts_returns(), $posts);
2247         $this->assertEquals(2, count($posts['posts']));
2248         $this->assertTrue($posts['posts'][0]['isprivatereply']);
2250         // Another student will not receive the private reply.
2251         self::setUser($student2);
2252         $posts = mod_forum_external::get_forum_discussion_posts($discussion->id);
2253         $posts = external_api::clean_returnvalue(mod_forum_external::get_forum_discussion_posts_returns(), $posts);
2254         $this->assertEquals(1, count($posts['posts']));
2255         $this->assertFalse($posts['posts'][0]['isprivatereply']);
2257         // A user cannot reply to a private reply.
2258         self::setUser($teacher2);
2259         $this->expectException('coding_exception');
2260         $post = mod_forum_external::add_discussion_post($privatereply->id, 'some subject', 'some text here...', [
2261                 'options' => [
2262                     'name' => 'private',
2263                     'value' => false,
2264                 ],
2265             ]);
2266     }