Beispiel #1
0
 /**
  * Form definition.
  *
  * @return void
  */
 function definition()
 {
     global $CFG;
     $mform =& $this->_form;
     $mform->addElement('header', 'search', get_string('search', 'search'));
     // Help info depends on the selected search engine.
     $mform->addElement('text', 'q', get_string('enteryoursearchquery', 'search'));
     $mform->addHelpButton('q', 'searchinfo', $this->_customdata['searchengine']);
     $mform->setType('q', PARAM_TEXT);
     $mform->addRule('q', get_string('required'), 'required', null, 'client');
     $mform->addElement('header', 'filtersection', get_string('filterheader', 'search'));
     $mform->setExpanded('filtersection', false);
     $mform->addElement('text', 'title', get_string('title', 'search'));
     $mform->setType('title', PARAM_TEXT);
     $search = \core_search\manager::instance();
     $searchareas = \core_search\manager::get_search_areas_list(true);
     $areanames = array('' => get_string('allareas', 'search'));
     foreach ($searchareas as $areaid => $searcharea) {
         $areanames[$areaid] = $searcharea->get_visible_name();
     }
     $mform->addElement('select', 'areaid', get_string('searcharea', 'search'), $areanames);
     $mform->addElement('date_time_selector', 'timestart', get_string('fromtime', 'search'), array('optional' => true));
     $mform->setDefault('timestart', 0);
     $mform->addElement('date_time_selector', 'timeend', get_string('totime', 'search'), array('optional' => true));
     $mform->setDefault('timeend', 0);
     $this->add_action_buttons(false, get_string('search', 'search'));
 }
Beispiel #2
0
 /**
  * Form definition.
  *
  * @return void
  */
 function definition()
 {
     global $CFG;
     $mform =& $this->_form;
     $mform->disable_form_change_checker();
     $mform->addElement('header', 'search', get_string('search', 'search'));
     // Help info depends on the selected search engine.
     $mform->addElement('text', 'q', get_string('enteryoursearchquery', 'search'));
     $mform->addHelpButton('q', 'searchinfo', $this->_customdata['searchengine']);
     $mform->setType('q', PARAM_TEXT);
     $mform->addRule('q', get_string('required'), 'required', null, 'client');
     $mform->addElement('header', 'filtersection', get_string('filterheader', 'search'));
     $mform->setExpanded('filtersection', false);
     $mform->addElement('text', 'title', get_string('title', 'search'));
     $mform->setType('title', PARAM_TEXT);
     $search = \core_search\manager::instance();
     $searchareas = \core_search\manager::get_search_areas_list(true);
     $areanames = array();
     foreach ($searchareas as $areaid => $searcharea) {
         $areanames[$areaid] = $searcharea->get_visible_name();
     }
     // Sort the array by the text.
     \core_collator::asort($areanames);
     $options = array('multiple' => true, 'noselectionstring' => get_string('allareas', 'search'));
     $mform->addElement('autocomplete', 'areaids', get_string('searcharea', 'search'), $areanames, $options);
     $options = array('multiple' => true, 'limittoenrolled' => !is_siteadmin(), 'noselectionstring' => get_string('allcourses', 'search'));
     $mform->addElement('course', 'courseids', get_string('courses', 'core'), $options);
     $mform->setType('courseids', PARAM_INT);
     $mform->addElement('date_time_selector', 'timestart', get_string('fromtime', 'search'), array('optional' => true));
     $mform->setDefault('timestart', 0);
     $mform->addElement('date_time_selector', 'timeend', get_string('totime', 'search'), array('optional' => true));
     $mform->setDefault('timeend', 0);
     $this->add_action_buttons(false, get_string('search', 'search'));
 }
Beispiel #3
0
 /**
  * Do the job.
  * Throw exceptions on errors (the job will be retried).
  */
 public function execute()
 {
     if (!\core_search\manager::is_global_search_enabled()) {
         return;
     }
     $globalsearch = \core_search\manager::instance();
     // Indexing database records for modules + rich documents of forum.
     $globalsearch->index();
 }
 /**
  * Do the job.
  * Throw exceptions on errors (the job will be retried).
  */
 public function execute()
 {
     if (!\core_search\manager::is_global_search_enabled()) {
         return;
     }
     $globalsearch = \core_search\manager::instance();
     // Optimize index at last.
     $globalsearch->optimize_index();
 }
Beispiel #5
0
 /**
  * Returns the appropiate document object as it depends on the engine.
  *
  * @param int $itemid Document itemid
  * @param string $componentname Document component name
  * @param string $areaname Document area name
  * @param \core_search\engine $engine Falls back to the search engine in use.
  * @return \core_search\document Base document or the engine implementation.
  */
 public static function instance($itemid, $componentname, $areaname, $engine = false)
 {
     if ($engine === false) {
         $search = \core_search\manager::instance();
         $engine = $search->get_engine();
     }
     $pluginname = $engine->get_plugin_name();
     if (!empty(self::$docclassnames[$pluginname])) {
         return new self::$docclassnames[$pluginname]($itemid, $componentname, $areaname);
     }
     self::$docclassnames[$pluginname] = $engine->get_document_classname();
     return new self::$docclassnames[$pluginname]($itemid, $componentname, $areaname);
 }
Beispiel #6
0
 /**
  * Test for assign file attachments.
  *
  * @return void
  */
 public function test_attach_files()
 {
     global $USER;
     $this->setAdminUser();
     // Setup test data.
     $course = $this->getDataGenerator()->create_course();
     $fs = get_file_storage();
     $usercontext = context_user::instance($USER->id);
     $record = new stdClass();
     $record->course = $course->id;
     $assign = $this->getDataGenerator()->create_module('assign', $record);
     $context = context_module::instance($assign->cmid);
     // Attach the main file. We put them in the draft area, create_module will move them.
     $filerecord = array('contextid' => $context->id, 'component' => 'mod_assign', 'filearea' => ASSIGN_INTROATTACHMENT_FILEAREA, 'itemid' => 0, 'filepath' => '/');
     // Attach 4 files.
     for ($i = 1; $i <= 4; $i++) {
         $filerecord['filename'] = 'myfile' . $i;
         $fs->create_file_from_string($filerecord, 'Test assign file ' . $i);
     }
     // And a fifth in a sub-folder.
     $filerecord['filename'] = 'myfile5';
     $filerecord['filepath'] = '/subfolder/';
     $fs->create_file_from_string($filerecord, 'Test assign file 5');
     // Returns the instance as long as the area is supported.
     $searcharea = \core_search\manager::get_search_area($this->assignareaid);
     $this->assertInstanceOf('\\mod_assign\\search\\activity', $searcharea);
     $recordset = $searcharea->get_recordset_by_timestamp(0);
     $nrecords = 0;
     foreach ($recordset as $record) {
         $doc = $searcharea->get_document($record);
         $searcharea->attach_files($doc);
         $files = $doc->get_files();
         // Assign should return all files attached.
         $this->assertCount(5, $files);
         // We don't know the order, so get all the names, then sort, then check.
         $filenames = array();
         foreach ($files as $file) {
             $filenames[] = $file->get_filename();
         }
         sort($filenames);
         for ($i = 1; $i <= 5; $i++) {
             $this->assertEquals('myfile' . $i, $filenames[$i - 1]);
         }
         $nrecords++;
     }
     // If there would be an error/failure in the foreach above the recordset would be closed on shutdown.
     $recordset->close();
     $this->assertEquals(1, $nrecords);
 }
