本文整理汇总了PHP中tag_set函数的典型用法代码示例。如果您正苦于以下问题:PHP tag_set函数的具体用法?PHP tag_set怎么用?PHP tag_set使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了tag_set函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: test_tag_set_get
/**
* Test the tag_set function.
* This function was deprecated in 3.1
*/
public function test_tag_set_get()
{
global $DB;
// Create a course to tag.
$course = $this->getDataGenerator()->create_course();
// Create the tag and tag instance.
tag_set('course', $course->id, array('A random tag'), 'core', context_course::instance($course->id)->id);
$this->assertDebuggingCalled();
// Get the tag instance that should have been created.
$taginstance = $DB->get_record('tag_instance', array('itemtype' => 'course', 'itemid' => $course->id), '*', MUST_EXIST);
$this->assertEquals('core', $taginstance->component);
$this->assertEquals(context_course::instance($course->id)->id, $taginstance->contextid);
$tagbyname = tag_get('name', 'A random tag');
$this->assertDebuggingCalled();
$this->assertEquals('A random tag', $tagbyname->rawname);
$this->assertEmpty(tag_get('name', 'Non existing tag'));
$this->assertDebuggingCalled();
$tagbyid = tag_get('id', $tagbyname->id);
$this->assertDebuggingCalled();
$this->assertEquals('A random tag', $tagbyid->rawname);
$tagid = $tagbyname->id;
$this->assertEmpty(tag_get('id', $tagid + 1));
$this->assertDebuggingCalled();
tag_set('tag', $tagid, array('Some related tag'));
$this->assertDebuggingCalled();
$relatedtags = tag_get_related_tags($tagid);
$this->assertDebuggingCalled();
$this->assertCount(1, $relatedtags);
$this->assertEquals('Some related tag', $relatedtags[0]->rawname);
$tagids = tag_get_id(array('A random tag', 'Some related tag'));
$this->assertDebuggingCalled();
$this->assertCount(2, $tagids);
$this->assertEquals($tagid, $tagids['a random tag']);
$this->assertEquals($relatedtags[0]->id, $tagids['some related tag']);
}
示例2: wiki_tags_save_tags
/**
* Save the wikitags list
*
* @param Object $WS WikiStorage
* @param String $taglist Comma-separated tags
*/
function wiki_tags_save_tags($WS, $taglist)
{
global $COURSE;
add_to_log($COURSE->id, 'wiki', 'save tags', addslashes("view.php?id={$WS->cm->id}&page={$WS->page}"), $WS->dfwiki->id, $WS->cm->id);
$page = wiki_page_last_version($WS->page, $WS);
// delete the tags of the current wiki page version
/*
*$tagids = tag_get_tags_ids('wiki', $taglist);
*foreach ($tagids as $tagid)
* tag_delete_instance('wiki', $page->created, $tagid);
*/
// add the tags to the next wiki page
tag_set('wiki', $page->created, explode(',', $taglist));
}
示例3: test_tag_set
/**
* Test the tag_set function.
*/
public function test_tag_set()
{
global $DB;
// Create a course to tag.
$course = $this->getDataGenerator()->create_course();
// Create the tag and tag instance.
tag_set('course', $course->id, array('A random tag'), 'core', context_course::instance($course->id)->id);
// Get the tag instance that should have been created.
$taginstance = $DB->get_record('tag_instance', array('itemtype' => 'course', 'itemid' => $course->id), '*', MUST_EXIST);
$this->assertEquals('core', $taginstance->component);
$this->assertEquals(context_course::instance($course->id)->id, $taginstance->contextid);
// Now call the tag_set function without specifying the component or contextid and
// ensure the function debugging is called.
tag_set('course', $course->id, array('Another tag'));
$this->assertDebuggingCalled();
}
示例4: forumng_update_instance
function forumng_update_instance($forumng)
{
global $DB, $CFG;
require_once dirname(__FILE__) . '/mod_forumng.php';
// Get the tag lib.php.
require_once $CFG->dirroot . '/tag/lib.php';
$forumng->id = $forumng->instance;
$previous = $DB->get_record('forumng', array('id' => $forumng->id), '*', MUST_EXIST);
$DB->update_record('forumng', $forumng);
$forum = mod_forumng::get_from_id($forumng->id, mod_forumng::CLONE_DIRECT);
$forum->updated($previous);
if (isset($forumng->settags)) {
$context = $forum->get_context(true);
tag_set('forumng', $forumng->id, $forumng->settags, 'mod_forumng', $context->id);
}
return true;
}
示例5: blog_sync_external_entries
//.........这里部分代码省略.........
$DB->update_record('blog_external', $externalblog);
}
}
$rss = new moodle_simplepie($externalblog->url);
if (empty($rss->data)) {
return null;
}
//used to identify blog posts that have been deleted from the source feed
$oldesttimestamp = null;
$uniquehashes = array();
foreach ($rss->get_items() as $entry) {
// If filtertags are defined, use them to filter the entries by RSS category
if (!empty($externalblog->filtertags)) {
$containsfiltertag = false;
$categories = $entry->get_categories();
$filtertags = explode(',', $externalblog->filtertags);
$filtertags = array_map('trim', $filtertags);
$filtertags = array_map('strtolower', $filtertags);
foreach ($categories as $category) {
if (in_array(trim(strtolower($category->term)), $filtertags)) {
$containsfiltertag = true;
}
}
if (!$containsfiltertag) {
continue;
}
}
$uniquehashes[] = $entry->get_permalink();
$newentry = new stdClass();
$newentry->userid = $externalblog->userid;
$newentry->module = 'blog_external';
$newentry->content = $externalblog->id;
$newentry->uniquehash = $entry->get_permalink();
$newentry->publishstate = 'site';
$newentry->format = FORMAT_HTML;
// Clean subject of html, just in case
$newentry->subject = clean_param($entry->get_title(), PARAM_TEXT);
// Observe 128 max chars in DB
// TODO: +1 to raise this to 255
if (textlib::strlen($newentry->subject) > 128) {
$newentry->subject = textlib::substr($newentry->subject, 0, 125) . '...';
}
$newentry->summary = $entry->get_description();
//used to decide whether to insert or update
//uses enty permalink plus creation date if available
$existingpostconditions = array('uniquehash' => $entry->get_permalink());
//our DB doesnt allow null creation or modified timestamps so check the external blog supplied one
$entrydate = $entry->get_date('U');
if (!empty($entrydate)) {
$existingpostconditions['created'] = $entrydate;
}
//the post ID or false if post not found in DB
$postid = $DB->get_field('post', 'id', $existingpostconditions);
$timestamp = null;
if (empty($entrydate)) {
$timestamp = time();
} else {
$timestamp = $entrydate;
}
//only set created if its a new post so we retain the original creation timestamp if the post is edited
if ($postid === false) {
$newentry->created = $timestamp;
}
$newentry->lastmodified = $timestamp;
if (empty($oldesttimestamp) || $timestamp < $oldesttimestamp) {
//found an older post
$oldesttimestamp = $timestamp;
}
if (textlib::strlen($newentry->uniquehash) > 255) {
// The URL for this item is too long for the field. Rather than add
// the entry without the link we will skip straight over it.
// RSS spec says recommended length 500, we use 255.
debugging('External blog entry skipped because of oversized URL', DEBUG_DEVELOPER);
continue;
}
if ($postid === false) {
$id = $DB->insert_record('post', $newentry);
// Set tags
if ($tags = tag_get_tags_array('blog_external', $externalblog->id)) {
tag_set('post', $id, $tags);
}
} else {
$newentry->id = $postid;
$DB->update_record('post', $newentry);
}
}
// Look at the posts we have in the database to check if any of them have been deleted from the feed.
// Only checking posts within the time frame returned by the rss feed. Older items may have been deleted or
// may just not be returned anymore. We can't tell the difference so we leave older posts alone.
$sql = "SELECT id, uniquehash\n FROM {post}\n WHERE module = 'blog_external'\n AND " . $DB->sql_compare_text('content') . " = " . $DB->sql_compare_text(':blogid') . "\n AND created > :ts";
$dbposts = $DB->get_records_sql($sql, array('blogid' => $externalblog->id, 'ts' => $oldesttimestamp));
$todelete = array();
foreach ($dbposts as $dbpost) {
if (!in_array($dbpost->uniquehash, $uniquehashes)) {
$todelete[] = $dbpost->id;
}
}
$DB->delete_records_list('post', 'id', $todelete);
$DB->update_record('blog_external', array('id' => $externalblog->id, 'timefetched' => time()));
}
示例6: restore_create_blogs
function restore_create_blogs($restore, $xml_file)
{
global $CFG;
$status = true;
//Check it exists
if (!file_exists($xml_file)) {
$status = false;
}
//Get info from xml
if ($status) {
//info will contain the number of blogs in the backup file
//in backup_ids->info will be the real info (serialized)
$info = restore_read_xml_blogs($restore, $xml_file);
//If we have info, then process blogs & blog_tags
if ($info > 0) {
//Count how many we have
$blogcount = count_records('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'blog');
if ($blogcount) {
//Number of records to get in every chunk
$recordset_size = 4;
//Process blog
if ($blogcount) {
$counter = 0;
while ($counter < $blogcount) {
//Fetch recordset_size records in each iteration
$recs = get_records_select("backup_ids", "table_name = 'blog' AND backup_code = '{$restore->backup_unique_code}'", "old_id", "old_id", $counter, $recordset_size);
if ($recs) {
foreach ($recs as $rec) {
//Get the full record from backup_ids
$data = backup_getid($restore->backup_unique_code, "blog", $rec->old_id);
if ($data) {
//Now get completed xmlized object
$info = $data->info;
//traverse_xmlize($info); //Debug
//print_object ($GLOBALS['traverse_array']); //Debug
//$GLOBALS['traverse_array']=""; //Debug
//Now build the BLOG record structure
$dbrec = new object();
$dbrec->module = backup_todb($info['BLOG']['#']['MODULE']['0']['#']);
$dbrec->userid = backup_todb($info['BLOG']['#']['USERID']['0']['#']);
$dbrec->courseid = backup_todb($info['BLOG']['#']['COURSEID']['0']['#']);
$dbrec->groupid = backup_todb($info['BLOG']['#']['GROUPID']['0']['#']);
$dbrec->moduleid = backup_todb($info['BLOG']['#']['MODULEID']['0']['#']);
$dbrec->coursemoduleid = backup_todb($info['BLOG']['#']['COURSEMODULEID']['0']['#']);
$dbrec->subject = backup_todb($info['BLOG']['#']['SUBJECT']['0']['#']);
$dbrec->summary = backup_todb($info['BLOG']['#']['SUMMARY']['0']['#']);
$dbrec->content = backup_todb($info['BLOG']['#']['CONTENT']['0']['#']);
$dbrec->uniquehash = backup_todb($info['BLOG']['#']['UNIQUEHASH']['0']['#']);
$dbrec->rating = backup_todb($info['BLOG']['#']['RATING']['0']['#']);
$dbrec->format = backup_todb($info['BLOG']['#']['FORMAT']['0']['#']);
$dbrec->attachment = backup_todb($info['BLOG']['#']['ATTACHMENT']['0']['#']);
$dbrec->publishstate = backup_todb($info['BLOG']['#']['PUBLISHSTATE']['0']['#']);
$dbrec->lastmodified = backup_todb($info['BLOG']['#']['LASTMODIFIED']['0']['#']);
$dbrec->created = backup_todb($info['BLOG']['#']['CREATED']['0']['#']);
$dbrec->usermodified = backup_todb($info['BLOG']['#']['USERMODIFIED']['0']['#']);
//We have to recode the userid field
$user = backup_getid($restore->backup_unique_code, "user", $dbrec->userid);
if ($user) {
//echo "User ".$dbrec->userid." to user ".$user->new_id."<br />"; //Debug
$dbrec->userid = $user->new_id;
}
//Check if the record doesn't exist in DB!
$exist = get_record('post', 'userid', $dbrec->userid, 'subject', $dbrec->subject, 'created', $dbrec->created);
$newblogid = 0;
if (!$exist) {
//Not exist. Insert
$newblogid = insert_record('post', $dbrec);
}
//Going to restore related tags. Check they are enabled and we have inserted a blog
if ($CFG->usetags && $newblogid) {
//Look for tags in this blog
if (isset($info['BLOG']['#']['BLOG_TAGS']['0']['#']['BLOG_TAG'])) {
$tagsarr = $info['BLOG']['#']['BLOG_TAGS']['0']['#']['BLOG_TAG'];
//Iterate over tags
$tags = array();
for ($i = 0; $i < sizeof($tagsarr); $i++) {
$tag_info = $tagsarr[$i];
///traverse_xmlize($tag_info); //Debug
///print_object ($GLOBALS['traverse_array']); //Debug
///$GLOBALS['traverse_array']=""; //Debug
$name = backup_todb($tag_info['#']['NAME']['0']['#']);
$rawname = backup_todb($tag_info['#']['RAWNAME']['0']['#']);
$tags[] = $rawname;
//Rawname is all we need
}
tag_set('post', $newblogid, $tags);
//Add all the tags in one API call
}
}
}
//Do some output
$counter++;
if ($counter % 10 == 0) {
if (!defined('RESTORE_SILENTLY')) {
echo ".";
if ($counter % 200 == 0) {
echo "<br />";
}
}
backup_flush(300);
//.........这里部分代码省略.........
示例7: test_course_delete_module
/**
* Tests the function that deletes a course module
*
* @param string $type The type of module for the test
* @param array $options The options for the module creation
* @dataProvider provider_course_delete_module
*/
public function test_course_delete_module($type, $options)
{
global $DB;
$this->resetAfterTest(true);
$this->setAdminUser();
// Create course and modules.
$course = $this->getDataGenerator()->create_course(array('numsections' => 5));
$options['course'] = $course->id;
// Generate an assignment with due date (will generate a course event).
$module = $this->getDataGenerator()->create_module($type, $options);
// Get the module context.
$modcontext = context_module::instance($module->cmid);
// Verify context exists.
$this->assertInstanceOf('context_module', $modcontext);
// Make module specific messes.
switch ($type) {
case 'assign':
// Add some tags to this assignment.
tag_set('assign', $module->id, array('Tag 1', 'Tag 2', 'Tag 3'), 'mod_assign', $modcontext->id);
// Confirm the tag instances were added.
$criteria = array('component' => 'mod_assign', 'contextid' => $modcontext->id);
$this->assertEquals(3, $DB->count_records('tag_instance', $criteria));
// Verify event assignment event has been generated.
$eventcount = $DB->count_records('event', array('instance' => $module->id, 'modulename' => $type));
$this->assertEquals(1, $eventcount);
break;
case 'quiz':
$qgen = $this->getDataGenerator()->get_plugin_generator('core_question');
$qcat = $qgen->create_question_category(array('contextid' => $modcontext->id));
$questions = array($qgen->create_question('shortanswer', null, array('category' => $qcat->id)), $qgen->create_question('shortanswer', null, array('category' => $qcat->id)));
$this->expectOutputRegex('/' . get_string('unusedcategorydeleted', 'question') . '/');
break;
default:
break;
}
// Run delete..
course_delete_module($module->cmid);
// Verify the context has been removed.
$this->assertFalse(context_module::instance($module->cmid, IGNORE_MISSING));
// Verify the course_module record has been deleted.
$cmcount = $DB->count_records('course_modules', array('id' => $module->cmid));
$this->assertEmpty($cmcount);
// Test clean up of module specific messes.
switch ($type) {
case 'assign':
// Verify event assignment events have been removed.
$eventcount = $DB->count_records('event', array('instance' => $module->id, 'modulename' => $type));
$this->assertEmpty($eventcount);
// Verify the tag instances were deleted.
$criteria = array('component' => 'mod_assign', 'contextid' => $modcontext->id);
$this->assertEquals(0, $DB->count_records('tag_instance', $criteria));
break;
case 'quiz':
// Verify category deleted.
$criteria = array('contextid' => $modcontext->id);
$this->assertEquals(0, $DB->count_records('question_categories', $criteria));
// Verify questions deleted.
$criteria = array('category' => $qcat->id);
$this->assertEquals(0, $DB->count_records('question', $criteria));
break;
default:
break;
}
}
示例8: process_tag
protected function process_tag($data)
{
global $CFG, $DB;
$data = (object) $data;
$newquestion = $this->get_new_parentid('question');
if (!empty($CFG->usetags)) {
// if enabled in server
// TODO: This is highly inefficient. Each time we add one tag
// we fetch all the existing because tag_set() deletes them
// so everything must be reinserted on each call
$tags = array();
$existingtags = tag_get_tags('question', $newquestion);
// Re-add all the existitng tags
foreach ($existingtags as $existingtag) {
$tags[] = $existingtag->rawname;
}
// Add the one being restored
$tags[] = $data->rawname;
// Get the category, so we can then later get the context.
$categoryid = $this->get_new_parentid('question_category');
if (empty($this->cachedcategory) || $this->cachedcategory->id != $categoryid) {
$this->cachedcategory = $DB->get_record('question_categories', array('id' => $categoryid));
}
// Send all the tags back to the question
tag_set('question', $newquestion, $tags, 'core_question', $this->cachedcategory->contextid);
}
}
示例9: booking_update_instance
function booking_update_instance($booking)
{
global $DB;
// Given an object containing all the necessary data,
// (defined by the form in mod.html) this function
// will update an existing instance with new data.
// we have to prepare the bookingclosingtimes as an $arrray, currently they are in $booking as $key (string)
$booking->id = $booking->instance;
$booking->timemodified = time();
if (isset($booking->additionalfields) && count($booking->additionalfields) > 0) {
$booking->additionalfields = implode(',', $booking->additionalfields);
}
if (isset($booking->categoryid) && count($booking->categoryid) > 0) {
$booking->categoryid = implode(',', $booking->categoryid);
}
tag_set('booking', $booking->id, $booking->tags);
$cm = get_coursemodule_from_instance('booking', $booking->id);
$context = context_module::instance($cm->id);
file_save_draft_area_files($booking->myfilemanager, $context->id, 'mod_booking', 'myfilemanager', $booking->id, array('subdirs' => 0, 'maxbytes' => 0, 'maxfiles' => 50));
if (empty($booking->timerestrict)) {
$booking->timeopen = 0;
$booking->timeclose = 0;
}
// Copy the text fields out:
$booking->bookedtext = $booking->bookedtext['text'];
$booking->waitingtext = $booking->waitingtext['text'];
$booking->statuschangetext = $booking->statuschangetext['text'];
$booking->deletedtext = $booking->deletedtext['text'];
$booking->pollurltext = $booking->pollurltext['text'];
$booking->pollurlteacherstext = $booking->pollurlteacherstext['text'];
$booking->notificationtext = $booking->notificationtext['text'];
$booking->userleave = $booking->userleave['text'];
//update, delete or insert answers
if (!empty($booking->option)) {
foreach ($booking->option as $key => $value) {
$value = trim($value);
$option = new stdClass();
$option->text = $value;
$option->bookingid = $booking->id;
if (isset($booking->limit[$key])) {
$option->maxanswers = $booking->limit[$key];
}
$option->timemodified = time();
if (isset($booking->optionid[$key]) && !empty($booking->optionid[$key])) {
//existing booking record
$option->id = $booking->optionid[$key];
if (isset($value) && $value != '') {
$DB->update_record("booking_options", $option);
} else {
//empty old option - needs to be deleted.
$DB->delete_records("booking_options", array("id" => $option->id));
}
} else {
if (isset($value) && $value != '') {
$DB->insert_record("booking_options", $option);
}
}
}
}
return $DB->update_record('booking', $booking);
}
示例10: useredit_update_interests
function useredit_update_interests($user, $interests)
{
tag_set('user', $user->id, $interests);
}
示例11: tag_set_delete
/**
* Removes a tag from a record, without overwriting other current tags.
*
* @param string $record_type the type of record to tag ('post' for blogs,
* 'user' for users, etc.
* @param int $record_id the id of the record to tag
* @param string $tag the tag to delete
* @return void
*/
function tag_set_delete($record_type, $record_id, $tag)
{
$new_tags = array();
foreach (tag_get_tags($record_type, $record_id) as $current_tag) {
if ($current_tag->name != $tag) {
// Keep all tags but the one specified
$new_tags[] = $current_tag->name;
}
}
return tag_set($record_type, $record_id, $new_tags);
}
示例12: remove_course_contents
//.........这里部分代码省略.........
// Cleanup the rest of plugins.
$cleanuplugintypes = array('report', 'coursereport', 'format');
$callbacks = get_plugins_with_function('delete_course', 'lib.php');
foreach ($cleanuplugintypes as $type) {
if (!empty($callbacks[$type])) {
foreach ($callbacks[$type] as $pluginfunction) {
$pluginfunction($course->id, $showfeedback);
}
}
if ($showfeedback) {
echo $OUTPUT->notification($strdeleted . get_string('type_' . $type . '_plural', 'plugin'), 'notifysuccess');
}
}
// Delete questions and question categories.
question_delete_course($course, $showfeedback);
if ($showfeedback) {
echo $OUTPUT->notification($strdeleted . get_string('questions', 'question'), 'notifysuccess');
}
// Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
$childcontexts = $coursecontext->get_child_contexts();
// Returns all subcontexts since 2.2.
foreach ($childcontexts as $childcontext) {
$childcontext->delete();
}
unset($childcontexts);
// Remove all roles and enrolments by default.
if (empty($options['keep_roles_and_enrolments'])) {
// This hack is used in restore when deleting contents of existing course.
role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
enrol_course_delete($course);
if ($showfeedback) {
echo $OUTPUT->notification($strdeleted . get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
}
}
// Delete any groups, removing members and grouping/course links first.
if (empty($options['keep_groups_and_groupings'])) {
groups_delete_groupings($course->id, $showfeedback);
groups_delete_groups($course->id, $showfeedback);
}
// Filters be gone!
filter_delete_all_for_context($coursecontext->id);
// Notes, you shall not pass!
note_delete_all($course->id);
// Die comments!
comment::delete_comments($coursecontext->id);
// Ratings are history too.
$delopt = new stdclass();
$delopt->contextid = $coursecontext->id;
$rm = new rating_manager();
$rm->delete_ratings($delopt);
// Delete course tags.
tag_set('course', $course->id, array(), 'core', $coursecontext->id);
// Delete calendar events.
$DB->delete_records('event', array('courseid' => $course->id));
$fs->delete_area_files($coursecontext->id, 'calendar');
// Delete all related records in other core tables that may have a courseid
// This array stores the tables that need to be cleared, as
// table_name => column_name that contains the course id.
$tablestoclear = array('backup_courses' => 'courseid', 'user_lastaccess' => 'courseid');
foreach ($tablestoclear as $table => $col) {
$DB->delete_records($table, array($col => $course->id));
}
// Delete all course backup files.
$fs->delete_area_files($coursecontext->id, 'backup');
// Cleanup course record - remove links to deleted stuff.
$oldcourse = new stdClass();
$oldcourse->id = $course->id;
$oldcourse->summary = '';
$oldcourse->cacherev = 0;
$oldcourse->legacyfiles = 0;
if (!empty($options['keep_groups_and_groupings'])) {
$oldcourse->defaultgroupingid = 0;
}
$DB->update_record('course', $oldcourse);
// Delete course sections.
$DB->delete_records('course_sections', array('course' => $course->id));
// Delete legacy, section and any other course files.
$fs->delete_area_files($coursecontext->id, 'course');
// Files from summary and section.
// Delete all remaining stuff linked to context such as files, comments, ratings, etc.
if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
// Easy, do not delete the context itself...
$coursecontext->delete_content();
} else {
// Hack alert!!!!
// We can not drop all context stuff because it would bork enrolments and roles,
// there might be also files used by enrol plugins...
}
// Delete legacy files - just in case some files are still left there after conversion to new file api,
// also some non-standard unsupported plugins may try to store something there.
fulldelete($CFG->dataroot . '/' . $course->id);
// Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
$cachemodinfo = cache::make('core', 'coursemodinfo');
$cachemodinfo->delete($courseid);
// Trigger a course content deleted event.
$event = \core\event\course_content_deleted::create(array('objectid' => $course->id, 'context' => $coursecontext, 'other' => array('shortname' => $course->shortname, 'fullname' => $course->fullname, 'options' => $options)));
$event->add_record_snapshot('course', $course);
$event->trigger();
return true;
}
示例13: delete_user
/**
* Marks user deleted in internal user database and notifies the auth plugin.
* Also unenrols user from all roles and does other cleanup.
*
* Any plugin that needs to purge user data should register the 'user_deleted' event.
*
* @param object $user User object before delete
* @return boolean always true
*/
function delete_user($user)
{
global $CFG, $DB;
require_once $CFG->libdir . '/grouplib.php';
require_once $CFG->libdir . '/gradelib.php';
require_once $CFG->dirroot . '/message/lib.php';
require_once $CFG->dirroot . '/tag/lib.php';
// delete all grades - backup is kept in grade_grades_history table
grade_user_delete($user->id);
//move unread messages from this user to read
message_move_userfrom_unread2read($user->id);
// TODO: remove from cohorts using standard API here
// remove user tags
tag_set('user', $user->id, array());
// unconditionally unenrol from all courses
enrol_user_delete($user);
// unenrol from all roles in all contexts
role_unassign_all(array('userid' => $user->id));
// this might be slow but it is really needed - modules might do some extra cleanup!
//now do a brute force cleanup
// remove from all cohorts
$DB->delete_records('cohort_members', array('userid' => $user->id));
// remove from all groups
$DB->delete_records('groups_members', array('userid' => $user->id));
// brute force unenrol from all courses
$DB->delete_records('user_enrolments', array('userid' => $user->id));
// purge user preferences
$DB->delete_records('user_preferences', array('userid' => $user->id));
// purge user extra profile info
$DB->delete_records('user_info_data', array('userid' => $user->id));
// last course access not necessary either
$DB->delete_records('user_lastaccess', array('userid' => $user->id));
// now do a final accesslib cleanup - removes all role assignments in user context and context itself
delete_context(CONTEXT_USER, $user->id);
// workaround for bulk deletes of users with the same email address
$delname = "{$user->email}." . time();
while ($DB->record_exists('user', array('username' => $delname))) {
// no need to use mnethostid here
$delname++;
}
// mark internal user record as "deleted"
$updateuser = new stdClass();
$updateuser->id = $user->id;
$updateuser->deleted = 1;
$updateuser->username = $delname;
// Remember it just in case
$updateuser->email = md5($user->username);
// Store hash of username, useful importing/restoring users
$updateuser->idnumber = '';
// Clear this field to free it up
$updateuser->timemodified = time();
$DB->update_record('user', $updateuser);
// notify auth plugin - do not block the delete even when plugin fails
$authplugin = get_auth_plugin($user->auth);
$authplugin->user_delete($user);
// any plugin that needs to cleanup should register this event
events_trigger('user_deleted', $user);
return true;
}
示例14: test_course_delete_module
public function test_course_delete_module()
{
global $DB;
$this->resetAfterTest(true);
$this->setAdminUser();
// Create course and modules.
$course = $this->getDataGenerator()->create_course(array('numsections' => 5));
// Generate an assignment with due date (will generate a course event).
$assign = $this->getDataGenerator()->create_module('assign', array('duedate' => time(), 'course' => $course->id));
// Get the module context.
$modcontext = context_module::instance($assign->cmid);
// Verify context exists.
$this->assertInstanceOf('context_module', $modcontext);
// Add some tags to this assignment.
tag_set('assign', $assign->id, array('Tag 1', 'Tag 2', 'Tag 3'), 'mod_assign', $modcontext->id);
// Confirm the tag instances were added.
$this->assertEquals(3, $DB->count_records('tag_instance', array('component' => 'mod_assign', 'contextid' => $modcontext->id)));
// Verify event assignment event has been generated.
$eventcount = $DB->count_records('event', array('instance' => $assign->id, 'modulename' => 'assign'));
$this->assertEquals(1, $eventcount);
// Run delete..
course_delete_module($assign->cmid);
// Verify the context has been removed.
$this->assertFalse(context_module::instance($assign->cmid, IGNORE_MISSING));
// Verify the course_module record has been deleted.
$cmcount = $DB->count_records('course_modules', array('id' => $assign->cmid));
$this->assertEmpty($cmcount);
// Verify event assignment events have been removed.
$eventcount = $DB->count_records('event', array('instance' => $assign->id, 'modulename' => 'assign'));
$this->assertEmpty($eventcount);
// Verify the tag instances were deleted.
$this->assertEquals(0, $DB->count_records('tag_instance', array('component' => 'mod_assign', 'contextid' => $modcontext->id)));
}
示例15: update_course
/**
* Update a course.
*
* Please note this functions does not verify any access control,
* the calling code is responsible for all validation (usually it is the form definition).
*
* @param object $data - all the data needed for an entry in the 'course' table
* @param array $editoroptions course description editor options
* @return void
*/
function update_course($data, $editoroptions = NULL)
{
global $DB, $CFG;
require_once $CFG->dirroot . '/tag/lib.php';
$data->timemodified = time();
$oldcourse = course_get_format($data->id)->get_course();
$context = context_course::instance($oldcourse->id);
if ($editoroptions) {
$data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
}
if ($overviewfilesoptions = course_overviewfiles_options($data->id)) {
$data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
}
// Check we don't have a duplicate shortname.
if (!empty($data->shortname) && $oldcourse->shortname != $data->shortname) {
if ($DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data->shortname, $data->id))) {
throw new moodle_exception('shortnametaken', '', '', $data->shortname);
}
}
// Check we don't have a duplicate idnumber.
if (!empty($data->idnumber) && $oldcourse->idnumber != $data->idnumber) {
if ($DB->record_exists_sql('SELECT id from {course} WHERE idnumber = ? AND id <> ?', array($data->idnumber, $data->id))) {
throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
}
}
if (!isset($data->category) or empty($data->category)) {
// prevent nulls and 0 in category field
unset($data->category);
}
$changesincoursecat = $movecat = (isset($data->category) and $oldcourse->category != $data->category);
if (!isset($data->visible)) {
// data not from form, add missing visibility info
$data->visible = $oldcourse->visible;
}
if ($data->visible != $oldcourse->visible) {
// reset the visibleold flag when manually hiding/unhiding course
$data->visibleold = $data->visible;
$changesincoursecat = true;
} else {
if ($movecat) {
$newcategory = $DB->get_record('course_categories', array('id' => $data->category));
if (empty($newcategory->visible)) {
// make sure when moving into hidden category the course is hidden automatically
$data->visible = 0;
}
}
}
// Update with the new data
$DB->update_record('course', $data);
// make sure the modinfo cache is reset
rebuild_course_cache($data->id);
// update course format options with full course data
course_get_format($data->id)->update_course_format_options($data, $oldcourse);
$course = $DB->get_record('course', array('id' => $data->id));
if ($movecat) {
$newparent = context_coursecat::instance($course->category);
$context->update_moved($newparent);
}
$fixcoursesortorder = $movecat || isset($data->sortorder) && $oldcourse->sortorder != $data->sortorder;
if ($fixcoursesortorder) {
fix_course_sortorder();
}
// purge appropriate caches in case fix_course_sortorder() did not change anything
cache_helper::purge_by_event('changesincourse');
if ($changesincoursecat) {
cache_helper::purge_by_event('changesincoursecat');
}
// Test for and remove blocks which aren't appropriate anymore
blocks_remove_inappropriate($course);
// Save any custom role names.
save_local_role_names($course->id, $data);
// update enrol settings
enrol_course_updated(false, $course, $data);
// Update course tags.
if ($CFG->usetags && isset($data->tags)) {
tag_set('course', $course->id, $data->tags, 'core', context_course::instance($course->id)->id);
}
// Trigger a course updated event.
$event = \core\event\course_updated::create(array('objectid' => $course->id, 'context' => context_course::instance($course->id), 'other' => array('shortname' => $course->shortname, 'fullname' => $course->fullname)));
$event->set_legacy_logdata(array($course->id, 'course', 'update', 'edit.php?id=' . $course->id, $course->id));
$event->trigger();
if ($oldcourse->format !== $course->format) {
// Remove all options stored for the previous format
// We assume that new course format migrated everything it needed watching trigger
// 'course_updated' and in method format_XXX::update_course_format_options()
$DB->delete_records('course_format_options', array('courseid' => $course->id, 'format' => $oldcourse->format));
}
}