public function __construct($html = true)
 {
     // Register "destructor"
     core_shutdown_manager::register_function(array(&$this, "finalize"));
     $this->html = $html != false;
     $this->Clear();
 }
Beispiel #2
0
 /**
  * Delayed initialisation of singleton.
  */
 protected function init()
 {
     if (isset($this->stores)) {
         // Do not bother checking readers and writers here
         // because everything is init here.
         return;
     }
     $this->stores = array();
     $this->readers = array();
     $this->writers = array();
     // Register shutdown handler - this may be useful for buffering, file handle closing, etc.
     \core_shutdown_manager::register_function(array($this, 'dispose'));
     $plugins = get_config('tool_log', 'enabled_stores');
     if (empty($plugins)) {
         return;
     }
     $plugins = explode(',', $plugins);
     foreach ($plugins as $plugin) {
         $classname = "\\{$plugin}\\log\\store";
         if (class_exists($classname)) {
             $store = new $classname($this);
             $this->stores[$plugin] = $store;
             if ($store instanceof \tool_log\log\writer) {
                 $this->writers[$plugin] = $store;
             }
             if ($store instanceof \core\log\reader) {
                 $this->readers[$plugin] = $store;
             }
         }
     }
 }
 /**
  * Almighty constructor.
  * @param string $type - Used to prefix lock keys.
  */
 public function __construct($type)
 {
     global $DB;
     $this->type = $type;
     // Save a reference to the global $DB so it will not be released while we still have open locks.
     $this->db = $DB;
     \core_shutdown_manager::register_function(array($this, 'auto_release'));
 }
Beispiel #4
0
 /**
  * Register self as main shutdown handler.
  *
  * @private to be called from lib/setup.php only!
  */
 public static function initialize()
 {
     if (self::$registered) {
         debugging('Shutdown manager is already initialised!');
     }
     self::$registered = true;
     register_shutdown_function(array('core_shutdown_manager', 'shutdown_handler'));
 }
Beispiel #5
0
 /**
  * The observer monitoring all the events.
  *
  * This observers puts small event objects in buffer for later writing to the database. At the end of the request the buffer
  * is cleaned up and all data dumped into the tool_monitor_events table.
  *
  * @param \core\event\base $event event object
  */
 public static function process_event(\core\event\base $event)
 {
     if (empty(self::$instance)) {
         self::$instance = new static();
         // Register shutdown handler - this is useful for buffering, processing events, etc.
         \core_shutdown_manager::register_function(array(self::$instance, 'process_buffer'));
     }
     self::$instance->buffer_event($event);
     if (PHPUNIT_TEST) {
         // Process buffer after every event when unit testing.
         self::$instance->process_buffer();
     }
 }
Beispiel #6
0
 /**
  * The observer monitoring all the events.
  *
  * This observers puts small event objects in buffer for later writing to the database. At the end of the request the buffer
  * is cleaned up and all data dumped into the tool_monitor_events table.
  *
  * @param \core\event\base $event event object
  */
 public static function process_event(\core\event\base $event)
 {
     if (!get_config('tool_monitor', 'enablemonitor')) {
         return;
         // The tool is disabled. Nothing to do.
     }
     if (empty(self::$instance)) {
         self::$instance = new static();
         // Register shutdown handler - this is useful for buffering, processing events, etc.
         \core_shutdown_manager::register_function(array(self::$instance, 'process_buffer'));
     }
     self::$instance->buffer_event($event);
     if (PHPUNIT_TEST) {
         // Process buffer after every event when unit testing.
         self::$instance->process_buffer();
     }
 }
/**
 * Register shutdown handler.
 *
 * Should be called from your config.php
 *
 * @return void
 */