Beispiel #7
0
 /**
  * Constructor.
  *
  * @throws \coding_exception
  * @return void
  */
 public final function __construct()
 {
     $classname = get_class($this);
     // Detect possible issues when defining the class.
     if (strpos($classname, '\\search') === false) {
         throw new \coding_exception('Search area classes should be located in \\PLUGINTYPE_PLUGINNAME\\search\\AREANAME.');
     } else {
         if (strpos($classname, '_') === false) {
             throw new \coding_exception($classname . ' class namespace level 1 should be its component frankenstyle name');
         }
     }
     $this->areaname = substr(strrchr($classname, '\\'), 1);
     $this->componentname = substr($classname, 0, strpos($classname, '\\'));
     $this->areaid = \core_search\manager::generate_areaid($this->componentname, $this->areaname);
     $this->componenttype = substr($this->componentname, 0, strpos($this->componentname, '_'));
 }
Beispiel #8
0
 /**
  * Test engine caches.
  *
  * @return void
  */
 public function test_engine_caches()
 {
     global $DB;
     $engine = new \mock_search\engine();
     $course1 = self::getDataGenerator()->create_course();
     $this->assertEquals($course1->id, $engine->get_course($course1->id)->id);
     $dbreads = $DB->perf_get_reads();
     $engine->get_course($course1->id);
     $this->assertEquals($dbreads, $DB->perf_get_reads());
     $fakearea1 = \core_search\manager::generate_areaid('plugintype_unexisting', 'fakearea');
     $fakearea2 = \core_search\manager::generate_areaid('mod_unexisting', 'morefake');
     $this->assertFalse($engine->get_search_area($fakearea1));
     $this->assertFalse($engine->get_search_area($fakearea2));
     $this->assertFalse($engine->get_search_area($fakearea2));
     $areaid = \core_search\manager::generate_areaid('mod_forum', 'post');
     $this->assertInstanceOf('\\mod_forum\\search\\post', $engine->get_search_area($areaid));
     $dbreads = $DB->perf_get_reads();
     $this->assertInstanceOf('\\mod_forum\\search\\post', $engine->get_search_area($areaid));
     $this->assertEquals($dbreads, $DB->perf_get_reads());
 }
Beispiel #9
0
 /**
  * test_search_results_viewed
  *
  * @return void
  */
 public function test_search_results_viewed()
 {
     $this->resetAfterTest();
     $user = $this->getDataGenerator()->create_user();
     $this->setUser($user);
     $sink = $this->redirectEvents();
     // Basic event.
     \core_search\manager::trigger_search_results_viewed(['q' => 'I am a query', 'page' => 0]);
     $events = $sink->get_events();
     $event = reset($events);
     $sink->clear();
     $this->assertEquals(context_system::instance(), $event->get_context());
     $urlparams = ['q' => 'I am a query', 'page' => 0];
     $this->assertEquals($urlparams, $event->get_url()->params());
     \core_search\manager::trigger_search_results_viewed(['q' => 'I am a query', 'page' => 2, 'title' => 'I am the title', 'areaids' => array(3, 4, 5), 'courseids' => array(2, 3), 'timestart' => 1445644800, 'timeend' => 1477267200]);
     $events = $sink->get_events();
     $event = reset($events);
     $this->assertEquals(context_system::instance(), $event->get_context());
     $urlparams = ['q' => 'I am a query', 'page' => 2, 'title' => 'I am the title', 'timestart' => 1445644800, 'timeend' => 1477267200];
     $this->assertEquals($urlparams, $event->get_url()->params());
 }
Beispiel #10
0
 /**
  * Test for resource file attachments.
  *
  * @return void
  */
 public function test_attach_files()
 {
     global $USER;
     $this->setAdminUser();
     // Setup test data.
     $course = $this->getDataGenerator()->create_course();
     $fs = get_file_storage();
     $usercontext = context_user::instance($USER->id);
     $record = new stdClass();
     $record->course = $course->id;
     $record->files = file_get_unused_draft_itemid();
     // Attach the main file. We put them in the draft area, create_module will move them.
     $filerecord = array('contextid' => $usercontext->id, 'component' => 'user', 'filearea' => 'draft', 'itemid' => $record->files, 'filepath' => '/', 'filename' => 'mainfile', 'sortorder' => 1);
     $fs->create_file_from_string($filerecord, 'Test resource file');
     // Attach a second file that shouldn't be returned with the search doc.
     $filerecord['filename'] = 'extrafile';
     $filerecord['sortorder'] = 0;
     $fs->create_file_from_string($filerecord, 'Test resource file 2');
     $resource = $this->getDataGenerator()->create_module('resource', $record);
     $searcharea = \core_search\manager::get_search_area($this->resourceareaid);
     $this->assertInstanceOf('\\mod_resource\\search\\activity', $searcharea);
     $recordset = $searcharea->get_recordset_by_timestamp(0);
     $nrecords = 0;
     foreach ($recordset as $record) {
         $doc = $searcharea->get_document($record);
         $searcharea->attach_files($doc);
         $files = $doc->get_files();
         // Resources should only return their main file.
         $this->assertCount(1, $files);
         $file = reset($files);
         $this->assertEquals('mainfile', $file->get_filename());
         $nrecords++;
     }
     $recordset->close();
     $this->assertEquals(1, $nrecords);
 }
