From 67799264f6c24dd99fd13ffff977b5fc9a12861a Mon Sep 17 00:00:00 2001 From: Tim Starling Date: Tue, 8 Sep 2009 02:04:31 +0000 Subject: [PATCH] * Fixed whitespace, indenting, line length. Ran stylize.php on the PHP files, did the JS ones by hand. * Fixed spelling, grammar, etc. in comments. Removed some unnecessary comments. * Other code style tweaks, e.g. removed some redundant brackets. * Renamed functions which were misspellings: runQuededFunctions -> runQueuedFunctions, setSwapableToLoading -> setSwappableToLoading, rewrite_for_oggHanlder -> rewrite_for_OggHandler, doProccessJsFile -> doProcessJsFile --- js2/editPage.js | 72 +- js2/mwEmbed/jsScriptLoader.php | 289 ++- js2/mwEmbed/mv_embed.js | 1564 +++++++++-------- js2/mwEmbed/php/jsAutoloadLocalClasses.php | 22 +- .../php/maintenance/mergeJavascriptMsg.php | 6 +- js2/mwEmbed/php/mv_embed_iframe.php | 29 +- js2/mwEmbed/php/noMediaWikiConfig.php | 49 +- js2/remoteMwEmbed.js | 114 +- js2/uploadPage.js | 169 +- 9 files changed, 1172 insertions(+), 1142 deletions(-) diff --git a/js2/editPage.js b/js2/editPage.js index f8f5edae11..a78c9723b1 100644 --- a/js2/editPage.js +++ b/js2/editPage.js @@ -1,48 +1,50 @@ /* - * js2 style replacement for mediaWiki edit.js + * JS2-style replacement for MediaWiki edit.js + * @todo port the rest of it to here */ -//setup configuration vars: -if(!mwAddMediaConfig) + +// Setup configuration vars +if( !mwAddMediaConfig ) var mwAddMediaConfig = { - 'profile':'mediawiki_edit', - 'target_textbox': '#wpTextbox1', - //note selections in the textbox will take over the default query + 'profile': 'mediawiki_edit', + 'target_textbox': '#wpTextbox1', + // Note: selections in the textbox will take over the default query 'default_query': wgTitle, - 'target_title':wgPageName, - //here we can setup the conten provider overides - 'cpconfig': {}, - - //the local wiki api url: + 'target_title': wgPageName, + // Here we can setup the content provider overrides + 'cpconfig': {}, + // The local wiki API URL: 'local_wiki_api_url': wgServer + wgScriptPath + '/api.php' }; -js2AddOnloadHook( function(){ - mwEditPageHelper.init(); +js2AddOnloadHook( function() { + mwEditPageHelper.init(); }); -var mwEditPageHelper = { - init:function(){ +var mwEditPageHelper = { + init: function() { var _this = this; - //@@todo check for new version of toolbar and via toolbar api: - - //kind of tricky would be nice to use a "loader" call here to avoid concurancy issues. - if( typeof $j.wikiEditor != 'undefined' ){ - setTimeout(function(){ - $j('.wikiEditor-ui [rel=file]').unbind().addMediaWiz( - mwAddMediaConfig - ); - },100 ); - }else{ - //add the add-media-wizard button for old toolbar: - $j('#toolbar').append(''); - $j('#btn-add-media-wiz').addMediaWiz( - mwAddMediaConfig - ); + //@@todo check for a new version of the toolbar and via toolbar API + + // Kind of tricky, it would be nice to use a "loader" call here to avoid concurrency issues. + if( typeof $j.wikiEditor != 'undefined' ) { + setTimeout( function() { + $j( '.wikiEditor-ui [rel=file]' ).unbind().addMediaWiz( + mwAddMediaConfig + ); + }, 100 ); + } else { + // Add the add-media-wizard button for old toolbar: + $j( '#toolbar' ).append( '' ); + $j( '#btn-add-media-wiz' ).addMediaWiz( + mwAddMediaConfig + ); } - - //add to new toolbar (need to use api) - /*$j('[rel=insert] tool-file').addMediaWiz( - mwAddMediaConfig - );*/ + + // Add to new toolbar (need to use api) + /*$j( '[rel=insert] tool-file' ).addMediaWiz( + mwAddMediaConfig + );*/ } } diff --git a/js2/mwEmbed/jsScriptLoader.php b/js2/mwEmbed/jsScriptLoader.php index b44f64f885..0dc7758e71 100644 --- a/js2/mwEmbed/jsScriptLoader.php +++ b/js2/mwEmbed/jsScriptLoader.php @@ -3,155 +3,153 @@ * This core jsScriptLoader class provides the script loader functionality * @file */ -// check if we are being invoked in MediaWiki context or stand alone usage: -if ( !defined( 'MEDIAWIKI' ) ){ - // load noMediaWiki helper: +// Check if we are being invoked in a MediaWiki context or stand alone usage: +if ( !defined( 'MEDIAWIKI' ) ) { + // Load noMediaWiki helper require_once( realpath( dirname( __FILE__ ) ) . '/php/noMediaWikiConfig.php' ); - - // run the main action: $myScriptLoader = new jsScriptLoader(); - // preset request values via normal $_GET operation: $myScriptLoader->doScriptLoader(); } else { $wgExtensionMessagesFiles['mwEmbed'] = realpath( dirname( __FILE__ ) ) . '/php/mwEmbed.i18n.php'; } -// setup page output hook class jsScriptLoader { var $jsFileList = array(); var $jsout = ''; var $rKey = ''; // the request key var $error_msg = ''; var $debug = false; - var $jsvarurl = false; // if we should include generated js (special class '-') + var $jsvarurl = false; // whether we should include generated JS (special class '-') var $doProcReqFlag = true; - function doScriptLoader(){ + function doScriptLoader() { global $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses, $wgEnableScriptLoaderJsFile, $IP, $wgEnableScriptMinify, $wgUseFileCache; - // process the request + // Process the request $this->procRequestVars(); - // if cache is on and file is present grab it from there: - if( $wgUseFileCache && !$this->debug ) { - // setup file cache obj: + // If the cache is on and the file is present, grab it from there + if ( $wgUseFileCache && !$this->debug ) { + // Setup file cache object $this->sFileCache = new simpleFileCache( $this->rKey ); - if( $this->sFileCache->isFileCached() ){ - // just output headers so we can use php "efficient" readfile + if ( $this->sFileCache->isFileCached() ) { + // Just output headers so we can use PHP's "efficient" readfile $this->outputJsHeaders(); $this->sFileCache->outputFromFileCache(); die(); } } - // setup script loader header info + // Setup script loader header info $this->jsout .= 'var mwSlScript = "' . htmlspecialchars( $_SERVER['SCRIPT_NAME'] ) . '";' . "\n"; - $this->jsout .= 'var mwSlGenISODate = "' . date( 'c' ) . '";' ."\n"; - $this->jsout .= 'var mwSlURID = "' . htmlspecialchars( $this->urid ) . '";' ."\n"; - // Build the output: - // swap in the appropriate language per js_file - foreach( $this->jsFileList as $classKey => $file_name ){ - - // special case: - title classes: - if( substr( $classKey, 0, 3 ) == 'WT:' ){ + $this->jsout .= 'var mwSlGenISODate = "' . date( 'c' ) . '";' . "\n"; + $this->jsout .= 'var mwSlURID = "' . htmlspecialchars( $this->urid ) . '";' . "\n"; + // Build the output + + // Swap in the appropriate language per js_file + foreach ( $this->jsFileList as $classKey => $file_name ) { + // Special case: title classes + if ( substr( $classKey, 0, 3 ) == 'WT:' ) { global $wgUser; - // get just the tile part: + // Get just the title part $title_block = substr( $classKey, 3 ); - if( $title_block[0] == '-' && strpos( $title_block, '|' ) !== false ){ - // special case of "-" title with skin + if ( $title_block[0] == '-' && strpos( $title_block, '|' ) !== false ) { + // Special case of "-" title with skin $parts = explode( '|', $title_block ); $title = array_shift( $parts ); - foreach( $parts as $tparam ){ + foreach ( $parts as $tparam ) { list( $key, $val ) = explode( '=', $tparam ); - if( $key == 'useskin' ){ + if ( $key == 'useskin' ) { $skin = $val; } } $sk = $wgUser->getSkin(); - // make sure the skin name is valid + // Make sure the skin name is valid $skinNames = Skin::getSkinNames(); - // get the lower case skin name (array keys) $skinNames = array_keys( $skinNames ); - if( in_array( strtolower( $skin ), $skinNames ) ){ + if ( in_array( strtolower( $skin ), $skinNames ) ) { $this->jsout .= $sk->generateUserJs( $skin ) . "\n"; - // success continue: + // success continue; } } else { - //make sure the wiki title ends with .js - if( substr( $title_block, -3 ) != '.js'){ + // Make sure the wiki title ends with .js + if ( substr( $title_block, - 3 ) != '.js' ) { $this->error_msg .= 'WikiTitle includes should end with .js'; continue; } - // it's a wikiTitle append the output of the wikitext: + // It's a wiki title, append the output of the wikitext: $t = Title::newFromText( $title_block ); $a = new Article( $t ); - // only get content if the page is not empty: - if( $a->getID() !== 0 ){ + // Only get the content if the page is not empty: + if ( $a->getID() !== 0 ) { $this->jsout .= $a->getContent() . "\n"; } continue; } } - //dealing with files:: - //check that the filename ends with .js and does not include ../ traversing - if( substr( $file_name, -3 ) != '.js'){ - $this->error_msg .= "\nError file name must end with .js: ". htmlspecialchars( $file_name ) . " \n "; + + // Dealing with files + + // Check that the filename ends with .js and does not include ../ traversing + if ( substr( $file_name, - 3 ) != '.js' ) { + $this->error_msg .= "\nError file name must end with .js: " . htmlspecialchars( $file_name ) . " \n "; continue; } - if( strpos($file_name, '../') !== false ){ - $this->error_msg .= "\nError file name must not traverse paths: ". htmlspecialchars( $file_name ) . " \n "; + if ( strpos( $file_name, '../' ) !== false ) { + $this->error_msg .= "\nError file name must not traverse paths: " . htmlspecialchars( $file_name ) . " \n "; continue; } - if( trim( $file_name ) != '' ){ - // if in debug add a comment with the file name: - if( $this->debug ) + if ( trim( $file_name ) != '' ) { + // If in debug mode, add a comment with the file name + if ( $this->debug ) $this->jsout .= "\n/** -* File: ". htmlspecialchars( $file_name ) ." +* File: " . htmlspecialchars( $file_name ) . " */\n"; - $this->jsout .= ( $this->doProccessJsFile( $file_name ) ) . "\n"; + $this->jsout .= ( $this->doProcessJsFile( $file_name ) ) . "\n"; } } - // check if we should minify : - if( $wgEnableScriptMinify && !$this->debug ){ + // Check if we should minify + if ( $wgEnableScriptMinify && !$this->debug ) { // do the minification and output - $this->jsout = JSMin::minify( $this->jsout); + $this->jsout = JSMin::minify( $this->jsout ); } - // save to the file cache: - if( $wgUseFileCache && !$this->debug ) { + // Save to the file cache + if ( $wgUseFileCache && !$this->debug ) { $status = $this->sFileCache->saveToFileCache( $this->jsout ); - if( $status !== true ) - $this->error_msg.= $status; + if ( $status !== true ) + $this->error_msg .= $status; } - // check for error msg: - if( $this->error_msg != ''){ - echo 'alert(\'Error With ScriptLoader.php ::' . str_replace( "\n", '\'+"\n"+'."\n'", $this->error_msg ) . '\');'; + // Check for an error msg + if ( $this->error_msg != '' ) { + echo 'alert(\'Error With ScriptLoader.php ::' . str_replace( "\n", '\'+"\n"+' . "\n'", $this->error_msg ) . '\');'; echo trim( $this->jsout ); } else { - // all good lets output cache forever headers: + // All good, let's output "cache forever" headers $this->outputJsWithHeaders(); } } - function outputJsHeaders(){ + function outputJsHeaders() { global $wgJsMimeType; - // output js mime type: - header( 'Content-type: ' . $wgJsMimeType ); + // Output JS MIME type: + header( 'Content-Type: ' . $wgJsMimeType ); header( 'Pragma: public' ); - // cache forever: - // (the point is we never have to revalidate since we should always change the request url based on the svn or article version) - $one_year = 60*60*24*365; + // Cache forever + // The point is we never have to revalidate, since we should always change the request URL + // based on the SVN or article version. + $one_year = 60 * 60 * 24 * 365; header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + $one_year ) . " GM" ); } - function outputJsWithHeaders(){ + function outputJsWithHeaders() { global $wgUseGzip; $this->outputJsHeaders(); - if( $wgUseGzip ) { - if( wfClientAcceptsGzip() ) { + if ( $wgUseGzip ) { + if ( wfClientAcceptsGzip() ) { header( 'Content-Encoding: gzip' ); echo gzencode( $this->jsout ); } else { @@ -163,115 +161,116 @@ class jsScriptLoader { } /** - * updates the proc Request + * Process request variables and load them into $this */ - function procRequestVars(){ + function procRequestVars() { global $wgContLanguageCode, $wgEnableScriptMinify, $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses, $wgStyleVersion, $wgEnableScriptLoaderJsFile; - // set debug flag: - if( ( isset( $_GET['debug'] ) && $_GET['debug'] == 'true' ) || ( isset( $wgEnableScriptDebug ) && $wgEnableScriptDebug == true ) ){ + // Set debug flag + if ( ( isset( $_GET['debug'] ) && $_GET['debug'] == 'true' ) || ( isset( $wgEnableScriptDebug ) && $wgEnableScriptDebug == true ) ) { $this->debug = true; } - // set the urid: (be sure to escape it as it goes into our js output) - if( isset( $_GET['urid'] ) && $_GET['urid'] !=''){ + // Set the urid. Be sure to escape it as it goes into our JS output. + if ( isset( $_GET['urid'] ) && $_GET['urid'] != '' ) { $this->urid = htmlspecialchars( $_GET['urid'] ); } else { - // just give it the current style sheet id: + // Just give it the current style sheet ID: // @@todo read the svn version number $this->urid = $wgStyleVersion; } $reqClassList = false; - if( isset( $_GET['class'] ) && $_GET['class'] != '' ){ + if ( isset( $_GET['class'] ) && $_GET['class'] != '' ) { $reqClassList = explode( ',', $_GET['class'] ); } - // check for the requested classes - if( $reqClassList ){ - // clean the class list and populate jsFileList - foreach( $reqClassList as $reqClass ){ - if( trim( $reqClass ) != '' ){ - // check for special case '-' class for user generated js - if( substr( $reqClass, 0, 3 ) == 'WT:' ){ + // Check for the requested classes + if ( $reqClassList ) { + // Clean the class list and populate jsFileList + foreach ( $reqClassList as $reqClass ) { + if ( trim( $reqClass ) != '' ) { + // Check for special case '-' class for user-generated JS + if ( substr( $reqClass, 0, 3 ) == 'WT:' ) { $this->jsFileList[$reqClass] = true; $this->rKey .= $reqClass; $this->jsvarurl = true; continue; } - $reqClass = preg_replace("/[^A-Za-z0-9_\-\.]/", '', $reqClass ); + $reqClass = preg_replace( "/[^A-Za-z0-9_\-\.]/", '', $reqClass ); - if( isset( $wgJSAutoloadLocalClasses[$reqClass] ) ){ + if ( isset( $wgJSAutoloadLocalClasses[$reqClass] ) ) { $this->jsFileList[$reqClass] = $wgJSAutoloadLocalClasses[$reqClass]; - $this->rKey.= $reqClass; - } else if( isset( $wgJSAutoloadClasses[$reqClass] ) ) { + $this->rKey .= $reqClass; + } else if ( isset( $wgJSAutoloadClasses[$reqClass] ) ) { $this->jsFileList[$reqClass] = $wgJSAutoloadClasses[$reqClass]; - $this->rKey.= $reqClass; + $this->rKey .= $reqClass; } else { - $this->error_msg.= 'Requested class: ' . htmlspecialchars( $reqClass ) . ' not found' . "\n"; + $this->error_msg .= 'Requested class: ' . htmlspecialchars( $reqClass ) . ' not found' . "\n"; } } } } - // check for requested files if enabled: - if( $wgEnableScriptLoaderJsFile ){ - if( isset( $_GET['files'] ) ){ + // Check for requested files, if enabled + if ( $wgEnableScriptLoaderJsFile ) { + if ( isset( $_GET['files'] ) ) { $reqFileList = explode( ',', isset( $_GET['files'] ) ); - // clean the file list and populate jsFileList - foreach( $reqFileList as $reqFile ){ - // no jumping dirs: + // Clean the file list and populate jsFileList + foreach ( $reqFileList as $reqFile ) { + // No jumping dirs $reqFile = str_replace( '../', '', $reqFile ); - // only allow alphanumeric underscores periods and ending with .js + // Only allow alphanumeric underscores periods and ending with .js $reqFile = ereg_replace( "[^A-Za-z0-9_\-\/\.]", '', $reqFile ); - if( substr( $reqFile, -3 ) == '.js' ){ - // don't add it twice: - if( !in_array( $reqFile, $jsFileList ) ) { + if ( substr( $reqFile, - 3 ) == '.js' ) { + // Don't add it twice: + if ( !in_array( $reqFile, $jsFileList ) ) { $this->jsFileList[] = $IP . $reqFile; - $this->rKey.= $reqFile; + $this->rKey .= $reqFile; } } else { - $this->error_msg.= 'Not valid requsted JavaScript file' . "\n"; + $this->error_msg .= 'Not valid requsted JavaScript file' . "\n"; } } } } - // add the language code to the rKey: + // Add the language code to the rKey: $this->rKey .= '_' . $wgContLanguageCode; - // add the unique rid to the rKey + // Add the unique rid $this->rKey .= $this->urid; - // add a min flag: - if( $wgEnableScriptMinify ){ - $this->rKey.= '_min'; + // Add a minify flag + if ( $wgEnableScriptMinify ) { + $this->rKey .= '_min'; } } - function doProccessJsFile( $file_name ){ + function doProcessJsFile( $file_name ) { global $IP, $wgEnableScriptLocalization, $IP; - // load the file: + // Load the file $str = @file_get_contents( "{$IP}/{$file_name}" ); - if( $str === false ){ - // @@todo check php error level (don't want to expose paths if errors are hidden) - $this->error_msg.= 'Requested File: ' . htmlspecialchars( $file_name ) . ' could not be read' . "\n"; + if ( $str === false ) { + // @@todo check PHP error level. Don't want to expose paths if errors are hidden. + $this->error_msg .= 'Requested File: ' . htmlspecialchars( $file_name ) . ' could not be read' . "\n"; return ''; } $this->cur_file = $file_name; - // strip out js_log debug lines not much luck with this regExp yet: - //if( !$this->debug ) + // Strip out js_log debug lines. Not much luck with this regExp yet: + // if( !$this->debug ) // $str = preg_replace('/\n\s*js_log\s*\([^\)]([^;]|\n])*;/', "\n", $str); - // do language swap - if( $wgEnableScriptLocalization ) + // Do language swap + if ( $wgEnableScriptLocalization ) $str = preg_replace_callback( - '/loadGM\s*\(\s*{(.*)}\s*\)\s*/siU', // @@todo fix: will break down if someone does }) in their msg text + // @@todo fix: will break down if someone does }) in their msg text + '/loadGM\s*\(\s*{(.*)}\s*\)\s*/siU', array( $this, 'languageMsgReplace' ), $str ); @@ -279,28 +278,28 @@ class jsScriptLoader { return $str; } - function languageMsgReplace( $jvar ){ - if( !isset( $jvar[1] ) ) + function languageMsgReplace( $jvar ) { + if ( !isset( $jvar[1] ) ) return; $jmsg = json_decode( '{' . $jvar[1] . '}', true ); - // do the language lookup: - if( $jmsg ){ - foreach( $jmsg as $msgKey => $default_en_value ){ + // Do the language lookup + if ( $jmsg ) { + foreach ( $jmsg as $msgKey => $default_en_value ) { $jmsg[$msgKey] = wfMsgNoTrans( $msgKey ); } - //return the updated loadGM json with fixed new lines: + // Return the updated loadGM JSON with fixed new lines return 'loadGM( ' . json_encode( $jmsg ) . ')'; } else { - $this->error_msg.= "Could not parse JSON language msg in File:\n" . + $this->error_msg .= "Could not parse JSON language msg in File:\n" . htmlspecialchars ( $this->cur_file ) . "\n"; } - // could not parse json (throw error?) + // Could not parse JSON (throw error?) return $jvar[0]; } } -//a simple version of HTMLFileCache (@@todo abstract shared pieces) +// A simple version of HTMLFileCache (@@todo abstract shared pieces) class simpleFileCache { var $mFileCache; var $filename = null; @@ -308,12 +307,12 @@ class simpleFileCache { public function __construct( &$rKey ) { $this->rKey = $rKey; - $this->filename = $this->fileCacheName(); // init name + $this->filename = $this->fileCacheName(); } public function fileCacheName() { global $wgUseGzip; - if( !$this->mFileCache ) { + if ( !$this->mFileCache ) { global $wgFileCacheDirectory; $hash = md5( $this->rKey ); @@ -324,7 +323,7 @@ class simpleFileCache { $hash2 = substr( $hash, 0, 2 ); $this->mFileCache = "{$wgFileCacheDirectory}/{$hash1}/{$hash2}/{$this->rKey}.js"; - if( $wgUseGzip ) + if ( $wgUseGzip ) $this->mFileCache .= '.gz'; wfDebug( " fileCacheName() - {$this->mFileCache}\n" ); @@ -336,50 +335,50 @@ class simpleFileCache { return file_exists( $this->filename ); } - public function outputFromFileCache(){ + public function outputFromFileCache() { global $wgUseGzip; - if( $wgUseGzip ) { - if( wfClientAcceptsGzip() ) { + if ( $wgUseGzip ) { + if ( wfClientAcceptsGzip() ) { header( 'Content-Encoding: gzip' ); readfile( $this->filename ); } else { - /* Send uncompressed (check if fileCache is in compressed state (ends with .gz) - * (unlikely to execute this since $wgUseGzip would have created a new file above.. but just in case: + /* Send uncompressed. Check if fileCache is in compressed state (ends with .gz) + * We're unlikely to execute this since $wgUseGzip would have created a new file + * above, but just in case. */ - if( substr( $this->filename, -3 ) == '.gz' ){ + if ( substr( $this->filename, - 3 ) == '.gz' ) { readgzfile( $this->filename ); } else { readfile( $this->filename ); } } } else { - // just output the file + // Just output the file readfile( $this->filename ); } - //return true return true; } public function saveToFileCache( &$text ) { global $wgUseFileCache, $wgUseGzip; - if( !$wgUseFileCache ) { + if ( !$wgUseFileCache ) { return 'Error: Called saveToFileCache with $wgUseFileCache off'; } - if( strcmp( $text, '' ) == 0 ) return 'saveToFileCache: empty output file'; + if ( strcmp( $text, '' ) == 0 ) return 'saveToFileCache: empty output file'; - // check the directories if we could not create them error out: + // Check the directories. If we could not create them, error out. $status = $this->checkCacheDirs(); - if( $wgUseGzip ){ + if ( $wgUseGzip ) { $outputText = gzencode( trim( $text ) ); } else { $outputText = trim( $text ); } - if( $status !== true ) + if ( $status !== true ) return $status; $f = fopen( $this->filename, 'w' ); - if( $f ) { + if ( $f ) { fwrite( $f, $outputText ); fclose( $f ); } else { @@ -392,10 +391,10 @@ class simpleFileCache { $mydir2 = substr( $this->filename, 0, strrpos( $this->filename, '/' ) ); # subdirectory level 2 $mydir1 = substr( $mydir2, 0, strrpos( $mydir2, '/' ) ); # subdirectory level 1 - if( wfMkdirParents( $mydir1 ) === false || wfMkdirParents( $mydir2 ) === false ){ + if ( wfMkdirParents( $mydir1 ) === false || wfMkdirParents( $mydir2 ) === false ) { return 'Could not create cache directory. Check your cache directory permissions?'; } else { return true; } } -} \ No newline at end of file +} diff --git a/js2/mwEmbed/mv_embed.js b/js2/mwEmbed/mv_embed.js index 97e26bd553..997ca6eed0 100644 --- a/js2/mwEmbed/mv_embed.js +++ b/js2/mwEmbed/mv_embed.js @@ -1,31 +1,31 @@ /* * ~mv_embed ~ - * for details see: http://metavid.org/wiki/index.php/Mv_embed + * For details see: http://metavid.org/wiki/index.php/Mv_embed * - * All Metavid Wiki code is Released under the GPL2 - * for more info visit http://metavid.org/wiki/Code + * All Metavid Wiki code is released under the GPL2. + * For more information visit http://metavid.org/wiki/Code * * @url http://metavid.org * * parseUri: * http://stevenlevithan.com/demo/parseuri/js/ * - * config values you can manually set the location of the mv_embed folder here + * Config values: you can manually set the location of the mv_embed folder here * (in cases where media will be hosted in a different place than the embedding page) * */ -//fix multiple instances of mv_embed (ie include twice from two different servers) +// Fix multiple instances of mv_embed (i.e. include twice from two different servers) var MV_DO_INIT=true; if( MV_EMBED_VERSION ){ MV_DO_INIT=false; } -//used to grab fresh copies of scripts. (should be changed on commit) +// Used to grab fresh copies of scripts. (should be changed on commit) var MV_EMBED_VERSION = '1.0r19'; /* - * Configuration variables (can be set from some precceding script) - * set up mwConfig global overide any of the defaultMwConfig values: - * @@ more config valuse on the way ;) + * Configuration variables (can be set from some preceding script). + * Set up mwConfig global, override any of the defaultMwConfig values: + * @@ more config values on the way ;) */ var defaultMwConfig = { 'skin_name': 'mvpcf', @@ -33,52 +33,54 @@ var defaultMwConfig = { 'video_size':'400x300' } -if(!mwConfig) - var mwConfig = {}; +if( !mwConfig ) + var mwConfig = {}; -//install the default config values for anything not set in mwConfig +// Install the default config values for anything not set in mwConfig checkDefaultMwConfig(); -//whether or not to load java from an iframe. -//note: this is necessary for remote embedding because of java security model) -if(!mv_java_iframe) +// Whether or not to load java from an iframe. +// Note: this is necessary for remote embedding because of Java's security model) +if( !mv_java_iframe ) var mv_java_iframe = true; -//for when useing mv_embed with script-loader in root mediawiki path +// For use when mv_embed with script-loader is in the root MediaWiki path var mediaWiki_mvEmbed_path = 'js2/mwEmbed/'; -var global_player_list = new Array(); //the global player list per page -var global_req_cb = new Array(); //the global request callback array -var _global = this; //global obj +var global_player_list = new Array(); // The global player list per page +var global_req_cb = new Array(); // The global request callback array +var _global = this; // Global obj var mv_init_done = false; -var global_cb_count =0; +var global_cb_count = 0; /*parseUri class parses URIs:*/ var parseUri=function(d){var o=parseUri.options,value=o.parser[o.strictMode?"strict":"loose"].exec(d);for(var i=0,uri={};i<14;i++){uri[o.key[i]]=value[i]||""}uri[o.q.name]={};uri[o.key[12]].replace(o.q.parser,function(a,b,c){if(b)uri[o.q.name][b]=c});return uri};parseUri.options={strictMode:false,key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}}; -//get mv_embed location if it has not been set -if( !mv_embed_path ){ +// Get the mv_embed location if it has not been set +if( !mv_embed_path ) { var mv_embed_path = getMvEmbedPath(); } -//setup the skin path: +// Set up the skin path var mv_jquery_skin_path = mv_embed_path + 'jquery/jquery.ui/themes/' +mwConfig['jui_skin'] + '/'; var mv_skin_img_path = mv_embed_path + 'skins/' + mwConfig['skin_name'] + '/images/'; var mv_default_thumb_url = mv_skin_img_path + 'vid_default_thumb.jpg'; -//init the global Msg if not already -if(!gMsg){var gMsg={};} +// Init the global message table if it has not been initialised already +if( !gMsg ) { + var gMsg = {}; +} -//laguage msg loader: -function loadGM( msgSet ){ - for(var i in msgSet){ +// Language msg loader +function loadGM( msgSet ) { + for( var i in msgSet ) { gMsg[ i ] = msgSet[i]; } } -//all default msg in [English] should be overwritten by the CMS language msg system. +// All default messages in [English] should be overwritten by the CMS language message system. loadGM({ "mwe-loading_txt" : "loading ...<\/blink>", "mwe-loading_title" : "Loading...", @@ -90,36 +92,36 @@ loadGM({ /** * AutoLoader paths (this should mirror the file: jsAutoloadLocalClasses.php ) - * any file _not_ listed here won't be auto-loadable - * @path the path to the file (or set of files) with ending slash - * @gClasses the set of classes - * if an array $j.className become jquery.className.js - * if an asssociative object then key => value paris are used + * Any file _not_ listed here won't be auto-loadable + * @path The path to the file (or set of files) with ending slash + * @gClasses The set of classes + * if it's an array, $j.className becomes jquery.className.js + * if it's an associative object then key => value pairs are used */ -if(typeof mvAutoLoadClasses == 'undefined') +if( typeof mvAutoLoadClasses == 'undefined' ) mvAutoLoadClasses = {}; -//the script that loads the classet -function lcPaths( classSet){ - for(var i in classSet){ +// The script that loads the class set +function lcPaths( classSet ){ + for( var i in classSet ) { mvAutoLoadClasses[i] = classSet[i]; } } function mvGetClassPath(k){ - if( mvAutoLoadClasses[k] ){ - //js_log('got classpath:' + k + ' : '+ mvClassPaths[k]); + if( mvAutoLoadClasses[k] ) { + //js_log('got class path:' + k + ' : '+ mvClassPaths[k]); return mvAutoLoadClasses[k]; - }else{ + } else { return js_error('could not find path for requested class ' + k ); } } -if(typeof mvCssPaths == 'undefined') +if( typeof mvCssPaths == 'undefined' ) mvCssPaths = {}; -function lcCssPath(cssSet){ - for(var i in cssSet){ - mvCssPaths[i]= mv_embed_path + cssSet[i]; +function lcCssPath( cssSet ) { + for( var i in cssSet ) { + mvCssPaths[i] = mv_embed_path + cssSet[i]; } } @@ -127,15 +129,16 @@ function lcCssPath(cssSet){ * -- Load Class Paths -- * * MUST BE VALID JSON (NOT JS) - * is used by the scriptloader to autoLoad classes (so we only define this once for php & javascript) + * This is used by the script loader to auto-load classes (so we only define + * this once for PHP & JavaScript) * - * this is more verbose than earlier version that compressed paths - * but its all good gziping help compress repetative path strings - * grouped by + * This is more verbose than the earlier version that compressed paths + * but it's all good, gzipping helps compress repetetive path strings + * grouped by directory. * - * right now php AutoLoader only reads this mv_embed.js file - * in the future we could have multiple lcPath calls that php reads - * (if our autoloading class list becomes too long) just have to add thouse + * Right now the PHP AutoLoader only reads this mv_embed.js file. + * In the future we could have multiple lcPath calls that PHP reads + * (if our autoloading class list becomes too long) just have to add those * files to the jsAutoLoader file list. */ lcPaths({ @@ -185,7 +188,7 @@ lcPaths({ "mvFirefogg" : "libAddMedia/mvFirefogg.js", "mvAdvFirefogg" : "libAddMedia/mvAdvFirefogg.js", - "mvBaseUploadInterface" : "libAddMedia/mvBaseUploadInterface.js", + "mvBaseUploadInterface" : "libAddMedia/mvBaseUploadInterface.js", "remoteSearchDriver" : "libAddMedia/remoteSearchDriver.js", "seqRemoteSearchDriver" : "libAddMedia/seqRemoteSearchDriver.js", @@ -215,7 +218,7 @@ lcPaths({ }); -//depencency mapping for css files for self contained included plugins: +// Dependency mapping for CSS files for self-contained included plugins: lcCssPath({ '$j.Jcrop' : 'libClipEdit/Jcrop/css/jquery.Jcrop.css', '$j.fn.ColorPicker' : 'libClipEdit/colorpicker/css/colorpicker.css' @@ -224,59 +227,59 @@ lcCssPath({ /** * Language Functions: * - * These functions try to losely mirro the functionality of Language.php in mediaWiki + * These functions try to loosely mirror the functionality of Language.php in MediaWiki */ function gM( key , args ) { - var ms =''; + var ms = ''; if ( key in gMsg ) { ms = gMsg[ key ]; - if(typeof args == 'object' || typeof args == 'array'){ - for(var v in args){ - //msg test replace arguments start at 1 insted of zero: - var rep = '\$'+ ( parseInt(v) + 1 ); - ms = ms.replace( rep, args[v]); - } - }else if(typeof args =='string' || typeof args =='number'){ + if( typeof args == 'object' || typeof args == 'array' ) { + for( var v in args ) { + // Message test replace arguments start at 1 instead of zero: + var rep = '\$'+ ( parseInt(v) + 1 ); + ms = ms.replace( rep, args[v] ); + } + } else if( typeof args =='string' || typeof args =='number' ) { ms = ms.replace(/\$1/, args); - } - return ms; - } else{ - //key is missing return indication: + } + return ms; + } else { + // Missing key placeholder return '<' + key + '>'; } } /* - * msgSet is either a string corresponding to a single msg to load - * or msgSet is an array with set of msg to load + * msgSet is either a string corresponding to a single message to load, or an + * array with a set of messages to load. */ -function gMsgLoadRemote(msgSet, callback){ +function gMsgLoadRemote( msgSet, callback ) { var ammessages = ''; - if(typeof msgSet == 'object' ){ - for(var i in msgSet){ - ammessages += msgSet[i] + '|'; + if( typeof msgSet == 'object' ) { + for( var i in msgSet ) { + ammessages += msgSet[i] + '|'; } - }else if(typeof msgSet == 'string'){ + } else if( typeof msgSet == 'string' ) { ammessages += msgSet; } - if(ammessages == ''){ - js_log('gMsgLoadRemote::no msg set requested'); + if( ammessages == '' ) { + js_log( 'gMsgLoadRemote: no message set requested' ); return false; } do_api_req({ - 'data':{ - 'meta':'allmessages', - 'ammessages':ammessages + 'data': { + 'meta': 'allmessages', + 'ammessages': ammessages } - },function(data){ - if(data.query.allmessages){ + }, function( data ) { + if( data.query.allmessages ) { var msgs = data.query.allmessages; - for(var i in msgs){ + for( var i in msgs ) { var ld = {}; - ld[ msgs[i]['name'] ] = msgs[i]['*']; + ld[ msgs[i]['name'] ] = msgs[i]['*']; loadGM( ld ); } } - //load the result into local msg var + // Load the result into local msg var callback(); }); } @@ -289,7 +292,7 @@ function gMsgLoadRemote(msgSet, callback){ * @return string Plain text (not HTML) */ function formatSize( size ) { - // For small sizes no decimal places necessary + // For small sizes no decimal places are necessary var round = 0; var msg = ''; if( size > 1024 ) { @@ -310,15 +313,15 @@ function formatSize( size ) { } else { msg = 'mwe-size-bytes'; } - //javascript does not let you do precession points in rounding - var p = Math.pow(10,round); - var size = Math.round( size * p ) / p; + // JavaScript does not let you choose the precision when rounding + var p = Math.pow(10,round); + var size = Math.round( size * p ) / p; //@@todo we need a formatNum and we need to request some special packaged info to deal with that case. - return gM( msg , size ); + return gM( msg , size ); } -//gets the loading image: -function mv_get_loading_img( style , class_attr ){ +// Get the loading image +function mv_get_loading_img( style, class_attr ){ var style_txt = (style)?style:''; var class_attr = (class_attr)?'class="'+class_attr+'"':'class="mv_loading_img"'; return '
'; @@ -335,172 +338,182 @@ function mv_set_loading(target, load_id){ /** * mvJsLoader class handles initialization and js file loads */ - -//shortcut: -function mwLoad(loadSet, callback){ - mvJsLoader.doLoad(loadSet, callback); -} + +// Shortcut +function mwLoad( loadSet, callback ) { + mvJsLoader.doLoad( loadSet, callback ); +} var mvJsLoader = { - libreq : {}, - libs : {}, - //base lib flags: - onReadyEvents:new Array(), - doneReadyEvents:false, - jQueryCheckFlag:false, - //to keep consistency across threads: - ptime:0, - ctime:0, - load_error:false, //load error flag (false by default) - load_time:0, - callbacks:new Array(), - cur_path: null, - missing_path : null, - doLoad:function(loadLibs, callback){ - this.ctime++; - if( loadLibs && loadLibs.length!=0 ){ //setup this.libs: - - //first check if we already have this lib loaded - var all_libs_loaded=true; - for(var i=0; i< loadLibs.length; i++){ - //check if the lib is already loaded: - if( ! this.checkObjPath( loadLibs[i] ) ){ - all_libs_loaded=false; + libreq : {}, + libs : {}, + + // Base lib flags + onReadyEvents: new Array(), + doneReadyEvents: false, + jQueryCheckFlag: false, + + // To keep consistency across threads + ptime: 0, + ctime: 0, + + load_error: false, // Load error flag (false by default) + load_time: 0, + callbacks: new Array(), + cur_path: null, + missing_path : null, + doLoad: function( loadLibs, callback ) { + this.ctime++; + + if( loadLibs && loadLibs.length != 0 ) { + // Set up this.libs + // First check if we already have this library loaded + var all_libs_loaded = true; + for( var i = 0; i< loadLibs.length; i++ ) { + // Check if the library is already loaded + if( ! this.checkObjPath( loadLibs[i] ) ) { + all_libs_loaded = false; } - } - if( all_libs_loaded ){ - js_log('all libs already loaded skipping... load req'); + } + if( all_libs_loaded ) { + js_log( 'All libraries already loaded, skipping load request' ); callback(); - return ; + return; } - //do a check for any css we may need and get it: - for(var i=0; i< loadLibs.length; i++){ - if( typeof mvCssPaths[ loadLibs[i] ] != 'undefined' ){ - loadExternalCss( mvCssPaths[ loadLibs[i] ]); + // Do a check for any CSS we may need and get it + for( var i = 0; i < loadLibs.length; i++ ) { + if( typeof mvCssPaths[ loadLibs[i] ] != 'undefined' ) { + loadExternalCss( mvCssPaths[ loadLibs[i] ] ); } } - //check if we should use the script loader to combine all the requests into one: - if( typeof mwSlScript != 'undefined' ){ + // Check if we should use the script loader to combine all the requests into one + if( typeof mwSlScript != 'undefined' ) { var class_set = ''; - var last_class = ''; - var coma = ''; - for(var i=0; i< loadLibs.length; i++){ - var curLib = loadLibs[i]; - //only add if not included yet: - if( ! this.checkObjPath( curLib ) ){ - class_set+=coma + curLib ; - last_class=curLib; - coma=','; - } - } - var puri = parseUri( getMvEmbedURL() ); - if( (getMvEmbedURL().indexOf('://')!=-1) && puri.host != parseUri( document.URL).host){ - mwSlScript = puri.protocol + '://' + puri.authority + mwSlScript; - } - - var dbug_attr = (puri.queryKey['debug'])?'&debug=true':''; - this.libs[ last_class ] = mwSlScript + '?class=' + class_set + - '&urid=' + getMvUniqueReqId() + dbug_attr; - - }else{ - //do many requests: - for(var i=0; i< loadLibs.length; i++){ - var curLib = loadLibs[i]; - if(curLib){ - var libLoc = mvGetClassPath(curLib); - // do a direct load of the file (pass along unique request id from request or mv_embed Version ) - var qmark = (libLoc.indexOf('?')!==true)?'?':'&'; - this.libs[curLib] = mv_embed_path + libLoc + qmark + 'urid='+ getMvUniqueReqId(); - } - } + var last_class = ''; + var coma = ''; + for( var i = 0; i < loadLibs.length; i++ ) { + var curLib = loadLibs[i]; + // Only add if not included yet: + if( ! this.checkObjPath( curLib ) ) { + class_set += coma + curLib; + last_class = curLib; + coma = ','; + } + } + var puri = parseUri( getMvEmbedURL() ); + if( ( getMvEmbedURL().indexOf('://') != -1 ) + && puri.host != parseUri( document.URL ).host ) + { + mwSlScript = puri.protocol + '://' + puri.authority + mwSlScript; + } + + var dbug_attr = ( puri.queryKey['debug'] ) ? '&debug=true' : ''; + this.libs[ last_class ] = mwSlScript + '?class=' + class_set + + '&urid=' + getMvUniqueReqId() + dbug_attr; + + } else { + // Do many requests + for( var i = 0; i < loadLibs.length; i++ ) { + var curLib = loadLibs[i]; + if( curLib ) { + var libLoc = mvGetClassPath( curLib ); + // Do a direct load of the file (pass along unique request id from + // request or mv_embed Version ) + var qmark = (libLoc.indexOf( '?' ) !== true) ? '?' : '&'; + this.libs[curLib] = mv_embed_path + libLoc + qmark + 'urid=' + getMvUniqueReqId(); + } + } } } - if( callback ){ - this.callbacks.push(callback); + if( callback ) { + this.callbacks.push( callback ); } - if( this.checkLoading() ){ - if( this.load_time++ > 2000){ //time out after ~80seconds - js_error( gM('mwe-error_load_lib') + this.missing_path ); - this.load_error = true; - }else{ + if( this.checkLoading() ) { + if( this.load_time++ > 2000 ){ // Time out after ~80 seconds + js_error( gM('mwe-error_load_lib') + this.missing_path ); + this.load_error = true; + } else { setTimeout( 'mvJsLoader.doLoad()', 20 ); - } - }else{ - //js_log('checkLoading passed run callbacks'); - //only do callback if we are in the same instance (weird concurency issue) - var cb_count=0; - for(var i=0; i < this.callbacks.length; i++) - cb_count++; - //js_log('REST LIBS: loading is: '+ loading + ' run callbacks: '+cb_count +' p:'+ this.ptime +' c:'+ this.ctime); - //reset the libs - this.libs={}; - //js_log('done loading do call: ' + this.callbacks[0] ); - while( this.callbacks.length !=0 ){ - if( this.ptime== ( this.ctime-1) ){ //enforce thread consistency - this.callbacks.pop()(); - //func = this.callbacks.pop(); - //js_log(' run: '+this.ctime+ ' p: ' + this.ptime + ' ' +loading+ ' :'+ func); + } + } else { + //js_log('checkLoading passed. Running callbacks...'); + // Only do callbacks if we are in the same instance (weird concurency issue) + var cb_count=0; + for( var i = 0; i < this.callbacks.length; i++ ) + cb_count++; + //js_log('RESET LIBS: loading is: '+ loading + ' callback count: '+cb_count + + // ' p:'+ this.ptime +' c:'+ this.ctime); + + // Reset the libs + this.libs = {}; + //js_log('done loading, do call: ' + this.callbacks[0] ); + while( this.callbacks.length != 0 ) { + if( this.ptime == this.ctime - 1 ) { // Enforce thread consistency + this.callbacks.pop()(); + //func = this.callbacks.pop(); + //js_log(' run: '+this.ctime+ ' p: ' + this.ptime + ' ' +loading+ ' :'+ func); //func(); - }else{ - //re-issue doLoad ( ptime will be set to ctime so we should catch up) - setTimeout( 'mvJsLoader.doLoad()', 25 ); - break; - } - } - } - this.ptime=this.ctime; - }, - doLoadFullPaths:function(loadObj, callback){ - - }, - doLoadDepMode:function(loadChain, callback){ - //firefox executes js ~in-order of it being included~ so just directly issue request: - if( $j.browser.firefox ){ - var loadSet = []; - for(var i=0; i< loadChain.length;i++){ - for(var j=0;j= 1.1.4 not working: http://pastie.caboo.se/92595 * $j(document).ready( function(){ */ -function mwdomReady(force){ - js_log('f:mwdomReady:'); - if( !force && mv_init_done ){ - js_log("mv_init_done already done do nothing..."); +function mwdomReady( force ) { + js_log( 'f:mwdomReady:' ); + if( !force && mv_init_done ) { + js_log( "mv_init_done already done, do nothing..." ); return false; } - mv_init_done=true; - //handle the execution of Queded function with jQuery "ready" + mv_init_done = true; + // Handle the execution of queued functions with jQuery "ready" - //check if this page does have video or playlist + // Check if this page has a video or playlist var e = [ - document.getElementsByTagName("video"), - document.getElementsByTagName("audio"), - document.getElementsByTagName("playlist") + document.getElementsByTagName( "video" ), + document.getElementsByTagName( "audio" ), + document.getElementsByTagName( "playlist" ) ]; - if(e[0].length!=0 || e[1].length!=0 || e[2].length!=0){ - js_log('we have items to rewrite'); - setSwapableToLoading(e); - //load libs and proccess: - mvJsLoader.embedVideoCheck(function(){ - //run any queded global events: - mv_video_embed( function(){ - mvJsLoader.runQuededFunctions(); + if( e[0].length != 0 || e[1].length != 0 || e[2].length != 0 ) { + js_log( 'we have items to rewrite' ); + setSwappableToLoading( e ); + // Load libs and process them + mvJsLoader.embedVideoCheck( function() { + // Run any queued global events: + mv_video_embed( function() { + mvJsLoader.runQueuedFunctions(); }); }); - }else{ - //if we already have jQuery make sure its loaded into its proper context $j - //run any queded global events: - mvJsLoader.runQuededFunctions(); + } else { + // If we already have jQuery, make sure it's loaded into its proper context $j + // Run any queued global events + mvJsLoader.runQueuedFunctions(); } } -//a quick function that sets the intial text of swapable elements to "loading" -// (jquery might not be ready) -//(does not destroy inner elements) -function setSwapableToLoading(e){ +// A quick function that sets the initial text of swappable elements to "loading". +// jQuery might not be ready. Does not destroy inner elements. +function setSwappableToLoading( e ) { //for(var i =0) //for(var j = 0; i < j.length; j++){ //} } -//js2AddOnloadHook: ensure jQuery and the DOM are ready: +//js2AddOnloadHook: ensure jQuery and the DOM are ready function js2AddOnloadHook( func ) { - //make sure the skin/style sheets are avaliable always: + // Make sure the skin/style sheets are always available: loadExternalCss( mv_jquery_skin_path + 'jquery-ui-1.7.1.custom.css' ); - loadExternalCss( mv_embed_path + 'skins/'+mwConfig['skin_name']+'/styles.css'); + loadExternalCss( mv_embed_path + 'skins/'+mwConfig['skin_name'] + '/styles.css' ); - //if we have already run the dom ready just run the function directly: - if( mvJsLoader.doneReadyEvents ){ - //make sure jQuery is there: - mvJsLoader.jQueryCheck(function(){ + // If we have already run the DOM-ready function, just run the function directly: + if( mvJsLoader.doneReadyEvents ) { + // Make sure jQuery is there: + mvJsLoader.jQueryCheck( function() { func(); }); - }else{ - //if using js2AddOnloadHook we need to get jQuery into place (if its not already included) + } else { + // If we are using js2AddOnloadHook we need to get jQuery into place (if it's not already included) mvJsLoader.jQueryCheckFlag = true; mvJsLoader.addLoadEvent( func ); - }; + } } -//depreciated mwAddOnloadHook in favor of js2 naming (for clear seperation of js2 code from old mw code +// Deprecated mwAddOnloadHook in favor of js2 naming (for clear separation of js2 code from old MW code var mwAddOnloadHook = js2AddOnloadHook; /* - * this function allows for targeted rewriting + * This function allows for targeted rewriting */ -function rewrite_by_id( vid_id, ready_callback ){ - js_log('f:rewrite_by_id: ' + vid_id); - //force a recheck of the dom for playlist or video element: - mvJsLoader.embedVideoCheck(function(){ - mv_video_embed(ready_callback, vid_id ); +function rewrite_by_id( vid_id, ready_callback ) { + js_log( 'f:rewrite_by_id: ' + vid_id ); + // Force a recheck of the DOM for playlist or video elements: + mvJsLoader.embedVideoCheck( function() { + mv_video_embed( ready_callback, vid_id ); }); } -//depricated in favor of updates to oggHanlder -function rewrite_for_oggHanlder( vidIdList ){ - for(var i = 0; i < vidIdList.length ; i++){ +// Deprecated in favor of updates to OggHandler +function rewrite_for_OggHandler( vidIdList ){ + for( var i = 0; i < vidIdList.length; i++ ) { var vidId = vidIdList[i]; - js_log('looking at vid: ' + i +' ' + vidId); - //grab the thumbnail and src video - var pimg = $j('#'+vidId + ' img'); - var poster_attr = 'poster = "' + pimg.attr('src') + '" '; - var pwidth = pimg.attr('width'); - var pheight = pimg.attr('height'); + js_log( 'looking at vid: ' + i +' ' + vidId ); + // Grab the thumbnail and src of the video + var pimg = $j( '#' + vidId + ' img' ); + var poster_attr = 'poster = "' + pimg.attr( 'src' ) + '" '; + var pwidth = pimg.attr( 'width' ); + var pheight = pimg.attr( 'height' ); var type_attr = ''; - //check for audio - if( pwidth=='22' && pheight=='22'){ - pwidth='400'; - pheight='300'; + // Check for audio + if( pwidth == '22' && pheight == '22' ) { + pwidth = '400'; + pheight = '300'; type_attr = 'type="audio/ogg"'; poster_attr = ''; } - //parsed values: + // Parsed values: var src = ''; var duration = ''; var re = new RegExp( /videoUrl(":?\s*)*([^&]*)/ ); - src = re.exec( $j('#'+vidId).html() )[2]; + src = re.exec( $j( '#'+vidId).html() )[2]; var re = new RegExp( /length(":?\s*)*([^&]*)/ ); - duration = re.exec( $j('#'+vidId).html() )[2]; + duration = re.exec( $j( '#'+vidId).html() )[2]; var re = new RegExp( /offset(":?\s*)*([^&]*)/ ); - offset = re.exec( $j('#'+vidId).html() )[2]; - var offset_attr = (offset)? 'startOffset="'+ offset + '"': ''; + offset = re.exec( $j( '#'+vidId).html() )[2]; + var offset_attr = offset ? 'startOffset="' + offset + '"' : ''; - if( src ){ - //replace the top div with mv_embed based player: + if( src ) { + // Replace the top div with the mv_embed based player: var vid_html = ''; - //js_log("video html: " + vid_html); - $j('#'+vidId).html( vid_html ); + 'src="' + src + '" ' + + poster_attr + ' ' + + type_attr + ' ' + + offset_attr + ' ' + + 'duration="' + duration + '" ' + + 'style="width:' + pwidth + 'px;height:' + + pheight + 'px;">'; + //js_log("Video HTML: " + vid_html); + $j( '#'+vidId ).html( vid_html ); } - //rewrite that video id: - rewrite_by_id('vid_' + i); + // Rewrite that video ID: + rewrite_by_id( 'vid_' + i ); } } /*********** INITIALIZATION CODE ************* - * set DOM ready callback to init_mv_embed + * set DOM-ready callback to init_mv_embed *********************************************/ // for Mozilla browsers -if (document.addEventListener ) { - document.addEventListener("DOMContentLoaded", function(){mwdomReady()}, false); -}else{ - //backup "onload" method in case on DOMContentLoaded does not exist - window.onload = function(){ mwdomReady() }; +if ( document.addEventListener ) { + document.addEventListener( "DOMContentLoaded", function(){ mwdomReady() }, false ); +} else { + // Use the onload method instead when DOMContentLoaded does not exist + window.onload = function() { mwdomReady() }; } /* - * should depreciate and use jquery.ui.dialog instead + * Should deprecate and use jquery.ui.dialog instead */ -function mv_write_modal(content, speed){ - $j('#modalbox,#mv_overlay').remove(); - $j('body').append(''+ - '
'); - $j('#modalbox,#mv_overlay').show( speed ); +function mv_write_modal( content, speed ) { + $j( '#modalbox,#mv_overlay' ).remove(); + $j( 'body' ).append( + '' + + '
'); + $j( '#modalbox,#mv_overlay' ).show( speed ); } -function mv_remove_modal(speed){ - $j('#modalbox,#mv_overlay').remove( speed); +function mv_remove_modal( speed ) { + $j( '#modalbox,#mv_overlay' ).remove( speed ); } /* - * stores all the mwEmbed jQuery specific bindings - * (setup after jQuery is avaliable) - * lets you call rewrites in a jquery "way" + * Store all the mwEmbed jQuery-specific bindings + * (set up after jQuery is available). + * This lets you call rewrites in a jQuery way * * @@ eventually we should refactor mwCode over to jQuery style plugins - * and mv_embed.js will just hanndle dependency mapping and loading. + * and mv_embed.js will just handle dependency mapping and loading. * */ -function mv_jqueryBindings(){ - js_log('mv_jqueryBindings'); - (function($) { - $.fn.addMediaWiz = function( iObj, callback ){ - //first set the cursor for the button to "loading" - $j(this.selector).css('cursor','wait').attr('title', gM('mwe-loading_title')); +function mv_jqueryBindings() { + js_log( 'mv_jqueryBindings' ); + (function( $ ) { + $.fn.addMediaWiz = function( iObj, callback ) { + // First set the cursor for the button to "loading" + $j( this.selector ).css( 'cursor', 'wait' ).attr( 'title', gM( 'mwe-loading_title' ) ); iObj['target_invocation'] = this.selector; - //load the mv_embed_base skin: + // Load the mv_embed_base skin: loadExternalCss( mv_jquery_skin_path + 'jquery-ui-1.7.1.custom.css' ); - loadExternalCss( mv_embed_path + 'skins/'+mwConfig['skin_name']+'/styles.css' ); - //load all the req libs: - mvJsLoader.jQueryCheck(function(){ - //load with staged dependeinces (for ie and safari that don't execute in order) + loadExternalCss( mv_embed_path + 'skins/' + mwConfig['skin_name']+'/styles.css' ); + // Load all the required libs: + mvJsLoader.jQueryCheck( function() { + // Load with staged dependencies (for IE and Safari that don't execute in order) mvJsLoader.doLoadDepMode([ [ 'remoteSearchDriver', '$j.cookie', @@ -784,83 +798,87 @@ function mv_jqueryBindings(){ '$j.ui.tabs', '$j.ui.sortable' ] - ], function(){ - iObj['instance_name']= 'rsdMVRS'; + ], function() { + iObj['instance_name'] = 'rsdMVRS'; _global['rsdMVRS'] = new remoteSearchDriver( iObj ); - if( callback ){ - callback( _global['rsdMVRS'] ); + if( callback ) { + callback( _global['rsdMVRS'] ); } }); }); } - $.fn.sequencer = function( iObj, callback){ - //debugger; + $.fn.sequencer = function( iObj, callback ) { + // Debugger iObj['target_sequence_container'] = this.selector; - //issue a request to get the css file (if not already included): - loadExternalCss( mv_jquery_skin_path + 'jquery-ui-1.7.1.custom.css'); - loadExternalCss( mv_embed_path+'skins/'+mwConfig['skin_name']+'/mv_sequence.css'); - //make sure we have the required mv_embed libs (they are not loaded when no video element is on the page) - mvJsLoader.embedVideoCheck(function(){ - //load playlist object and then jquery ui stuff: - mvJsLoader.doLoadDepMode([ - [ - 'mvPlayList', - '$j.ui', - '$j.contextMenu', - '$j.secureEvalJSON', - 'mvSequencer' - ], - [ - '$j.ui.accordion', - '$j.ui.dialog', - '$j.ui.droppable', - '$j.ui.draggable', - '$j.ui.progressbar', - '$j.ui.sortable', - '$j.ui.resizable', - '$j.ui.slider', - '$j.ui.tabs' - ] - ], function(){ - js_log('calling new mvSequencer'); - //init the sequence object (it will take over from there) no more than one mvSeq obj for now: - if(!_global['mvSeq']){ - _global['mvSeq'] = new mvSequencer(iObj); - }else{ - js_log('mvSeq already init'); - } - }); - }); + // Issue a request to get the CSS file (if not already included): + loadExternalCss( mv_jquery_skin_path + 'jquery-ui-1.7.1.custom.css' ); + loadExternalCss( mv_embed_path + 'skins/' + mwConfig['skin_name'] + '/mv_sequence.css' ); + // Make sure we have the required mv_embed libs (they are not loaded when no video + // element is on the page) + mvJsLoader.embedVideoCheck( function() { + // Load the playlist object and then the jQuery UI stuff: + mvJsLoader.doLoadDepMode([ + [ + 'mvPlayList', + '$j.ui', + '$j.contextMenu', + '$j.secureEvalJSON', + 'mvSequencer' + ], + [ + '$j.ui.accordion', + '$j.ui.dialog', + '$j.ui.droppable', + '$j.ui.draggable', + '$j.ui.progressbar', + '$j.ui.sortable', + '$j.ui.resizable', + '$j.ui.slider', + '$j.ui.tabs' + ] + ], function() { + js_log( 'calling new mvSequencer' ); + // Initialise the sequence object (it will take over from there) + // No more than one mvSeq obj for now: + if( !_global['mvSeq'] ) { + _global['mvSeq'] = new mvSequencer( iObj ); + } else { + js_log( 'mvSeq already init' ); + } + }); + }); } /* - * the firefogg jquery function: - * @@note this firefogg envocation could be made to work more like real jquery plugins + * The Firefogg jQuery function: + * @@note This Firefogg invocation could be made to work more like real jQuery plugins */ $.fn.firefogg = function( iObj, callback ) { - if(!iObj) - iObj={}; - //add base theme css: - loadExternalCss( mv_jquery_skin_path + 'jquery-ui-1.7.1.custom.css'); - loadExternalCss( mv_embed_path + 'skins/'+mwConfig['skin_name']+'/styles.css' ); - - //check if we already have firefogg loaded (the call just updates properties for that element) - var sElm = $j(this.selector).get(0); - if(sElm['firefogg']){ - if(sElm['firefogg']=='loading'){ - js_log("Error: called firefogg operations on Firefogg selector that is not done loading"); + if( !iObj ) + iObj = {}; + // Add the base theme CSS: + loadExternalCss( mv_jquery_skin_path + 'jquery-ui-1.7.1.custom.css' ); + loadExternalCss( mv_embed_path + 'skins/'+mwConfig['skin_name'] + '/styles.css' ); + + // Check if we already have Firefogg loaded (the call just updates the element's + // properties) + var sElm = $j( this.selector ).get( 0 ); + if( sElm['firefogg'] ) { + if( sElm['firefogg'] == 'loading' ) { + js_log( "Error: called firefogg operations on Firefogg selector that is " + + "not done loading" ); return false; } - //update properties: - for(var i in iObj){ - js_log("firefogg::updated: "+ i + ' to '+ iObj[i]); + // Update properties + for( var i in iObj ) { + js_log( "firefogg::updated: " + i + ' to '+ iObj[i] ); sElm['firefogg'][i] = iObj[i]; } return sElm['firefogg']; - }else{ - //avoid concurency + } else { + // Avoid concurency sElm['firefogg'] = 'loading'; } - //add the selector: + // Add the selector iObj['selector'] = this.selector; var loadSet = [ @@ -874,7 +892,7 @@ function mv_jqueryBindings(){ '$j.ui.dialog' ] ]; - if( iObj.encoder_interface ){ + if( iObj.encoder_interface ) { loadSet.push([ 'mvAdvFirefogg', '$j.cookie', @@ -883,81 +901,83 @@ function mv_jqueryBindings(){ '$j.ui.datepicker' ]); } - //make sure we have everything loaded that we need: - mvJsLoader.doLoadDepMode( loadSet, function(){ - js_log('firefogg libs loaded. target select:' + iObj.selector); - //select interface provicer based on if we want to include the encoder interface or not: - if(iObj.encoder_interface){ + // Make sure we have everything loaded that we need: + mvJsLoader.doLoadDepMode( loadSet, function() { + js_log( 'firefogg libs loaded. target select:' + iObj.selector ); + // Select interface provider based on whether we want to include the + // encoder interface or not + if( iObj.encoder_interface ) { var myFogg = new mvAdvFirefogg( iObj ); - }else{ + } else { var myFogg = new mvFirefogg( iObj ); } - if(myFogg){ + if( myFogg ) { myFogg.doRewrite( callback ); - var selectorElement = $j( iObj.selector ).get(0); - selectorElement['firefogg']=myFogg; + var selectorElement = $j( iObj.selector ).get( 0 ); + selectorElement['firefogg'] = myFogg; } }); } - //takes a input player as the selector and exposes basic rendering controls - $.fn.firefoggRender = function( iObj, callback ){ - //check if we already have render loaded then just pass on updates/actions - var sElm = $j(this.selector).get(0); - if(sElm['fogg_render']){ - if(sElm['fogg_render']=='loading'){ - js_log("Error: called firefoggRender while loading"); + // Take an input player as the selector and expose basic rendering controls + $.fn.firefoggRender = function( iObj, callback ) { + // Check if we already have render loaded then just pass on updates/actions + var sElm = $j( this.selector ).get( 0 ); + if( sElm['fogg_render'] ) { + if( sElm['fogg_render'] == 'loading' ) { + js_log( "Error: called firefoggRender while loading" ); return false; } - //call or update the property: + // Call or update the property: } - sElm['fogg_render']='loading'; - //add the selector: + sElm['fogg_render'] = 'loading'; + // Add the selector iObj['player_target'] = this.selector; mvJsLoader.doLoad([ 'mvFirefogg', 'mvFirefoggRender' - ],function(){ - sElm['fogg_render']= new mvFirefoggRender( iObj ); + ], function() { + sElm['fogg_render'] = new mvFirefoggRender( iObj ); if( callback && typeof callback == 'function' ) callback( sElm['fogg_render'] ); }); } - $.fn.baseUploadInterface = function(iObj){ + $.fn.baseUploadInterface = function(iObj) { mvJsLoader.doLoadDepMode([ [ 'mvBaseUploadInterface', '$j.ui', ], [ - '$j.ui.progressbar', - '$j.ui.dialog' + '$j.ui.progressbar', + '$j.ui.dialog' ] - ],function(){ + ], function() { myUp = new mvBaseUploadInterface( iObj ); myUp.setupForm(); }); } - //shortcut to a themed button: - $.btnHtml = function(msg, className, iconId, opt){ - if(!opt) - opt = {}; - var href = (opt.href)?opt.href:'#'; - var target_attr = (opt.target)?' target="' + opt.target + '" ':''; - var style_attr = (opt.style)?' style="'+opt.style +'" ':''; - return '' + - msg + ''; + // Shortcut to a themed button + $.btnHtml = function( msg, className, iconId, opt ) { + if( !opt ) + opt = {}; + var href = (opt.href) ? opt.href : '#'; + var target_attr = (opt.target) ? ' target="' + opt.target + '" ' : ''; + var style_attr = (opt.style) ? ' style="' + opt.style + '" ' : ''; + return '' + + msg + ''; } - //shortcut to bind hover state: - $.fn.btnBind = function(){ - $j(this).hover( - function(){ - $j(this).addClass('ui-state-hover'); + // Shortcut to bind hover state + $.fn.btnBind = function() { + $j( this ).hover( + function() { + $j( this ).addClass( 'ui-state-hover' ); }, - function(){ - $j(this).removeClass('ui-state-hover'); + function() { + $j( this ).removeClass( 'ui-state-hover' ); } ) return this; @@ -966,392 +986,396 @@ function mv_jqueryBindings(){ })(jQuery); } /* -* utility functions: +* Utility functions: */ -//simple url re-writer for rewriting urls (could probably be refactored into an inline regular expresion) -function getURLParamReplace( url, opt ){ +// Simple URL rewriter (could probably be refactored into an inline regular expresion) +function getURLParamReplace( url, opt ) { var pSrc = parseUri( url ); - if(pSrc.protocol != '' ){ - var new_url = pSrc.protocol +'://'+ pSrc.authority + pSrc.path +'?'; - }else{ - var new_url = pSrc.path +'?'; + if( pSrc.protocol != '' ) { + var new_url = pSrc.protocol + '://' + pSrc.authority + pSrc.path + '?'; + } else { + var new_url = pSrc.path + '?'; } var amp = ''; - for(var key in pSrc.queryKey){ + for( var key in pSrc.queryKey ) { var val = pSrc.queryKey[ key ]; - //do override if requested + // Do override if requested if( opt[ key ] ) val = opt[ key ]; - new_url+= amp + key + '=' + val; + new_url += amp + key + '=' + val; amp = '&'; }; - //add any vars that did were not originally there: - for(var i in opt){ - if(!pSrc.queryKey[i]){ - new_url+=amp + i + '=' + opt[i]; - amp = '&'; + // Add any vars that were not already there: + for( var i in opt ) { + if( !pSrc.queryKey[i] ) { + new_url += amp + i + '=' + opt[i]; + amp = '&'; } } return new_url; } /** - * seconds2npt given a float seconds returns npt format response: - * @param float seconds - * @param boolean if we should show ms or not. + * Given a float number of seconds, returns npt format response. + * + * @param float Seconds + * @param boolean If we should show milliseconds or not. */ -function seconds2npt(sec, show_ms){ - if( isNaN( sec ) ){ - //js_log("warning: trying to get npt time on NaN:" + sec); +function seconds2npt( sec, show_ms ) { + if( isNaN( sec ) ) { + // js_log("warning: trying to get npt time on NaN:" + sec); return '0:0:0'; } - var hours = Math.floor(sec/ 3600); - var minutes = Math.floor((sec/60) % 60); + var hours = Math.floor( sec / 3600 ); + var minutes = Math.floor( (sec / 60) % 60 ); var seconds = sec % 60; - //round the second amount requested significant digits - if(show_ms){ + // Round the number of seconds to the required number of significant digits + if( show_ms ) { seconds = Math.round( seconds * 1000 ) / 1000; - }else{ + } else { seconds = Math.round( seconds ); } - if(seconds <10 ) - seconds = '0'+ seconds; - if(minutes < 10 ) + if( seconds < 10 ) + seconds = '0' + seconds; + if( minutes < 10 ) minutes = '0' + minutes; - return hours+":"+minutes+":"+seconds; + return hours + ":" + minutes + ":" + seconds; } /* - * takes hh:mm:ss,ms or hh:mm:ss.ms input returns number of seconds + * Take hh:mm:ss,ms or hh:mm:ss.ms input, return the number of seconds */ -function npt2seconds( npt_str ){ - if(!npt_str){ +function npt2seconds( npt_str ) { + if( !npt_str ) { //js_log('npt2seconds:not valid ntp:'+ntp); return false; } - //strip npt: time definition if present - npt_str = npt_str.replace('npt:', ''); + // Strip "npt:" time definition if present + npt_str = npt_str.replace( 'npt:', '' ); - times = npt_str.split(':'); - if(times.length!=3){ - js_log('error: npt2seconds on ' + npt_str); + times = npt_str.split( ':' ); + if( times.length != 3 ){ + js_log( 'error: npt2seconds on ' + npt_str ); return false; } - //sometimes the comma is used inplace of pereid for ms - times[2] = times[2].replace(/,\s?/,'.'); - //return seconds float (ie take seconds float value if present): - return parseInt(times[0]*3600)+parseInt(times[1]*60)+parseFloat(times[2]); + // Sometimes a comma is used instead of period for ms + times[2] = times[2].replace( /,\s?/, '.' ); + // Return seconds float + return parseInt( times[0] * 3600) + parseInt( times[1] * 60 ) + parseFloat( times[2] ); } /* - * simple helper to grab a edit token + * Simple helper to grab an edit token * - * @param title the wiki page title you want to edit ) - * @param api_url 'optional' the target api url - * @param callback the callback function to pass the token or "false" to + * @param title The wiki page title you want to edit + * @param api_url 'optional' The target API URL + * @param callback The callback function to pass the token to */ -function get_mw_token( title, api_url, callback){ - js_log(':get_mw_token:'); - if(!title && wgUserName){ +function get_mw_token( title, api_url, callback ) { + js_log( ':get_mw_token:' ); + if( !title && wgUserName ) { title = 'User:' + wgUserName; } var reqObj = { - 'action':'query', - 'prop':'info', - 'intoken':'edit', - 'titles':title + 'action': 'query', + 'prop': 'info', + 'intoken': 'edit', + 'titles': title }; - do_api_req( { - 'data': reqObj, - 'url' : api_url - },function(data){ - for(var i in data.query.pages){ - if(data.query.pages[i]['edittoken']){ - if(typeof callback == 'function') - callback ( data.query.pages[i]['edittoken'] ); - } + do_api_req( { + 'data': reqObj, + 'url' : api_url + }, function(data) { + for( var i in data.query.pages ) { + if( data.query.pages[i]['edittoken'] ) { + if( typeof callback == 'function' ) + callback ( data.query.pages[i]['edittoken'] ); } - //no token found: - return false; } - ); + // No token found: + return false; + } + ); } -//does a remote or local api request based on request url +// Do a remote or local API request based on request URL //@param options: url, data, cbParam, callback -function do_api_req( options, callback ){ - if(typeof options.data != 'object'){ - return js_error('Error: request paramaters must be an object');; +function do_api_req( options, callback ) { + if( typeof options.data != 'object' ) { + return js_error( 'Error: request paramaters must be an object' ); } - //gennerate the url if its missing: - if( typeof options.url == 'undefined' || options.url === false){ - if(!wgServer || ! wgScriptPath){ - return js_error('Error: no api url for api request');; + // Generate the URL if it's missing + if( typeof options.url == 'undefined' || options.url === false ) { + if( !wgServer || ! wgScriptPath ) { + return js_error('Error: no api url for api request'); } - //update to api.php (if index.php was in the wgScript path): - options.url = mwGetLocalApiUrl(); + options.url = mwGetLocalApiUrl(); } if( typeof options.data == 'undefined' ) options.data = {}; - //force format to json (if not already set) + // Force format to JSON options.data['format'] = 'json'; - //if action not set assume query - if(!options.data['action']) - options.data['action']='query'; + // If action is not set, assume query + if( !options.data['action'] ) + options.data['action'] = 'query'; - //js_log('do api req: ' + options.url +'?' + jQuery.param(options.data) ); - //build request string: - if( parseUri( document.URL ).host == parseUri( options.url ).host ){ - //local request do api request directly + // js_log('do api req: ' + options.url +'?' + jQuery.param(options.data) ); + // Build request string + if( parseUri( document.URL ).host == parseUri( options.url ).host ) { + // Local request: do API request directly $j.ajax({ type: "POST", url: options.url, data: options.data, - dataType:'json', //api requests _should_ always return JSON data: + dataType: 'json', // API requests _should_ always return JSON data: async: false, - success:function(data){ - callback( data ); + success: function( data ) { + callback( data ); }, - error:function(e){ - js_error( ' error' + e +' in getting: ' + options.url); + error: function( e ) { + js_error( ' error' + e + ' in getting: ' + options.url ); } }); - }else{ - //set the callback param if not already set: - if( typeof options.jsonCB == 'undefined') + } else { + // Remote request + // Set the callback param if it's not already set + if( typeof options.jsonCB == 'undefined' ) options.jsonCB = 'callback'; var req_url = options.url; - var paramAnd = (req_url.indexOf('?')==-1)?'?':'&'; - //put all the values into the GET req: - for(var i in options.data){ + var paramAnd = ( req_url.indexOf( '?' ) == -1 ) ? '?' : '&'; + // Put all the parameters into the URL + for( var i in options.data ) { req_url += paramAnd + encodeURIComponent( i ) + '=' + encodeURIComponent( options.data[i] ); - paramAnd ='&'; + paramAnd = '&'; } var fname = 'mycpfn_' + ( global_cb_count++ ); - _global[ fname ] = callback; + _global[ fname ] = callback; req_url += '&' + options.jsonCB + '=' + fname; loadExternalJs( req_url ); } } -function mwGetLocalApiUrl(url){ - if (wgServer && wgScriptPath){ +function mwGetLocalApiUrl( url ) { + if ( wgServer && wgScriptPath ) { return wgServer + wgScriptPath + '/api.php'; } return false; } -//grab wiki form error for wiki html page proccessing (should be depricated) -function grabWikiFormError ( result_page ){ +// Grab wiki form error for wiki html page proccessing (should be deprecated) +function grabWikiFormError( result_page ) { var res = {}; - sp = result_page.indexOf(''); - if(sp!=-1){ - se = result_page.indexOf('', sp); - res.error_txt = result_page.substr(sp, (sp-se)) + ''; - }else{ - //look for warning: - sp = result_page.indexOf('
    ') - if(sp != -1){ - se = result_page.indexOf('
