MDL-14679 fixed double encoding of html entities in debuginfo coming from the dml...
[moodle.git] / lib / setuplib.php
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
19 /**
20  * These functions are required very early in the Moodle
21  * setup process, before any of the main libraries are
22  * loaded.
23  *
24  * @package   moodlecore
25  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
26  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27  */
29 /// Debug levels ///
30 /** no warnings at all */
31 define ('DEBUG_NONE', 0);
32 /** E_ERROR | E_PARSE */
33 define ('DEBUG_MINIMAL', 5);
34 /** E_ERROR | E_PARSE | E_WARNING | E_NOTICE */
35 define ('DEBUG_NORMAL', 15);
36 /** E_ALL without E_STRICT for now, do show recoverable fatal errors */
37 define ('DEBUG_ALL', 6143);
38 /** DEBUG_ALL with extra Moodle debug messages - (DEBUG_ALL | 32768) */
39 define ('DEBUG_DEVELOPER', 38911);
41 /**
42  * Simple class. It is usually used instead of stdClass because it looks
43  * more familiar to Java developers ;-) Do not use for type checking of
44  * function parameters.
45  *
46  * @package   moodlecore
47  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
48  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49  */
50 class object extends stdClass {};
52 /**
53  * Base Moodle Exception class
54  *
55  * Although this class is defined here, you cannot throw a moodle_exception until
56  * after moodlelib.php has been included (which will happen very soon).
57  *
58  * @package   moodlecore
59  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
60  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
61  */
62 class moodle_exception extends Exception {
63     public $errorcode;
64     public $module;
65     public $a;
66     public $link;
67     public $debuginfo;
69     /**
70      * Constructor
71      * @param string $errorcode The name of the string from error.php to print
72      * @param string $module name of module
73      * @param string $link The url where the user will be prompted to continue. If no url is provided the user will be directed to the site index page.
74      * @param object $a Extra words and phrases that might be required in the error string
75      * @param string $debuginfo optional debugging information
76      */
77     function __construct($errorcode, $module='', $link='', $a=NULL, $debuginfo=null) {
78         if (empty($module) || $module == 'moodle' || $module == 'core') {
79             $module = 'error';
80         }
82         $this->errorcode = $errorcode;
83         $this->module    = $module;
84         $this->link      = $link;
85         $this->a         = $a;
86         $this->debuginfo = $debuginfo;
88         $message = get_string($errorcode, $module, $a);
90         parent::__construct($message, 0);
91     }
92 }
94 /**
95  * Web service parameter exception class
96  *
97  * This exception must be thrown to the web service client when a web service parameter is invalid
98  * The error string is gotten from webservice.php
99  */
100 class webservice_parameter_exception extends moodle_exception {
101     /**
102      * Constructor
103      * @param string $errorcode The name of the string from webservice.php to print
104      * @param string $a The name of the parameter
105      */
106     function __construct($errorcode=null, $a = '') {
107         parent::__construct($errorcode, 'webservice', '', $a, null);
108     }
111 /**
112  * Exceptions indicating user does not have permissions to do something
113  * and the execution can not continue.
114  */
115 class required_capability_exception extends moodle_exception {
116     function __construct($context, $capability, $errormessage, $stringfile) {
117         $capabilityname = get_capability_string($capability);
118         parent::__construct($errormessage, $stringfile, get_context_url($context), $capabilityname);
119     }
122 /**
123  * Exception indicating programming error, must be fixed by a programer. For example
124  * a core API might throw this type of exception if a plugin calls it incorrectly.
125  *
126  * @package   moodlecore
127  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
128  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
129  */
130 class coding_exception extends moodle_exception {
131     /**
132      * Constructor
133      * @param string $hint short description of problem
134      * @param string $debuginfo detailed information how to fix problem
135      */
136     function __construct($hint, $debuginfo=null) {
137         parent::__construct('codingerror', 'debug', '', $hint, $debuginfo);
138     }
141 /**
142  * Exception indicating malformed parameter problem.
143  * This exception is not supposed to be thrown when processing
144  * user submitted data in forms. It is more suitable
145  * for WS and other low level stuff.
146  */
147 class invalid_parameter_exception extends moodle_exception {
148     /**
149      * Constructor
150      * @param string $debuginfo some detailed information
151      */
152     function __construct($debuginfo=null) {
153         parent::__construct('invalidparameter', 'debug', '', null, $debuginfo);
154     }
157 /**
158  * Exception indicating malformed response problem.
159  * This exception is not supposed to be thrown when processing
160  * user submitted data in forms. It is more suitable
161  * for WS and other low level stuff.
162  */
163 class invalid_response_exception extends moodle_exception {
164     /**
165      * Constructor
166      * @param string $debuginfo some detailed information
167      */
168     function __construct($debuginfo=null) {
169         parent::__construct('invalidresponse', 'debug', '', null, $debuginfo);
170     }
173 /**
174  * An exception that indicates something really weird happened. For example,
175  * if you do switch ($context->contextlevel), and have one case for each
176  * CONTEXT_... constant. You might throw an invalid_state_exception in the
177  * default case, to just in case something really weird is going on, and
178  * $context->contextlevel is invalid - rather than ignoring this possibility.
179  *
180  * @package   moodlecore
181  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
182  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
183  */
184 class invalid_state_exception extends moodle_exception {
185     /**
186      * Constructor
187      * @param string $hint short description of problem
188      * @param string $debuginfo optional more detailed information
189      */
190     function __construct($hint, $debuginfo=null) {
191         parent::__construct('invalidstatedetected', 'debug', '', $hint, $debuginfo);
192     }
195 /**
196  * Default exception handler, uncaught exceptions are equivalent to error() in 1.9 and earlier
197  *
198  * @param Exception $ex
199  * @return void -does not return. Terminates execution!
200  */
201 function default_exception_handler($ex) {
202     global $DB, $OUTPUT;
204     // detect active db transactions, rollback and log as error
205     abort_all_db_transactions();
207     $info = get_exception_info($ex);
209     if (debugging('', DEBUG_MINIMAL)) {
210         $logerrmsg = "Default exception handler: ".$info->message.' Debug: '.$info->debuginfo."\n".format_backtrace($info->backtrace, true);
211         error_log($logerrmsg);
212     }
214     if (is_early_init($info->backtrace)) {
215         echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
216     } else {
217         try {
218             if ($DB) {
219                 // If you enable db debugging and exception is thrown, the print footer prints a lot of rubbish
220                 $DB->set_debug(0);
221             }
222             echo $OUTPUT->fatal_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
223         } catch (Exception $out_ex) {
224             // default exception handler MUST not throw any exceptions!!
225             // the problem here is we do not know if page already started or not, we only know that somebody messed up in outputlib or theme
226             // so we just print at least something instead of "Exception thrown without a stack frame in Unknown on line 0":-(
227             echo bootstrap_renderer::early_error_content($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
228             $outinfo = get_exception_info($out_ex);
229             echo bootstrap_renderer::early_error_content($outinfo->message, $outinfo->moreinfourl, $outinfo->link, $outinfo->backtrace, $outinfo->debuginfo);
230         }
231     }
233     exit(1); // General error code
236 /**
237  * Unconditionally abort all database transactions, this function
238  * should be called from exception handlers only.
239  * @return void
240  */
241 function abort_all_db_transactions() {
242     global $CFG, $DB, $SCRIPT;
244     // default exception handler MUST not throw any exceptions!!
246     if ($DB && $DB->is_transaction_started()) {
247         error_log('Database transaction aborted automatically in ' . $CFG->dirroot . $SCRIPT);
248         // note: transaction blocks should never change current $_SESSION
249         $DB->force_transaction_rollback();
250     }
253 /**
254  * This function encapsulates the tests for whether an exception was thrown in
255  * early init -- either during setup.php or during init of $OUTPUT.
256  *
257  * If another exception is thrown then, and if we do not take special measures,
258  * we would just get a very cryptic message "Exception thrown without a stack
259  * frame in Unknown on line 0". That makes debugging very hard, so we do take
260  * special measures in default_exception_handler, with the help of this function.
261  *
262  * @param array $backtrace the stack trace to analyse.
263  * @return boolean whether the stack trace is somewhere in output initialisation.
264  */
265 function is_early_init($backtrace) {
266     $dangerouscode = array(
267         array('function' => 'header', 'type' => '->'),
268         array('class' => 'bootstrap_renderer'),
269         array('file' => dirname(__FILE__).'/setup.php'),
270     );
271     foreach ($backtrace as $stackframe) {
272         foreach ($dangerouscode as $pattern) {
273             $matches = true;
274             foreach ($pattern as $property => $value) {
275                 if (!isset($stackframe[$property]) || $stackframe[$property] != $value) {
276                     $matches = false;
277                 }
278             }
279             if ($matches) {
280                 return true;
281             }
282         }
283     }
284     return false;
287 /**
288  * Abort execution by throwing of a general exception,
289  * default exception handler displays the error message in most cases.
290  *
291  * @param string $errorcode The name of the language string containing the error message.
292  *      Normally this should be in the error.php lang file.
293  * @param string $module The language file to get the error message from.
294  * @param string $link The url where the user will be prompted to continue.
295  *      If no url is provided the user will be directed to the site index page.
296  * @param object $a Extra words and phrases that might be required in the error string
297  * @param string $debuginfo optional debugging information
298  * @return void, always throws exception!
299  */
300 function print_error($errorcode, $module = 'error', $link = '', $a = null, $debuginfo = null) {
301     throw new moodle_exception($errorcode, $module, $link, $a, $debuginfo);
304 /**
305  * Returns detailed information about specified exception.
306  * @param exception $ex
307  * @return object
308  */
309 function get_exception_info($ex) {
310     global $CFG, $DB, $SESSION;
312     if ($ex instanceof moodle_exception) {
313         $errorcode = $ex->errorcode;
314         $module = $ex->module;
315         $a = $ex->a;
316         $link = $ex->link;
317         $debuginfo = $ex->debuginfo;
318     } else {
319         $errorcode = 'generalexceptionmessage';
320         $module = 'error';
321         $a = $ex->getMessage();
322         $link = '';
323         $debuginfo = null;
324     }
326     $backtrace = $ex->getTrace();
327     $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex));
328     array_unshift($backtrace, $place);
330     // Be careful, no guarantee moodlelib.php is loaded.
331     if (empty($module) || $module == 'moodle' || $module == 'core') {
332         $module = 'error';
333     }
334     if (function_exists('get_string')) {
335         $message = get_string($errorcode, $module, $a);
336         if ($module === 'error' and strpos($message, '[[') === 0) {
337             // Search in moodle file if error specified - needed for backwards compatibility
338             $message = get_string($errorcode, 'moodle', $a);
339         }
340     } else {
341         $message = $module . '/' . $errorcode;
342     }
344     // Be careful, no guarantee weblib.php is loaded.
345     if (function_exists('clean_text')) {
346         $message = clean_text($message);
347     } else {
348         $message = htmlspecialchars($message);
349     }
351     if (!empty($CFG->errordocroot)) {
352         $errordocroot = $CFG->errordocroot;
353     } else if (!empty($CFG->docroot)) {
354         $errordocroot = $CFG->docroot;
355     } else {
356         $errordocroot = 'http://docs.moodle.org';
357     }
358     if ($module === 'error') {
359         $modulelink = 'moodle';
360     } else {
361         $modulelink = $module;
362     }
363     $moreinfourl = $errordocroot . '/en/error/' . $modulelink . '/' . $errorcode;
365     if (empty($link)) {
366         if (!empty($SESSION->fromurl)) {
367             $link = $SESSION->fromurl;
368             unset($SESSION->fromurl);
369         } else {
370             $link = $CFG->wwwroot .'/';
371         }
372     }
374     $info = new object();
375     $info->message     = $message;
376     $info->errorcode   = $errorcode;
377     $info->backtrace   = $backtrace;
378     $info->link        = $link;
379     $info->moreinfourl = $moreinfourl;
380     $info->a           = $a;
381     $info->debuginfo   = $debuginfo;
383     return $info;
386 /**
387  * Formats a backtrace ready for output.
388  *
389  * @param array $callers backtrace array, as returned by debug_backtrace().
390  * @param boolean $plaintext if false, generates HTML, if true generates plain text.
391  * @return string formatted backtrace, ready for output.
392  */
393 function format_backtrace($callers, $plaintext = false) {
394     // do not use $CFG->dirroot because it might not be available in destructors
395     $dirroot = dirname(dirname(__FILE__));
397     if (empty($callers)) {
398         return '';
399     }
401     $from = $plaintext ? '' : '<ul style="text-align: left">';
402     foreach ($callers as $caller) {
403         if (!isset($caller['line'])) {
404             $caller['line'] = '?'; // probably call_user_func()
405         }
406         if (!isset($caller['file'])) {
407             $caller['file'] = 'unknownfile'; // probably call_user_func()
408         }
409         $from .= $plaintext ? '* ' : '<li>';
410         $from .= 'line ' . $caller['line'] . ' of ' . str_replace($dirroot, '', $caller['file']);
411         if (isset($caller['function'])) {
412             $from .= ': call to ';
413             if (isset($caller['class'])) {
414                 $from .= $caller['class'] . $caller['type'];
415             }
416             $from .= $caller['function'] . '()';
417         } else if (isset($caller['exception'])) {
418             $from .= ': '.$caller['exception'].' thrown';
419         }
420         $from .= $plaintext ? "\n" : '</li>';
421     }
422     $from .= $plaintext ? '' : '</ul>';
424     return $from;
427 /**
428  * This function verifies the sanity of PHP configuration
429  * and stops execution if anything critical found.
430  */
431 function setup_validate_php_configuration() {
432    // this must be very fast - no slow checks here!!!
434    if (ini_get_bool('register_globals')) {
435        print_error('globalswarning', 'admin');
436    }
437    if (ini_get_bool('session.auto_start')) {
438        print_error('sessionautostartwarning', 'admin');
439    }
440    if (ini_get_bool('magic_quotes_runtime')) {
441        print_error('fatalmagicquotesruntime', 'admin');
442    }
445 /**
446  * Initialises $FULLME and friends. Private function. Should only be called from
447  * setup.php.
448  */
449 function initialise_fullme() {
450     global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
452     // Detect common config error.
453     if (substr($CFG->wwwroot, -1) == '/') {
454         print_error('wwwrootslash', 'error');
455     }
457     if (CLI_SCRIPT) {
458         initialise_fullme_cli();
459         return;
460     }
462     $wwwroot = parse_url($CFG->wwwroot);
463     if (!isset($wwwroot['path'])) {
464         $wwwroot['path'] = '';
465     }
466     $wwwroot['path'] .= '/';
468     $rurl = setup_get_remote_url();
470     // Check that URL is under $CFG->wwwroot.
471     if (strpos($rurl['path'], $wwwroot['path']) === 0) {
472         $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
473     } else {
474         // Probably some weird external script
475         $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
476         return;
477     }
479     // $CFG->sslproxy specifies if external SSL appliance is used
480     // (That is, the Moodle server uses http, with an external box translating everything to https).
481     if (empty($CFG->sslproxy)) {
482         if ($rurl['scheme'] == 'http' and $wwwroot['scheme'] == 'https') {
483             print_error('sslonlyaccess', 'error');
484         }
485     }
487     // $CFG->reverseproxy specifies if reverse proxy server used.
488     // Used in load balancing scenarios.
489     // Do not abuse this to try to solve lan/wan access problems!!!!!
490     if (empty($CFG->reverseproxy)) {
491         if (($rurl['host'] != $wwwroot['host']) or
492                 (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port'])) {
493             print_error('wwwrootmismatch', 'error', '', $CFG->wwwroot);
494         }
495     }
497     // hopefully this will stop all those "clever" admins trying to set up moodle
498     // with two different addresses in intranet and Internet
499     if (!empty($CFG->reverseproxy) && $rurl['host'] == $wwwroot['host']) {
500         print_error('reverseproxyabused', 'error');
501     }
503     $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
504     if (!empty($wwwroot['port'])) {
505         $hostandport .= ':'.$wwwroot['port'];
506     }
508     $FULLSCRIPT = $hostandport . $rurl['path'];
509     $FULLME = $hostandport . $rurl['fullpath'];
510     $ME = $rurl['fullpath'];
511     $rurl['path'] = $rurl['fullpath'];
514 /**
515  * Initialises $FULLME and friends for command line scripts.
516  * This is a private method for use by initialise_fullme.
517  */
518 function initialise_fullme_cli() {
519     global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
521     // Urls do not make much sense in CLI scripts
522     $backtrace = debug_backtrace();
523     $topfile = array_pop($backtrace);
524     $topfile = realpath($topfile['file']);
525     $dirroot = realpath($CFG->dirroot);
527     if (strpos($topfile, $dirroot) !== 0) {
528         // Probably some weird external script
529         $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
530     } else {
531         $relativefile = substr($topfile, strlen($dirroot));
532         $relativefile = str_replace('\\', '/', $relativefile); // Win fix
533         $SCRIPT = $FULLSCRIPT = $relativefile;
534         $FULLME = $ME = null;
535     }
538 /**
539  * Get the URL that PHP/the web server thinks it is serving. Private function
540  * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.
541  * @return array in the same format that parse_url returns, with the addition of
542  *      a 'fullpath' element, which includes any slasharguments path.
543  */
544 function setup_get_remote_url() {
545     $rurl = array();
546     list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
547     $rurl['port'] = $_SERVER['SERVER_PORT'];
548     $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
550     if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
551         //Apache server
552         $rurl['scheme']   = empty($_SERVER['HTTPS']) ? 'http' : 'https';
553         $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
555     } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
556         //lighttpd
557         $rurl['scheme']   = empty($_SERVER['HTTPS']) ? 'http' : 'https';
558         $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
560     } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
561         //nginx
562         $rurl['scheme']   = empty($_SERVER['HTTPS']) ? 'http' : 'https';
563         $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
565     } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
566         //IIS
567         $rurl['scheme']   = ($_SERVER['HTTPS'] == 'off') ? 'http' : 'https';
568         $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
570         // NOTE: ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS
571         //       since 2.0 we rely on iis rewrite extenssion like Helicon ISAPI_rewrite
572         //       example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
574         if ($_SERVER['QUERY_STRING'] != '') {
575             $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
576         }
577         $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
579     } else {
580         throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
581     }
582     return $rurl;
585 /**
586  * Initializes our performance info early.
587  *
588  * Pairs up with get_performance_info() which is actually
589  * in moodlelib.php. This function is here so that we can
590  * call it before all the libs are pulled in.
591  *
592  * @uses $PERF
593  */
594 function init_performance_info() {
596     global $PERF, $CFG, $USER;
598     $PERF = new object();
599     $PERF->logwrites = 0;
600     if (function_exists('microtime')) {
601         $PERF->starttime = microtime();
602     }
603     if (function_exists('memory_get_usage')) {
604         $PERF->startmemory = memory_get_usage();
605     }
606     if (function_exists('posix_times')) {
607         $PERF->startposixtimes = posix_times();
608     }
609     if (function_exists('apd_set_pprof_trace')) {
610         // APD profiling
611         if ($USER->id > 0 && $CFG->perfdebug >= 15) {
612             $tempdir = $CFG->dataroot . '/temp/profile/' . $USER->id;
613             mkdir($tempdir);
614             apd_set_pprof_trace($tempdir);
615             $PERF->profiling = true;
616         }
617     }
620 /**
621  * Indicates whether we are in the middle of the initial Moodle install.
622  *
623  * Very occasionally it is necessary avoid running certain bits of code before the
624  * Moodle installation has completed. The installed flag is set in admin/index.php
625  * after Moodle core and all the plugins have been installed, but just before
626  * the person doing the initial install is asked to choose the admin password.
627  *
628  * @return boolean true if the initial install is not complete.
629  */
630 function during_initial_install() {
631     global $CFG;
632     return empty($CFG->rolesactive);
635 /**
636  * Function to raise the memory limit to a new value.
637  * Will respect the memory limit if it is higher, thus allowing
638  * settings in php.ini, apache conf or command line switches
639  * to override it
640  *
641  * The memory limit should be expressed with a string (eg:'64M')
642  *
643  * @param string $newlimit the new memory limit
644  * @return bool
645  */
646 function raise_memory_limit($newlimit) {
648     if (empty($newlimit)) {
649         return false;
650     }
652     $cur = @ini_get('memory_limit');
653     if (empty($cur)) {
654         // if php is compiled without --enable-memory-limits
655         // apparently memory_limit is set to ''
656         $cur=0;
657     } else {
658         if ($cur == -1){
659             return true; // unlimited mem!
660         }
661       $cur = get_real_size($cur);
662     }
664     $new = get_real_size($newlimit);
665     if ($new > $cur) {
666         ini_set('memory_limit', $newlimit);
667         return true;
668     }
669     return false;
672 /**
673  * Function to reduce the memory limit to a new value.
674  * Will respect the memory limit if it is lower, thus allowing
675  * settings in php.ini, apache conf or command line switches
676  * to override it
677  *
678  * The memory limit should be expressed with a string (eg:'64M')
679  *
680  * @param string $newlimit the new memory limit
681  * @return bool
682  */
683 function reduce_memory_limit($newlimit) {
684     if (empty($newlimit)) {
685         return false;
686     }
687     $cur = @ini_get('memory_limit');
688     if (empty($cur)) {
689         // if php is compiled without --enable-memory-limits
690         // apparently memory_limit is set to ''
691         $cur=0;
692     } else {
693         if ($cur == -1){
694             return true; // unlimited mem!
695         }
696         $cur = get_real_size($cur);
697     }
699     $new = get_real_size($newlimit);
700     // -1 is smaller, but it means unlimited
701     if ($new < $cur && $new != -1) {
702         ini_set('memory_limit', $newlimit);
703         return true;
704     }
705     return false;
708 /**
709  * Converts numbers like 10M into bytes.
710  *
711  * @param mixed $size The size to be converted
712  * @return mixed
713  */
714 function get_real_size($size=0) {
715     if (!$size) {
716         return 0;
717     }
718     $scan = array();
719     $scan['MB'] = 1048576;
720     $scan['Mb'] = 1048576;
721     $scan['M'] = 1048576;
722     $scan['m'] = 1048576;
723     $scan['KB'] = 1024;
724     $scan['Kb'] = 1024;
725     $scan['K'] = 1024;
726     $scan['k'] = 1024;
728     while (list($key) = each($scan)) {
729         if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
730             $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
731             break;
732         }
733     }
734     return $size;
737 /**
738  * Check whether a major upgrade is needed. That is defined as an upgrade that
739  * changes something really fundamental in the database, so nothing can possibly
740  * work until the database has been updated, and that is defined by the hard-coded
741  * version number in this function.
742  */
743 function redirect_if_major_upgrade_required() {
744     global $CFG;
745     $lastmajordbchanges = 2009110400;
746     if (empty($CFG->version) or (int)$CFG->version < $lastmajordbchanges or
747             during_initial_install() or !empty($CFG->adminsetuppending)) {
748         try {
749             @session_get_instance()->terminate_current();
750         } catch (Exception $e) {
751             // Ignore any errors, redirect to upgrade anyway.
752         }
753         $url = $CFG->wwwroot . '/' . $CFG->admin . '/index.php';
754         @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
755         @header('Location: ' . $url);
756         echo bootstrap_renderer::plain_redirect_message(htmlspecialchars($url));
757         exit;
758     }
761 /**
762  * Create a directory.
763  *
764  * @uses $CFG
765  * @param string $directory  a string of directory names under $CFG->dataroot eg  stuff/assignment/1
766  * param bool $shownotices If true then notification messages will be printed out on error.
767  * @return string|false Returns full path to directory if successful, false if not
768  */
769 function make_upload_directory($directory, $shownotices=true) {
771     global $CFG;
773     $currdir = $CFG->dataroot;
775     umask(0000);
777     if (!file_exists($currdir)) {
778         if (!mkdir($currdir, $CFG->directorypermissions) or !is_writable($currdir)) {
779             if ($shownotices) {
780                 echo '<div class="notifyproblem" align="center">ERROR: You need to create the directory '.
781                      $currdir .' with web server write access</div>'."<br />\n";
782             }
783             return false;
784         }
785     }
787     // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open
788     if (!file_exists($currdir.'/.htaccess')) {
789         if ($handle = fopen($currdir.'/.htaccess', 'w')) {   // For safety
790             @fwrite($handle, "deny from all\r\nAllowOverride None\r\nNote: this file is broken intentionally, we do not want anybody to undo it in subdirectory!\r\n");
791             @fclose($handle);
792         }
793     }
795     $dirarray = explode('/', $directory);
797     foreach ($dirarray as $dir) {
798         $currdir = $currdir .'/'. $dir;
799         if (! file_exists($currdir)) {
800             if (! mkdir($currdir, $CFG->directorypermissions)) {
801                 if ($shownotices) {
802                     echo '<div class="notifyproblem" align="center">ERROR: Could not find or create a directory ('.
803                          $currdir .')</div>'."<br />\n";
804                 }
805                 return false;
806             }
807             //@chmod($currdir, $CFG->directorypermissions);  // Just in case mkdir didn't do it
808         }
809     }
811     return $currdir;
814 function init_memcached() {
815     global $CFG, $MCACHE;
817     include_once($CFG->libdir . '/memcached.class.php');
818     $MCACHE = new memcached;
819     if ($MCACHE->status()) {
820         return true;
821     }
822     unset($MCACHE);
823     return false;
826 function init_eaccelerator() {
827     global $CFG, $MCACHE;
829     include_once($CFG->libdir . '/eaccelerator.class.php');
830     $MCACHE = new eaccelerator;
831     if ($MCACHE->status()) {
832         return true;
833     }
834     unset($MCACHE);
835     return false;
839 /**
840  * This class solves the problem of how to initialise $OUTPUT.
841  *
842  * The problem is caused be two factors
843  * <ol>
844  * <li>On the one hand, we cannot be sure when output will start. In particular,
845  * an error, which needs to be displayed, could be thrown at any time.</li>
846  * <li>On the other hand, we cannot be sure when we will have all the information
847  * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
848  * (potentially) depends on the current course, course categories, and logged in user.
849  * It also depends on whether the current page requires HTTPS.</li>
850  * </ol>
851  *
852  * So, it is hard to find a single natural place during Moodle script execution,
853  * which we can guarantee is the right time to initialise $OUTPUT. Instead we
854  * adopt the following strategy
855  * <ol>
856  * <li>We will initialise $OUTPUT the first time it is used.</li>
857  * <li>If, after $OUTPUT has been initialised, the script tries to change something
858  * that $OUTPUT depends on, we throw an exception making it clear that the script
859  * did something wrong.
860  * </ol>
861  *
862  * The only problem with that is, how do we initialise $OUTPUT on first use if,
863  * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
864  * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
865  * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
866  *
867  * Note that this class is used before lib/outputlib.php has been loaded, so we
868  * must be careful referring to classes/functions from there, they may not be
869  * defined yet, and we must avoid fatal errors.
870  *
871  * @copyright 2009 Tim Hunt
872  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
873  * @since     Moodle 2.0
874  */
875 class bootstrap_renderer {
876     /**
877      * Handles re-entrancy. Without this, errors or debugging output that occur
878      * during the initialisation of $OUTPUT, cause infinite recursion.
879      * @var boolean
880      */
881     protected $initialising = false;
883     /**
884      * Have we started output yet?
885      * @return boolean true if the header has been printed.
886      */
887     public function has_started() {
888         return false;
889     }
891     public function __call($method, $arguments) {
892         global $OUTPUT, $PAGE;
894         $recursing = false;
895         if ($method == 'notification') {
896             // Catch infinite recursion caused by debugging output during print_header.
897             $backtrace = debug_backtrace();
898             array_shift($backtrace);
899             array_shift($backtrace);
900             $recursing = is_early_init($backtrace);
901         }
903         // If lib/outputlib.php has been loaded, call it.
904         if (!empty($PAGE) && !$recursing) {
905             $PAGE->initialise_theme_and_output();
906             return call_user_func_array(array($OUTPUT, $method), $arguments);
907         }
909         $this->initialising = true;
910         // Too soon to initialise $OUTPUT, provide a couple of key methods.
911         $earlymethods = array(
912             'fatal_error' => 'early_error',
913             'notification' => 'early_notification',
914         );
915         if (array_key_exists($method, $earlymethods)) {
916             return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
917         }
919         throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
920     }
922     /**
923      * Returns nicely formatted error message in a div box.
924      * @return string
925      */
926     public static function early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
927         global $CFG;
929         $content = '<div style="margin-top: 6em; margin-left:auto; margin-right:auto; color:#990000; text-align:center; font-size:large; border-width:1px;
930 border-color:black; background-color:#ffffee; border-style:solid; border-radius: 20px; border-collapse: collapse;
931 width: 80%; -moz-border-radius: 20px; padding: 15px">
932 ' . $message . '
933 </div>';
934         if (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER) {
935             if (!empty($debuginfo)) {
936                 $debuginfo = s($debuginfo); // removes all nasty JS
937                 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
938                 $content .= '<div class="notifytiny">Debug info: ' . $debuginfo . '</div>';
939             }
940             if (!empty($backtrace)) {
941                 $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
942             }
943         }
945         return $content;
946     }
948     /**
949      * This function should only be called by this class, or from exception handlers
950      * @return string
951      */
952     public static function early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
953         // In the name of protocol correctness, monitoring and performance
954         // profiling, set the appropriate error headers for machine consumption
955         if (isset($_SERVER['SERVER_PROTOCOL'])) {
956             // Avoid it with cron.php. Note that we assume it's HTTP/1.x
957             // The 503 ode here means our Moodle does not work at all, the error happened too early
958             @header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
959         }
961         // better disable any caching
962         @header('Content-Type: text/html; charset=utf-8');
963         @header('Cache-Control: no-store, no-cache, must-revalidate');
964         @header('Cache-Control: post-check=0, pre-check=0', false);
965         @header('Pragma: no-cache');
966         @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
967         @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
969         if (function_exists('get_string')) {
970             $strerror = get_string('error');
971         } else {
972             $strerror = 'Error';
973         }
975         $content = self::early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo);
977         return self::plain_page($strerror, $content);
978     }
980     public static function early_notification($message, $classes = 'notifyproblem') {
981         return '<div class="' . $classes . '">' . $message . '</div>';
982     }
984     public static function plain_redirect_message($encodedurl) {
985         $message = '<p>' . get_string('pageshouldredirect') . '</p><p><a href="'.
986                 $encodedurl .'">'. get_string('continue') .'</a></p>';
987         return self::plain_page(get_string('redirect'), $message);
988     }
990     protected static function plain_page($title, $content) {
991         if (function_exists('get_string') && function_exists('get_html_lang')) {
992             $htmllang = get_html_lang();
993         } else {
994             $htmllang = '';
995         }
997         return '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
998 <html xmlns="http://www.w3.org/1999/xhtml" ' . $htmllang . '>
999 <head>
1000 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1001 <title>' . $title . '</title>
1002 </head><body>' . $content . '</body></html>';
1003     }