Beispiel #11
0
        if (file_exists($settingspath)) {
            $settings = new admin_settingpage('search' . $engine, new lang_string('pluginname', 'search_' . $engine), 'moodle/site:config');
            include $settingspath;
            if ($settings) {
                $pages[] = $settings;
            }
        }
    }
    // Setup status.
    $temp->add(new admin_setting_searchsetupinfo());
    // Search engine selection.
    $temp->add(new admin_setting_heading('searchengineheading', new lang_string('searchengine', 'admin'), ''));
    $temp->add(new admin_setting_configselect('searchengine', new lang_string('selectsearchengine', 'admin'), '', 'solr', $engines));
    // Enable search areas.
    $temp->add(new admin_setting_heading('searchareasheading', new lang_string('availablesearchareas', 'admin'), ''));
    $searchareas = \core_search\manager::get_search_areas_list();
    foreach ($searchareas as $areaid => $searcharea) {
        list($componentname, $varname) = $searcharea->get_config_var_name();
        $temp->add(new admin_setting_configcheckbox($componentname . '/' . $varname . '_enabled', $searcharea->get_visible_name(true), '', 1, 1, 0));
    }
    $ADMIN->add('searchplugins', $temp);
    core_collator::asort_objects_by_property($pages, 'visiblename');
    foreach ($pages as $page) {
        $ADMIN->add('searchplugins', $page);
    }
}
/// Add all admin tools
if ($hassiteconfig) {
    $ADMIN->add('modules', new admin_category('tools', new lang_string('tools', 'admin')));
    $ADMIN->add('tools', new admin_externalpage('managetools', new lang_string('toolsmanage', 'admin'), $CFG->wwwroot . '/' . $CFG->admin . '/tools.php'));
}
Beispiel #12
0
 /**
  * Test for post attachments.
  *
  * @return void
  */
 public function test_attach_files()
 {
     global $DB;
     $fs = get_file_storage();
     // Returns the instance as long as the area is supported.
     $searcharea = \core_search\manager::get_search_area($this->forumpostareaid);
     $this->assertInstanceOf('\\mod_forum\\search\\post', $searcharea);
     $user1 = self::getDataGenerator()->create_user();
     $user2 = self::getDataGenerator()->create_user();
     $course1 = self::getDataGenerator()->create_course();
     $this->getDataGenerator()->enrol_user($user1->id, $course1->id, 'student');
     $this->getDataGenerator()->enrol_user($user2->id, $course1->id, 'student');
     $record = new stdClass();
     $record->course = $course1->id;
     $forum1 = self::getDataGenerator()->create_module('forum', $record);
     // Create discussion1.
     $record = new stdClass();
     $record->course = $course1->id;
     $record->userid = $user1->id;
     $record->forum = $forum1->id;
     $record->message = 'discussion';
     $record->attachemt = 1;
     $discussion1 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
     // Attach 2 file to the discussion post.
     $post = $DB->get_record('forum_posts', array('discussion' => $discussion1->id));
     $filerecord = array('contextid' => context_module::instance($forum1->cmid)->id, 'component' => 'mod_forum', 'filearea' => 'attachment', 'itemid' => $post->id, 'filepath' => '/', 'filename' => 'myfile1');
     $file1 = $fs->create_file_from_string($filerecord, 'Some contents 1');
     $filerecord['filename'] = 'myfile2';
     $file2 = $fs->create_file_from_string($filerecord, 'Some contents 2');
     // Create post1 in discussion1.
     $record = new stdClass();
     $record->discussion = $discussion1->id;
     $record->parent = $discussion1->firstpost;
     $record->userid = $user2->id;
     $record->message = 'post2';
     $record->attachemt = 1;
     $discussion1reply1 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_post($record);
     $filerecord['itemid'] = $discussion1reply1->id;
     $filerecord['filename'] = 'myfile3';
     $file3 = $fs->create_file_from_string($filerecord, 'Some contents 3');
     // Create post2 in discussion1.
     $record = new stdClass();
     $record->discussion = $discussion1->id;
     $record->parent = $discussion1->firstpost;
     $record->userid = $user2->id;
     $record->message = 'post3';
     $discussion1reply2 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_post($record);
     // Now get all the posts and see if they have the right files attached.
     $searcharea = \core_search\manager::get_search_area($this->forumpostareaid);
     $recordset = $searcharea->get_recordset_by_timestamp(0);
     $nrecords = 0;
     foreach ($recordset as $record) {
         $doc = $searcharea->get_document($record);
         $searcharea->attach_files($doc);
         $files = $doc->get_files();
         // Now check that each doc has the right files on it.
         switch ($doc->get('itemid')) {
             case $post->id:
                 $this->assertCount(2, $files);
                 $this->assertEquals($file1->get_id(), $files[$file1->get_id()]->get_id());
                 $this->assertEquals($file2->get_id(), $files[$file2->get_id()]->get_id());
                 break;
             case $discussion1reply1->id:
                 $this->assertCount(1, $files);
                 $this->assertEquals($file3->get_id(), $files[$file3->get_id()]->get_id());
                 break;
             case $discussion1reply2->id:
                 $this->assertCount(0, $files);
                 break;
             default:
                 $this->fail('Unexpected post returned');
                 break;
         }
         $nrecords++;
     }
     $recordset->close();
     $this->assertEquals(3, $nrecords);
 }
Beispiel #13
0
 /**
  * Check collaborative_page check access.
  *
  * @return void
  */
 public function test_collaborative_page_check_access()
 {
     global $DB;
     // Returns the instance as long as the area is supported.
     $searcharea = \core_search\manager::get_search_area($this->wikicollabpageareaid);
     $this->assertInstanceOf('\\mod_wiki\\search\\collaborative_page', $searcharea);
     $user1 = self::getDataGenerator()->create_user();
     $course1 = self::getDataGenerator()->create_course();
     $this->getDataGenerator()->enrol_user($user1->id, $course1->id, 'student');
     $wikigenerator = $this->getDataGenerator()->get_plugin_generator('mod_wiki');
     $collabwiki = $this->getDataGenerator()->create_module('wiki', array('course' => $course1->id));
     $cpage1 = $wikigenerator->create_first_page($collabwiki);
     $this->setAdminUser();
     $this->assertEquals(\core_search\manager::ACCESS_GRANTED, $searcharea->check_access($cpage1->id));
     $this->setUser($user1);
     $this->assertEquals(\core_search\manager::ACCESS_GRANTED, $searcharea->check_access($cpage1->id));
     $this->assertEquals(\core_search\manager::ACCESS_DELETED, $searcharea->check_access($cpage1->id + 10));
 }
 /**
  * Changes visibility.
  *
  * @return array
  */
 public function get_areas_user_accesses($limitcourseids = false)
 {
     return parent::get_areas_user_accesses($limitcourseids);
 }
Beispiel #15
0
 /**
  * Builds the HTML to display the control
  *
  * @param string $data Unused
  * @param string $query
  * @return string
  */
 public function output_html($data, $query = '')
 {
     global $CFG, $OUTPUT;
     $return = '';
     $brtag = html_writer::empty_tag('br');
     // Available search areas.
     $searchareas = \core_search\manager::get_search_areas_list();
     $anyenabled = false;
     $anyindexed = false;
     foreach ($searchareas as $areaid => $searcharea) {
         list($componentname, $varname) = $searcharea->get_config_var_name();
         if (!$anyenabled) {
             $anyenabled = get_config($componentname, $varname . '_enabled');
         }
         if (!$anyindexed) {
             $anyindexed = get_config($componentname, $varname . '_indexingstart');
         }
         if ($anyenabled && $anyindexed) {
             break;
         }
     }
     $return .= $OUTPUT->heading(get_string('searchsetupinfo', 'admin'), 3, 'main');
     $table = new html_table();
     $table->head = array(get_string('step', 'search'), get_string('status'));
     $table->colclasses = array('leftalign step', 'leftalign status');
     $table->id = 'searchsetup';
     $table->attributes['class'] = 'admintable generaltable';
     $table->data = array();
     $return .= $brtag . get_string('searchsetupdescription', 'search') . $brtag . $brtag;
     // Select a search engine.
     $row = array();
     $url = new moodle_url('/admin/settings.php?section=manageglobalsearch#admin-searchengine');
     $row[0] = '1. ' . html_writer::tag('a', get_string('selectsearchengine', 'admin'), array('href' => $url));
     $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
     if (!empty($CFG->searchengine)) {
         $status = html_writer::tag('span', get_string('pluginname', 'search_' . $CFG->searchengine), array('class' => 'statusok'));
     }
     $row[1] = $status;
     $table->data[] = $row;
     // Available areas.
     $row = array();
     $url = new moodle_url('/admin/settings.php?section=manageglobalsearch#admin-searchengine');
     $row[0] = '2. ' . html_writer::tag('a', get_string('enablesearchareas', 'admin'), array('href' => $url));
     $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
     if ($anyenabled) {
         $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
     }
     $row[1] = $status;
     $table->data[] = $row;
     // Setup search engine.
     $row = array();
     if (empty($CFG->searchengine)) {
         $row[0] = '3. ' . get_string('setupsearchengine', 'admin');
         $row[1] = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
     } else {
         $url = new moodle_url('/admin/settings.php?section=search' . $CFG->searchengine);
         $row[0] = '3. ' . html_writer::tag('a', get_string('setupsearchengine', 'admin'), array('href' => $url));
         // Check the engine status.
         $searchengine = \core_search\manager::search_engine_instance();
         $serverstatus = $searchengine->is_server_ready();
         if ($serverstatus === true) {
             $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
         } else {
             $status = html_writer::tag('span', $serverstatus, array('class' => 'statuscritical'));
         }
         $row[1] = $status;
     }
     $table->data[] = $row;
     // Indexed data.
     $row = array();
     $url = new moodle_url('/report/search/index.php#searchindexform');
     $row[0] = '4. ' . html_writer::tag('a', get_string('indexdata', 'admin'), array('href' => $url));
     if ($anyindexed) {
         $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
     } else {
         $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
     }
     $row[1] = $status;
     $table->data[] = $row;
     // Enable global search.
     $row = array();
     $url = new moodle_url("/admin/search.php?query=enableglobalsearch");
     $row[0] = '5. ' . html_writer::tag('a', get_string('enableglobalsearch', 'admin'), array('href' => $url));
     $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
     if (\core_search\manager::is_global_search_enabled()) {
         $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
     }
     $row[1] = $status;
     $table->data[] = $row;
     $return .= html_writer::table($table);
     return highlight($query, $return);
 }