', sp); - res.error_txt = result_page.substr(sp, (se-sp)) + ''; - //try and add the ignore form item: - sfp = result_page.indexOf('
', sfp); - res.form_txt = result_page.substr(sfp, ( sfe - sfp )) + '
'; + sp = result_page.indexOf( '' ); + if( sp != -1 ) { + se = result_page.indexOf( '', sp ); + res.error_txt = result_page.substr( sp, sp - se ) + ''; + } else { + // Look for warning + sp = result_page.indexOf( '
    ' ) + if( sp != -1 ) { + se = result_page.indexOf( '
', sp ); + res.error_txt = result_page.substr( sp, se - sp ) + ''; + // Try to add the ignore form item + sfp = result_page.indexOf( '
', sfp ); + res.form_txt = result_page.substr( sfp, sfe - sfp ) + '
'; } - }else{ - //one more error type check: - sp = result_page.indexOf('class="mw-warning-with-logexcerpt">') - if(sp!=-1){ - se = result_page.indexOf('
', sp); - res.error_txt = result_page.substr(sp, ( se - sp )) + '
'; + } else { + // One more error type check + sp = result_page.indexOf( 'class="mw-warning-with-logexcerpt">' ) + if( sp != -1 ) { + se = result_page.indexOf( '', sp ); + res.error_txt = result_page.substr( sp, se - sp ) + ''; } } } return res; } -//do a "normal" request -function do_request(req_url, callback){ - js_log('do_request::req_url:' + req_url + ' != ' + parseUri( req_url).host); - //if we are doing a request to the same domain or relative link do a normal GET: - if( parseUri(document.URL).host == parseUri(req_url).host || - req_url.indexOf('://') == -1 ){ //relative url - //do a direct request: +// Do a "normal" request +function do_request( req_url, callback ) { + js_log( 'do_request::req_url:' + req_url + ' != ' + parseUri( req_url ).host ); + // If we are doing a request to the same domain or relative link, do a normal GET + if( parseUri( document.URL ).host == parseUri( req_url ).host || + req_url.indexOf('://') == -1 ) // Relative url + { + // Do a direct request $j.ajax({ type: "GET", - url:req_url, - async: false, - success:function(data){ + url: req_url, + async: false, + success: function( data ) { callback( data ); } }); - }else{ - //get data via DOM injection with callback - global_req_cb.push(callback); - //prepend json_ to feed_format if not already requesting json format - if( req_url.indexOf("feed_format=")!=-1 && req_url.indexOf("feed_format=json")==-1) - req_url = req_url.replace(/feed_format=/, 'feed_format=json_'); - loadExternalJs( req_url + '&cb=mv_jsdata_cb&cb_inx=' + (global_req_cb.length-1)); + } else { + // Get data via DOM injection with callback + global_req_cb.push( callback ); + // Prepend json_ to feed_format if not already requesting json format + if( req_url.indexOf( "feed_format=" ) != -1 && req_url.indexOf( "feed_format=json" ) == -1 ) + req_url = req_url.replace( /feed_format=/, 'feed_format=json_' ); + loadExternalJs( req_url + '&cb=mv_jsdata_cb&cb_inx=' + (global_req_cb.length - 1) ); } } -function mv_jsdata_cb(response){ - js_log('f:mv_jsdata_cb:'+ response['cb_inx']); - //run the callback from the global req cb object: - if( !global_req_cb[response['cb_inx']] ){ - js_log('missing req cb index'); +function mv_jsdata_cb( response ) { + js_log( 'f:mv_jsdata_cb:'+ response['cb_inx'] ); + // Run the callback from the global request callback object + if( !global_req_cb[response['cb_inx']] ) { + js_log( 'missing req cb index' ); return false; } - if( !response['pay_load'] ){ - js_log("missing pay load"); + if( !response['pay_load'] ) { + js_log( "missing pay load" ); return false; } - //switch on content type: - switch(response['content-type']){ + switch( response['content-type'] ) { case 'text/plain': break; case 'text/xml': - if(typeof response['pay_load'] == 'string'){ + if( typeof response['pay_load'] == 'string' ) { //js_log('load string:'+"\n"+ response['pay_load']); - //debugger; - //attempt to parse as xml for IE - if( $j.browser.msie ){ - var xmldata=new ActiveXObject("Microsoft.XMLDOM"); - xmldata.async="false"; - xmldata.loadXML(response['pay_load']); - }else{ //for others (firefox, safari etc) - try{ - var xmldata = (new DOMParser()).parseFromString(response['pay_load'], "text/xml"); - }catch(e) { - js_log('XML parse ERROR: ' + e.message); - } + // Debugger; + if( $j.browser.msie ) { + // Attempt to parse as XML for IE + var xmldata = new ActiveXObject("Microsoft.XMLDOM"); + xmldata.async = "false"; + xmldata.loadXML( response['pay_load'] ); + } else { + // For others (Firefox, Safari etc.) + try { + var xmldata = (new DOMParser()).parseFromString( response['pay_load'], "text/xml" ); + } catch( e ) { + js_log( 'XML parse ERROR: ' + e.message ); + } } - //@@todo hanndle xml parser errors - if(xmldata)response['pay_load']=xmldata; + //@@todo handle XML parser errors + if( xmldata )response['pay_load'] = xmldata; } break default: - js_log('bad response type' + response['content-type']); + js_log( 'bad response type' + response['content-type'] ); return false; break; } global_req_cb[response['cb_inx']]( response['pay_load'] ); } -//load external js via dom injection -function loadExternalJs( url, callback ){ - js_log('load js: '+ url); - //if(window['$j']) //use jquery call: - /*$j.ajax({ +// Load external JS via DOM injection +function loadExternalJs( url, callback ) { + js_log( 'load js: '+ url ); + //if(window['$j']) // use jquery call: + /*$j.ajax({ type: "GET", url: url, dataType: 'script', cache: true });*/ - // else{ - var e = document.createElement("script"); - e.setAttribute('src', url); - e.setAttribute('type', "text/javascript"); + //else{ + var e = document.createElement( "script" ); + e.setAttribute( 'src', url ); + e.setAttribute( 'type', "text/javascript" ); /*if(callback) e.onload = callback; */ //e.setAttribute('defer', true); - document.getElementsByTagName("head")[0].appendChild(e); - // } + document.getElementsByTagName( "head" )[0].appendChild( e ); + // } } -function styleSheetPresent(url){ - style_elements = document.getElementsByTagName('link'); - if( style_elements.length > 0) { - for(i = 0; i < style_elements.length; i++) { - if(style_elements[i].href == url) +function styleSheetPresent( url ) { + style_elements = document.getElementsByTagName( 'link' ); + if( style_elements.length > 0 ) { + for( i = 0; i < style_elements.length; i++ ) { + if( style_elements[i].href == url ) return true; } } return false; } -function loadExternalCss(url){ - //if could have script loader group thes css request - //but debatable it may hurt more than it helps with caching and all - if(typeof url =='object'){ - for(var i in url){ - loadExternalCss ( url[i] ); +function loadExternalCss( url ) { + // We could have the script loader group these CSS requests. + // But it's debatable: it may hurt more than it helps with caching and all + if( typeof url =='object' ) { + for( var i in url ) { + loadExternalCss( url[i] ); } return ; } - if( url.indexOf('?') == -1 ){ - url+='?'+getMvUniqueReqId(); + if( url.indexOf('?') == -1 ) { + url += '?' + getMvUniqueReqId(); } - if(!styleSheetPresent(url) ){ - js_log('load css: ' + url); - var e = document.createElement("link"); - e.href = url; - e.type = "text/css"; - e.rel = 'stylesheet'; - document.getElementsByTagName("head")[0].appendChild(e); + if( !styleSheetPresent( url ) ) { + js_log( 'load css: ' + url ); + var e = document.createElement( "link" ); + e.href = url; + e.type = "text/css"; + e.rel = 'stylesheet'; + document.getElementsByTagName( "head" )[0].appendChild( e ); } } -function getMvEmbedURL(){ +function getMvEmbedURL() { if( _global['mv_embed_url'] ) return _global['mv_embed_url']; - var js_elements = document.getElementsByTagName("script"); - for(var i=0; i < js_elements.length; i++){ - //check for normal mv_embed.js and or script loader - var src = js_elements[i].getAttribute("src"); - if( src ){ - if( src.indexOf('mv_embed.js') !=-1 || ( - ( src.indexOf('mwScriptLoader.php') != -1 || src.indexOf('jsScriptLoader.php') != -1 ) - && src.indexOf('mv_embed') != -1) ){ //(check for class=mv_embed script_loader call) + var js_elements = document.getElementsByTagName( "script" ); + for( var i = 0; i < js_elements.length; i++ ) { + // Check for mv_embed.js and/or script loader + var src = js_elements[i].getAttribute( "src" ); + if( src ) { + if( src.indexOf( 'mv_embed.js' ) != -1 || ( + ( src.indexOf( 'mwScriptLoader.php' ) != -1 || src.indexOf('jsScriptLoader.php') != -1 ) + && src.indexOf('mv_embed') != -1) ) //(check for class=mv_embed script_loader call) + { _global['mv_embed_url'] = src; - return src; + return src; } } } - js_error('Error: getMvEmbedURL failed to get Embed Path'); + js_error( 'Error: getMvEmbedURL failed to get Embed Path' ); return false; } -//gets a unique request id to ensure fresh javascript -function getMvUniqueReqId(){ +// Get a unique request ID to ensure fresh JavaScript +function getMvUniqueReqId() { if( _global['urid'] ) return _global['urid']; var mv_embed_url = getMvEmbedURL(); - //if we have a uri retun that: - var urid = parseUri( mv_embed_url).queryKey['urid'] - if( urid ){ + // If we have a URI, return it + var urid = parseUri( mv_embed_url ).queryKey['urid'] + if( urid ) { _global['urid'] = urid; return urid; } - //if in debug mode get a fresh unique request key: - if( parseUri( mv_embed_url ).queryKey['debug'] == 'true'){ + // If we're in debug mode, get a fresh unique request key + if( parseUri( mv_embed_url ).queryKey['debug'] == 'true' ) { var d = new Date(); var urid = d.getTime(); _global['urid'] = urid; return urid; } - //else just return the mv_embed version; + // Otherwise, just return the mv_embed version return MV_EMBED_VERSION; } /* - * sets the global mv_embed path based on the scripts location + * Set the global mv_embed path based on the script's location */ -function getMvEmbedPath(){ - if( _global['mv_embed_path']) +function getMvEmbedPath() { + if( _global['mv_embed_path'] ) return _global['mv_embed_path']; var mv_embed_url = getMvEmbedURL(); - if( mv_embed_url.indexOf('mv_embed.js') !== -1 ){ - mv_embed_path = mv_embed_url.substr(0, mv_embed_url.indexOf('mv_embed.js')); - }else if(mv_embed_url.indexOf('mwScriptLoader.php')!==-1){ - //script load is in the root of mediaWiki so include the default mv_embed extention path (if using the script loader) - mv_embed_path = mv_embed_url.substr(0, mv_embed_url.indexOf('mwScriptLoader.php')) + mediaWiki_mvEmbed_path ; - }else{ - mv_embed_path = mv_embed_url.substr(0, mv_embed_url.indexOf('jsScriptLoader.php')); + if( mv_embed_url.indexOf( 'mv_embed.js' ) !== -1 ) { + mv_embed_path = mv_embed_url.substr( 0, mv_embed_url.indexOf( 'mv_embed.js' ) ); + } else if( mv_embed_url.indexOf( 'mwScriptLoader.php' ) !== -1 ) { + // Script loader is in the root of MediaWiki, so include the default mv_embed extension path + mv_embed_path = mv_embed_url.substr( 0, mv_embed_url.indexOf( 'mwScriptLoader.php' ) ) + + mediaWiki_mvEmbed_path; + } else { + mv_embed_path = mv_embed_url.substr( 0, mv_embed_url.indexOf( 'jsScriptLoader.php' ) ); } - //absolute the url (if relative) (if we don't have mv_embed path) - if( mv_embed_path.indexOf('://') == -1){ + // Make an absolute URL (if it's relative and we don't have an mv_embed path) + if( mv_embed_path.indexOf( '://' ) == -1 ) { var pURL = parseUri( document.URL ); - if(mv_embed_path.charAt(0)=='/'){ + if( mv_embed_path.charAt( 0 ) == '/' ) { mv_embed_path = pURL.protocol + '://' + pURL.authority + mv_embed_path; - }else{ - //relative: - if(mv_embed_path==''){ + } else { + // Relative + if( mv_embed_path == '' ) { mv_embed_path = pURL.protocol + '://' + pURL.authority + pURL.directory + mv_embed_path; } } @@ -1360,60 +1384,60 @@ function getMvEmbedPath(){ return mv_embed_path; } -if (typeof DOMParser == "undefined") { - DOMParser = function () {} - DOMParser.prototype.parseFromString = function (str, contentType) { - if (typeof ActiveXObject != "undefined") { - var d = new ActiveXObject("MSXML.DomDocument"); - d.loadXML(str); - return d; - } else if (typeof XMLHttpRequest != "undefined") { - var req = new XMLHttpRequest; - req.open("GET", "data:" + (contentType || "application/xml") + - ";charset=utf-8," + encodeURIComponent(str), false); - if (req.overrideMimeType) { - req.overrideMimeType(contentType); - } - req.send(null); - return req.responseXML; - } - } +if ( typeof DOMParser == "undefined" ) { + DOMParser = function () {} + DOMParser.prototype.parseFromString = function ( str, contentType ) { + if ( typeof ActiveXObject != "undefined" ) { + var d = new ActiveXObject( "MSXML.DomDocument" ); + d.loadXML( str ); + return d; + } else if ( typeof XMLHttpRequest != "undefined" ) { + var req = new XMLHttpRequest; + req.open( "GET", "data:" + (contentType || "application/xml") + + ";charset=utf-8," + encodeURIComponent(str), false ); + if ( req.overrideMimeType ) { + req.overrideMimeType(contentType); + } + req.send( null ); + return req.responseXML; + } + } } /* -* utility functions: +* Utility functions */ -function js_log(string){ - if( window.console ){ - window.console.log(string); - }else{ - /* - * IE and non-firebug debug: - */ - /*var log_elm = document.getElementById('mv_js_log'); - if(!log_elm){ - document.getElementsByTagName("body")[0].innerHTML = document.getElementsByTagName("body")[0].innerHTML + - '
'+ - ''+ - '
'; - - var log_elm = document.getElementById('mv_js_log'); - } - if(log_elm){ - log_elm.value+=string+"\n"; - }*/ - } - return false; +function js_log( string ) { + if( window.console ) { + window.console.log( string ); + } else { + /* + * IE and non-Firebug debug: + */ + /*var log_elm = document.getElementById('mv_js_log'); + if(!log_elm){ + document.getElementsByTagName("body")[0].innerHTML = document.getElementsByTagName("body")[0].innerHTML + + '
'+ + ''+ + '
'; + + var log_elm = document.getElementById('mv_js_log'); + } + if(log_elm){ + log_elm.value+=string+"\n"; + }*/ + } + return false; } -function checkDefaultMwConfig(){ - for(var i in defaultMwConfig){ - if(typeof(mwConfig[i])=='undefined'){ - mwConfig[i] =defaultMwConfig[i]; - } - } +function checkDefaultMwConfig() { + for( var i in defaultMwConfig ) { + if( typeof( mwConfig[i] ) == 'undefined' ) { + mwConfig[i] = defaultMwConfig[i]; + } } +} -function js_error(string){ - alert(string); +function js_error( string ) { + alert( string ); return false; } diff --git a/js2/mwEmbed/php/jsAutoloadLocalClasses.php b/js2/mwEmbed/php/jsAutoloadLocalClasses.php index effd1e9759..1cf264af5b 100644 --- a/js2/mwEmbed/php/jsAutoloadLocalClasses.php +++ b/js2/mwEmbed/php/jsAutoloadLocalClasses.php @@ -3,27 +3,27 @@ if ( !defined( 'MEDIAWIKI' ) ) die( 1 ); global $wgJSAutoloadLocalClasses, $wgMwEmbedDirectory; -//load classes from mv_embed.js:: +// Load classes from mv_embed.js -//read the file: -if( is_file( $wgMwEmbedDirectory . 'mv_embed.js' )){ - - $str = @file_get_contents( $wgMwEmbedDirectory . 'mv_embed.js'); +if ( is_file( $wgMwEmbedDirectory . 'mv_embed.js' ) ) { + // Read the file + $str = @file_get_contents( $wgMwEmbedDirectory . 'mv_embed.js' ); + // Call jsClassPathLoader() for each lcPaths() call in the JS source $str = preg_replace_callback( '/lcPaths\s*\(\s*{(.*)}\s*\)\s*/siU', 'jsClassPathLoader', $str ); } -function jsClassPathLoader($jvar){ - global $wgJSAutoloadLocalClasses,$wgMwEmbedDirectory; - if( !isset( $jvar[1] ) ) +function jsClassPathLoader( $jvar ) { + global $wgJSAutoloadLocalClasses, $wgMwEmbedDirectory; + if ( !isset( $jvar[1] ) ) return false; $jClassSet = json_decode( '{' . $jvar[1] . '}', true ); - foreach( $jClassSet as $jClass => $jPath ){ - //strip $ from jsclass (as they are striped on url request param input) - $jClass = str_replace('$', '', $jClass); + foreach ( $jClassSet as $jClass => $jPath ) { + // Strip $ from jClass (as they are stripped on URL request parameter input) + $jClass = str_replace( '$', '', $jClass ); $wgJSAutoloadLocalClasses[$jClass] = $wgMwEmbedDirectory . $jPath; } } diff --git a/js2/mwEmbed/php/maintenance/mergeJavascriptMsg.php b/js2/mwEmbed/php/maintenance/mergeJavascriptMsg.php index 32e79dc17f..58b8d7184e 100644 --- a/js2/mwEmbed/php/maintenance/mergeJavascriptMsg.php +++ b/js2/mwEmbed/php/maintenance/mergeJavascriptMsg.php @@ -64,7 +64,7 @@ $msgSet = ""; $objects = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path ), RecursiveIteratorIterator::SELF_FIRST ); foreach ( $objects as $fname => $object ) { - if ( substr( $fname, -3 ) == '.js' ) { + if ( substr( $fname, - 3 ) == '.js' ) { $jsFileText = file_get_contents( $fname ); $mwPos = strpos( $fname, 'mwEmbed' ) + 7; $curFileName = substr( $fname, $mwPos ); @@ -171,9 +171,9 @@ function jsonReadable( $json ) { } break; case ':': - if($inquote){ + if ( $inquote ) { $result .= $char; - }else{ + } else { $result .= ' ' . $char . ' '; } break; diff --git a/js2/mwEmbed/php/mv_embed_iframe.php b/js2/mwEmbed/php/mv_embed_iframe.php index 28f5e7c109..35f1500e93 100644 --- a/js2/mwEmbed/php/mv_embed_iframe.php +++ b/js2/mwEmbed/php/mv_embed_iframe.php @@ -1,31 +1,32 @@ filter_input() function
' ); } - // default to null media in not provided: - $stream_name = ( isset( $_GET['sn'] ) )? $_GET['sn'] : die('no stream name provided'); - $time = ( isset( $_GET['t'] ) )? $_GET['t']: ''; - $width = ( isset( $_GET['width'] ) )? intval( $_GET['width'] ) : '400'; - $height = ( isset( $_GET['height'] ) )? intval( $_GET['height'] ) : '300'; // + // Default to null media if not provided + $stream_name = ( isset( $_GET['sn'] ) ) ? $_GET['sn'] : die( 'no stream name provided' ); + $time = ( isset( $_GET['t'] ) ) ? $_GET['t']: ''; + $width = ( isset( $_GET['width'] ) ) ? intval( $_GET['width'] ) : '400'; + $height = ( isset( $_GET['height'] ) ) ? intval( $_GET['height'] ) : '300'; // - $roe_url = 'http://metavid.org/wiki/Special:MvExportStream?feed_format=roe&stream_name=' . htmlspecialchars( $stream_name ) . - '&t=' . htmlspecialchars( $time ); - //everything good output page: - output_page(array( + $roe_url = 'http://metavid.org/wiki/Special:MvExportStream?feed_format=roe' . + '&stream_name=' . htmlspecialchars( $stream_name ) . + '&t=' . htmlspecialchars( $time ); + // Everything good, output page: + output_page( array( 'roe_url' => $roe_url, 'width' => $width, 'height' => $height, - )); + ) ); } -function output_page( $params ){ +function output_page( $params ) { extract( $params ); ?> @@ -80,4 +81,4 @@ function escapeJsString( $string ) { "\xe2\x80\x8d" => "\\u200d", // ZERO WIDTH JOINER ); return strtr( $string, $pairs ); -} \ No newline at end of file +} diff --git a/js2/mwEmbed/php/noMediaWikiConfig.php b/js2/mwEmbed/php/noMediaWikiConfig.php index 78d7353afd..b7326ae5f7 100644 --- a/js2/mwEmbed/php/noMediaWikiConfig.php +++ b/js2/mwEmbed/php/noMediaWikiConfig.php @@ -1,25 +1,26 @@ \ No newline at end of file +?> diff --git a/js2/remoteMwEmbed.js b/js2/remoteMwEmbed.js index d41075e3bd..bb68bbaf9e 100644 --- a/js2/remoteMwEmbed.js +++ b/js2/remoteMwEmbed.js @@ -1,81 +1,81 @@ -/* - * this file exposes some of the functionality of mwEmbed to wikis +/* + * this file exposes some of the functionality of mwEmbed to wikis * that are not yet running the new-upload branch */ -var urlparts = getRemoteEmbedPath(); -var mwEmbedHostPath =urlparts[0]; -var reqAguments =urlparts[1]; +var urlparts = getRemoteEmbedPath(); +var mwEmbedHostPath = urlparts[0]; +var reqAguments = urlparts[1]; -//check if mvEmbed is already loaded (ie the js2 branch is active) in which case do nothing -if( typeof MV_EMBED_VERSION == 'undefined' ){ +// Check if mvEmbed is already loaded (ie the js2 branch is active) in which case do nothing +if( typeof MV_EMBED_VERSION == 'undefined' ) { doPageSpecificRewrite(); -} +} -function doPageSpecificRewrite(){ - //add media wizard: - if( wgAction == 'edit' || wgAction == 'submit' ){ - load_mv_embed( function(){ - importScriptURI(mwEmbedHostPath + '/editPage.js' + reqAguments); +function doPageSpecificRewrite() { + // Add media wizard + if( wgAction == 'edit' || wgAction == 'submit' ) { + load_mv_embed( function() { + importScriptURI( mwEmbedHostPath + '/editPage.js' + reqAguments ); }); } - - //firefogg integration: - if( wgPageName== "Special:Upload" ){ - load_mv_embed( function(){ - importScriptURI(mwEmbedHostPath + '/uploadPage.js' +reqAguments); + + // Firefogg integration + if( wgPageName == "Special:Upload" ){ + load_mv_embed( function() { + importScriptURI( mwEmbedHostPath + '/uploadPage.js' + reqAguments ); }); } - - //oggHandler rewrite: - var vidIdList = []; - var divs = document.getElementsByTagName('div'); - for(var i = 0; i < divs.length; i++){ - if( divs[i].id && divs[i].id.substring(0,11) == 'ogg_player_'){ - vidIdList.push( divs[i].getAttribute("id") ); - } - } - if( vidIdList.length > 0){ - load_mv_embed( function(){ - mvJsLoader.embedVideoCheck(function(){ - //do utilty rewrite of oggHanlder content: - rewrite_for_oggHanlder( vidIdList ); + + // OggHandler rewrite + var vidIdList = []; + var divs = document.getElementsByTagName( 'div' ); + for( var i = 0; i < divs.length; i++ ) { + if( divs[i].id && divs[i].id.substring( 0, 11 ) == 'ogg_player_' ) { + vidIdList.push( divs[i].getAttribute( "id" ) ); + } + } + if( vidIdList.length > 0 ) { + load_mv_embed( function() { + mvJsLoader.embedVideoCheck( function() { + // Do utilty rewrite of OggHandler content: + rewrite_for_OggHandler( vidIdList ); }); }); } } -function getRemoteEmbedPath(){ - for(var i=0; i < document.getElementsByTagName('script').length; i++){ - var s = document.getElementsByTagName('script')[i]; - if( s.src.indexOf('remoteMwEmbed.js') != -1 ){ - var reqStr=''; - var scriptPath=''; - if( s.src.indexOf('?') != -1){ - reqStr = s.src.substr( s.src.indexOf('?') ); - scriptPath = s.src.substr(0, s.src.indexOf('?')).replace('remoteMwEmbed.js', ''); - }else{ - scriptPath = s.src.replace('remoteMwEmbed.js', '') - } - //use the external_media_wizard path: +function getRemoteEmbedPath() { + for( var i = 0; i < document.getElementsByTagName( 'script' ).length; i++ ) { + var s = document.getElementsByTagName( 'script' )[i]; + if( s.src.indexOf( 'remoteMwEmbed.js' ) != -1 ) { + var reqStr = ''; + var scriptPath = ''; + if( s.src.indexOf( '?' ) != -1) { + reqStr = s.src.substr( s.src.indexOf( '?' ) ); + scriptPath = s.src.substr( 0, s.src.indexOf( '?' ) ).replace( 'remoteMwEmbed.js', '' ); + } else { + scriptPath = s.src.replace( 'remoteMwEmbed.js', '' ) + } + // Use the external_media_wizard path: return [scriptPath, reqStr]; } - } + } } -function load_mv_embed( callback ){ - //inject mv_embed if needed: - if( typeof mvEmbed == 'undefined'){ - importScriptURI(mwEmbedHostPath +'/mwEmbed/mv_embed.js' + reqAguments); - check_for_mv_embed( callback ); - }else{ +function load_mv_embed( callback ) { + // Inject mv_embed if needed + if( typeof mvEmbed == 'undefined' ) { + importScriptURI( mwEmbedHostPath + '/mwEmbed/mv_embed.js' + reqAguments ); + check_for_mv_embed( callback ); + } else { check_for_mv_embed( callback ); - } + } } -function check_for_mv_embed( callback ){ - if( typeof MV_EMBED_VERSION == 'undefined'){ - setTimeout('check_for_mv_embed( ' + callback +');', 25); - }else{ +function check_for_mv_embed( callback ) { + if( typeof MV_EMBED_VERSION == 'undefined' ) { + setTimeout( 'check_for_mv_embed( ' + callback + ');', 25 ); + } else { callback(); } } diff --git a/js2/uploadPage.js b/js2/uploadPage.js index 205ca13f52..87158bfc50 100644 --- a/js2/uploadPage.js +++ b/js2/uploadPage.js @@ -1,136 +1,139 @@ /* - * uploadPage.js to be run on specialUpload page. - * controls the invocation of the mvUploader class based on local config. + * This script is run on [[Special:Upload]]. + * It controls the invocation of the mvUploader class based on local config. */ -js2AddOnloadHook( function(){ +js2AddOnloadHook( function() { mwUploadHelper.init(); }); var mwUploadFormTarget = '#mw-upload-form'; -//set up the upoload form bindings once all dom manipluation is done -var mwUploadHelper = { - init:function(){ +// Set up the upload form bindings once all DOM manipulation is done +var mwUploadHelper = { + init: function() { var _this = this; - //if not boolean false set to true: - if(typeof wgEnableFirefogg == 'undefined') + // If wgEnableFirefogg is not boolean false, set to true + if( typeof wgEnableFirefogg == 'undefined' ) wgEnableFirefogg = true; - if( wgEnableFirefogg ){ - //setup the upload handler to firefogg (supports our upload proccess) (should work with the http uploads too) - $j('#wpUploadFile').firefogg({ - //an api url (we won't submit directly to action of the form) - 'api_url' : wgServer + wgScriptPath + '/api.php', + if( wgEnableFirefogg ) { + // Set up the upload handler to Firefogg. Should work with the HTTP uploads too. + $j( '#wpUploadFile' ).firefogg( { + // An API URL (we won't submit directly to action of the form) + 'api_url': wgServer + wgScriptPath + '/api.php', 'form_rewrite': true, - 'target_edit_from' : mwUploadFormTarget, - 'new_source_cb' : function( orgFilename, oggName ){ - if($j('#wpDestFile').val() == "") - $j('#wpDestFile').val( oggName ); - $j('#wpDestFile').doDestCheck({ - 'warn_target':'#wpDestFile-warning' + 'target_edit_from': mwUploadFormTarget, + 'new_source_cb': function( orgFilename, oggName ) { + if( $j( '#wpDestFile' ).val() == "" ) + $j( '#wpDestFile' ).val( oggName ); + $j( '#wpDestFile' ).doDestCheck({ + 'warn_target': '#wpDestFile-warning' }); - } - }); - }else{ - //Add basic upload profile support ( http status monitoring, progress box for browsers that support it etc.) - if($j('#wpUploadFileURL').length != 0){ - $j('#wpUploadFileURL').baseUploadInterface({ - 'api_url' : wgServer + wgScriptPath + '/api.php', - 'target_edit_from' : mwUploadFormTarget + } + }); + } else { + // Add basic upload profile support ( http status monitoring, progress box for + // browsers that support it, etc.) + if( $j( '#wpUploadFileURL' ).length != 0 ) { + $j( '#wpUploadFileURL' ).baseUploadInterface( { + 'api_url': wgServer + wgScriptPath + '/api.php', + 'target_edit_from': mwUploadFormTarget }); } } - if( wgAjaxUploadDestCheck ){ - //do destination check: - $j('#wpDestFile').change(function(){ - $j('#wpDestFile').doDestCheck({ + if( wgAjaxUploadDestCheck ) { + // Do destination check + $j( '#wpDestFile' ).change( function() { + $j( '#wpDestFile' ).doDestCheck({ 'warn_target':'#wpDestFile-warning' }); }); } - //check if we have http enabled & setup enable/disable toggle: - if($j('#wpUploadFileURL').length != 0){ - //set the initial toggleUpType - _this.toggleUpType(true); + // Check if we have HTTP enabled & setup enable/disable toggle: + if( $j( '#wpUploadFileURL' ).length != 0 ) { + // Set the initial toggleUpType + _this.toggleUpType( true ); - $j("input[name='wpSourceType']").click(function(){ + $j( "input[name='wpSourceType']" ).click( function() { _this.toggleUpType( this.id == 'wpSourceTypeFile' ); }); } - $j('#wpUploadFile,#wpUploadFileURL').focus(function(){ - _this.toggleUpType( this.id == 'wpUploadFile' ); - }).change(function(){ //also setup the onChange event binding: - if ( wgUploadAutoFill ) { - mwUploadHelper.doDestinationFill( this ); - } - }); + $j( '#wpUploadFile,#wpUploadFileURL' ) + .focus( function() { + _this.toggleUpType( this.id == 'wpUploadFile' ); + }) + // Also setup the onChange event binding: + .change( function() { + if ( wgUploadAutoFill ) { + mwUploadHelper.doDestinationFill( this ); + } + }); }, /** - * toggleUpType sets the upload radio buttons + * Set the upload radio buttons * * boolean set */ - toggleUpType:function( set ){ - $j('#wpSourceTypeFile').attr('checked', set); - $j('#wpUploadFile').attr('disabled', !set); + toggleUpType: function( set ) { + $j( '#wpSourceTypeFile' ).attr( 'checked', set ); + $j( '#wpUploadFile' ).attr( 'disabled', !set ); - $j('#wpSourceTypeURL').attr('checked', !set); - $j('#wpUploadFileURL').attr('disabled', set); + $j( '#wpSourceTypeURL' ).attr( 'checked', !set ); + $j( '#wpUploadFileURL' ).attr( 'disabled', set ); - //if firefogg is enbaled: toggle action per form select of http upload vs firefogg upload - if( wgEnableFirefogg ){ - $j('#wpUploadFile').firefogg({ - 'firefogg_form_action': $j('#wpSourceTypeFile').attr('checked') + // If Firefogg is enabled, toggle action according to wpSourceTypeFile selection + if( wgEnableFirefogg ) { + $j( '#wpUploadFile' ).firefogg({ + 'firefogg_form_action': $j( '#wpSourceTypeFile' ).attr( 'checked' ) }); } - }, + }, /** - * doDestinationFill fills in a destination file-name based on a source asset name. + * Fill in a destination file-name based on a source asset name. */ - doDestinationFill : function( targetElm ){ - js_log("doDestinationFill") - //remove any previously flagged errors - $j('#mw-upload-permitted,#mw-upload-prohibited').hide(); + doDestinationFill: function( targetElm ) { + js_log( "doDestinationFill" ) + // Remove any previously flagged errors + $j( '#mw-upload-permitted,#mw-upload-prohibited' ).hide(); - var path = $j(targetElm).val(); + var path = $j( targetElm ).val(); // Find trailing part - var slash = path.lastIndexOf('/'); - var backslash = path.lastIndexOf('\\'); + var slash = path.lastIndexOf( '/' ); + var backslash = path.lastIndexOf( '\\' ); var fname; - if (slash == -1 && backslash == -1) { + if ( slash == -1 && backslash == -1 ) { fname = path; - } else if (slash > backslash) { - fname = path.substring(slash+1, 10000); + } else if ( slash > backslash ) { + fname = path.substring( slash+1, 10000 ); } else { - fname = path.substring(backslash+1, 10000); + fname = path.substring( backslash+1, 10000 ); } - //urls are less likely to have a usefull extension don't include them in the extention check - if( wgFileExtensions && $j(targetElm).attr('id') != 'wpUploadFileURL' ){ + // URLs are less likely to have a useful extension. Don't include them in the extension check. + if( wgFileExtensions && $j( targetElm ).attr( 'id' ) != 'wpUploadFileURL' ) { var found = false; - if( fname.lastIndexOf('.')!=-1 ){ - var ext = fname.substr( fname.lastIndexOf('.')+1 ); - for(var i=0; i < wgFileExtensions.length; i++){ - if( wgFileExtensions[i].toLowerCase() == ext.toLowerCase() ) + if( fname.lastIndexOf( '.' ) != -1 ) { + var ext = fname.substr( fname.lastIndexOf( '.' ) + 1 ); + for( var i = 0; i < wgFileExtensions.length; i++ ) { + if( wgFileExtensions[i].toLowerCase() == ext.toLowerCase() ) found = true; } } - if(!found){ - //clear the upload set mw-upload-permitted to error - $j(targetElm).val(''); - $j('#mw-upload-permitted,#mw-upload-prohibited').show().addClass('error'); - //clear the wpDestFile as well: - $j('#wpDestFile').val(''); + if( !found ) { + // Clear the upload. Set mw-upload-permitted to error. + $j( targetElm ).val( '' ); + $j( '#mw-upload-permitted,#mw-upload-prohibited' ).show().addClass( 'error' ); + $j( '#wpDestFile' ).val( '' ); return false; } } // Capitalise first letter and replace spaces by underscores - fname = fname.charAt(0).toUpperCase().concat(fname.substring(1,10000)).replace(/ /g, '_'); + fname = fname.charAt( 0 ).toUpperCase().concat( fname.substring( 1, 10000 ) ).replace( / /g, '_' ); // Output result - $j('#wpDestFile').val( fname ); + $j( '#wpDestFile' ).val( fname ); - //do a destination check - $j('#wpDestFile').doDestCheck({ - 'warn_target':'#wpDestFile-warning' + // Do a destination check + $j( '#wpDestFile' ).doDestCheck({ + 'warn_target': '#wpDestFile-warning' }); } } -- 2.20.1