MDL-15727 basic jQuery support

See http://docs.moodle.org/dev/jQuery for more details.
This commit is contained in:
Petr Škoda 2013-03-19 11:47:31 +01:00
parent 373a8e052c
commit 63c88397f5
30 changed files with 26840 additions and 0 deletions

View File

@ -0,0 +1,26 @@
Copyright 2013 jQuery Foundation and other contributors,
http://jqueryui.com/
This software consists of voluntary contributions made by many
individuals (AUTHORS.txt, http://jqueryui.com/about) For exact
contribution history, see the revision history and logs, available
at http://jquery-ui.googlecode.com/svn/
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

9597
lib/jquery/jquery-1.9.1.js vendored Normal file

File diff suppressed because it is too large Load Diff

5
lib/jquery/jquery-1.9.1.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,511 @@
/*!
* jQuery Migrate - v1.1.1 - 2013-02-16
* https://github.com/jquery/jquery-migrate
* Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors; Licensed MIT
*/
(function( jQuery, window, undefined ) {
// See http://bugs.jquery.com/ticket/13335
// "use strict";
var warnedAbout = {};
// List of warnings already given; public read only
jQuery.migrateWarnings = [];
// Set to true to prevent console output; migrateWarnings still maintained
// jQuery.migrateMute = false;
// Show a message on the console so devs know we're active
if ( !jQuery.migrateMute && window.console && console.log ) {
console.log("JQMIGRATE: Logging is active");
}
// Set to false to disable traces that appear with warnings
if ( jQuery.migrateTrace === undefined ) {
jQuery.migrateTrace = true;
}
// Forget any warnings we've already given; public
jQuery.migrateReset = function() {
warnedAbout = {};
jQuery.migrateWarnings.length = 0;
};
function migrateWarn( msg) {
if ( !warnedAbout[ msg ] ) {
warnedAbout[ msg ] = true;
jQuery.migrateWarnings.push( msg );
if ( window.console && console.warn && !jQuery.migrateMute ) {
console.warn( "JQMIGRATE: " + msg );
if ( jQuery.migrateTrace && console.trace ) {
console.trace();
}
}
}
}
function migrateWarnProp( obj, prop, value, msg ) {
if ( Object.defineProperty ) {
// On ES5 browsers (non-oldIE), warn if the code tries to get prop;
// allow property to be overwritten in case some other plugin wants it
try {
Object.defineProperty( obj, prop, {
configurable: true,
enumerable: true,
get: function() {
migrateWarn( msg );
return value;
},
set: function( newValue ) {
migrateWarn( msg );
value = newValue;
}
});
return;
} catch( err ) {
// IE8 is a dope about Object.defineProperty, can't warn there
}
}
// Non-ES5 (or broken) browser; just set the property
jQuery._definePropertyBroken = true;
obj[ prop ] = value;
}
if ( document.compatMode === "BackCompat" ) {
// jQuery has never supported or tested Quirks Mode
migrateWarn( "jQuery is not compatible with Quirks Mode" );
}
var attrFn = jQuery( "<input/>", { size: 1 } ).attr("size") && jQuery.attrFn,
oldAttr = jQuery.attr,
valueAttrGet = jQuery.attrHooks.value && jQuery.attrHooks.value.get ||
function() { return null; },
valueAttrSet = jQuery.attrHooks.value && jQuery.attrHooks.value.set ||
function() { return undefined; },
rnoType = /^(?:input|button)$/i,
rnoAttrNodeType = /^[238]$/,
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
ruseDefault = /^(?:checked|selected)$/i;
// jQuery.attrFn
migrateWarnProp( jQuery, "attrFn", attrFn || {}, "jQuery.attrFn is deprecated" );
jQuery.attr = function( elem, name, value, pass ) {
var lowerName = name.toLowerCase(),
nType = elem && elem.nodeType;
if ( pass ) {
// Since pass is used internally, we only warn for new jQuery
// versions where there isn't a pass arg in the formal params
if ( oldAttr.length < 4 ) {
migrateWarn("jQuery.fn.attr( props, pass ) is deprecated");
}
if ( elem && !rnoAttrNodeType.test( nType ) &&
(attrFn ? name in attrFn : jQuery.isFunction(jQuery.fn[name])) ) {
return jQuery( elem )[ name ]( value );
}
}
// Warn if user tries to set `type`, since it breaks on IE 6/7/8; by checking
// for disconnected elements we don't warn on $( "<button>", { type: "button" } ).
if ( name === "type" && value !== undefined && rnoType.test( elem.nodeName ) && elem.parentNode ) {
migrateWarn("Can't change the 'type' of an input or button in IE 6/7/8");
}
// Restore boolHook for boolean property/attribute synchronization
if ( !jQuery.attrHooks[ lowerName ] && rboolean.test( lowerName ) ) {
jQuery.attrHooks[ lowerName ] = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
// Fall back to attribute presence where some booleans are not supported
var attrNode,
property = jQuery.prop( elem, name );
return property === true || typeof property !== "boolean" &&
( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
var propName;
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
// value is true since we know at this point it's type boolean and not false
// Set boolean attributes to the same name and set the DOM property
propName = jQuery.propFix[ name ] || name;
if ( propName in elem ) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = true;
}
elem.setAttribute( name, name.toLowerCase() );
}
return name;
}
};
// Warn only for attributes that can remain distinct from their properties post-1.9
if ( ruseDefault.test( lowerName ) ) {
migrateWarn( "jQuery.fn.attr('" + lowerName + "') may use property instead of attribute" );
}
}
return oldAttr.call( jQuery, elem, name, value );
};
// attrHooks: value
jQuery.attrHooks.value = {
get: function( elem, name ) {
var nodeName = ( elem.nodeName || "" ).toLowerCase();
if ( nodeName === "button" ) {
return valueAttrGet.apply( this, arguments );
}
if ( nodeName !== "input" && nodeName !== "option" ) {
migrateWarn("jQuery.fn.attr('value') no longer gets properties");
}
return name in elem ?
elem.value :
null;
},
set: function( elem, value ) {
var nodeName = ( elem.nodeName || "" ).toLowerCase();
if ( nodeName === "button" ) {
return valueAttrSet.apply( this, arguments );
}
if ( nodeName !== "input" && nodeName !== "option" ) {
migrateWarn("jQuery.fn.attr('value', val) no longer sets properties");
}
// Does not return so that setAttribute is also used
elem.value = value;
}
};
var matched, browser,
oldInit = jQuery.fn.init,
oldParseJSON = jQuery.parseJSON,
// Note this does NOT include the #9521 XSS fix from 1.7!
rquickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*|#([\w\-]*))$/;
// $(html) "looks like html" rule change
jQuery.fn.init = function( selector, context, rootjQuery ) {
var match;
if ( selector && typeof selector === "string" && !jQuery.isPlainObject( context ) &&
(match = rquickExpr.exec( selector )) && match[1] ) {
// This is an HTML string according to the "old" rules; is it still?
if ( selector.charAt( 0 ) !== "<" ) {
migrateWarn("$(html) HTML strings must start with '<' character");
}
// Now process using loose rules; let pre-1.8 play too
if ( context && context.context ) {
// jQuery object as context; parseHTML expects a DOM object
context = context.context;
}
if ( jQuery.parseHTML ) {
return oldInit.call( this, jQuery.parseHTML( jQuery.trim(selector), context, true ),
context, rootjQuery );
}
}
return oldInit.apply( this, arguments );
};
jQuery.fn.init.prototype = jQuery.fn;
// Let $.parseJSON(falsy_value) return null
jQuery.parseJSON = function( json ) {
if ( !json && json !== null ) {
migrateWarn("jQuery.parseJSON requires a valid JSON string");
return null;
}
return oldParseJSON.apply( this, arguments );
};
jQuery.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
// Don't clobber any existing jQuery.browser in case it's different
if ( !jQuery.browser ) {
matched = jQuery.uaMatch( navigator.userAgent );
browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
browser.webkit = true;
} else if ( browser.webkit ) {
browser.safari = true;
}
jQuery.browser = browser;
}
// Warn if the code tries to get jQuery.browser
migrateWarnProp( jQuery, "browser", jQuery.browser, "jQuery.browser is deprecated" );
jQuery.sub = function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
migrateWarn( "jQuery.sub() is deprecated" );
return jQuerySub;
};
// Ensure that $.ajax gets the new parseJSON defined in core.js
jQuery.ajaxSetup({
converters: {
"text json": jQuery.parseJSON
}
});
var oldFnData = jQuery.fn.data;
jQuery.fn.data = function( name ) {
var ret, evt,
elem = this[0];
// Handles 1.7 which has this behavior and 1.8 which doesn't
if ( elem && name === "events" && arguments.length === 1 ) {
ret = jQuery.data( elem, name );
evt = jQuery._data( elem, name );
if ( ( ret === undefined || ret === evt ) && evt !== undefined ) {
migrateWarn("Use of jQuery.fn.data('events') is deprecated");
return evt;
}
}
return oldFnData.apply( this, arguments );
};
var rscriptType = /\/(java|ecma)script/i,
oldSelf = jQuery.fn.andSelf || jQuery.fn.addBack;
jQuery.fn.andSelf = function() {
migrateWarn("jQuery.fn.andSelf() replaced by jQuery.fn.addBack()");
return oldSelf.apply( this, arguments );
};
// Since jQuery.clean is used internally on older versions, we only shim if it's missing
if ( !jQuery.clean ) {
jQuery.clean = function( elems, context, fragment, scripts ) {
// Set context per 1.8 logic
context = context || document;
context = !context.nodeType && context[0] || context;
context = context.ownerDocument || context;
migrateWarn("jQuery.clean() is deprecated");
var i, elem, handleScript, jsTags,
ret = [];
jQuery.merge( ret, jQuery.buildFragment( elems, context ).childNodes );
// Complex logic lifted directly from jQuery 1.8
if ( fragment ) {
// Special handling of each script element
handleScript = function( elem ) {
// Check if we consider it executable
if ( !elem.type || rscriptType.test( elem.type ) ) {
// Detach the script and store it in the scripts array (if provided) or the fragment
// Return truthy to indicate that it has been handled
return scripts ?
scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) :
fragment.appendChild( elem );
}
};
for ( i = 0; (elem = ret[i]) != null; i++ ) {
// Check if we're done after handling an executable script
if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) {
// Append to fragment and handle embedded scripts
fragment.appendChild( elem );
if ( typeof elem.getElementsByTagName !== "undefined" ) {
// handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration
jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript );
// Splice the scripts into ret after their former ancestor and advance our index beyond them
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
i += jsTags.length;
}
}
}
}
return ret;
};
}
var eventAdd = jQuery.event.add,
eventRemove = jQuery.event.remove,
eventTrigger = jQuery.event.trigger,
oldToggle = jQuery.fn.toggle,
oldLive = jQuery.fn.live,
oldDie = jQuery.fn.die,
ajaxEvents = "ajaxStart|ajaxStop|ajaxSend|ajaxComplete|ajaxError|ajaxSuccess",
rajaxEvent = new RegExp( "\\b(?:" + ajaxEvents + ")\\b" ),
rhoverHack = /(?:^|\s)hover(\.\S+|)\b/,
hoverHack = function( events ) {
if ( typeof( events ) !== "string" || jQuery.event.special.hover ) {
return events;
}
if ( rhoverHack.test( events ) ) {
migrateWarn("'hover' pseudo-event is deprecated, use 'mouseenter mouseleave'");
}
return events && events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
};
// Event props removed in 1.9, put them back if needed; no practical way to warn them
if ( jQuery.event.props && jQuery.event.props[ 0 ] !== "attrChange" ) {
jQuery.event.props.unshift( "attrChange", "attrName", "relatedNode", "srcElement" );
}
// Undocumented jQuery.event.handle was "deprecated" in jQuery 1.7
if ( jQuery.event.dispatch ) {
migrateWarnProp( jQuery.event, "handle", jQuery.event.dispatch, "jQuery.event.handle is undocumented and deprecated" );
}
// Support for 'hover' pseudo-event and ajax event warnings
jQuery.event.add = function( elem, types, handler, data, selector ){
if ( elem !== document && rajaxEvent.test( types ) ) {
migrateWarn( "AJAX events should be attached to document: " + types );
}
eventAdd.call( this, elem, hoverHack( types || "" ), handler, data, selector );
};
jQuery.event.remove = function( elem, types, handler, selector, mappedTypes ){
eventRemove.call( this, elem, hoverHack( types ) || "", handler, selector, mappedTypes );
};
jQuery.fn.error = function() {
var args = Array.prototype.slice.call( arguments, 0);
migrateWarn("jQuery.fn.error() is deprecated");
args.splice( 0, 0, "error" );
if ( arguments.length ) {
return this.bind.apply( this, args );
}
// error event should not bubble to window, although it does pre-1.7
this.triggerHandler.apply( this, args );
return this;
};
jQuery.fn.toggle = function( fn, fn2 ) {
// Don't mess with animation or css toggles
if ( !jQuery.isFunction( fn ) || !jQuery.isFunction( fn2 ) ) {
return oldToggle.apply( this, arguments );
}
migrateWarn("jQuery.fn.toggle(handler, handler...) is deprecated");
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
};
jQuery.fn.live = function( types, data, fn ) {
migrateWarn("jQuery.fn.live() is deprecated");
if ( oldLive ) {
return oldLive.apply( this, arguments );
}
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
};
jQuery.fn.die = function( types, fn ) {
migrateWarn("jQuery.fn.die() is deprecated");
if ( oldDie ) {
return oldDie.apply( this, arguments );
}
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
};
// Turn global events into document-triggered events
jQuery.event.trigger = function( event, data, elem, onlyHandlers ){
if ( !elem && !rajaxEvent.test( event ) ) {
migrateWarn( "Global events are undocumented and deprecated" );
}
return eventTrigger.call( this, event, data, elem || document, onlyHandlers );
};
jQuery.each( ajaxEvents.split("|"),
function( _, name ) {
jQuery.event.special[ name ] = {
setup: function() {
var elem = this;
// The document needs no shimming; must be !== for oldIE
if ( elem !== document ) {
jQuery.event.add( document, name + "." + jQuery.guid, function() {
jQuery.event.trigger( name, null, elem, true );
});
jQuery._data( this, name, jQuery.guid++ );
}
return false;
},
teardown: function() {
if ( this !== document ) {
jQuery.event.remove( document, name + "." + jQuery._data( this, name ) );
}
return false;
}
};
}
);
})( jQuery, window );