Beispiel #16
0
 /**
  * Returns a document instance prepared to be rendered.
  *
  * @param \core_search\area\base $searcharea
  * @param array $docdata
  * @return \core_search\document
  */
 protected function to_document(\core_search\area\base $searcharea, $docdata)
 {
     list($componentname, $areaname) = \core_search\manager::extract_areaid_parts($docdata['areaid']);
     $doc = \core_search\document_factory::instance($docdata['itemid'], $componentname, $areaname, $this);
     $doc->set_data_from_engine($docdata);
     $doc->set_doc_url($searcharea->get_doc_url($doc));
     $doc->set_context_url($searcharea->get_context_url($doc));
     // Uses the internal caches to get required data needed to render the document later.
     $course = $this->get_course($doc->get('courseid'));
     $doc->set_extra('coursefullname', $course->fullname);
     if ($doc->is_set('userid')) {
         $user = $this->get_user($doc->get('userid'));
         $doc->set_extra('userfullname', fullname($user));
     }
     return $doc;
 }
Beispiel #17
0
 /**
  * Reset contents of all database tables to initial values, reset caches, etc.
  *
  * Note: this is relatively slow (cca 2 seconds for pg and 7 for mysql) - please use with care!
  *
  * @static
  * @param bool $detectchanges
  *      true  - changes in global state and database are reported as errors
  *      false - no errors reported
  *      null  - only critical problems are reported as errors
  * @return void
  */
 public static function reset_all_data($detectchanges = false)
 {
     global $DB, $CFG, $USER, $SITE, $COURSE, $PAGE, $OUTPUT, $SESSION, $FULLME;
     // Stop any message redirection.
     self::stop_message_redirection();
     // Stop any message redirection.
     self::stop_event_redirection();
     // Start a new email redirection.
     // This will clear any existing phpmailer redirection.
     // We redirect all phpmailer output to this message sink which is
     // called instead of phpmailer actually sending the message.
     self::start_phpmailer_redirection();
     // We used to call gc_collect_cycles here to ensure desctructors were called between tests.
     // This accounted for 25% of the total time running phpunit - so we removed it.
     // Show any unhandled debugging messages, the runbare() could already reset it.
     self::display_debugging_messages();
     self::reset_debugging();
     // reset global $DB in case somebody mocked it
     $DB = self::get_global_backup('DB');
     if ($DB->is_transaction_started()) {
         // we can not reset inside transaction
         $DB->force_transaction_rollback();
     }
     $resetdb = self::reset_database();
     $localename = self::get_locale_name();
     $warnings = array();
     if ($detectchanges === true) {
         if ($resetdb) {
             $warnings[] = 'Warning: unexpected database modification, resetting DB state';
         }
         $oldcfg = self::get_global_backup('CFG');
         $oldsite = self::get_global_backup('SITE');
         foreach ($CFG as $k => $v) {
             if (!property_exists($oldcfg, $k)) {
                 $warnings[] = 'Warning: unexpected new $CFG->' . $k . ' value';
             } else {
                 if ($oldcfg->{$k} !== $CFG->{$k}) {
                     $warnings[] = 'Warning: unexpected change of $CFG->' . $k . ' value';
                 }
             }
             unset($oldcfg->{$k});
         }
         if ($oldcfg) {
             foreach ($oldcfg as $k => $v) {
                 $warnings[] = 'Warning: unexpected removal of $CFG->' . $k;
             }
         }
         if ($USER->id != 0) {
             $warnings[] = 'Warning: unexpected change of $USER';
         }
         if ($COURSE->id != $oldsite->id) {
             $warnings[] = 'Warning: unexpected change of $COURSE';
         }
         if ($FULLME !== self::get_global_backup('FULLME')) {
             $warnings[] = 'Warning: unexpected change of $FULLME';
         }
         if (setlocale(LC_TIME, 0) !== $localename) {
             $warnings[] = 'Warning: unexpected change of locale';
         }
     }
     if (ini_get('max_execution_time') != 0) {
         // This is special warning for all resets because we do not want any
         // libraries to mess with timeouts unintentionally.
         // Our PHPUnit integration is not supposed to change it either.
         if ($detectchanges !== false) {
             $warnings[] = 'Warning: max_execution_time was changed to ' . ini_get('max_execution_time');
         }
         set_time_limit(0);
     }
     // restore original globals
     $_SERVER = self::get_global_backup('_SERVER');
     $CFG = self::get_global_backup('CFG');
     $SITE = self::get_global_backup('SITE');
     $FULLME = self::get_global_backup('FULLME');
     $_GET = array();
     $_POST = array();
     $_FILES = array();
     $_REQUEST = array();
     $COURSE = $SITE;
     // reinitialise following globals
     $OUTPUT = new bootstrap_renderer();
     $PAGE = new moodle_page();
     $FULLME = null;
     $ME = null;
     $SCRIPT = null;
     // Empty sessison and set fresh new not-logged-in user.
     \core\session\manager::init_empty_session();
     // reset all static caches
     \core\event\manager::phpunit_reset();
     accesslib_clear_all_caches(true);
     get_string_manager()->reset_caches(true);
     reset_text_filters_cache(true);
     events_get_handlers('reset');
     core_text::reset_caches();
     get_message_processors(false, true, true);
     filter_manager::reset_caches();
     core_filetypes::reset_caches();
     \core_search\manager::clear_static();
     core_user::reset_caches();
     if (class_exists('core_media_manager', false)) {
         core_media_manager::reset_caches();
     }
     // Reset static unit test options.
     if (class_exists('\\availability_date\\condition', false)) {
         \availability_date\condition::set_current_time_for_test(0);
     }
     // Reset internal users.
     core_user::reset_internal_users();
     //TODO MDL-25290: add more resets here and probably refactor them to new core function
     // Reset course and module caches.
     if (class_exists('format_base')) {
         // If file containing class is not loaded, there is no cache there anyway.
         format_base::reset_course_cache(0);
     }
     get_fast_modinfo(0, 0, true);
     // Reset other singletons.
     if (class_exists('core_plugin_manager')) {
         core_plugin_manager::reset_caches(true);
     }
     if (class_exists('\\core\\update\\checker')) {
         \core\update\checker::reset_caches(true);
     }
     // Clear static cache within restore.
     if (class_exists('restore_section_structure_step')) {
         restore_section_structure_step::reset_caches();
     }
     // purge dataroot directory
     self::reset_dataroot();
     // restore original config once more in case resetting of caches changed CFG
     $CFG = self::get_global_backup('CFG');
     // inform data generator
     self::get_data_generator()->reset();
     // fix PHP settings
     error_reporting($CFG->debug);
     // Reset the date/time class.
     core_date::phpunit_reset();
     // Make sure the time locale is consistent - that is Australian English.
     setlocale(LC_TIME, $localename);
     // Reset the log manager cache.
     get_log_manager(true);
     // verify db writes just in case something goes wrong in reset
     if (self::$lastdbwrites != $DB->perf_get_writes()) {
         error_log('Unexpected DB writes in phpunit_util::reset_all_data()');
         self::$lastdbwrites = $DB->perf_get_writes();
     }
     if ($warnings) {
         $warnings = implode("\n", $warnings);
         trigger_error($warnings, E_USER_WARNING);
     }
 }
