/**
* Returns an instance of the cache_helper.
*
* This is designed for internal use only and acts as a static store.
* @staticvar null $instance
* @return cache_helper
*/
protected static function instance()
{
if (is_null(self::$instance)) {
self::$instance = new cache_helper();
}
return self::$instance;
}
开发者ID:numbas,项目名称:moodle,代码行数:14,代码来源:helper.php
示例2: create_group
public static function create_group($group)
{
global $DB, $CFG;
// Valida os parametros.
$params = self::validate_parameters(self::create_group_parameters(), array('group' => $group));
// Transforma o array em objeto.
$group = (object) $group;
// Inicia a transacao, qualquer erro que aconteca o rollback sera executado.
$transaction = $DB->start_delegated_transaction();
// Busca o id do curso apartir do trm_id da turma.
$courseid = self::get_course_by_trm_id($group->trm_id);
// Se nao existir curso mapeado para a turma dispara uma excessao.
if (!$courseid) {
throw new Exception("Nenhum curso mapeado com a turma com trm_id: " . $group->trm_id);
}
$groupbyname = self::get_group_by_name($courseid, $group->name);
// Dispara uma excessao caso ja exista um grupo com o mesmo nome no mesmo curso
if ($groupbyname) {
throw new Exception("ja existe um grupo com o mesmo nome nessa turma trm_id: " . $group->trm_id);
}
$groupdata['courseid'] = $courseid;
$groupdata['name'] = $group->name;
$groupdata['description'] = $group->description;
$groupdata['descriptionformat'] = 1;
$groupdata['timecreated'] = time();
$groupdata['timemodified'] = $groupdata['timecreated'];
$resultid = $DB->insert_record('groups', $groupdata);
// Caso o curso tenha sido criado adiciona a tabela de controle os dados dos curso e da turma.
if ($resultid) {
$data['trm_id'] = $group->trm_id;
$data['grp_id'] = $group->grp_id;
$data['groupid'] = $resultid;
$res = $DB->insert_record('itg_grupo_group', $data);
// Busca as configuracoes do curso
$courseoptions = $DB->get_record('course', array('id' => $courseid), '*');
// Altera o formato de grupos do curso
$courseoptions->groupmode = 1;
$courseoptions->groupmodeforce = 1;
$DB->update_record('course', $courseoptions);
// Invalidate the grouping cache for the course
cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
// Prepara o array de retorno.
$returndata = null;
if ($res) {
$returndata['id'] = $resultid;
$returndata['status'] = 'success';
$returndata['message'] = 'Grupo criado com sucesso';
} else {
$returndata['id'] = 0;
$returndata['status'] = 'error';
$returndata['message'] = 'Erro ao tentar criar o grupo';
}
}
// Persiste as operacoes em caso de sucesso.
$transaction->allow_commit();
return $returndata;
}
//.........这里部分代码省略.........
if (!empty($CFG->enableblogs) && $CFG->useblogassociations) {
require_once $CFG->dirroot . '/blog/lib.php';
// delete entries whose contextids no longer exists
mtrace("Deleting blog associations linked to non-existent contexts...", '');
cron_trace_time_and_memory();
$DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})');
mtrace('done.');
}
// Run question bank clean-up.
mtrace("Starting the question bank cron...", '');
cron_trace_time_and_memory();
require_once $CFG->libdir . '/questionlib.php';
question_bank::cron();
mtrace('done.');
//Run registration updated cron
mtrace(get_string('siteupdatesstart', 'hub'));
cron_trace_time_and_memory();
require_once $CFG->dirroot . '/' . $CFG->admin . '/registration/lib.php';
$registrationmanager = new registration_manager();
$registrationmanager->cron();
mtrace(get_string('siteupdatesend', 'hub'));
// If enabled, fetch information about available updates and eventually notify site admins
if (empty($CFG->disableupdatenotifications)) {
$updateschecker = \core\update\checker::instance();
$updateschecker->cron();
}
//cleanup old session linked tokens
//deletes the session linked tokens that are over a day old.
mtrace("Deleting session linked tokens more than one day old...", '');
cron_trace_time_and_memory();
$DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype', array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED));
mtrace('done.');
// all other plugins
cron_execute_plugin_type('message', 'message plugins');
cron_execute_plugin_type('filter', 'filters');
cron_execute_plugin_type('editor', 'editors');
cron_execute_plugin_type('format', 'course formats');
cron_execute_plugin_type('profilefield', 'profile fields');
cron_execute_plugin_type('webservice', 'webservices');
cron_execute_plugin_type('repository', 'repository plugins');
cron_execute_plugin_type('qbehaviour', 'question behaviours');
cron_execute_plugin_type('qformat', 'question import/export formats');
cron_execute_plugin_type('qtype', 'question types');
cron_execute_plugin_type('plagiarism', 'plagiarism plugins');
cron_execute_plugin_type('theme', 'themes');
cron_execute_plugin_type('tool', 'admin tools');
// and finally run any local cronjobs, if any
if ($locals = core_component::get_plugin_list('local')) {
mtrace('Processing customized cron scripts ...', '');
// new cron functions in lib.php first
cron_execute_plugin_type('local');
// legacy cron files are executed directly
foreach ($locals as $local => $localdir) {
if (file_exists("{$localdir}/cron.php")) {
include "{$localdir}/cron.php";
}
}
mtrace('done.');
}
mtrace('Running cache cron routines');
cache_helper::cron();
mtrace('done.');
// Run automated backups if required - these may take a long time to execute
require_once $CFG->dirroot . '/backup/util/includes/backup_includes.php';
require_once $CFG->dirroot . '/backup/util/helper/backup_cron_helper.class.php';
backup_cron_automated_helper::run_automated_backup();
// Run stats as at the end because they are known to take very long time on large sites
if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
require_once $CFG->dirroot . '/lib/statslib.php';
// check we're not before our runtime
$timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour * 60 * 60 + $CFG->statsruntimestartminute * 60;
if (time() > $timetocheck) {
// process configured number of days as max (defaulting to 31)
$maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays);
if (stats_cron_daily($maxdays)) {
if (stats_cron_weekly()) {
if (stats_cron_monthly()) {
stats_clean_old();
}
}
}
@set_time_limit(0);
} else {
mtrace('Next stats run after:' . userdate($timetocheck));
}
}
// Run badges review cron.
mtrace("Starting badges cron...");
require_once $CFG->dirroot . '/badges/cron.php';
badge_cron();
mtrace('done.');
// cleanup file trash - not very important
$fs = get_file_storage();
$fs->cron();
mtrace("Cron script completed correctly");
gc_collect_cycles();
mtrace('Cron completed at ' . date('H:i:s') . '. Memory used ' . display_size(memory_get_usage()) . '.');
$difftime = microtime_diff($starttime, microtime());
mtrace("Execution took " . $difftime . " seconds");
}
/**
* Sends several key => value pairs to the cache.
*
* Using this function comes with potential performance implications.
* Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
* the equivalent singular method for each item provided.
* This should not deter you from using this function as there is a performance benefit in situations where the cache store
* does support it, but you should be aware of this fact.
*
* <code>
* // This code will add four entries to the cache, one for each url.
* $cache->set_many(array(
* 'main' => 'http://moodle.org',
* 'docs' => 'http://docs.moodle.org',
* 'tracker' => 'http://tracker.moodle.org',
* 'qa' => ''http://qa.moodle.net'
* ));
* </code>
*
* @param array $keyvaluearray An array of key => value pairs to send to the cache.
* @return int The number of items successfully set. It is up to the developer to check this matches the number of items.
* ... if they care that is.
*/
public function set_many(array $keyvaluearray)
{
$this->check_tracked_user();
$loader = $this->get_loader();
if ($loader !== false) {
// We have a loader available set it there as well.
// We have to let the loader do its own parsing of data as it may be unique.
$loader->set_many($keyvaluearray);
}
$data = array();
$definitionid = $this->get_definition()->get_ttl();
$simulatettl = $this->has_a_ttl() && !$this->store_supports_native_ttl();
foreach ($keyvaluearray as $key => $value) {
if (is_object($value) && $value instanceof cacheable_object) {
$value = new cache_cached_object($value);
} else {
if (!is_scalar($value)) {
// If data is an object it will be a reference.
// If data is an array if may contain references.
// We want to break references so that the cache cannot be modified outside of itself.
// Call the function to unreference it (in the best way possible).
$value = $this->unref($value);
}
}
if ($simulatettl) {
$value = new cache_ttl_wrapper($value, $definitionid);
}
$data[$key] = array('key' => $this->parse_key($key), 'value' => $value);
}
$successfullyset = $this->get_store()->set_many($data);
if ($this->perfdebug && $successfullyset) {
cache_helper::record_cache_set($this->storetype, $definitionid, $successfullyset);
}
return $successfullyset;
}
//.........这里部分代码省略.........
} else {
if (strpos($filter, 'filter/') === 0) {
$newfilters[] = substr($filter, 7);
}
}
}
$filters = implode(',', $newfilters);
set_config($config, $filters);
}
}
unset($tables);
unset($table);
unset($configs);
unset($newfilters);
unset($filters);
unset($filter);
// Main savepoint reached.
upgrade_main_savepoint(true, 2012123000.0);
}
if ($oldversion < 2013021100.01) {
// Make sure there are no bogus nulls in old MySQL tables.
$DB->set_field_select('user', 'password', '', "password IS NULL");
// Changing precision of field password on table user to (255).
$table = new xmldb_table('user');
$field = new xmldb_field('password', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'username');
// Launch change of precision for field password.
$dbman->change_field_precision($table, $field);
// Main savepoint reached.
upgrade_main_savepoint(true, 2013021100.01);
}
if ($oldversion < 2013021800.0) {
// Add the site identifier to the cache config's file.
$siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
cache_helper::update_site_identifier($siteidentifier);
// Main savepoint reached.
upgrade_main_savepoint(true, 2013021800.0);
}
if ($oldversion < 2013021801.0) {
// Fixing possible wrong MIME types for SMART Notebook files.
$extensions = array('%.gallery', '%.galleryitem', '%.gallerycollection', '%.nbk', '%.notebook', '%.xbk');
$select = $DB->sql_like('filename', '?', false);
foreach ($extensions as $extension) {
$DB->set_field_select('files', 'mimetype', 'application/x-smarttech-notebook', $select, array($extension));
}
upgrade_main_savepoint(true, 2013021801.0);
}
if ($oldversion < 2013021801.01) {
// This upgrade step is re-written under MDL-38228 (see below).
/*
// Retrieve the list of course_sections as a recordset to save memory
$coursesections = $DB->get_recordset('course_sections', null, 'course, id', 'id, course, sequence');
foreach ($coursesections as $coursesection) {
// Retrieve all of the actual modules in this course and section combination to reduce DB calls
$actualsectionmodules = $DB->get_records('course_modules',
array('course' => $coursesection->course, 'section' => $coursesection->id), '', 'id, section');
// Break out the current sequence so that we can compare it
$currentsequence = explode(',', $coursesection->sequence);
$newsequence = array();
// Check each of the modules in the current sequence
foreach ($currentsequence as $module) {
if (isset($actualsectionmodules[$module])) {
$newsequence[] = $module;
// We unset the actualsectionmodules so that we don't get duplicates and that we can add orphaned
// modules later
/**
* Purge dataroot directory
* @static
* @return void
*/
public static function reset_dataroot() {
global $CFG;
$childclassname = self::get_framework() . '_util';
$handle = opendir($CFG->dataroot);
while (false !== ($item = readdir($handle))) {
if (in_array($item, $childclassname::$datarootskiponreset)) {
continue;
}
if (is_dir("$CFG->dataroot/$item")) {
remove_dir("$CFG->dataroot/$item", false);
} else {
unlink("$CFG->dataroot/$item");
}
}
closedir($handle);
make_temp_directory('');
make_cache_directory('');
make_cache_directory('htmlpurifier');
// Reset the cache API so that it recreates it's required directories as well.
cache_factory::reset();
// Purge all data from the caches. This is required for consistency.
// Any file caches that happened to be within the data root will have already been clearer (because we just deleted cache)
// and now we will purge any other caches as well.
cache_helper::purge_all();
}
/**
* Uninstall a message processor
*
* @param string $name A message processor name like 'email', 'jabber'
*/
function message_processor_uninstall($name) {
global $DB;
$transaction = $DB->start_delegated_transaction();
$DB->delete_records('message_processors', array('name' => $name));
$DB->delete_records_select('config_plugins', "plugin = ?", array("message_{$name}"));
// delete permission preferences only, we do not care about loggedin/loggedoff
// defaults, they will be removed on the next attempt to update the preferences
$DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("{$name}_provider_%"));
$transaction->allow_commit();
// Purge all messaging settings from the caches. They are stored by plugin so we have to clear all message settings.
cache_helper::invalidate_by_definition('core', 'config', array(), array('message', "message_{$name}"));
}
/**
* Show course category and restores visibility for child course and subcategories
*
* Note that there is no capability check inside this function
*
* This function does not update field course_categories.timemodified
* If you want to update timemodified, use
* $coursecat->update(array('visible' => 1));
*/
public function show()
{
if ($this->show_raw()) {
cache_helper::purge_by_event('changesincoursecat');
add_to_log(SITEID, "category", "show", "editcategory.php?id={$this->id}", $this->id);
}
}
/**
* Purge dataroot directory
* @static
* @return void
*/
public static function reset_dataroot()
{
global $CFG;
$childclassname = self::get_framework() . '_util';
// Do not delete automatically installed files.
self::skip_original_data_files($childclassname);
// Clear file status cache, before checking file_exists.
clearstatcache();
// Clean up the dataroot folder.
$handle = opendir(self::get_dataroot());
while (false !== ($item = readdir($handle))) {
if (in_array($item, $childclassname::$datarootskiponreset)) {
continue;
}
if (is_dir(self::get_dataroot() . "/{$item}")) {
remove_dir(self::get_dataroot() . "/{$item}", false);
} else {
unlink(self::get_dataroot() . "/{$item}");
}
}
closedir($handle);
// Clean up the dataroot/filedir folder.
if (file_exists(self::get_dataroot() . '/filedir')) {
$handle = opendir(self::get_dataroot() . '/filedir');
while (false !== ($item = readdir($handle))) {
if (in_array('filedir/' . $item, $childclassname::$datarootskiponreset)) {
continue;
}
if (is_dir(self::get_dataroot() . "/filedir/{$item}")) {
remove_dir(self::get_dataroot() . "/filedir/{$item}", false);
} else {
unlink(self::get_dataroot() . "/filedir/{$item}");
}
}
closedir($handle);
}
make_temp_directory('');
make_cache_directory('');
make_localcache_directory('');
// Reset the cache API so that it recreates it's required directories as well.
cache_factory::reset();
// Purge all data from the caches. This is required for consistency.
// Any file caches that happened to be within the data root will have already been clearer (because we just deleted cache)
// and now we will purge any other caches as well.
cache_helper::purge_all();
}
}
$newgroup = new stdClass();
$newgroup->courseid = $data->courseid;
$newgroup->name = $group['name'];
$groupid = groups_create_group($newgroup);
$createdgroups[] = $groupid;
foreach ($group['members'] as $user) {
groups_add_member($groupid, $user->id);
}
if ($grouping) {
// Ask this function not to invalidate the cache, we'll do that manually once at the end.
groups_assign_grouping($grouping->id, $groupid, null, false);
}
}
// Invalidate the course groups cache seeing as we've changed it.
cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
if ($failed) {
foreach ($createdgroups as $groupid) {
groups_delete_group($groupid);
}
if ($createdgrouping) {
groups_delete_grouping($createdgrouping);
}
} else {
redirect($returnurl);
}
}
}
$PAGE->navbar->add($strparticipants, new moodle_url('/user/index.php', array('id' => $courseid)));
$PAGE->navbar->add($strgroups, new moodle_url('/group/index.php', array('id' => $courseid)));
$PAGE->navbar->add($strautocreategroups);
/**
* Common public method to create a cache instance given a definition.
*
* This is used by the static make methods.
*
* @param cache_definition $definition
* @return cache_application|cache_session|cache_store
* @throws coding_exception
*/
public function create_cache(cache_definition $definition)
{
$class = $definition->get_cache_class();
$stores = cache_helper::get_stores_suitable_for_definition($definition);
foreach ($stores as $key => $store) {
if (!$store::are_requirements_met()) {
unset($stores[$key]);
}
}
if (count($stores) === 0) {
// Hmm still no stores, better provide a dummy store to mimic functionality. The dev will be none the wiser.
$stores[] = $this->create_dummy_store($definition);
}
$loader = null;
if ($definition->has_data_source()) {
$loader = $definition->get_data_source();
}
while (($store = array_pop($stores)) !== null) {
$loader = new $class($definition, $store, $loader);
}
return $loader;
}
$factory = cache_factory::instance();
$definition = $factory->create_definition($component, $area);
if ($definition->has_required_identifiers()) {
// We will have to purge the stores used by this definition.
cache_helper::purge_stores_used_by_definition($component, $area);
} else {
// Alrighty we can purge just the data belonging to this definition.
cache_helper::purge_by_definition($component, $area);
}
redirect($PAGE->url, get_string('purgedefinitionsuccess', 'cache'), 5);
break;
case 'purgestore':
case 'purge':
// Purge a store cache.
$store = required_param('store', PARAM_TEXT);
cache_helper::purge_store($store);
redirect($PAGE->url, get_string('purgestoresuccess', 'cache'), 5);
break;
case 'newlockinstance':
// Adds a new lock instance.
$lock = required_param('lock', PARAM_ALPHANUMEXT);
$mform = cache_administration_helper::get_add_lock_form($lock);
if ($mform->is_cancelled()) {
redirect($PAGE->url);
} else {
if ($data = $mform->get_data()) {
$factory = cache_factory::instance();
$config = $factory->create_config_instance(true);
$name = $data->name;
$data = cache_administration_helper::get_lock_configuration_from_data($lock, $data);
$config->add_lock_instance($name, $lock, $data);
/**
* Delete subscription and all related events.
*
* @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
*/
function calendar_delete_subscription($subscription)
{
global $DB;
if (!is_object($subscription)) {
$subscription = $DB->get_record('event_subscriptions', array('id' => $subscription), '*', MUST_EXIST);
}
// Delete subscription and related events.
$DB->delete_records('event', array('subscriptionid' => $subscription->id));
$DB->delete_records('event_subscriptions', array('id' => $subscription->id));
cache_helper::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription->id));
// Trigger event, calendar subscription deleted.
$eventparams = array('objectid' => $subscription->id, 'context' => calendar_get_calendar_context($subscription), 'other' => array('courseid' => $subscription->courseid));
$event = \core\event\calendar_subscription_deleted::create($eventparams);
$event->trigger();
}
开发者ID:stronk7,项目名称:moodle,代码行数:20,代码来源:lib.php
示例18: calendar_delete_subscription
/**
* Delete subscription and all related events.
*
* @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
*/
function calendar_delete_subscription($subscription)
{
global $DB;
if (is_object($subscription)) {
$subscription = $subscription->id;
}
// Delete subscription and related events.
$DB->delete_records('event', array('subscriptionid' => $subscription));
$DB->delete_records('event_subscriptions', array('id' => $subscription));
cache_helper::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription));
}
请发表评论