File diff suppressed because one or more lines are too long

44
lib/jquery/plugins.php Normal file
View File

@ -0,0 +1,44 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file describes jQuery plugins available in the Moodle
* core component. These can be included in page using:
* $PAGE->requires->jquery();
* $PAGE->requires->jquery_plugin('migrate');
* $PAGE->requires->jquery_plugin('ui');
* $PAGE->requires->jquery_plugin('ui-css');
*
* Please note that other moodle plugins can not use the same
* jquery plugin names, only one is loaded if collision detected.
*
* Any Moodle plugin may add jquery/plugins.php that defines extra
* jQuery plugins.
*
* Themes and other plugins may override any jquery plugin,
* for example to override default jQueryUI theme.
*
* @package core
* @copyright 2013 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$plugins = array(
'jquery' => array('files' => array('jquery-1.9.1.min.js')),
'migrate' => array('files' => array('jquery-migrate-1.1.1.min.js')),
'ui' => array('files' => array('ui-1.10.2/jquery-ui.min.js')),
'ui-css' => array('files' => array('ui-1.10.2/css/base/jquery-ui.min.css')),
);

View File

@ -0,0 +1,7 @@
Description of import of various jQuery libraries into Moodle:
1/ download jQuery JS and Migrate files from http://jquery.com/download/,
delete old files and edit plugins.php
2/ download jQuery UI files from http://jqueryui.com/download/all/,
delete old files and edit plugins.php

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 180 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 178 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 120 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 105 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 111 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 110 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 119 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