Beispiel #18
0
 public function test_search_config()
 {
     $this->resetAfterTest();
     $search = testable_core_search::instance();
     // We should test both plugin types and core subsystems. No core subsystems available yet.
     $searcharea = $search->get_search_area($this->forumpostareaid);
     list($componentname, $varname) = $searcharea->get_config_var_name();
     // Just with a couple of vars should be enough.
     $start = time() - 100;
     $end = time();
     set_config($varname . '_indexingstart', $start, $componentname);
     set_config($varname . '_indexingend', $end, $componentname);
     $configs = $search->get_areas_config(array($this->forumpostareaid => $searcharea));
     $this->assertEquals($start, $configs[$this->forumpostareaid]->indexingstart);
     $this->assertEquals($end, $configs[$this->forumpostareaid]->indexingend);
     try {
         $fakeareaid = \core_search\manager::generate_areaid('mod_unexisting', 'chihuaquita');
         $search->reset_config($fakeareaid);
         $this->fail('An exception should be triggered if the provided search area does not exist.');
     } catch (moodle_exception $ex) {
         $this->assertContains($fakeareaid . ' search area is not available.', $ex->getMessage());
     }
     // We clean it all but enabled components.
     $search->reset_config($this->forumpostareaid);
     $this->assertEquals(1, get_config($componentname, $varname . '_enabled'));
     $this->assertEquals(0, get_config($componentname, $varname . '_indexingstart'));
     $this->assertEquals(0, get_config($componentname, $varname . '_indexingend'));
     $this->assertEquals(0, get_config($componentname, $varname . '_lastindexrun'));
     // No caching.
     $configs = $search->get_areas_config(array($this->forumpostareaid => $searcharea));
     $this->assertEquals(0, $configs[$this->forumpostareaid]->indexingstart);
     $this->assertEquals(0, $configs[$this->forumpostareaid]->indexingend);
     set_config($varname . '_indexingstart', $start, $componentname);
     set_config($varname . '_indexingend', $end, $componentname);
     // All components config should be reset.
     $search->reset_config();
     $this->assertEquals(0, get_config($componentname, $varname . '_indexingstart'));
     $this->assertEquals(0, get_config($componentname, $varname . '_indexingend'));
     $this->assertEquals(0, get_config($componentname, $varname . '_lastindexrun'));
     // No caching.
     $configs = $search->get_areas_config(array($this->forumpostareaid => $searcharea));
     $this->assertEquals(0, $configs[$this->forumpostareaid]->indexingstart);
     $this->assertEquals(0, $configs[$this->forumpostareaid]->indexingend);
 }
Beispiel #19
0
 /**
  * Adding this test here as get_areas_user_accesses process is the same, results just depend on the context level.
  *
  * @return void
  */
 public function test_search_user_accesses()
 {
     global $DB;
     $this->resetAfterTest();
     $frontpage = $DB->get_record('course', array('id' => SITEID));
     $course1 = $this->getDataGenerator()->create_course();
     $course1ctx = context_course::instance($course1->id);
     $course2 = $this->getDataGenerator()->create_course();
     $course2ctx = context_course::instance($course2->id);
     $teacher = $this->getDataGenerator()->create_user();
     $teacherctx = context_user::instance($teacher->id);
     $student = $this->getDataGenerator()->create_user();
     $studentctx = context_user::instance($student->id);
     $noaccess = $this->getDataGenerator()->create_user();
     $noaccessctx = context_user::instance($noaccess->id);
     $this->getDataGenerator()->enrol_user($teacher->id, $course1->id, 'teacher');
     $this->getDataGenerator()->enrol_user($student->id, $course1->id, 'student');
     $frontpageforum = $this->getDataGenerator()->create_module('forum', array('course' => $frontpage->id));
     $forum1 = $this->getDataGenerator()->create_module('forum', array('course' => $course1->id));
     $forum2 = $this->getDataGenerator()->create_module('forum', array('course' => $course1->id));
     $forum3 = $this->getDataGenerator()->create_module('forum', array('course' => $course2->id));
     $frontpageforumcontext = context_module::instance($frontpageforum->cmid);
     $context1 = context_module::instance($forum1->cmid);
     $context2 = context_module::instance($forum2->cmid);
     $context3 = context_module::instance($forum3->cmid);
     $search = testable_core_search::instance();
     $mockareaid = \core_search\manager::generate_areaid('core_mocksearch', 'mock_search_area');
     $search->add_core_search_areas();
     $search->add_search_area($mockareaid, new core_mocksearch\search\mock_search_area());
     $this->setAdminUser();
     $this->assertTrue($search->get_areas_user_accesses());
     $sitectx = \context_course::instance(SITEID);
     $systemctxid = \context_system::instance()->id;
     // Can access the frontpage ones.
     $this->setUser($noaccess);
     $contexts = $search->get_areas_user_accesses();
     $this->assertEquals(array($frontpageforumcontext->id => $frontpageforumcontext->id), $contexts[$this->forumpostareaid]);
     $this->assertEquals(array($sitectx->id => $sitectx->id), $contexts[$this->mycoursesareaid]);
     $mockctxs = array($noaccessctx->id => $noaccessctx->id, $systemctxid => $systemctxid);
     $this->assertEquals($mockctxs, $contexts[$mockareaid]);
     $this->setUser($teacher);
     $contexts = $search->get_areas_user_accesses();
     $frontpageandcourse1 = array($frontpageforumcontext->id => $frontpageforumcontext->id, $context1->id => $context1->id, $context2->id => $context2->id);
     $this->assertEquals($frontpageandcourse1, $contexts[$this->forumpostareaid]);
     $this->assertEquals(array($sitectx->id => $sitectx->id, $course1ctx->id => $course1ctx->id), $contexts[$this->mycoursesareaid]);
     $mockctxs = array($teacherctx->id => $teacherctx->id, $systemctxid => $systemctxid);
     $this->assertEquals($mockctxs, $contexts[$mockareaid]);
     $this->setUser($student);
     $contexts = $search->get_areas_user_accesses();
     $this->assertEquals($frontpageandcourse1, $contexts[$this->forumpostareaid]);
     $this->assertEquals(array($sitectx->id => $sitectx->id, $course1ctx->id => $course1ctx->id), $contexts[$this->mycoursesareaid]);
     $mockctxs = array($studentctx->id => $studentctx->id, $systemctxid => $systemctxid);
     $this->assertEquals($mockctxs, $contexts[$mockareaid]);
     // Hide the activity.
     set_coursemodule_visible($forum2->cmid, 0);
     $contexts = $search->get_areas_user_accesses();
     $this->assertEquals(array($frontpageforumcontext->id => $frontpageforumcontext->id, $context1->id => $context1->id), $contexts[$this->forumpostareaid]);
     // Now test course limited searches.
     set_coursemodule_visible($forum2->cmid, 1);
     $this->getDataGenerator()->enrol_user($student->id, $course2->id, 'student');
     $contexts = $search->get_areas_user_accesses();
     $allcontexts = array($frontpageforumcontext->id => $frontpageforumcontext->id, $context1->id => $context1->id, $context2->id => $context2->id, $context3->id => $context3->id);
     $this->assertEquals($allcontexts, $contexts[$this->forumpostareaid]);
     $this->assertEquals(array($sitectx->id => $sitectx->id, $course1ctx->id => $course1ctx->id, $course2ctx->id => $course2ctx->id), $contexts[$this->mycoursesareaid]);
     $contexts = $search->get_areas_user_accesses(array($course1->id, $course2->id));
     $allcontexts = array($context1->id => $context1->id, $context2->id => $context2->id, $context3->id => $context3->id);
     $this->assertEquals($allcontexts, $contexts[$this->forumpostareaid]);
     $this->assertEquals(array($course1ctx->id => $course1ctx->id, $course2ctx->id => $course2ctx->id), $contexts[$this->mycoursesareaid]);
     $contexts = $search->get_areas_user_accesses(array($course2->id));
     $allcontexts = array($context3->id => $context3->id);
     $this->assertEquals($allcontexts, $contexts[$this->forumpostareaid]);
     $this->assertEquals(array($course2ctx->id => $course2ctx->id), $contexts[$this->mycoursesareaid]);
     $contexts = $search->get_areas_user_accesses(array($course1->id));
     $allcontexts = array($context1->id => $context1->id, $context2->id => $context2->id);
     $this->assertEquals($allcontexts, $contexts[$this->forumpostareaid]);
     $this->assertEquals(array($course1ctx->id => $course1ctx->id), $contexts[$this->mycoursesareaid]);
 }
