MDL-21249 improved php docs and adding direct access prevention in dtl
[moodle.git] / lib / javascript.php
CommitLineData
0139ec3f
PS
1<?php
2
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/>.
17
18/**
19 * This file is serving optimised JS
20 *
21 * @package moodlecore
22 * @copyright 2010 Petr Skoda (skodak)
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
26// we need just the values from config.php and minlib.php
27define('ABORT_AFTER_CONFIG', true);
28require('../config.php'); // this stops immediately at the beginning of lib/setup.php
29
045f492c
SH
30// setup include path
31set_include_path($CFG->libdir . '/minify/lib' . PATH_SEPARATOR . get_include_path());
32require_once('Minify.php');
0139ec3f 33
045f492c
SH
34$file = min_optional_param('file', '', 'RAW');
35$rev = min_optional_param('rev', 0, 'INT');
0139ec3f 36
7a2df05c
PS
37// some security first - pick only files with .js extension in dirroot
38$jsfiles = array();
39$files = explode(',', $file);
40foreach ($files as $fsfile) {
41 $jsfile = realpath($CFG->dirroot.$fsfile);
42 if ($jsfile === false) {
43 // does not exist
44 continue;
5a75ac0a 45 }
7a2df05c
PS
46 if (strpos($jsfile, $CFG->dirroot . DIRECTORY_SEPARATOR) !== 0) {
47 // hackers - not in dirroot
48 continue;
49 }
5ac09e8b 50 if (substr($jsfile, -3) !== '.js') {
7a2df05c
PS
51 // hackers - not a JS file
52 continue;
53 }
54 $jsfiles[] = $jsfile;
55}
56
57if (!$jsfiles) {
58 // bad luck - no valid files
59 die();
0139ec3f
PS
60}
61
045f492c 62minify($jsfiles);
baeb20bb 63
045f492c
SH
64function minify($files) {
65 global $CFG;
0139ec3f 66
09c48cea
PS
67 $cachedir = $CFG->dataroot.'/cache/js';
68 // make sure the cache dir exist
69 if (!file_exists($cachedir)) {
70 @mkdir($cachedir, $CFG->directorypermissions, true);
71 }
72
045f492c
SH
73 if (0 === stripos(PHP_OS, 'win')) {
74 Minify::setDocRoot(); // IIS may need help
75 }
09c48cea 76 Minify::setCache($cachedir, true);
0139ec3f 77
045f492c
SH
78 $options = array(
79 // Maximum age to cache
80 'maxAge' => (60*60*24*20),
81 // The files to minify
82 'files' => $files
83 );
0139ec3f 84
045f492c
SH
85 Minify::serve('Files', $options);
86 die();
5a75ac0a 87}