function local_telemetry_init()
{
    global $DB, $ME;
    if (defined('ABORT_AFTER_CONFIG') && ABORT_AFTER_CONFIG || defined('AJAX_SCRIPT') && AJAX_SCRIPT || defined('CLI_SCRIPT') && CLI_SCRIPT) {
        /* We should probably be logging these, but since an extremely minimal
         * subset of the Moodle framework is loaded we can't locate our classes
         * without installing our own class autoloader. A task for a rainier
         * day. */
        return;
    }
    $config = new config();
    if (!$config->get('enable', false)) {
        return;
    }
    $url = new moodle_url($ME);
    $request = new request($config, $DB, $url);
    core_shutdown_manager::register_function(array($request, 'commit'));
    if ($config->get('rs_wincache')) {
        $request->add_state(new wincache_request_state());
    }
}
Beispiel #8
0
 /**
  * Marks the cache as being volatile (likely to change)
  *
  * Any caches marked as volatile will be destroyed at the on shutdown by
  * {@link navigation_node::destroy_volatile_caches()} which is registered
  * as a shutdown function if any caches are marked as volatile.
  *
  * @param bool $setting True to destroy the cache false not too
  */
 public function volatile($setting = true)
 {
     if (self::$volatilecaches === null) {
         self::$volatilecaches = array();
         core_shutdown_manager::register_function(array('navigation_cache', 'destroy_volatile_caches'));
     }
     if ($setting) {
         self::$volatilecaches[$this->area] = $this->area;
     } else {
         if (array_key_exists($this->area, self::$volatilecaches)) {
             unset(self::$volatilecaches[$this->area]);
         }
     }
 }
    if (NO_DEBUG_DISPLAY) {
        // Some parts of Moodle cannot display errors and debug at all.
        ini_set('display_errors', '0');
        ini_set('log_errors', '1');
    } else {
        if (empty($CFG->debugdisplay)) {
            ini_set('display_errors', '0');
            ini_set('log_errors', '1');
        } else {
            // This is very problematic in XHTML strict mode!
            ini_set('display_errors', '1');
        }
    }
}
// Register our shutdown manager, do NOT use register_shutdown_function().
core_shutdown_manager::initialize();
// Verify upgrade is not running unless we are in a script that needs to execute in any case
if (!defined('NO_UPGRADE_CHECK') and isset($CFG->upgraderunning)) {
    if ($CFG->upgraderunning < time()) {
        unset_config('upgraderunning');
    } else {
        print_error('upgraderunning');
    }
}
// Turn on SQL logging if required
if (!empty($CFG->logsql)) {
    $DB->set_logging(true);
}
// enable circular reference collector in PHP 5.3,
// it helps a lot when using large complex OOP structures such as in amos or gradebook
if (function_exists('gc_enable')) {
Beispiel #10
0
/**
 * Handles the sending of temporary file to user, download is forced.
 * File is deleted after abort or successful sending, does not return, script terminated
 *
 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
 * @param string $filename proposed file name when saving file
 * @param bool $pathisstring If the path is string
 */
function send_temp_file($path, $filename, $pathisstring = false)
{
    global $CFG;
    // Guess the file's MIME type.
    $mimetype = get_mimetype_for_sending($filename);
    // close session - not needed anymore
    \core\session\manager::write_close();
    if (!$pathisstring) {
        if (!file_exists($path)) {
            send_header_404();
            print_error('filenotfound', 'error', $CFG->wwwroot . '/');
        }
        // executed after normal finish or abort
        core_shutdown_manager::register_function('send_temp_file_finished', array($path));
    }
    // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
    if (core_useragent::is_ie()) {
        $filename = urlencode($filename);
    }
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    if (is_https()) {
        // HTTPS sites - watch out for IE! KB812935 and KB316431.
        header('Cache-Control: private, max-age=10, no-transform');
        header('Expires: ' . gmdate('D, d M Y H:i:s', 0) . ' GMT');
        header('Pragma: ');
    } else {
        //normal http - prevent caching at all cost
        header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
        header('Expires: ' . gmdate('D, d M Y H:i:s', 0) . ' GMT');
        header('Pragma: no-cache');
    }
    // send the contents - we can not accelerate this because the file will be deleted asap
    if ($pathisstring) {
        readstring_accel($path, $mimetype, false);
    } else {
        readfile_accel($path, $mimetype, false);
        @unlink($path);
    }
    die;
    //no more chars to output
}
Beispiel #11
0
/**
 * Marks start of upgrade, blocks any other access to site.
 * The upgrade is finished at the end of script or after timeout.
 *
 * @global object
 * @global object
 * @global object
 */
function upgrade_started($preinstall=false) {
    global $CFG, $DB, $PAGE, $OUTPUT;

    static $started = false;

    if ($preinstall) {
        ignore_user_abort(true);
        upgrade_setup_debug(true);

    } else if ($started) {
        upgrade_set_timeout(120);

    } else {
        if (!CLI_SCRIPT and !$PAGE->headerprinted) {
            $strupgrade  = get_string('upgradingversion', 'admin');
            $PAGE->set_pagelayout('maintenance');
            upgrade_init_javascript();
            $PAGE->set_title($strupgrade.' - Moodle '.$CFG->target_release);
            $PAGE->set_heading($strupgrade);
            $PAGE->navbar->add($strupgrade);
            $PAGE->set_cacheable(false);
            echo $OUTPUT->header();
        }

        ignore_user_abort(true);
        core_shutdown_manager::register_function('upgrade_finished_handler');
        upgrade_setup_debug(true);
        set_config('upgraderunning', time()+300);
        $started = true;
    }
}
Beispiel #12
0
/**
 * Get a per-request storage directory in the tempdir.
 *
 * The directory is automatically cleaned up during the shutdown handler.
 *
 * @param bool $exceptiononerror throw exception if error encountered
 * @return string|false Returns full path to directory if successful, false if not; may throw exception
 */
function get_request_storage_directory($exceptiononerror = true)
{
    global $CFG;
    static $requestdir = null;
    if (!$requestdir || !file_exists($requestdir) || !is_dir($requestdir) || !is_writable($requestdir)) {
        if ($CFG->localcachedir !== "{$CFG->dataroot}/localcache") {
            check_dir_exists($CFG->localcachedir, true, true);
            protect_directory($CFG->localcachedir);
        } else {
            protect_directory($CFG->dataroot);
        }
        if ($requestdir = make_unique_writable_directory($CFG->localcachedir, $exceptiononerror)) {
            // Register a shutdown handler to remove the directory.
            \core_shutdown_manager::register_function('remove_dir', array($requestdir));
        }
    }
    return $requestdir;
}
Beispiel #13
0
    }
}
// Switch to CLI maintenance mode if required, we need to do it here after all the settings are initialised.
if (isset($CFG->maintenance_later) and $CFG->maintenance_later <= time()) {
    if (!file_exists("{$CFG->dataroot}/climaintenance.html")) {
        require_once "{$CFG->libdir}/adminlib.php";
        enable_cli_maintenance_mode();
    }
    unset_config('maintenance_later');
    if (AJAX_SCRIPT) {
        die;
    } else {
        if (!CLI_SCRIPT) {
            redirect(new moodle_url('/'));
        }
    }
}
// Add behat_shutdown_function to shutdown manager, so we can capture php errors,
// but not necessary for behat CLI command as it's being captured by behat process.
if (defined('BEHAT_SITE_RUNNING') && !defined('BEHAT_TEST')) {
    core_shutdown_manager::register_function('behat_shutdown_function');
}
// note: we can not block non utf-8 installations here, because empty mysql database
// might be converted to utf-8 in admin/index.php during installation
// this is a funny trick to make Eclipse believe that $OUTPUT and other globals
// contains an instance of core_renderer, etc. which in turn fixes autocompletion ;-)
if (false) {
    $DB = new moodle_database();
    $OUTPUT = new core_renderer(null, null);
    $PAGE = new moodle_page();
}
Beispiel #14
0
/**
 * Create CLI maintenance file to prevent all access.
 */