Beispiel #20
0
 /**
  * Document accesses.
  *
  * @return void
  */
 public function test_message_sent_access()
 {
     global $CFG;
     // Returns the instance as long as the area is supported.
     $searcharea = \core_search\manager::get_search_area($this->messagesentareaid);
     $user1 = self::getDataGenerator()->create_user();
     $user2 = self::getDataGenerator()->create_user();
     $user3 = self::getDataGenerator()->create_user();
     $this->preventResetByRollback();
     $sink = $this->redirectMessages();
     $message = new \core\message\message();
     $message->courseid = SITEID;
     $message->userfrom = $user1;
     $message->userto = $user2;
     $message->subject = "Test Subject";
     $message->smallmessage = "Test small messsage";
     $message->fullmessage = "Test full messsage";
     $message->fullmessageformat = 0;
     $message->fullmessagehtml = null;
     $message->notification = 0;
     $message->component = "moodle";
     $message->name = "instantmessage";
     $messageid = message_send($message);
     $messages = $sink->get_messages();
     $message = $messages[0];
     $this->setUser($user1);
     if ($CFG->messaging) {
         $this->assertEquals(\core_search\manager::ACCESS_GRANTED, $searcharea->check_access($messageid));
     } else {
         $this->assertEquals(\core_search\manager::ACCESS_DENIED, $searcharea->check_access($messageid));
     }
     $this->assertEquals(\core_search\manager::ACCESS_DELETED, $searcharea->check_access(-123));
     message_delete_message($message, $user1->id);
     $this->assertEquals(\core_search\manager::ACCESS_DELETED, $searcharea->check_access($messageid));
     $this->setUser($user2);
     $this->assertEquals(\core_search\manager::ACCESS_DENIED, $searcharea->check_access($messageid));
     $this->setUser($user3);
     $this->assertEquals(\core_search\manager::ACCESS_DENIED, $searcharea->check_access($messageid));
     $this->setGuestUser();
     $this->assertEquals(\core_search\manager::ACCESS_DENIED, $searcharea->check_access($messageid));
     $this->setAdminUser();
     $this->assertEquals(\core_search\manager::ACCESS_DENIED, $searcharea->check_access($messageid));
     delete_user($user2);
     $this->setUser($user1);
     $this->assertEquals(\core_search\manager::ACCESS_DELETED, $searcharea->check_access($messageid));
 }
Beispiel #21
0
 /**
  * Document accesses.
  *
  * @return void
  */
 public function test_mycourses_access()
 {
     // Returns the instance as long as the area is supported.
     $searcharea = \core_search\manager::get_search_area($this->mycoursesareaid);
     $user1 = self::getDataGenerator()->create_user();
     $user2 = self::getDataGenerator()->create_user();
     $course1 = self::getDataGenerator()->create_course();
     $course2 = self::getDataGenerator()->create_course(array('visible' => 0));
     $course3 = self::getDataGenerator()->create_course();
     $this->getDataGenerator()->enrol_user($user1->id, $course1->id, 'teacher');
     $this->getDataGenerator()->enrol_user($user2->id, $course1->id, 'student');
     $this->getDataGenerator()->enrol_user($user1->id, $course2->id, 'teacher');
     $this->getDataGenerator()->enrol_user($user2->id, $course2->id, 'student');
     $this->setUser($user1);
     $this->assertEquals(\core_search\manager::ACCESS_GRANTED, $searcharea->check_access($course1->id));
     $this->assertEquals(\core_search\manager::ACCESS_GRANTED, $searcharea->check_access($course2->id));
     $this->assertEquals(\core_search\manager::ACCESS_DENIED, $searcharea->check_access($course3->id));
     $this->assertEquals(\core_search\manager::ACCESS_DELETED, $searcharea->check_access(-123));
     $this->setUser($user2);
     $this->assertEquals(\core_search\manager::ACCESS_GRANTED, $searcharea->check_access($course1->id));
     $this->assertEquals(\core_search\manager::ACCESS_DENIED, $searcharea->check_access($course2->id));
     $this->assertEquals(\core_search\manager::ACCESS_DENIED, $searcharea->check_access($course3->id));
 }
Beispiel #22
0
    if (!empty($data->areaids)) {
        $urlparams['areaids'] = implode(',', $data->areaids);
    }
    if (!empty($data->courseids)) {
        $urlparams['courseids'] = implode(',', $data->courseids);
    }
    $urlparams['timestart'] = $data->timestart;
    $urlparams['timeend'] = $data->timeend;
}
$url = new moodle_url('/search/index.php', $urlparams);
$PAGE->set_url($url);
// We are ready to render.
echo $OUTPUT->header();
echo $OUTPUT->heading($pagetitle);
// Get the results.
if ($data) {
    $results = $search->paged_search($data, $page);
}
if ($errorstr = $search->get_engine()->get_query_error()) {
    echo $OUTPUT->notification(get_string('queryerror', 'search', $errorstr), 'notifyproblem');
} else {
    if (empty($results->totalcount) && !empty($data)) {
        echo $OUTPUT->notification(get_string('noresults', 'search'), 'notifymessage');
    }
}
$mform->display();
if (!empty($results)) {
    echo $searchrenderer->render_results($results->results, $results->actualpage, $results->totalcount, $url);
    \core_search\manager::trigger_search_results_viewed(['q' => $data->q, 'page' => $page, 'title' => $data->title, 'areaids' => !empty($data->areaids) ? $data->areaids : array(), 'courseids' => !empty($data->courseids) ? $data->courseids : array(), 'timestart' => isset($data->timestart) ? $data->timestart : 0, 'timeend' => isset($data->timeend) ? $data->timeend : 0]);
}
echo $OUTPUT->footer();
Beispiel #23
0
 /**
  * Export the document data to be used as a template context.
  *
  * Adding more info than the required one as people might be interested in extending the template.
  *
  * Although content is a required field when setting up the document, it accepts '' (empty) values
  * as they may be the result of striping out HTML.
  *
  * @param renderer_base $output The renderer.
  * @return array
  */
 public function export_for_template(\renderer_base $output)
 {
     list($componentname, $areaname) = \core_search\manager::extract_areaid_parts($this->get('areaid'));
     $data = ['courseurl' => new \moodle_url('/course/view.php?id=' . $this->get('courseid')), 'coursefullname' => format_string($this->get('coursefullname'), true, array('context' => $this->get('contextid'))), 'modified' => userdate($this->get('modified')), 'title' => format_string($this->get('title'), true, array('context' => $this->get('contextid'))), 'docurl' => $this->get_doc_url(), 'content' => $this->is_set('content') ? $this->format_text($this->get('content')) : null, 'contexturl' => $this->get_context_url(), 'description1' => $this->is_set('description1') ? $this->format_text($this->get('description1')) : null, 'description2' => $this->is_set('description2') ? $this->format_text($this->get('description2')) : null];
     if ($this->is_set('userid')) {
         $data['userurl'] = new \moodle_url('/user/view.php', array('id' => $this->get('userid'), 'course' => $this->get('courseid')));
         $data['userfullname'] = format_string($this->get('userfullname'), true, array('context' => $this->get('contextid')));
     }
     return $data;
 }