14987
lib/jquery/ui-1.10.2/jquery-ui.js vendored Normal file

File diff suppressed because it is too large Load Diff

12
lib/jquery/ui-1.10.2/jquery-ui.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -481,6 +481,20 @@ class theme_config {
$this->check_theme_arrows();
}
/**
* Let the theme initialise the page object (usually $PAGE).
*
* This may be used for example to request jQuery in add-ons.
*
* @param moodle_page $page
*/
public function init_page(moodle_page $page) {
$themeinitfunction = 'theme_'.$this->name.'_page_init';
if (function_exists($themeinitfunction)) {
$themeinitfunction($page);
}
}
/**
* Checks if arrows $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
* If not it applies sensible defaults.

View File

@ -757,6 +757,9 @@ class core_renderer extends renderer_base {
$this->page->add_body_class('userloggedinas');
}
// Give themes a chance to init/alter the page object.
$this->page->theme->init_page($this->page);
$this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
// Find the appropriate page layout file, based on $this->page->pagelayout.

View File

@ -145,6 +145,16 @@ class page_requirements_manager {
*/
protected $debug_moduleloadstacktraces = array();
/**
* @var array list of requested jQuery plugins
*/
protected $jqueryplugins = array();
/**
* @var array list of jQuery plugin overrides
*/
protected $jquerypluginoverrides = array();
/**
* Page requirements constructor.
*/
@ -316,6 +326,255 @@ class page_requirements_manager {
$this->jsincludes[$where][$url->out()] = $url;
}
/**
* Request inclusion of jQuery library in the page.
*
* NOTE: this should not be used in official Moodle distribution!
*
* We are going to bundle jQuery 1.9.x until we drop support
* all support for IE 6-8. Use $PAGE->requires->jquery_plugin('migrate')
* for code written for earlier jQuery versions.
*
* {@see http://docs.moodle.org/dev/jQuery}
*/
public function jquery() {
$this->jquery_plugin('jquery');
}
/**
* Request inclusion of jQuery plugin.
*
* NOTE: this should not be used in official Moodle distribution!
*
* jQuery plugins are located in plugin/jquery/* subdirectory,
* plugin/jquery/plugins.php lists all available plugins.
*
* Included core plugins:
* - jQuery UI
* - jQuery Migrate (useful for code written for previous UI version)
*
* Add-ons may include extra jQuery plugins in jquery/ directory,
* plugins.php file defines the mapping between plugin names and
* necessary page includes.
*
* Examples:
* <code>
* // file: mod/xxx/view.php
* $PAGE->requires->jquery();
* $PAGE->requires->jquery_plugin('ui');
* $PAGE->requires->jquery_plugin('ui-css');
* </code>
*
* <code>
* // file: theme/yyy/lib.php
* function theme_yyy_page_init(moodle_page $page) {
* $page->requires->jquery();
* $page->requires->jquery_plugin('ui');
* $page->requires->jquery_plugin('ui-css');
* }
* </code>
*
* <code>
* // file: blocks/zzz/block_zzz.php
* public function get_required_javascript() {
* parent::get_required_javascript();
* $this->page->requires->jquery();
* $page->requires->jquery_plugin('ui');
* $page->requires->jquery_plugin('ui-css');
* }
* </code>
*
* {@see http://docs.moodle.org/dev/jQuery}
*
* @param string $plugin name of the jQuery plugin as defined in jquery/plugins.php
* @param string $component name of the component
* @return bool success
*/
public function jquery_plugin($plugin, $component = 'core') {
global $CFG;
if ($this->headdone) {
debugging('Can not add jQuery plugins after starting page output!');
return false;
}
if ($component !== 'core' and in_array($plugin, array('jquery', 'ui', 'ui-css', 'migrate'))) {
debugging("jQuery plugin '$plugin' is included in Moodle core, other components can not use the same name.", DEBUG_DEVELOPER);
$component = 'core';
} else if ($component !== 'core' and strpos($component, '_') === false) {
// Let's normalise the legacy activity names, Frankenstyle rulez!
$component = 'mod_' . $component;
}
if (empty($this->jqueryplugins) and ($component !== 'core' or $plugin !== 'jquery')) {
// Make sure the jQuery itself is always loaded first,
// the order of all other plugins depends on order of $PAGE_>requires->.
$this->jquery_plugin('jquery', 'core');
}
if (isset($this->jqueryplugins[$plugin])) {
// No problem, we already have something, first Moodle plugin to register the jQuery plugin wins.
return true;
}
$componentdir = get_component_directory($component);
if (!file_exists($componentdir) or !file_exists("$componentdir/jquery/plugins.php")) {
debugging("Can not load jQuery plugin '$plugin', missing plugins.php in component '$component'.", DEBUG_DEVELOPER);
return false;
}
$plugins = array();
require("$componentdir/jquery/plugins.php");
if (!isset($plugins[$plugin])) {
debugging("jQuery plugin '$plugin' can not be found in component '$component'.", DEBUG_DEVELOPER);
return false;
}
$this->jqueryplugins[$plugin] = new stdClass();
$this->jqueryplugins[$plugin]->plugin = $plugin;
$this->jqueryplugins[$plugin]->component = $component;
$this->jqueryplugins[$plugin]->urls = array();
foreach ($plugins[$plugin]['files'] as $file) {
if (debugging('', DEBUG_DEVELOPER)) {
if (!file_exists("$componentdir/jquery/$file")) {
debugging("Invalid file '$file' specified in jQuery plugin '$plugin' in component '$component'");
continue;
}
$file = str_replace('.min.css', '.css', $file);
$file = str_replace('.min.js', '.js', $file);
}
if (!file_exists("$componentdir/jquery/$file")) {
debugging("Invalid file '$file' specified in jQuery plugin '$plugin' in component '$component'");
continue;
}
if (!empty($CFG->slasharguments)) {
$url = new moodle_url("$CFG->httpswwwroot/theme/jquery.php");
$url->set_slashargument("/$component/$file");
} else {
// This is not really good, we need slasharguments for relative links, this means no caching...
$path = realpath("$componentdir/jquery/$file");
if (strpos($path, $CFG->dirroot) === 0) {
$url = $CFG->httpswwwroot.preg_replace('/^'.preg_quote($CFG->dirroot, '/').'/', '', $path);
$url = new moodle_url($url);
} else {
// Bad luck, fix your server!
debugging("Moodle jQuery integration requires 'slasharguments' setting to be enabled.");
continue;
}
}
$this->jqueryplugins[$plugin]->urls[] = $url;
}
return true;
}
/**
* Request replacement of one jQuery plugin by another.
*
* This is useful when themes want to replace the jQuery UI theme,
* the problem is that theme can not prevent others from including the core ui-css plugin.
*
* Example:
* 1/ generate new jQuery UI theme and place it into theme/yourtheme/jquery/
* 2/ write theme/yourtheme/jquery/plugins.php
* 3/ init jQuery from theme
*
* <code>
* // file theme/yourtheme/lib.php
* function theme_yourtheme_page_init($page) {
* $page->requires->jquery_plugin('yourtheme-ui-css', 'theme_yourtheme');
* $page->requires->jquery_override_plugin('ui-css', 'yourtheme-ui-css');
* }
* </code>
*
* This code prevents loading of standard 'ui-css' which my be requested by other plugins,
* the 'yourtheme-ui-css' gets loaded only if some other code requires jquery.
*
* {@see http://docs.moodle.org/dev/jQuery}
*
* @param string $oldplugin original plugin
* @param string $newplugin the replacement
*/
public function jquery_override_plugin($oldplugin, $newplugin) {
if ($this->headdone) {
debugging('Can not override jQuery plugins after starting page output!');
return;
}
$this->jquerypluginoverrides[$oldplugin] = $newplugin;
}
/**
* Return jQuery related markup for page start.
* @return string
*/
protected function get_jquery_headcode() {
if (empty($this->jqueryplugins['jquery'])) {
// If nobody requested jQuery then do not bother to load anything.
// This may be useful for themes that want to override 'ui-css' only if requested by something else.
return '';
}
$included = array();
$urls = array();
foreach ($this->jqueryplugins as $name => $unused) {
if (isset($included[$name])) {
continue;
}
if (array_key_exists($name, $this->jquerypluginoverrides)) {
// The following loop tries to resolve the replacements,
// use max 100 iterations to prevent infinite loop resulting
// in blank page.
$cyclic = true;
$oldname = $name;
for ($i=0; $i<100; $i++) {
$name = $this->jquerypluginoverrides[$name];
if (!array_key_exists($name, $this->jquerypluginoverrides)) {
$cyclic = false;
break;
}
}
if ($cyclic) {
// We can not do much with cyclic references here, let's use the old plugin.
$name = $oldname;
debugging("Cyclic overrides detected for jQuery plugin '$name'");
} else if (empty($name)) {
// Developer requested removal of the plugin.
continue;
} else if (!isset($this->jqueryplugins[$name])) {
debugging("Unknown jQuery override plugin '$name' detected");
$name = $oldname;
} else if (isset($included[$name])) {
// The plugin was already included, easy.
continue;
}
}
$plugin = $this->jqueryplugins[$name];
$urls = array_merge($urls, $plugin->urls);
$included[$name] = true;
}
$output = '';
$attributes = array('rel' => 'stylesheet', 'type' => 'text/css');
foreach ($urls as $url) {
if (preg_match('/\.js$/', $url)) {
$output .= html_writer::script('', $url);
} else if (preg_match('/\.css$/', $url)) {
$attributes['href'] = $url;
$output .= html_writer::empty_tag('link', $attributes) . "\n";
}
}
return $output;
}
/**
* This method was used to load YUI2 libraries into global scope,
* use YUI 2in3 instead. Every YUI2 module is represented as a yui2-*
@ -1067,6 +1326,9 @@ class page_requirements_manager {
// They should be cached well by the browser.
$output .= $this->get_yui3lib_headcode($page);
// Add hacked jQuery support, it is not intended for standard Moodle distribution!
$output .= $this->get_jquery_headcode();
// Now theme CSS + custom CSS in this specific order.
$output .= $this->get_css_code();

View File

@ -203,6 +203,27 @@
<version>3.9.0</version>
<licenseversion></licenseversion>
</library>
<library>
<location>jquery</location>
<name>jQuery</name>
<license>MIT</license>
<version>1.9.1</version>
<licenseversion></licenseversion>
</library>
<library>
<location>jquery</location>
<name>jQuery Migrate</name>
<license>MIT</license>
<version>1.1.1</version>
<licenseversion></licenseversion>
</library>
<library>
<location>jquery</location>
<name>jQuery UI</name>
<license>MIT</license>
<version>1.10.2</version>
<licenseversion></licenseversion>
</library>
<library>
<location>zend</location>
<name>Zend Framework</name>

158
theme/jquery.php Normal file
View File

@ -0,0 +1,158 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* jQuery serving script.
*
* Do not include jQuery scripts or CSS directly, always use
* $PAGE->requires->jquery() or $PAGE->requires->jquery_plugin('xx', 'yy').
*
* @package core
* @copyright 2013 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// Disable moodle specific debug messages and any errors in output,
// comment out when debugging or better look into error log!
define('NO_DEBUG_DISPLAY', true);
// We need just the values from config.php and minlib.php.
define('ABORT_AFTER_CONFIG', true);
require('../config.php'); // This stops immediately at the beginning of lib/setup.php.
if ($slashargument = min_get_slash_argument()) {
$path = ltrim($slashargument, '/');
} else {
$path = min_optional_param('file', '', 'SAFEPATH');
$path = ltrim($path, '/');
}
if (strpos($path, '/') === false) {
jquery_file_not_found();
}
list($component, $path) = explode('/', $path, 2);
if (empty($path) or empty($component)) {
jquery_file_not_found();
}
// Find the jQuery dir for this component.
if ($component === 'core') {
$componentdir = "$CFG->dirroot/lib";
} else if (strpos($component, 'theme_')) {
if (!empty($CFG->themedir)) {
$componentdir = "$CFG->themedir/$component";
} else {
$componentdir = "$CFG->dirroot/theme/$component";
}
} else {
define('ABORT_AFTER_CONFIG_CANCEL', true);
define('NO_MOODLE_COOKIES', true); // Session not used here.
define('NO_UPGRADE_CHECK', true); // Ignore upgrade check.
require("$CFG->dirroot/lib/setup.php");
$componentdir = get_component_directory($component);
}
if (!file_exists($componentdir) or !file_exists("$componentdir/jquery/plugins.php")) {
jquery_file_not_found();
}
$file = realpath("$componentdir/jquery/$path");
if (!$file or is_dir($file)) {
jquery_file_not_found();
}
$etag = sha1("$component/$path");
$lifetime = 60*60*24*120; // 120 days should be enough.
$pathinfo = pathinfo($path);
if (empty($pathinfo['extension'])) {
jquery_file_not_found();
}
$filename = $pathinfo['filename'].'.'.$pathinfo['extension'];
switch($pathinfo['extension']) {
case 'gif' : $mimetype = 'image/gif';
break;
case 'png' : $mimetype = 'image/png';
break;
case 'jpg' : $mimetype = 'image/jpeg';
break;
case 'jpeg' : $mimetype = 'image/jpeg';
break;
case 'ico' : $mimetype = 'image/vnd.microsoft.icon';
break;
case 'svg' : $mimetype = 'image/svg+xml';
break;
case 'js' : $mimetype = 'application/javascript';
break;
case 'css' : $mimetype = 'text/css';
break;
case 'php' : jquery_file_not_found();
break;
default : $mimetype = 'document/unknown';
}
if (!empty($_SERVER['HTTP_IF_NONE_MATCH']) || !empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
// We do not actually need to verify the etag value because these files
// never change, devs need to change file names on update!
header('HTTP/1.1 304 Not Modified');
header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
header('Cache-Control: public, max-age='.$lifetime);
header('Content-Type: '.$mimetype);
header('Etag: '.$etag);
die;
}
require_once("$CFG->dirroot/lib/xsendfilelib.php");
header('Etag: '.$etag);
header('Content-Disposition: inline; filename="'.$filename.'"');
header('Last-Modified: '. gmdate('D, d M Y H:i:s', filemtime($file)) .' GMT');
header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
header('Pragma: ');
header('Cache-Control: public, max-age='.$lifetime);
header('Accept-Ranges: none');
header('Content-Type: '.$mimetype);
if (xsendfile($file)) {
die;
}
if ($mimetype === 'text/css' or $mimetype === 'application/javascript') {
if (!min_enable_zlib_compression()) {
header('Content-Length: '.filesize($file));
}
} else {
// No need to compress images.
header('Content-Length: '.filesize($file));
}
readfile($file);
die;
function jquery_file_not_found() {
// Note: we can not disclose the exact file path here, sorry.
header('HTTP/1.0 404 not found');
die('File was not found, sorry.');
}