MDL-67673 phpunit: Remove deprecated assertContains() uses on strings
[moodle.git] / search / tests / manager_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  * Search manager unit tests.
19  *
20  * @package     core_search
21  * @category    phpunit
22  * @copyright   2015 David Monllao {@link http://www.davidmonllao.com}
23  * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
26 defined('MOODLE_INTERNAL') || die();
28 require_once(__DIR__ . '/fixtures/testable_core_search.php');
29 require_once(__DIR__ . '/fixtures/mock_search_area.php');
31 /**
32  * Unit tests for search manager.
33  *
34  * @package     core_search
35  * @category    phpunit
36  * @copyright   2015 David Monllao {@link http://www.davidmonllao.com}
37  * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38  */
39 class search_manager_testcase extends advanced_testcase {
41     /**
42      * Forum area id.
43      *
44      * @var string
45      */
47     protected $forumpostareaid = null;
49     /**
50      * Courses area id.
51      *
52      * @var string
53      */
54     protected $coursesareaid = null;
56     public function setUp(): void {
57         $this->forumpostareaid = \core_search\manager::generate_areaid('mod_forum', 'post');
58         $this->coursesareaid = \core_search\manager::generate_areaid('core_course', 'course');
59     }
61     protected function tearDown(): void {
62         // Stop it from faking time in the search manager (if set by test).
63         testable_core_search::fake_current_time();
64         parent::tearDown();
65     }
67     public function test_search_enabled() {
69         $this->resetAfterTest();
71         // Disabled by default.
72         $this->assertFalse(\core_search\manager::is_global_search_enabled());
74         set_config('enableglobalsearch', true);
75         $this->assertTrue(\core_search\manager::is_global_search_enabled());
77         set_config('enableglobalsearch', false);
78         $this->assertFalse(\core_search\manager::is_global_search_enabled());
79     }
81     public function test_course_search_url() {
83         $this->resetAfterTest();
85         // URL is course/search.php by default.
86         $this->assertEquals(new moodle_url("/course/search.php"), \core_search\manager::get_course_search_url());
88         set_config('enableglobalsearch', true);
89         $this->assertEquals(new moodle_url("/search/index.php"), \core_search\manager::get_course_search_url());
91         set_config('enableglobalsearch', false);
92         $this->assertEquals(new moodle_url("/course/search.php"), \core_search\manager::get_course_search_url());
93     }
95     public function test_search_areas() {
96         global $CFG;
98         $this->resetAfterTest();
100         set_config('enableglobalsearch', true);
102         $fakeareaid = \core_search\manager::generate_areaid('mod_unexisting', 'chihuaquita');
104         $searcharea = \core_search\manager::get_search_area($this->forumpostareaid);
105         $this->assertInstanceOf('\core_search\base', $searcharea);
107         $this->assertFalse(\core_search\manager::get_search_area($fakeareaid));
109         $this->assertArrayHasKey($this->forumpostareaid, \core_search\manager::get_search_areas_list());
110         $this->assertArrayNotHasKey($fakeareaid, \core_search\manager::get_search_areas_list());
112         // Enabled by default once global search is enabled.
113         $this->assertArrayHasKey($this->forumpostareaid, \core_search\manager::get_search_areas_list(true));
115         list($componentname, $varname) = $searcharea->get_config_var_name();
116         set_config($varname . '_enabled', 0, $componentname);
117         \core_search\manager::clear_static();
119         $this->assertArrayNotHasKey('mod_forum', \core_search\manager::get_search_areas_list(true));
121         set_config($varname . '_enabled', 1, $componentname);
123         // Although the result is wrong, we want to check that \core_search\manager::get_search_areas_list returns cached results.
124         $this->assertArrayNotHasKey($this->forumpostareaid, \core_search\manager::get_search_areas_list(true));
126         // Now we check the real result.
127         \core_search\manager::clear_static();
128         $this->assertArrayHasKey($this->forumpostareaid, \core_search\manager::get_search_areas_list(true));
129     }
131     public function test_search_config() {
133         $this->resetAfterTest();
135         $search = testable_core_search::instance();
137         // We should test both plugin types and core subsystems. No core subsystems available yet.
138         $searcharea = $search->get_search_area($this->forumpostareaid);
140         list($componentname, $varname) = $searcharea->get_config_var_name();
142         // Just with a couple of vars should be enough.
143         $start = time() - 100;
144         $end = time();
145         set_config($varname . '_indexingstart', $start, $componentname);
146         set_config($varname . '_indexingend', $end, $componentname);
148         $configs = $search->get_areas_config(array($this->forumpostareaid => $searcharea));
149         $this->assertEquals($start, $configs[$this->forumpostareaid]->indexingstart);
150         $this->assertEquals($end, $configs[$this->forumpostareaid]->indexingend);
151         $this->assertEquals(false, $configs[$this->forumpostareaid]->partial);
153         try {
154             $fakeareaid = \core_search\manager::generate_areaid('mod_unexisting', 'chihuaquita');
155             $search->reset_config($fakeareaid);
156             $this->fail('An exception should be triggered if the provided search area does not exist.');
157         } catch (moodle_exception $ex) {
158             $this->assertStringContainsString($fakeareaid . ' search area is not available.', $ex->getMessage());
159         }
161         // We clean it all but enabled components.
162         $search->reset_config($this->forumpostareaid);
163         $config = $searcharea->get_config();
164         $this->assertEquals(1, $config[$varname . '_enabled']);
165         $this->assertEquals(0, $config[$varname . '_indexingstart']);
166         $this->assertEquals(0, $config[$varname . '_indexingend']);
167         $this->assertEquals(0, $config[$varname . '_lastindexrun']);
168         $this->assertEquals(0, $config[$varname . '_partial']);
169         // No caching.
170         $configs = $search->get_areas_config(array($this->forumpostareaid => $searcharea));
171         $this->assertEquals(0, $configs[$this->forumpostareaid]->indexingstart);
172         $this->assertEquals(0, $configs[$this->forumpostareaid]->indexingend);
174         set_config($varname . '_indexingstart', $start, $componentname);
175         set_config($varname . '_indexingend', $end, $componentname);
177         // All components config should be reset.
178         $search->reset_config();
179         $this->assertEquals(0, get_config($componentname, $varname . '_indexingstart'));
180         $this->assertEquals(0, get_config($componentname, $varname . '_indexingend'));
181         $this->assertEquals(0, get_config($componentname, $varname . '_lastindexrun'));
182         // No caching.
183         $configs = $search->get_areas_config(array($this->forumpostareaid => $searcharea));
184         $this->assertEquals(0, $configs[$this->forumpostareaid]->indexingstart);
185         $this->assertEquals(0, $configs[$this->forumpostareaid]->indexingend);
186     }
188     /**
189      * Tests the get_last_indexing_duration method in the base area class.
190      */
191     public function test_get_last_indexing_duration() {
192         $this->resetAfterTest();
194         $search = testable_core_search::instance();
196         $searcharea = $search->get_search_area($this->forumpostareaid);
198         // When never indexed, the duration is false.
199         $this->assertSame(false, $searcharea->get_last_indexing_duration());
201         // Set the start/end times.
202         list($componentname, $varname) = $searcharea->get_config_var_name();
203         $start = time() - 100;
204         $end = time();
205         set_config($varname . '_indexingstart', $start, $componentname);
206         set_config($varname . '_indexingend', $end, $componentname);
208         // The duration should now be 100.
209         $this->assertSame(100, $searcharea->get_last_indexing_duration());
210     }
212     /**
213      * Tests that partial indexing works correctly.
214      */
215     public function test_partial_indexing() {
216         global $USER;
218         $this->resetAfterTest();
219         $this->setAdminUser();
221         // Create a course and a forum.
222         $generator = $this->getDataGenerator();
223         $course = $generator->create_course();
224         $forum = $generator->create_module('forum', ['course' => $course->id]);
226         // Index everything up to current. Ensure the course is older than current second so it
227         // definitely doesn't get indexed again next time.
228         $this->waitForSecond();
229         $search = testable_core_search::instance();
230         $search->index(false, 0);
232         $searcharea = $search->get_search_area($this->forumpostareaid);
233         list($componentname, $varname) = $searcharea->get_config_var_name();
234         $this->assertFalse(get_config($componentname, $varname . '_partial'));
236         // Add 3 discussions to the forum.
237         $now = time();
238         $generator->get_plugin_generator('mod_forum')->create_discussion(['course' => $course->id,
239                 'forum' => $forum->id, 'userid' => $USER->id, 'timemodified' => $now,
240                 'name' => 'Frog']);
241         $generator->get_plugin_generator('mod_forum')->create_discussion(['course' => $course->id,
242                 'forum' => $forum->id, 'userid' => $USER->id, 'timemodified' => $now + 1,
243                 'name' => 'Toad']);
244         $generator->get_plugin_generator('mod_forum')->create_discussion(['course' => $course->id,
245                 'forum' => $forum->id, 'userid' => $USER->id, 'timemodified' => $now + 2,
246                 'name' => 'Zombie']);
247         $generator->get_plugin_generator('mod_forum')->create_discussion(['course' => $course->id,
248                 'forum' => $forum->id, 'userid' => $USER->id, 'timemodified' => $now + 2,
249                 'name' => 'Werewolf']);
250         time_sleep_until($now + 3);
252         // Clear the count of added documents.
253         $search->get_engine()->get_and_clear_added_documents();
255         // Make the search engine delay while indexing each document.
256         $search->get_engine()->set_add_delay(1.2);
258         // Use fake time, starting from now.
259         testable_core_search::fake_current_time(time());
261         // Index with a limit of 2 seconds - it should index 2 of the documents (after the second
262         // one, it will have taken 2.4 seconds so it will stop).
263         $search->index(false, 2);
264         $added = $search->get_engine()->get_and_clear_added_documents();
265         $this->assertCount(2, $added);
266         $this->assertEquals('Frog', $added[0]->get('title'));
267         $this->assertEquals('Toad', $added[1]->get('title'));
268         $this->assertEquals(1, get_config($componentname, $varname . '_partial'));
269         // Whilst 2.4 seconds of "time" have elapsed, the indexing duration is
270         // measured in seconds, so should be 2.
271         $this->assertEquals(2, $searcharea->get_last_indexing_duration());
273         // Add a label.
274         $generator->create_module('label', ['course' => $course->id, 'intro' => 'Vampire']);
276         // Wait to next second (so as to not reindex the label more than once, as it will now
277         // be timed before the indexing run).
278         $this->waitForSecond();
279         testable_core_search::fake_current_time(time());
281         // Next index with 1 second limit should do the label and not the forum - the logic is,
282         // if it spent ages indexing an area last time, do that one last on next run.
283         $search->index(false, 1);
284         $added = $search->get_engine()->get_and_clear_added_documents();
285         $this->assertCount(1, $added);
286         $this->assertEquals('Vampire', $added[0]->get('title'));
288         // Index again with a 3 second limit - it will redo last post for safety (because of other
289         // things possibly having the same time second), and then do the remaining one. (Note:
290         // because it always does more than one second worth of items, it would actually index 2
291         // posts even if the limit were less than 2, we are testing it does 3 posts to make sure
292         // the time limiting is actually working with the specified time.)
293         $search->index(false, 3);
294         $added = $search->get_engine()->get_and_clear_added_documents();
295         $this->assertCount(3, $added);
296         $this->assertEquals('Toad', $added[0]->get('title'));
297         $remainingtitles = [$added[1]->get('title'), $added[2]->get('title')];
298         sort($remainingtitles);
299         $this->assertEquals(['Werewolf', 'Zombie'], $remainingtitles);
300         $this->assertFalse(get_config($componentname, $varname . '_partial'));
302         // Index again - there should be nothing to index this time.
303         $search->index(false, 2);
304         $added = $search->get_engine()->get_and_clear_added_documents();
305         $this->assertCount(0, $added);
306         $this->assertFalse(get_config($componentname, $varname . '_partial'));
307     }
309     /**
310      * Tests the progress display while indexing.
311      *
312      * This tests the different logic about displaying progress for slow/fast and
313      * complete/incomplete processing.
314      */
315     public function test_index_progress() {
316         $this->resetAfterTest();
317         $generator = $this->getDataGenerator();
319         // Set up the fake search area.
320         $search = testable_core_search::instance();
321         $area = new \core_mocksearch\search\mock_search_area();
322         $search->add_search_area('whatever', $area);
323         $searchgenerator = $generator->get_plugin_generator('core_search');
324         $searchgenerator->setUp();
326         // Add records with specific time modified values.
327         $time = strtotime('2017-11-01 01:00');
328         for ($i = 0; $i < 8; $i ++) {
329             $searchgenerator->create_record((object)['timemodified' => $time]);
330             $time += 60;
331         }
333         // Simulate slow progress on indexing and initial query.
334         $now = strtotime('2017-11-11 01:00');
335         \testable_core_search::fake_current_time($now);
336         $area->set_indexing_delay(10.123);
337         $search->get_engine()->set_add_delay(15.789);
339         // Run search indexing and check output.
340         $progress = new progress_trace_buffer(new text_progress_trace(), false);
341         $search->index(false, 75, $progress);
342         $out = $progress->get_buffer();
343         $progress->reset_buffer();
345         // Check for the standard text.
346         $this->assertStringContainsString('Processing area: Mock search area', $out);
347         $this->assertStringContainsString('Stopping indexing due to time limit', $out);
349         // Check for initial query performance indication.
350         $this->assertStringContainsString('Initial query took 10.1 seconds.', $out);
352         // Check for the two (approximately) every-30-seconds messages.
353         $this->assertStringContainsString('01:00:41: Done to 1/11/17, 01:01', $out);
354         $this->assertStringContainsString('01:01:13: Done to 1/11/17, 01:03', $out);
356         // Check for the 'not complete' indicator showing when it was done until.
357         $this->assertStringContainsString('Processed 5 records containing 5 documents, in 89.1 seconds ' .
358                 '(not complete; done to 1/11/17, 01:04)', $out);
360         // Make the initial query delay less than 5 seconds, so it won't appear. Make the documents
361         // quicker, so that the 30-second delay won't be needed.
362         $area->set_indexing_delay(4.9);
363         $search->get_engine()->set_add_delay(1);
365         // Run search indexing (still partial) and check output.
366         $progress = new progress_trace_buffer(new text_progress_trace(), false);
367         $search->index(false, 5, $progress);
368         $out = $progress->get_buffer();
369         $progress->reset_buffer();
371         $this->assertStringContainsString('Processing area: Mock search area', $out);
372         $this->assertStringContainsString('Stopping indexing due to time limit', $out);
373         $this->assertStringNotContainsString('Initial query took', $out);
374         $this->assertStringNotContainsString(': Done to', $out);
375         $this->assertStringContainsString('Processed 2 records containing 2 documents, in 6.9 seconds ' .
376                 '(not complete; done to 1/11/17, 01:05).', $out);
378         // Run the remaining items to complete it.
379         $progress = new progress_trace_buffer(new text_progress_trace(), false);
380         $search->index(false, 100, $progress);
381         $out = $progress->get_buffer();
382         $progress->reset_buffer();
384         $this->assertStringContainsString('Processing area: Mock search area', $out);
385         $this->assertStringNotContainsString('Stopping indexing due to time limit', $out);
386         $this->assertStringNotContainsString('Initial query took', $out);
387         $this->assertStringNotContainsString(': Done to', $out);
388         $this->assertStringContainsString('Processed 3 records containing 3 documents, in 7.9 seconds.', $out);
390         $searchgenerator->tearDown();
391     }
393     /**
394      * Tests that documents with modified time in the future are NOT indexed (as this would cause
395      * a problem by preventing it from indexing other documents modified between now and the future
396      * date).
397      */
398     public function test_future_documents() {
399         $this->resetAfterTest();
401         // Create a course and a forum.
402         $generator = $this->getDataGenerator();
403         $course = $generator->create_course();
404         $forum = $generator->create_module('forum', ['course' => $course->id]);
406         // Index everything up to current. Ensure the course is older than current second so it
407         // definitely doesn't get indexed again next time.
408         $this->waitForSecond();
409         $search = testable_core_search::instance();
410         $search->index(false, 0);
411         $search->get_engine()->get_and_clear_added_documents();
413         // Add 2 discussions to the forum, one of which happend just now, but the other is
414         // incorrectly set to the future.
415         $now = time();
416         $userid = get_admin()->id;
417         $generator->get_plugin_generator('mod_forum')->create_discussion(['course' => $course->id,
418                 'forum' => $forum->id, 'userid' => $userid, 'timemodified' => $now,
419                 'name' => 'Frog']);
420         $generator->get_plugin_generator('mod_forum')->create_discussion(['course' => $course->id,
421                 'forum' => $forum->id, 'userid' => $userid, 'timemodified' => $now + 100,
422                 'name' => 'Toad']);
424         // Wait for a second so we're not actually on the same second as the forum post (there's a
425         // 1 second overlap between indexing; it would get indexed in both checks below otherwise).
426         $this->waitForSecond();
428         // Index.
429         $search->index(false);
430         $added = $search->get_engine()->get_and_clear_added_documents();
431         $this->assertCount(1, $added);
432         $this->assertEquals('Frog', $added[0]->get('title'));
434         // Check latest time - it should be the same as $now, not the + 100.
435         $searcharea = $search->get_search_area($this->forumpostareaid);
436         list($componentname, $varname) = $searcharea->get_config_var_name();
437         $this->assertEquals($now, get_config($componentname, $varname . '_lastindexrun'));
439         // Index again - there should be nothing to index this time.
440         $search->index(false);
441         $added = $search->get_engine()->get_and_clear_added_documents();
442         $this->assertCount(0, $added);
443     }
445     /**
446      * Tests that indexing a specified context works correctly.
447      */
448     public function test_context_indexing() {
449         global $USER;
451         $this->resetAfterTest();
452         $this->setAdminUser();
454         // Create a course and two forums and a page.
455         $generator = $this->getDataGenerator();
456         $course = $generator->create_course();
457         $now = time();
458         $forum1 = $generator->create_module('forum', ['course' => $course->id]);
459         $generator->get_plugin_generator('mod_forum')->create_discussion(['course' => $course->id,
460                 'forum' => $forum1->id, 'userid' => $USER->id, 'timemodified' => $now,
461                 'name' => 'Frog']);
462         $this->waitForSecond();
463         $generator->get_plugin_generator('mod_forum')->create_discussion(['course' => $course->id,
464                 'forum' => $forum1->id, 'userid' => $USER->id, 'timemodified' => $now + 2,
465                 'name' => 'Zombie']);
466         $forum2 = $generator->create_module('forum', ['course' => $course->id]);
467         $this->waitForSecond();
468         $generator->get_plugin_generator('mod_forum')->create_discussion(['course' => $course->id,
469                 'forum' => $forum2->id, 'userid' => $USER->id, 'timemodified' => $now + 1,
470                 'name' => 'Toad']);
471         $generator->create_module('page', ['course' => $course->id]);
472         $generator->create_module('forum', ['course' => $course->id]);
474         // Index forum 1 only.
475         $search = testable_core_search::instance();
476         $buffer = new progress_trace_buffer(new text_progress_trace(), false);
477         $result = $search->index_context(\context_module::instance($forum1->cmid), '', 0, $buffer);
478         $this->assertTrue($result->complete);
479         $log = $buffer->get_buffer();
480         $buffer->reset_buffer();
482         // Confirm that output only processed 1 forum activity and 2 posts.
483         $this->assertNotFalse(strpos($log, "area: Forum - activity information\n  Processed 1 "));
484         $this->assertNotFalse(strpos($log, "area: Forum - posts\n  Processed 2 "));
486         // Confirm that some areas for different types of context were skipped.
487         $this->assertNotFalse(strpos($log, "area: Users\n  Skipping"));
488         $this->assertNotFalse(strpos($log, "area: Courses\n  Skipping"));
490         // Confirm that another module area had no results.
491         $this->assertNotFalse(strpos($log, "area: Page\n  No documents"));
493         // Index whole course.
494         $result = $search->index_context(\context_course::instance($course->id), '', 0, $buffer);
495         $this->assertTrue($result->complete);
496         $log = $buffer->get_buffer();
497         $buffer->reset_buffer();
499         // Confirm that output processed 3 forum activities and 3 posts.
500         $this->assertNotFalse(strpos($log, "area: Forum - activity information\n  Processed 3 "));
501         $this->assertNotFalse(strpos($log, "area: Forum - posts\n  Processed 3 "));
503         // The course area was also included this time.
504         $this->assertNotFalse(strpos($log, "area: Courses\n  Processed 1 "));
506         // Confirm that another module area had results too.
507         $this->assertNotFalse(strpos($log, "area: Page\n  Processed 1 "));
509         // Index whole course, but only forum posts.
510         $result = $search->index_context(\context_course::instance($course->id), 'mod_forum-post',
511                 0, $buffer);
512         $this->assertTrue($result->complete);
513         $log = $buffer->get_buffer();
514         $buffer->reset_buffer();
516         // Confirm that output processed 3 posts but not forum activities.
517         $this->assertFalse(strpos($log, "area: Forum - activity information"));
518         $this->assertNotFalse(strpos($log, "area: Forum - posts\n  Processed 3 "));
520         // Set time limit and retry index of whole course, taking 3 tries to complete it.
521         $search->get_engine()->set_add_delay(0.4);
522         $result = $search->index_context(\context_course::instance($course->id), '', 1, $buffer);
523         $log = $buffer->get_buffer();
524         $buffer->reset_buffer();
525         $this->assertFalse($result->complete);
526         $this->assertNotFalse(strpos($log, "area: Forum - activity information\n  Processed 2 "));
528         $result = $search->index_context(\context_course::instance($course->id), '', 1, $buffer,
529                 $result->startfromarea, $result->startfromtime);
530         $log = $buffer->get_buffer();
531         $buffer->reset_buffer();
532         $this->assertNotFalse(strpos($log, "area: Forum - activity information\n  Processed 2 "));
533         $this->assertNotFalse(strpos($log, "area: Forum - posts\n  Processed 2 "));
534         $this->assertFalse($result->complete);
536         $result = $search->index_context(\context_course::instance($course->id), '', 1, $buffer,
537                 $result->startfromarea, $result->startfromtime);
538         $log = $buffer->get_buffer();
539         $buffer->reset_buffer();
540         $this->assertNotFalse(strpos($log, "area: Forum - posts\n  Processed 2 "));
541         $this->assertTrue($result->complete);
542     }
544     /**
545      * Adding this test here as get_areas_user_accesses process is the same, results just depend on the context level.
546      *
547      * @return void
548      */
549     public function test_search_user_accesses() {
550         global $DB;
552         $this->resetAfterTest();
554         $frontpage = $DB->get_record('course', array('id' => SITEID));
555         $frontpagectx = context_course::instance($frontpage->id);
556         $course1 = $this->getDataGenerator()->create_course();
557         $course1ctx = context_course::instance($course1->id);
558         $course2 = $this->getDataGenerator()->create_course();
559         $course2ctx = context_course::instance($course2->id);
560         $course3 = $this->getDataGenerator()->create_course();
561         $course3ctx = context_course::instance($course3->id);
562         $teacher = $this->getDataGenerator()->create_user();
563         $teacherctx = context_user::instance($teacher->id);
564         $student = $this->getDataGenerator()->create_user();
565         $studentctx = context_user::instance($student->id);
566         $noaccess = $this->getDataGenerator()->create_user();
567         $noaccessctx = context_user::instance($noaccess->id);
568         $this->getDataGenerator()->enrol_user($teacher->id, $course1->id, 'teacher');
569         $this->getDataGenerator()->enrol_user($student->id, $course1->id, 'student');
571         $frontpageforum = $this->getDataGenerator()->create_module('forum', array('course' => $frontpage->id));
572         $forum1 = $this->getDataGenerator()->create_module('forum', array('course' => $course1->id));
573         $forum2 = $this->getDataGenerator()->create_module('forum', array('course' => $course1->id));
574         $forum3 = $this->getDataGenerator()->create_module('forum', array('course' => $course2->id));
575         $frontpageforumcontext = context_module::instance($frontpageforum->cmid);
576         $context1 = context_module::instance($forum1->cmid);
577         $context2 = context_module::instance($forum2->cmid);
578         $context3 = context_module::instance($forum3->cmid);
579         $forum4 = $this->getDataGenerator()->create_module('forum', array('course' => $course3->id));
580         $context4 = context_module::instance($forum4->cmid);
582         $search = testable_core_search::instance();
583         $mockareaid = \core_search\manager::generate_areaid('core_mocksearch', 'mock_search_area');
584         $search->add_core_search_areas();
585         $search->add_search_area($mockareaid, new core_mocksearch\search\mock_search_area());
587         $this->setAdminUser();
588         $this->assertEquals((object)['everything' => true], $search->get_areas_user_accesses());
590         $sitectx = \context_course::instance(SITEID);
592         // Can access the frontpage ones.
593         $this->setUser($noaccess);
594         $contexts = $search->get_areas_user_accesses()->usercontexts;
595         $this->assertEquals(array($frontpageforumcontext->id => $frontpageforumcontext->id), $contexts[$this->forumpostareaid]);
596         $this->assertEquals(array($sitectx->id => $sitectx->id), $contexts[$this->coursesareaid]);
597         $mockctxs = array($noaccessctx->id => $noaccessctx->id, $frontpagectx->id => $frontpagectx->id);
598         $this->assertEquals($mockctxs, $contexts[$mockareaid]);
600         $this->setUser($teacher);
601         $contexts = $search->get_areas_user_accesses()->usercontexts;
602         $frontpageandcourse1 = array($frontpageforumcontext->id => $frontpageforumcontext->id, $context1->id => $context1->id,
603             $context2->id => $context2->id);
604         $this->assertEquals($frontpageandcourse1, $contexts[$this->forumpostareaid]);
605         $this->assertEquals(array($sitectx->id => $sitectx->id, $course1ctx->id => $course1ctx->id),
606             $contexts[$this->coursesareaid]);
607         $mockctxs = array($teacherctx->id => $teacherctx->id,
608                 $frontpagectx->id => $frontpagectx->id, $course1ctx->id => $course1ctx->id);
609         $this->assertEquals($mockctxs, $contexts[$mockareaid]);
611         $this->setUser($student);
612         $contexts = $search->get_areas_user_accesses()->usercontexts;
613         $this->assertEquals($frontpageandcourse1, $contexts[$this->forumpostareaid]);
614         $this->assertEquals(array($sitectx->id => $sitectx->id, $course1ctx->id => $course1ctx->id),
615             $contexts[$this->coursesareaid]);
616         $mockctxs = array($studentctx->id => $studentctx->id,
617                 $frontpagectx->id => $frontpagectx->id, $course1ctx->id => $course1ctx->id);
618         $this->assertEquals($mockctxs, $contexts[$mockareaid]);
620         // Hide the activity.
621         set_coursemodule_visible($forum2->cmid, 0);
622         $contexts = $search->get_areas_user_accesses()->usercontexts;
623         $this->assertEquals(array($frontpageforumcontext->id => $frontpageforumcontext->id, $context1->id => $context1->id),
624             $contexts[$this->forumpostareaid]);
626         // Now test course limited searches.
627         set_coursemodule_visible($forum2->cmid, 1);
628         $this->getDataGenerator()->enrol_user($student->id, $course2->id, 'student');
629         $contexts = $search->get_areas_user_accesses()->usercontexts;
630         $allcontexts = array($frontpageforumcontext->id => $frontpageforumcontext->id, $context1->id => $context1->id,
631             $context2->id => $context2->id, $context3->id => $context3->id);
632         $this->assertEquals($allcontexts, $contexts[$this->forumpostareaid]);
633         $this->assertEquals(array($sitectx->id => $sitectx->id, $course1ctx->id => $course1ctx->id,
634             $course2ctx->id => $course2ctx->id), $contexts[$this->coursesareaid]);
636         $contexts = $search->get_areas_user_accesses(array($course1->id, $course2->id))->usercontexts;
637         $allcontexts = array($context1->id => $context1->id, $context2->id => $context2->id, $context3->id => $context3->id);
638         $this->assertEquals($allcontexts, $contexts[$this->forumpostareaid]);
639         $this->assertEquals(array($course1ctx->id => $course1ctx->id,
640             $course2ctx->id => $course2ctx->id), $contexts[$this->coursesareaid]);
642         $contexts = $search->get_areas_user_accesses(array($course2->id))->usercontexts;
643         $allcontexts = array($context3->id => $context3->id);
644         $this->assertEquals($allcontexts, $contexts[$this->forumpostareaid]);
645         $this->assertEquals(array($course2ctx->id => $course2ctx->id), $contexts[$this->coursesareaid]);
647         $contexts = $search->get_areas_user_accesses(array($course1->id))->usercontexts;
648         $allcontexts = array($context1->id => $context1->id, $context2->id => $context2->id);
649         $this->assertEquals($allcontexts, $contexts[$this->forumpostareaid]);
650         $this->assertEquals(array($course1ctx->id => $course1ctx->id), $contexts[$this->coursesareaid]);
652         // Test context limited search with no course limit.
653         $contexts = $search->get_areas_user_accesses(false,
654                 [$frontpageforumcontext->id, $course2ctx->id])->usercontexts;
655         $this->assertEquals([$frontpageforumcontext->id => $frontpageforumcontext->id],
656                 $contexts[$this->forumpostareaid]);
657         $this->assertEquals([$course2ctx->id => $course2ctx->id],
658                 $contexts[$this->coursesareaid]);
660         // Test context limited search with course limit.
661         $contexts = $search->get_areas_user_accesses([$course1->id, $course2->id],
662                 [$frontpageforumcontext->id, $course2ctx->id])->usercontexts;
663         $this->assertArrayNotHasKey($this->forumpostareaid, $contexts);
664         $this->assertEquals([$course2ctx->id => $course2ctx->id],
665                 $contexts[$this->coursesareaid]);
667         // Single context and course.
668         $contexts = $search->get_areas_user_accesses([$course1->id], [$context1->id])->usercontexts;
669         $this->assertEquals([$context1->id => $context1->id], $contexts[$this->forumpostareaid]);
670         $this->assertArrayNotHasKey($this->coursesareaid, $contexts);
672         // Enable "Include all visible courses" feature.
673         set_config('searchincludeallcourses', 1);
674         $contexts = $search->get_areas_user_accesses()->usercontexts;
675         $expected = [
676             $sitectx->id => $sitectx->id,
677             $course1ctx->id => $course1ctx->id,
678             $course2ctx->id => $course2ctx->id,
679             $course3ctx->id => $course3ctx->id
680         ];
681         // Check that a student has assess to all courses data when "searchincludeallcourses" is enabled.
682         $this->assertEquals($expected, $contexts[$this->coursesareaid]);
683         // But at the same time doesn't have access to activities in the courses that the student can't access.
684         $this->assertFalse(key_exists($context4->id, $contexts[$this->forumpostareaid]));
686         // For admins, this is still limited only if we specify the things, so it should be same.
687         $this->setAdminUser();
688         $contexts = $search->get_areas_user_accesses([$course1->id], [$context1->id])->usercontexts;
689         $this->assertEquals([$context1->id => $context1->id], $contexts[$this->forumpostareaid]);
690         $this->assertArrayNotHasKey($this->coursesareaid, $contexts);
691     }
693     /**
694      * Tests the block support in get_search_user_accesses.
695      *
696      * @return void
697      */
698     public function test_search_user_accesses_blocks() {
699         global $DB;
701         $this->resetAfterTest();
702         $this->setAdminUser();
704         // Create course and add HTML block.
705         $generator = $this->getDataGenerator();
706         $course1 = $generator->create_course();
707         $context1 = \context_course::instance($course1->id);
708         $page = new \moodle_page();
709         $page->set_context($context1);
710         $page->set_course($course1);
711         $page->set_pagelayout('standard');
712         $page->set_pagetype('course-view');
713         $page->blocks->load_blocks();
714         $page->blocks->add_block_at_end_of_default_region('html');
716         // Create another course with HTML blocks only in some weird page or a module page (not
717         // yet supported, so both these blocks will be ignored).
718         $course2 = $generator->create_course();
719         $context2 = \context_course::instance($course2->id);
720         $page = new \moodle_page();
721         $page->set_context($context2);
722         $page->set_course($course2);
723         $page->set_pagelayout('standard');
724         $page->set_pagetype('bogus-page');
725         $page->blocks->load_blocks();
726         $page->blocks->add_block_at_end_of_default_region('html');
728         $forum = $this->getDataGenerator()->create_module('forum', array('course' => $course2->id));
729         $forumcontext = context_module::instance($forum->cmid);
730         $page = new \moodle_page();
731         $page->set_context($forumcontext);
732         $page->set_course($course2);
733         $page->set_pagelayout('standard');
734         $page->set_pagetype('mod-forum-view');
735         $page->blocks->load_blocks();
736         $page->blocks->add_block_at_end_of_default_region('html');
738         // The third course has 2 HTML blocks.
739         $course3 = $generator->create_course();
740         $context3 = \context_course::instance($course3->id);
741         $page = new \moodle_page();
742         $page->set_context($context3);
743         $page->set_course($course3);
744         $page->set_pagelayout('standard');
745         $page->set_pagetype('course-view');
746         $page->blocks->load_blocks();
747         $page->blocks->add_block_at_end_of_default_region('html');
748         $page->blocks->add_block_at_end_of_default_region('html');
750         // Student 1 belongs to all 3 courses.
751         $student1 = $generator->create_user();
752         $generator->enrol_user($student1->id, $course1->id, 'student');
753         $generator->enrol_user($student1->id, $course2->id, 'student');
754         $generator->enrol_user($student1->id, $course3->id, 'student');
756         // Student 2 belongs only to course 2.
757         $student2 = $generator->create_user();
758         $generator->enrol_user($student2->id, $course2->id, 'student');
760         // And the third student is only in course 3.
761         $student3 = $generator->create_user();
762         $generator->enrol_user($student3->id, $course3->id, 'student');
764         $search = testable_core_search::instance();
765         $search->add_core_search_areas();
767         // Admin gets 'true' result to function regardless of blocks.
768         $this->setAdminUser();
769         $this->assertEquals((object)['everything' => true], $search->get_areas_user_accesses());
771         // Student 1 gets all 3 block contexts.
772         $this->setUser($student1);
773         $contexts = $search->get_areas_user_accesses()->usercontexts;
774         $this->assertArrayHasKey('block_html-content', $contexts);
775         $this->assertCount(3, $contexts['block_html-content']);
777         // Student 2 does not get any blocks.
778         $this->setUser($student2);
779         $contexts = $search->get_areas_user_accesses()->usercontexts;
780         $this->assertArrayNotHasKey('block_html-content', $contexts);
782         // Student 3 gets only two of them.
783         $this->setUser($student3);
784         $contexts = $search->get_areas_user_accesses()->usercontexts;
785         $this->assertArrayHasKey('block_html-content', $contexts);
786         $this->assertCount(2, $contexts['block_html-content']);
788         // A course limited search for student 1 is the same as the student 3 search.
789         $this->setUser($student1);
790         $limitedcontexts = $search->get_areas_user_accesses([$course3->id])->usercontexts;
791         $this->assertEquals($contexts['block_html-content'], $limitedcontexts['block_html-content']);
793         // Get block context ids for the blocks that appear.
794         global $DB;
795         $blockcontextids = $DB->get_fieldset_sql('
796             SELECT x.id
797               FROM {block_instances} bi
798               JOIN {context} x ON x.instanceid = bi.id AND x.contextlevel = ?
799              WHERE (parentcontextid = ? OR parentcontextid = ?)
800                    AND blockname = ?
801           ORDER BY bi.id', [CONTEXT_BLOCK, $context1->id, $context3->id, 'html']);
803         // Context limited search (no course).
804         $contexts = $search->get_areas_user_accesses(false,
805                 [$blockcontextids[0], $blockcontextids[2]])->usercontexts;
806         $this->assertCount(2, $contexts['block_html-content']);
808         // Context limited search (with course 3).
809         $contexts = $search->get_areas_user_accesses([$course2->id, $course3->id],
810                 [$blockcontextids[0], $blockcontextids[2]])->usercontexts;
811         $this->assertCount(1, $contexts['block_html-content']);
812     }
814     /**
815      * Test get_areas_user_accesses with regard to the 'all available courses' config option.
816      *
817      * @return void
818      */
819     public function test_search_user_accesses_allavailable() {
820         global $DB, $CFG;
822         $this->resetAfterTest();
824         // Front page, including a forum.
825         $frontpage = $DB->get_record('course', array('id' => SITEID));
826         $forumfront = $this->getDataGenerator()->create_module('forum', array('course' => $frontpage->id));
827         $forumfrontctx = context_module::instance($forumfront->cmid);
829         // Course 1 does not allow guest access.
830         $course1 = $this->getDataGenerator()->create_course((object)array(
831                 'enrol_guest_status_0' => ENROL_INSTANCE_DISABLED,
832                 'enrol_guest_password_0' => ''));
833         $forum1 = $this->getDataGenerator()->create_module('forum', array('course' => $course1->id));
834         $forum1ctx = context_module::instance($forum1->cmid);
836         // Course 2 does not allow guest but is accessible by all users.
837         $course2 = $this->getDataGenerator()->create_course((object)array(
838                 'enrol_guest_status_0' => ENROL_INSTANCE_DISABLED,
839                 'enrol_guest_password_0' => ''));
840         $course2ctx = context_course::instance($course2->id);
841         $forum2 = $this->getDataGenerator()->create_module('forum', array('course' => $course2->id));
842         $forum2ctx = context_module::instance($forum2->cmid);
843         assign_capability('moodle/course:view', CAP_ALLOW, $CFG->defaultuserroleid, $course2ctx->id);
845         // Course 3 allows guest access without password.
846         $course3 = $this->getDataGenerator()->create_course((object)array(
847                 'enrol_guest_status_0' => ENROL_INSTANCE_ENABLED,
848                 'enrol_guest_password_0' => ''));
849         $forum3 = $this->getDataGenerator()->create_module('forum', array('course' => $course2->id));
850         $forum3ctx = context_module::instance($forum3->cmid);
852         // Student user is enrolled in course 1.
853         $student = $this->getDataGenerator()->create_user();
854         $this->getDataGenerator()->enrol_user($student->id, $course1->id, 'student');
856         // No access user is just a user with no permissions.
857         $noaccess = $this->getDataGenerator()->create_user();
859         // First test without the all available option.
860         $search = testable_core_search::instance();
862         // Admin user can access everything.
863         $this->setAdminUser();
864         $this->assertEquals((object)['everything' => true], $search->get_areas_user_accesses());
866         // No-access user can access only the front page forum.
867         $this->setUser($noaccess);
868         $contexts = $search->get_areas_user_accesses()->usercontexts;
869         $this->assertEquals([$forumfrontctx->id], array_keys($contexts[$this->forumpostareaid]));
871         // Student can access the front page forum plus the enrolled one.
872         $this->setUser($student);
873         $contexts = $search->get_areas_user_accesses()->usercontexts;
874         $this->assertEquals([$forum1ctx->id, $forumfrontctx->id],
875                 array_keys($contexts[$this->forumpostareaid]));
877         // Now turn on the all available option.
878         set_config('searchallavailablecourses', 1);
880         // Admin user can access everything.
881         $this->setAdminUser();
882         $this->assertEquals((object)['everything' => true], $search->get_areas_user_accesses());
884         // No-access user can access the front page forum and course 2, 3.
885         $this->setUser($noaccess);
886         $contexts = $search->get_areas_user_accesses()->usercontexts;
887         $this->assertEquals([$forum2ctx->id, $forum3ctx->id, $forumfrontctx->id],
888                 array_keys($contexts[$this->forumpostareaid]));
890         // Student can access the front page forum plus the enrolled one plus courses 2, 3.
891         $this->setUser($student);
892         $contexts = $search->get_areas_user_accesses()->usercontexts;
893         $this->assertEquals([$forum1ctx->id, $forum2ctx->id, $forum3ctx->id, $forumfrontctx->id],
894                 array_keys($contexts[$this->forumpostareaid]));
895     }
897     /**
898      * Tests group-related aspects of the get_areas_user_accesses function.
899      */
900     public function test_search_user_accesses_groups() {
901         global $DB;
903         $this->resetAfterTest();
904         $this->setAdminUser();
906         // Create 2 courses each with 2 groups and 2 forums (separate/visible groups).
907         $generator = $this->getDataGenerator();
908         $course1 = $generator->create_course();
909         $course2 = $generator->create_course();
910         $group1 = $generator->create_group(['courseid' => $course1->id]);
911         $group2 = $generator->create_group(['courseid' => $course1->id]);
912         $group3 = $generator->create_group(['courseid' => $course2->id]);
913         $group4 = $generator->create_group(['courseid' => $course2->id]);
914         $forum1s = $generator->create_module('forum', ['course' => $course1->id, 'groupmode' => SEPARATEGROUPS]);
915         $id1s = context_module::instance($forum1s->cmid)->id;
916         $forum1v = $generator->create_module('forum', ['course' => $course1->id, 'groupmode' => VISIBLEGROUPS]);
917         $id1v = context_module::instance($forum1v->cmid)->id;
918         $forum2s = $generator->create_module('forum', ['course' => $course2->id, 'groupmode' => SEPARATEGROUPS]);
919         $id2s = context_module::instance($forum2s->cmid)->id;
920         $forum2n = $generator->create_module('forum', ['course' => $course2->id, 'groupmode' => NOGROUPS]);
921         $id2n = context_module::instance($forum2n->cmid)->id;
923         // Get search instance.
924         $search = testable_core_search::instance();
925         $search->add_core_search_areas();
927         // User 1 is a manager in one course and a student in the other one. They belong to
928         // all of the groups 1, 2, 3, and 4.
929         $user1 = $generator->create_user();
930         $generator->enrol_user($user1->id, $course1->id, 'manager');
931         $generator->enrol_user($user1->id, $course2->id, 'student');
932         groups_add_member($group1, $user1);
933         groups_add_member($group2, $user1);
934         groups_add_member($group3, $user1);
935         groups_add_member($group4, $user1);
937         $this->setUser($user1);
938         $accessinfo = $search->get_areas_user_accesses();
939         $contexts = $accessinfo->usercontexts;
941         // Double-check all the forum contexts.
942         $postcontexts = $contexts['mod_forum-post'];
943         sort($postcontexts);
944         $this->assertEquals([$id1s, $id1v, $id2s, $id2n], $postcontexts);
946         // Only the context in the second course (no accessallgroups) is restricted.
947         $restrictedcontexts = $accessinfo->separategroupscontexts;
948         sort($restrictedcontexts);
949         $this->assertEquals([$id2s], $restrictedcontexts);
951         // Only the groups from the second course (no accessallgroups) are included.
952         $groupids = $accessinfo->usergroups;
953         sort($groupids);
954         $this->assertEquals([$group3->id, $group4->id], $groupids);
956         // User 2 is a student in each course and belongs to groups 2 and 4.
957         $user2 = $generator->create_user();
958         $generator->enrol_user($user2->id, $course1->id, 'student');
959         $generator->enrol_user($user2->id, $course2->id, 'student');
960         groups_add_member($group2, $user2);
961         groups_add_member($group4, $user2);
963         $this->setUser($user2);
964         $accessinfo = $search->get_areas_user_accesses();
965         $contexts = $accessinfo->usercontexts;
967         // Double-check all the forum contexts.
968         $postcontexts = $contexts['mod_forum-post'];
969         sort($postcontexts);
970         $this->assertEquals([$id1s, $id1v, $id2s, $id2n], $postcontexts);
972         // Both separate groups forums are restricted.
973         $restrictedcontexts = $accessinfo->separategroupscontexts;
974         sort($restrictedcontexts);
975         $this->assertEquals([$id1s, $id2s], $restrictedcontexts);
977         // Groups from both courses are included.
978         $groupids = $accessinfo->usergroups;
979         sort($groupids);
980         $this->assertEquals([$group2->id, $group4->id], $groupids);
982         // User 3 is a manager at system level.
983         $user3 = $generator->create_user();
984         role_assign($DB->get_field('role', 'id', ['shortname' => 'manager'], MUST_EXIST), $user3->id,
985                 \context_system::instance());
987         $this->setUser($user3);
988         $accessinfo = $search->get_areas_user_accesses();
990         // Nothing is restricted and no groups are relevant.
991         $this->assertEquals([], $accessinfo->separategroupscontexts);
992         $this->assertEquals([], $accessinfo->usergroups);
993     }
995     /**
996      * test_is_search_area
997      *
998      * @return void
999      */
1000     public function test_is_search_area() {
1002         $this->assertFalse(testable_core_search::is_search_area('\asd\asd'));
1003         $this->assertFalse(testable_core_search::is_search_area('\mod_forum\search\posta'));
1004         $this->assertFalse(testable_core_search::is_search_area('\core_search\base_mod'));
1005         $this->assertTrue(testable_core_search::is_search_area('\mod_forum\search\post'));
1006         $this->assertTrue(testable_core_search::is_search_area('\\mod_forum\\search\\post'));
1007         $this->assertTrue(testable_core_search::is_search_area('mod_forum\\search\\post'));
1008     }
1010     /**
1011      * Tests the request_index function used for reindexing certain contexts. This only tests
1012      * adding things to the request list, it doesn't test that they are actually indexed by the
1013      * scheduled task.
1014      */
1015     public function test_request_index() {
1016         global $DB;
1018         $this->resetAfterTest();
1020         $course1 = $this->getDataGenerator()->create_course();
1021         $course1ctx = context_course::instance($course1->id);
1022         $course2 = $this->getDataGenerator()->create_course();
1023         $course2ctx = context_course::instance($course2->id);
1024         $forum1 = $this->getDataGenerator()->create_module('forum', ['course' => $course1->id]);
1025         $forum1ctx = context_module::instance($forum1->cmid);
1026         $forum2 = $this->getDataGenerator()->create_module('forum', ['course' => $course2->id]);
1027         $forum2ctx = context_module::instance($forum2->cmid);
1029         // Initially no requests.
1030         $this->assertEquals(0, $DB->count_records('search_index_requests'));
1032         // Request update for course 1, all areas.
1033         \core_search\manager::request_index($course1ctx);
1035         // Check all details of entry.
1036         $results = array_values($DB->get_records('search_index_requests'));
1037         $this->assertCount(1, $results);
1038         $this->assertEquals($course1ctx->id, $results[0]->contextid);
1039         $this->assertEquals('', $results[0]->searcharea);
1040         $now = time();
1041         $this->assertLessThanOrEqual($now, $results[0]->timerequested);
1042         $this->assertGreaterThan($now - 10, $results[0]->timerequested);
1043         $this->assertEquals('', $results[0]->partialarea);
1044         $this->assertEquals(0, $results[0]->partialtime);
1046         // Request forum 1, all areas; not added as covered by course 1.
1047         \core_search\manager::request_index($forum1ctx);
1048         $this->assertEquals(1, $DB->count_records('search_index_requests'));
1050         // Request forum 1, specific area; not added as covered by course 1 all areas.
1051         \core_search\manager::request_index($forum1ctx, 'forum-post');
1052         $this->assertEquals(1, $DB->count_records('search_index_requests'));
1054         // Request course 1 again, specific area; not added as covered by all areas.
1055         \core_search\manager::request_index($course1ctx, 'forum-post');
1056         $this->assertEquals(1, $DB->count_records('search_index_requests'));
1058         // Request course 1 again, all areas; not needed as covered already.
1059         \core_search\manager::request_index($course1ctx);
1060         $this->assertEquals(1, $DB->count_records('search_index_requests'));
1062         // Request course 2, specific area.
1063         \core_search\manager::request_index($course2ctx, 'label-activity');
1064         // Note: I'm ordering by ID for convenience - this is dangerous in real code (see MDL-43447)
1065         // but in a unit test it shouldn't matter as nobody is using clustered databases for unit
1066         // test.
1067         $results = array_values($DB->get_records('search_index_requests', null, 'id'));
1068         $this->assertCount(2, $results);
1069         $this->assertEquals($course1ctx->id, $results[0]->contextid);
1070         $this->assertEquals($course2ctx->id, $results[1]->contextid);
1071         $this->assertEquals('label-activity', $results[1]->searcharea);
1073         // Request forum 2, same specific area; not added.
1074         \core_search\manager::request_index($forum2ctx, 'label-activity');
1075         $this->assertEquals(2, $DB->count_records('search_index_requests'));
1077         // Request forum 2, different specific area; added.
1078         \core_search\manager::request_index($forum2ctx, 'forum-post');
1079         $this->assertEquals(3, $DB->count_records('search_index_requests'));
1081         // Request forum 2, all areas; also added. (Note: This could obviously remove the previous
1082         // one, but for simplicity, I didn't make it do that; also it could perhaps cause problems
1083         // if we had already begun processing the previous entry.)
1084         \core_search\manager::request_index($forum2ctx);
1085         $this->assertEquals(4, $DB->count_records('search_index_requests'));
1087         // Clear queue and do tests relating to priority.
1088         $DB->delete_records('search_index_requests');
1090         // Request forum 1, specific area, priority 100.
1091         \core_search\manager::request_index($forum1ctx, 'forum-post', 100);
1092         $results = array_values($DB->get_records('search_index_requests', null, 'id'));
1093         $this->assertCount(1, $results);
1094         $this->assertEquals(100, $results[0]->indexpriority);
1096         // Request forum 1, same area, lower priority; no change.
1097         \core_search\manager::request_index($forum1ctx, 'forum-post', 99);
1098         $results = array_values($DB->get_records('search_index_requests', null, 'id'));
1099         $this->assertCount(1, $results);
1100         $this->assertEquals(100, $results[0]->indexpriority);
1102         // Request forum 1, same area, higher priority; priority stored changes.
1103         \core_search\manager::request_index($forum1ctx, 'forum-post', 101);
1104         $results = array_values($DB->get_records('search_index_requests', null, 'id'));
1105         $this->assertCount(1, $results);
1106         $this->assertEquals(101, $results[0]->indexpriority);
1108         // Request forum 1, all areas, lower priority; adds second entry.
1109         \core_search\manager::request_index($forum1ctx, '', 100);
1110         $results = array_values($DB->get_records('search_index_requests', null, 'id'));
1111         $this->assertCount(2, $results);
1112         $this->assertEquals(100, $results[1]->indexpriority);
1114         // Request course 1, all areas, lower priority; adds third entry.
1115         \core_search\manager::request_index($course1ctx, '', 99);
1116         $results = array_values($DB->get_records('search_index_requests', null, 'id'));
1117         $this->assertCount(3, $results);
1118         $this->assertEquals(99, $results[2]->indexpriority);
1119     }
1121     /**
1122      * Tests the process_index_requests function.
1123      */
1124     public function test_process_index_requests() {
1125         global $DB;
1127         $this->resetAfterTest();
1129         $search = testable_core_search::instance();
1131         // When there are no index requests, nothing gets logged.
1132         $progress = new progress_trace_buffer(new text_progress_trace(), false);
1133         $search->process_index_requests(0.0, $progress);
1134         $out = $progress->get_buffer();
1135         $progress->reset_buffer();
1136         $this->assertEquals('', $out);
1138         // Set up the course with 3 forums.
1139         $generator = $this->getDataGenerator();
1140         $course = $generator->create_course(['fullname' => 'TCourse']);
1141         $forum1 = $generator->create_module('forum', ['course' => $course->id, 'name' => 'TForum1']);
1142         $forum2 = $generator->create_module('forum', ['course' => $course->id, 'name' => 'TForum2']);
1143         $forum3 = $generator->create_module('forum', ['course' => $course->id, 'name' => 'TForum3']);
1145         // Hack the forums so they have different creation times.
1146         $now = time();
1147         $DB->set_field('forum', 'timemodified', $now - 30, ['id' => $forum1->id]);
1148         $DB->set_field('forum', 'timemodified', $now - 20, ['id' => $forum2->id]);
1149         $DB->set_field('forum', 'timemodified', $now - 10, ['id' => $forum3->id]);
1150         $forum2time = $now - 20;
1152         // Make 2 index requests.
1153         testable_core_search::fake_current_time($now - 3);
1154         $search::request_index(context_course::instance($course->id), 'mod_label-activity');
1155         testable_core_search::fake_current_time($now - 2);
1156         $search::request_index(context_module::instance($forum1->cmid));
1158         // Run with no time limit.
1159         $search->process_index_requests(0.0, $progress);
1160         $out = $progress->get_buffer();
1161         $progress->reset_buffer();
1163         // Check that it's done both areas.
1164         $this->assertStringContainsString(
1165                 'Indexing requested context: Course: TCourse (search area: mod_label-activity)',
1166                 $out);
1167         $this->assertStringContainsString(
1168                 'Completed requested context: Course: TCourse (search area: mod_label-activity)',
1169                 $out);
1170         $this->assertStringContainsString('Indexing requested context: Forum: TForum1', $out);
1171         $this->assertStringContainsString('Completed requested context: Forum: TForum1', $out);
1173         // Check the requests database table is now empty.
1174         $this->assertEquals(0, $DB->count_records('search_index_requests'));
1176         // Request indexing the course a couple of times.
1177         testable_core_search::fake_current_time($now - 3);
1178         $search::request_index(context_course::instance($course->id), 'mod_forum-activity');
1179         testable_core_search::fake_current_time($now - 2);
1180         $search::request_index(context_course::instance($course->id), 'mod_forum-post');
1182         // Do the processing again with a time limit and indexing delay. The time limit is too
1183         // small; because of the way the logic works, this means it will index 2 activities.
1184         $search->get_engine()->set_add_delay(0.2);
1185         $search->process_index_requests(0.1, $progress);
1186         $out = $progress->get_buffer();
1187         $progress->reset_buffer();
1189         // Confirm the right wrapper information was logged.
1190         $this->assertStringContainsString(
1191                 'Indexing requested context: Course: TCourse (search area: mod_forum-activity)',
1192                 $out);
1193         $this->assertStringContainsString('Stopping indexing due to time limit', $out);
1194         $this->assertStringContainsString(
1195                 'Ending requested context: Course: TCourse (search area: mod_forum-activity)',
1196                 $out);
1198         // Check the database table has been updated with progress.
1199         $records = array_values($DB->get_records('search_index_requests', null, 'searcharea'));
1200         $this->assertEquals('mod_forum-activity', $records[0]->partialarea);
1201         $this->assertEquals($forum2time, $records[0]->partialtime);
1203         // Run again and confirm it now finishes.
1204         $search->process_index_requests(2.0, $progress);
1205         $out = $progress->get_buffer();
1206         $progress->reset_buffer();
1207         $this->assertStringContainsString(
1208                 'Completed requested context: Course: TCourse (search area: mod_forum-activity)',
1209                 $out);
1210         $this->assertStringContainsString(
1211                 'Completed requested context: Course: TCourse (search area: mod_forum-post)',
1212                 $out);
1214         // Confirm table is now empty.
1215         $this->assertEquals(0, $DB->count_records('search_index_requests'));
1217         // Make 2 requests - first one is low priority.
1218         testable_core_search::fake_current_time($now - 3);
1219         $search::request_index(context_module::instance($forum1->cmid), 'mod_forum-activity',
1220                 \core_search\manager::INDEX_PRIORITY_REINDEXING);
1221         testable_core_search::fake_current_time($now - 2);
1222         $search::request_index(context_module::instance($forum2->cmid), 'mod_forum-activity');
1224         // Process with short time limit and confirm it does the second one first.
1225         $search->process_index_requests(0.1, $progress);
1226         $out = $progress->get_buffer();
1227         $progress->reset_buffer();
1228         $this->assertStringContainsString(
1229                 'Completed requested context: Forum: TForum2 (search area: mod_forum-activity)',
1230                 $out);
1231         $search->process_index_requests(0.1, $progress);
1232         $out = $progress->get_buffer();
1233         $progress->reset_buffer();
1234         $this->assertStringContainsString(
1235                 'Completed requested context: Forum: TForum1 (search area: mod_forum-activity)',
1236                 $out);
1238         // Make a request for a course context...
1239         $course = $generator->create_course();
1240         $context = context_course::instance($course->id);
1241         $search::request_index($context);
1243         // ...but then delete it (note: delete_course spews output, so we throw it away).
1244         ob_start();
1245         delete_course($course);
1246         ob_end_clean();
1248         // Process requests - it should only note the deleted context.
1249         $search->process_index_requests(10, $progress);
1250         $out = $progress->get_buffer();
1251         $progress->reset_buffer();
1252         $this->assertStringContainsString('Skipped deleted context: ' . $context->id, $out);
1254         // Confirm request table is now empty.
1255         $this->assertEquals(0, $DB->count_records('search_index_requests'));
1256     }
1258     /**
1259      * Test search area categories.
1260      */
1261     public function test_get_search_area_categories() {
1262         $categories = \core_search\manager::get_search_area_categories();
1264         $this->assertTrue(is_array($categories));
1265         $this->assertTrue(count($categories) >= 4); // We always should have 4 core categories.
1266         $this->assertArrayHasKey('core-all', $categories);
1267         $this->assertArrayHasKey('core-course-content', $categories);
1268         $this->assertArrayHasKey('core-courses', $categories);
1269         $this->assertArrayHasKey('core-users', $categories);
1271         foreach ($categories as $category) {
1272             $this->assertInstanceOf('\core_search\area_category', $category);
1273         }
1274     }
1276     /**
1277      * Test that we can find out if search area categories functionality is enabled.
1278      */
1279     public function test_is_search_area_categories_enabled() {
1280         $this->resetAfterTest();
1282         $this->assertFalse(\core_search\manager::is_search_area_categories_enabled());
1283         set_config('searchenablecategories', 1);
1284         $this->assertTrue(\core_search\manager::is_search_area_categories_enabled());
1285         set_config('searchenablecategories', 0);
1286         $this->assertFalse(\core_search\manager::is_search_area_categories_enabled());
1287     }
1289     /**
1290      * Test that we can find out if hiding all results category is enabled.
1291      */
1292     public function test_should_hide_all_results_category() {
1293         $this->resetAfterTest();
1295         $this->assertEquals(0, \core_search\manager::should_hide_all_results_category());
1296         set_config('searchhideallcategory', 1);
1297         $this->assertEquals(1, \core_search\manager::should_hide_all_results_category());
1298         set_config('searchhideallcategory', 0);
1299         $this->assertEquals(0, \core_search\manager::should_hide_all_results_category());
1300     }
1302     /**
1303      * Test that we can get default search category name.
1304      */
1305     public function test_get_default_area_category_name() {
1306         $this->resetAfterTest();
1308         $expected = 'core-all';
1309         $this->assertEquals($expected, \core_search\manager::get_default_area_category_name());
1311         set_config('searchhideallcategory', 1);
1312         $expected = 'core-course-content';
1313         $this->assertEquals($expected, \core_search\manager::get_default_area_category_name());
1315         set_config('searchhideallcategory', 0);
1316         $expected = 'core-all';
1317         $this->assertEquals($expected, \core_search\manager::get_default_area_category_name());
1318     }
1320     /**
1321      * Test that we can get correct search area category by its name.
1322      */
1323     public function test_get_search_area_category_by_name() {
1324         $this->resetAfterTest();
1326         $testcategory = \core_search\manager::get_search_area_category_by_name('test_random_name');
1327         $this->assertEquals('core-all', $testcategory->get_name());
1329         $testcategory = \core_search\manager::get_search_area_category_by_name('core-courses');
1330         $this->assertEquals('core-courses', $testcategory->get_name());
1332         set_config('searchhideallcategory', 1);
1333         $testcategory = \core_search\manager::get_search_area_category_by_name('test_random_name');
1334         $this->assertEquals('core-course-content', $testcategory->get_name());
1335     }
1337     /**
1338      * Test that we can check that "Include all visible courses" feature is enabled.
1339      */
1340     public function test_include_all_courses_enabled() {
1341         $this->resetAfterTest();
1342         $this->assertFalse(\core_search\manager::include_all_courses());
1343         set_config('searchincludeallcourses', 1);
1344         $this->assertTrue(\core_search\manager::include_all_courses());
1345     }
1347     /**
1348      * Test that we can correctly build a list of courses for a course filter for the search results.
1349      */
1350     public function test_build_limitcourseids() {
1351         global $USER;
1353         $this->resetAfterTest();
1354         $this->setAdminUser();
1356         $course1 = $this->getDataGenerator()->create_course();
1357         $course2 = $this->getDataGenerator()->create_course();
1358         $course3 = $this->getDataGenerator()->create_course();
1359         $course4 = $this->getDataGenerator()->create_course();
1361         $this->getDataGenerator()->enrol_user($USER->id, $course1->id);
1362         $this->getDataGenerator()->enrol_user($USER->id, $course3->id);
1364         $search = testable_core_search::instance();
1366         $formdata = new stdClass();
1367         $formdata->courseids = [];
1368         $formdata->mycoursesonly = false;
1369         $limitcourseids = $search->build_limitcourseids($formdata);
1370         $this->assertEquals(false, $limitcourseids);
1372         $formdata->courseids = [];
1373         $formdata->mycoursesonly = true;
1374         $limitcourseids = $search->build_limitcourseids($formdata);
1375         $this->assertEquals([$course1->id, $course3->id], $limitcourseids);
1377         $formdata->courseids = [$course1->id, $course2->id, $course4->id];
1378         $formdata->mycoursesonly = false;
1379         $limitcourseids = $search->build_limitcourseids($formdata);
1380         $this->assertEquals([$course1->id, $course2->id, $course4->id], $limitcourseids);
1382         $formdata->courseids = [$course1->id, $course2->id, $course4->id];
1383         $formdata->mycoursesonly = true;
1384         $limitcourseids = $search->build_limitcourseids($formdata);
1385         $this->assertEquals([$course1->id], $limitcourseids);
1386     }
1388     /**
1389      * Test data for test_parse_areaid test fucntion.
1390      *
1391      * @return array
1392      */
1393     public function parse_search_area_id_data_provider() {
1394         return [
1395             ['mod_book-chapter', ['mod_book', 'search_chapter']],
1396             ['mod_customcert-activity', ['mod_customcert', 'search_activity']],
1397             ['core_course-mycourse', ['core_search', 'core_course_mycourse']],
1398         ];
1399     }
1401     /**
1402      * Test that manager class can parse area id correctly.
1403      * @dataProvider parse_search_area_id_data_provider
1404      *
1405      * @param string $areaid Area id to parse.
1406      * @param array $expected Expected result of parsing.
1407      */
1408     public function test_parse_search_area_id($areaid, $expected) {
1409         $this->assertEquals($expected, \core_search\manager::parse_areaid($areaid));
1410     }
1412     /**
1413      * Test that manager class will throw an exception when parsing an invalid area id.
1414      */
1415     public function test_parse_invalid_search_area_id() {
1416         $this->expectException('coding_exception');
1417         $this->expectExceptionMessage('Trying to parse invalid search area id invalid_area');
1418         \core_search\manager::parse_areaid('invalid_area');
1419     }
1421     /**
1422      * Test getting a coding exception when trying to lean up existing search area.
1423      */
1424     public function test_cleaning_up_existing_search_area() {
1425         $expectedmessage = "Area mod_assign-activity exists. Please use appropriate search area class to manipulate the data.";
1427         $this->expectException('coding_exception');
1428         $this->expectExceptionMessage($expectedmessage);
1430         \core_search\manager::clean_up_non_existing_area('mod_assign-activity');
1431     }
1433     /**
1434      * Test clean up of non existing search area.
1435      */
1436     public function test_clean_up_non_existing_search_area() {
1437         global $DB;
1439         $this->resetAfterTest();
1441         $areaid = 'core_course-mycourse';
1442         $plugin = 'core_search';
1444         // Get all settings to DB and make sure they are there.
1445         foreach (\core_search\base::get_settingnames() as $settingname) {
1446             $record = new stdClass();
1447             $record->plugin = $plugin;
1448             $record->name = 'core_course_mycourse'. $settingname;
1449             $record->value = 'test';
1451             $DB->insert_record('config_plugins', $record);
1452             $this->assertTrue($DB->record_exists('config_plugins', ['plugin' => $plugin, 'name' => $record->name]));
1453         }
1455         // Clean up the search area.
1456         \core_search\manager::clean_up_non_existing_area($areaid);
1458         // Check that records are not in DB after we ran clean up.
1459         foreach (\core_search\base::get_settingnames() as $settingname) {
1460             $plugin = 'core_search';
1461             $name = 'core_course_mycourse'. $settingname;
1462             $this->assertFalse($DB->record_exists('config_plugins', ['plugin' => $plugin, 'name' => $name]));
1463         }
1464     }
1466     /**
1467      * Tests the context_deleted, course_deleting_start, and course_deleting_finish methods.
1468      */
1469     public function test_context_deletion() {
1470         $this->resetAfterTest();
1472         // Create one course with 4 activities, and another with one.
1473         $generator = $this->getDataGenerator();
1474         $course1 = $generator->create_course();
1475         $page1 = $generator->create_module('page', ['course' => $course1]);
1476         $context1 = \context_module::instance($page1->cmid);
1477         $page2 = $generator->create_module('page', ['course' => $course1]);
1478         $page3 = $generator->create_module('page', ['course' => $course1]);
1479         $context3 = \context_module::instance($page3->cmid);
1480         $page4 = $generator->create_module('page', ['course' => $course1]);
1481         $course2 = $generator->create_course();
1482         $page5 = $generator->create_module('page', ['course' => $course2]);
1483         $context5 = \context_module::instance($page5->cmid);
1485         // Also create a user.
1486         $user = $generator->create_user();
1487         $usercontext = \context_user::instance($user->id);
1489         $search = testable_core_search::instance();
1491         // Delete two of the pages individually.
1492         course_delete_module($page1->cmid);
1493         course_delete_module($page3->cmid);
1495         // Delete the course with another two.
1496         delete_course($course1->id, false);
1498         // Delete the user.
1499         delete_user($user);
1501         // Delete the page from the other course.
1502         course_delete_module($page5->cmid);
1504         // It should have deleted the contexts and the course, but not the contexts in the course.
1505         $expected = [
1506             ['context', $context1->id],
1507             ['context', $context3->id],
1508             ['course', $course1->id],
1509             ['context', $usercontext->id],
1510             ['context', $context5->id]
1511         ];
1512         $this->assertEquals($expected, $search->get_engine()->get_and_clear_deletes());
1513     }