Beispiel #24
0
 /**
  * Document accesses.
  *
  * @return void
  */
 public function test_users_access()
 {
     // Returns the instance as long as the area is supported.
     $searcharea = \core_search\manager::get_search_area($this->userareaid);
     $user1 = self::getDataGenerator()->create_user();
     $user2 = self::getDataGenerator()->create_user();
     $user3 = self::getDataGenerator()->create_user();
     $user4 = self::getDataGenerator()->create_user();
     $deleteduser = self::getDataGenerator()->create_user(array('deleted' => 1));
     $unconfirmeduser = self::getDataGenerator()->create_user(array('confirmed' => 0));
     $suspendeduser = self::getDataGenerator()->create_user(array('suspended' => 1));
     $course1 = self::getDataGenerator()->create_course();
     $course2 = self::getDataGenerator()->create_course();
     $group1 = $this->getDataGenerator()->create_group(array('courseid' => $course1->id));
     $group2 = $this->getDataGenerator()->create_group(array('courseid' => $course1->id));
     $this->getDataGenerator()->enrol_user($user1->id, $course1->id, 'teacher');
     $this->getDataGenerator()->enrol_user($user2->id, $course1->id, 'student');
     $this->getDataGenerator()->enrol_user($user2->id, $course2->id, 'student');
     $this->getDataGenerator()->enrol_user($user3->id, $course2->id, 'student');
     $this->getDataGenerator()->enrol_user($user4->id, $course2->id, 'student');
     $this->getDataGenerator()->enrol_user($suspendeduser->id, $course1->id, 'student');
     $this->getDataGenerator()->create_group_member(array('userid' => $user2->id, 'groupid' => $group1->id));
     $this->getDataGenerator()->create_group_member(array('userid' => $user3->id, 'groupid' => $group1->id));
     $this->getDataGenerator()->create_group_member(array('userid' => $user4->id, 'groupid' => $group2->id));
     $this->setAdminUser();
     $this->assertEquals(\core_search\manager::ACCESS_GRANTED, $searcharea->check_access($user1->id));
     $this->assertEquals(\core_search\manager::ACCESS_GRANTED, $searcharea->check_access($user2->id));
     $this->assertEquals(\core_search\manager::ACCESS_GRANTED, $searcharea->check_access($user3->id));
     $this->assertEquals(\core_search\manager::ACCESS_DELETED, $searcharea->check_access($deleteduser->id));
     $this->assertEquals(\core_search\manager::ACCESS_GRANTED, $searcharea->check_access($unconfirmeduser->id));
     $this->assertEquals(\core_search\manager::ACCESS_GRANTED, $searcharea->check_access($suspendeduser->id));
     $this->assertEquals(\core_search\manager::ACCESS_GRANTED, $searcharea->check_access(2));
     $this->setUser($user1);
     $this->assertEquals(\core_search\manager::ACCESS_GRANTED, $searcharea->check_access($user1->id));
     $this->assertEquals(\core_search\manager::ACCESS_GRANTED, $searcharea->check_access($user2->id));
     $this->assertEquals(\core_search\manager::ACCESS_DENIED, $searcharea->check_access($user3->id));
     $this->assertEquals(\core_search\manager::ACCESS_DENIED, $searcharea->check_access($user4->id));
     $this->assertEquals(\core_search\manager::ACCESS_DENIED, $searcharea->check_access(1));
     // Guest user can't be accessed.
     $this->assertEquals(\core_search\manager::ACCESS_DENIED, $searcharea->check_access(2));
     // Admin user can't be accessed.
     $this->assertEquals(\core_search\manager::ACCESS_DELETED, $searcharea->check_access(-123));
     $this->assertEquals(\core_search\manager::ACCESS_DENIED, $searcharea->check_access($unconfirmeduser->id));
     $this->assertEquals(\core_search\manager::ACCESS_GRANTED, $searcharea->check_access($suspendeduser->id));
     $this->setUser($user2);
     $this->assertEquals(\core_search\manager::ACCESS_GRANTED, $searcharea->check_access($user1->id));
     $this->assertEquals(\core_search\manager::ACCESS_GRANTED, $searcharea->check_access($user2->id));
     $this->assertEquals(\core_search\manager::ACCESS_GRANTED, $searcharea->check_access($user3->id));
     $this->assertEquals(\core_search\manager::ACCESS_GRANTED, $searcharea->check_access($user4->id));
     $this->setUser($user3);
     $this->assertEquals(\core_search\manager::ACCESS_DENIED, $searcharea->check_access($user1->id));
     $this->assertEquals(\core_search\manager::ACCESS_GRANTED, $searcharea->check_access($user2->id));
     $this->assertEquals(\core_search\manager::ACCESS_GRANTED, $searcharea->check_access($user3->id));
     $this->assertEquals(\core_search\manager::ACCESS_DENIED, $searcharea->check_access($suspendeduser->id));
     $this->setGuestUser();
     $this->assertEquals(\core_search\manager::ACCESS_GRANTED, $searcharea->check_access($user1->id));
     $this->assertEquals(\core_search\manager::ACCESS_GRANTED, $searcharea->check_access($user2->id));
     $this->assertEquals(\core_search\manager::ACCESS_GRANTED, $searcharea->check_access($user3->id));
 }
Beispiel #25
0
 /**
  * Export the document data to be used as a template context.
  *
  * Adding more info than the required one as people might be interested in extending the template.
  *
  * Although content is a required field when setting up the document, it accepts '' (empty) values
  * as they may be the result of striping out HTML.
  *
  * SECURITY NOTE: It is the responsibility of the document to properly escape any text to be displayed.
  * The renderer will output the content without any further cleaning.
  *
  * @param renderer_base $output The renderer.
  * @return array
  */
 public function export_for_template(\renderer_base $output)
 {
     list($componentname, $areaname) = \core_search\manager::extract_areaid_parts($this->get('areaid'));
     $title = $this->is_set('title') ? $this->format_text($this->get('title')) : '';
     $data = ['componentname' => $componentname, 'areaname' => $areaname, 'courseurl' => course_get_url($this->get('courseid')), 'coursefullname' => format_string($this->get('coursefullname'), true, array('context' => $this->get('contextid'))), 'modified' => userdate($this->get('modified')), 'title' => $title !== '' ? $title : get_string('notitle', 'search'), 'docurl' => $this->get_doc_url(), 'content' => $this->is_set('content') ? $this->format_text($this->get('content')) : null, 'contexturl' => $this->get_context_url(), 'description1' => $this->is_set('description1') ? $this->format_text($this->get('description1')) : null, 'description2' => $this->is_set('description2') ? $this->format_text($this->get('description2')) : null];
     // Now take any attached any files.
     $files = $this->get_files();
     if (!empty($files)) {
         if (count($files) > 1) {
             $filenames = array();
             foreach ($files as $file) {
                 $filenames[] = format_string($file->get_filename(), true, array('context' => $this->get('contextid')));
             }
             $data['multiplefiles'] = true;
             $data['filenames'] = $filenames;
         } else {
             $file = reset($files);
             $data['filename'] = format_string($file->get_filename(), true, array('context' => $this->get('contextid')));
         }
     }
     if ($this->is_set('userid')) {
         $data['userurl'] = new \moodle_url('/user/view.php', array('id' => $this->get('userid'), 'course' => $this->get('courseid')));
         $data['userfullname'] = format_string($this->get('userfullname'), true, array('context' => $this->get('contextid')));
     }
     return $data;
 }