function tool_dbtransfer_create_maintenance_file()
{
    global $CFG;
    core_shutdown_manager::register_function('tool_dbtransfer_maintenance_callback');
    $options = new stdClass();
    $options->trusted = false;
    $options->noclean = false;
    $options->smiley = false;
    $options->filter = false;
    $options->para = true;
    $options->newlines = false;
    $message = format_text(get_string('climigrationnotice', 'tool_dbtransfer'), FORMAT_MARKDOWN, $options);
    $message = bootstrap_renderer::early_error_content($message, '', '', array());
    $html = <<<OET
<!DOCTYPE html>
<html>
<header><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><header/>
<body>{$message}</body>
</html>
OET;
    file_put_contents("{$CFG->dataroot}/climaintenance.html", $html);
    @chmod("{$CFG->dataroot}/climaintenance.html", $CFG->filepermissions);
}
/**
 * Handles the sending of temporary file to user, download is forced.
 * File is deleted after abort or successful sending, does not return, script terminated
 *
 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
 * @param string $filename proposed file name when saving file
 * @param bool $pathisstring If the path is string
 */
function send_temp_file($path, $filename, $pathisstring = false)
{
    global $CFG;
    if (core_useragent::is_firefox()) {
        // only FF is known to correctly save to disk before opening...
        $mimetype = mimeinfo('type', $filename);
    } else {
        $mimetype = 'application/x-forcedownload';
    }
    // close session - not needed anymore
    \core\session\manager::write_close();
    if (!$pathisstring) {
        if (!file_exists($path)) {
            send_header_404();
            print_error('filenotfound', 'error', $CFG->wwwroot . '/');
        }
        // executed after normal finish or abort
        core_shutdown_manager::register_function('send_temp_file_finished', array($path));
    }
    // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
    if (core_useragent::is_ie()) {
        $filename = urlencode($filename);
    }
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    if (strpos($CFG->wwwroot, 'https://') === 0) {
        //https sites - watch out for IE! KB812935 and KB316431
        header('Cache-Control: private, max-age=10');
        header('Expires: ' . gmdate('D, d M Y H:i:s', 0) . ' GMT');
        header('Pragma: ');
    } else {
        //normal http - prevent caching at all cost
        header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
        header('Expires: ' . gmdate('D, d M Y H:i:s', 0) . ' GMT');
        header('Pragma: no-cache');
    }
    // send the contents - we can not accelerate this because the file will be deleted asap
    if ($pathisstring) {
        readstring_accel($path, $mimetype, false);
    } else {
        readfile_accel($path, $mimetype, false);
        @unlink($path);
    }
    die;
    //no more chars to output
}
Beispiel #16
0
 /**
  * Try to acquire the lock
  *
  * @return boolean
  */
 public function get()
 {
     if ($this->backend->has_lock()) {
         return true;
         // Don't attempt to re-acquire
     }
     $result = $this->backend->get();
     if ($result) {
         core_shutdown_manager::register_function(array($this, 'shutdown'));
     }
     return $result;
 }