Beispiel #26
0
 /**
  * Document contents.
  *
  * @return void
  */
 public function test_check_access()
 {
     global $DB;
     // Returns the instance as long as the area is supported.
     $searcharea = \core_search\manager::get_search_area($this->bookchapterareaid);
     $this->assertInstanceOf('\\mod_book\\search\\chapter', $searcharea);
     $user1 = self::getDataGenerator()->create_user();
     $course1 = self::getDataGenerator()->create_course();
     $this->getDataGenerator()->enrol_user($user1->id, $course1->id, 'student');
     $book = $this->getDataGenerator()->create_module('book', array('course' => $course1->id));
     $bookgenerator = $this->getDataGenerator()->get_plugin_generator('mod_book');
     $chapter = array('bookid' => $book->id, 'content' => 'Chapter1', 'title' => 'Title1');
     $chapter1 = $bookgenerator->create_chapter($chapter);
     $chapter['content'] = 'Chapter2';
     $chapter['title'] = 'Title2';
     $chapter['hidden'] = 1;
     $chapter2 = $bookgenerator->create_chapter($chapter);
     $this->setAdminUser();
     $this->assertEquals(\core_search\manager::ACCESS_GRANTED, $searcharea->check_access($chapter1->id));
     $this->assertEquals(\core_search\manager::ACCESS_GRANTED, $searcharea->check_access($chapter2->id));
     $this->setUser($user1);
     $this->assertEquals(\core_search\manager::ACCESS_GRANTED, $searcharea->check_access($chapter1->id));
     $this->assertEquals(\core_search\manager::ACCESS_DENIED, $searcharea->check_access($chapter2->id));
     $this->assertEquals(\core_search\manager::ACCESS_DELETED, $searcharea->check_access($chapter2->id + 10));
 }
Beispiel #27
0
 /**
  * Test indexing a file we don't consider indexable.
  */
 public function test_index_filtered_file()
 {
     // Get area to work with.
     $areaid = \core_search\manager::generate_areaid('core_mocksearch', 'mock_search_area');
     $area = \core_search\manager::get_search_area($areaid);
     // Get a single record to make a doc from.
     $record = $this->generator->create_record();
     $doc = $area->get_document($record);
     // Now we are going to make some files.
     $fs = get_file_storage();
     $syscontext = \context_system::instance();
     // We need to make a file greater than 1kB in size, which is the lowest filter size.
     $filerecord = new \stdClass();
     $filerecord->filename = 'largefile';
     $filerecord->content = 'Some LargeFindContent to find.';
     for ($i = 0; $i < 200; $i++) {
         $filerecord->content .= ' The quick brown fox jumps over the lazy dog.';
     }
     $this->assertGreaterThan(1024, strlen($filerecord->content));
     $file = $this->generator->create_file($filerecord);
     $doc->add_stored_file($file);
     $filerecord->filename = 'smallfile';
     $filerecord->content = 'Some SmallFindContent to find.';
     $file = $this->generator->create_file($filerecord);
     $doc->add_stored_file($file);
     $this->engine->add_document($doc, true);
     $this->engine->area_index_complete($area->get_area_id());
     $querydata = new stdClass();
     // We shouldn't be able to find the large file contents.
     $querydata->q = 'LargeFindContent';
     $this->assertCount(0, $this->search->search($querydata));
     // But we should be able to find the filename.
     $querydata->q = 'largefile';
     $this->assertCount(1, $this->search->search($querydata));
     // We should be able to find the small file contents.
     $querydata->q = 'SmallFindContent';
     $this->assertCount(1, $this->search->search($querydata));
     // And we should be able to find the filename.
     $querydata->q = 'smallfile';
     $this->assertCount(1, $this->search->search($querydata));
 }
Beispiel #28
0
 /**
  * Changes visibility.
  *
  * @param string $classname
  * @return bool
  */
 public static function is_search_area($classname)
 {
     return parent::is_search_area($classname);
 }
Beispiel #29
0
require_once __DIR__ . '/../../config.php';
require_once $CFG->libdir . '/adminlib.php';
admin_externalpage_setup('reportsearch');
$pagetitle = get_string('pluginname', 'report_search');
$PAGE->set_title($pagetitle);
$PAGE->set_heading($pagetitle);
echo $OUTPUT->header();
echo $OUTPUT->heading($pagetitle);
if (\core_search\manager::is_global_search_enabled() === false) {
    $renderer = $PAGE->get_renderer('core_search');
    echo $renderer->render_search_disabled();
    echo $OUTPUT->footer();
    exit;
}
$renderer = $PAGE->get_renderer('report_search');
$search = \core_search\manager::instance();
// All enabled components.
$searchareas = $search->get_search_areas_list(true);
$mform = new \report_search\output\form(null, array('searchareas' => $searchareas));
if ($data = $mform->get_data()) {
    if (!empty($data->delete)) {
        if (!empty($data->all)) {
            $search->delete_index();
        } else {
            $anydelete = false;
            // We check that the component exist and is enabled.
            foreach ($searchareas as $areaid => $searcharea) {
                if (!empty($data->{$areaid})) {
                    $anydelete = true;
                    $search->delete_index($areaid);
                }
Beispiel #30
-1
 /**
  * Gets the block contents.
  *
  * If we can avoid it better not check the server status here as connecting
  * to the server will slow down the whole page load.
  *
  * @return string The block HTML.
  */
 public function get_content()
 {
     global $OUTPUT;
     if ($this->content !== null) {
         return $this->content;
     }
     $this->content = new stdClass();
     $this->content->footer = '';
     if (\core_search\manager::is_global_search_enabled() === false) {
         $this->content->text = get_string('globalsearchdisabled', 'search');
         return $this->content;
     }
     $url = new moodle_url('/search/index.php');
     $this->content->footer .= html_writer::link($url, get_string('advancedsearch', 'search'));
     $this->content->text = html_writer::start_tag('div', array('class' => 'searchform'));
     $this->content->text .= html_writer::start_tag('form', array('action' => $url->out()));
     $this->content->text .= html_writer::start_tag('fieldset', array('action' => 'invisiblefieldset'));
     // Input.
     $this->content->text .= html_writer::tag('label', get_string('search', 'search'), array('for' => 'searchform_search', 'class' => 'accesshide'));
     $inputoptions = array('id' => 'searchform_search', 'name' => 'q', 'type' => 'text', 'size' => '15');
     $this->content->text .= html_writer::empty_tag('input', $inputoptions);
     // Search button.
     $this->content->text .= html_writer::tag('button', get_string('search', 'search'), array('id' => 'searchform_button', 'type' => 'submit', 'title' => 'globalsearch'));
     $this->content->text .= html_writer::end_tag('fieldset');
     $this->content->text .= html_writer::end_tag('form');
     $this->content->text .= html_writer::end_tag('div');
     return $this->content;
 }