EmbedVideo: различия между версиями

Материал из свободной русской энциклопедии «Традиция»
Перейти к навигации Перейти к поиску
(→‎Исходный код: + Fixed YouTube videos (they now require &rel=1))
(→‎Исходный код: полностью заменил версию)
Строка 10: Строка 10:
 
  * EmbedVideo.php - Adds a parser function embedding video and audio from popular sources.
 
  * EmbedVideo.php - Adds a parser function embedding video and audio from popular sources.
 
  * @author Mithgol the Webmaster, based on the work by Jim R. Wilson
 
  * @author Mithgol the Webmaster, based on the work by Jim R. Wilson
  * @version 0.1.2.Mithgol.1
+
  * @version 0.1.2.Mithgol.2
 
  * @copyright Copyright (C) 2007 Jim R. Wilson, Copyright (C) 2008 Mithgol the Webmaster
 
  * @copyright Copyright (C) 2007 Jim R. Wilson, Copyright (C) 2008 Mithgol the Webmaster
 
  * @license The MIT License - http://www.opensource.org/licenses/mit-license.php  
 
  * @license The MIT License - http://www.opensource.org/licenses/mit-license.php  
Строка 74: Строка 74:
 
     'url'=>'http://www.traditio.ru/index.php?title=EmbedVideo',
 
     'url'=>'http://www.traditio.ru/index.php?title=EmbedVideo',
 
     'description'=>'Adds a parser function embedding video and audio from popular sources.',
 
     'description'=>'Adds a parser function embedding video and audio from popular sources.',
     'version'=>'0.1.2.1'
+
     'version'=>'0.1.2.2'
 
);
 
);
  

Версия от 14:08, 7 января 2008

EmbedVideo — расширение MediaWiki, создающее новую функцию парсера («ev»), позволяющую внедрять видеоролики на вики-страницы.

Первоначальный создатель — Jim R. Wilson (см. описание расширения на сайте MediaWiki и на странице создателя).

Mithgol the Webmaster, участник Традиции, доработал код расширения, чтобы оно могло невозбранно использоваться и для вставки звукозаписей, и для вставки таких видеопроигрывателей, ширина которых не относится к высоте в пропорции 425 / 350.

Исходный код

<?php
/*
 * EmbedVideo.php - Adds a parser function embedding video and audio from popular sources.
 * @author Mithgol the Webmaster, based on the work by Jim R. Wilson
 * @version 0.1.2.Mithgol.2
 * @copyright Copyright (C) 2007 Jim R. Wilson, Copyright (C) 2008 Mithgol the Webmaster
 * @license The MIT License - http://www.opensource.org/licenses/mit-license.php 
 * ---------------------------------------------------------------------------------------
 * Description:
 *     This is a MediaWiki extension which adds a parser function for embedding 
 *     video and audio from popular sources (configurable).
 * Requirements:
 *     MediaWiki 1.6.x, 1.9.x, 1.10.x or higher
 *     PHP 4.x, 5.x or higher.
 * Installation:
 *     1. Drop this script (EmbedVideo.php) in $IP/extensions
 *         Note: $IP is your MediaWiki install dir.
 *     2. Enable the extension by adding this line to your LocalSettings.php:
 *         require_once('extensions/EmbedVideo.php');
 * Version Notes:
 *     version 0.1.2.Mithgol.2:
 *         Fixed YouTube videos (they now require &rel=1).
 *     version 0.1.2.Mithgol.1:
 *         Bug fix: does not require width / height to be 425 / 350.
 *         (Now supports imeem.com audio, and YouTube does not glitch.)
 *         List of services is altered accommodating to the new requirements
 *         and general popularity of services across Traditio.Ru
 *     version 0.1.2:
 *         Bug fix: now can be inserted in lists without breakage (from newlines)
 *         Code cleanup: would previously give 'Notice' messages in PHP strict.
 *     version 0.1.1:
 *         Code cleanup: no functional difference.
 *     version 0.1:
 *         Initial release.
 * -----------------------------------------------------------------------
 * Copyright (c) 2007 Jim R. Wilson
 * Copyright (c) 2008 Mithgol the Webmaster
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy 
 * of this software and associated documentation files (the "Software"), to deal 
 * in the Software without restriction, including without limitation the rights to 
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 
 * the Software, and to permit persons to whom the Software is furnished to do 
 * so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all 
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 
 * OTHER DEALINGS IN THE SOFTWARE. 
 * -----------------------------------------------------------------------
 */
 
# Confirm MW environment
if (defined('MEDIAWIKI')) {

# Credits
$wgExtensionCredits['parserhook'][] = array(
    'name'=>'EmbedVideo',
    'author'=>'Mithgol the Webmaster (based on the work by Jim R. Wilson)',
    'url'=>'http://www.traditio.ru/index.php?title=EmbedVideo',
    'description'=>'Adds a parser function embedding video and audio from popular sources.',
    'version'=>'0.1.2.2'
);

/**
 * Wrapper class for encapsulating EmbedVideo related parser methods
 */
class EmbedVideo {

    /**
     * Sets up parser functions.
     */
    function setup( ) {
    
        # Setup parser hook
    	global $wgParser, $wgVersion;
    	$hook = (version_compare($wgVersion, '1.7', '<')?'#ev':'ev');
    	$wgParser->setFunctionHook( $hook, array($this, 'parserFunction') );
    	
    	# Add system messages
    	global $wgMessageCache;
        $wgMessageCache->addMessage('embedvideo-missing-params',
                                    'EmbedVideo is missing a required parameter.');
        $wgMessageCache->addMessage('embedvideo-bad-params',
                                    'EmbedVideo received a bad parameter.');
        $wgMessageCache->addMessage('embedvideo-unparsable-param-string',
                                    'EmbedVideo received the unparsable parameter string "<tt>$1</tt>".');
        $wgMessageCache->addMessage('embedvideo-unrecognized-service',
                                    'EmbedVideo does not recognize the video service "<tt>$1</tt>".');
        $wgMessageCache->addMessage('embedvideo-bad-id',
                                    'EmbedVideo received the bad id "$1" for the service "$2".');
        $wgMessageCache->addMessage('embedvideo-illegal-width',
                                    'EmbedVideo received the illegal width parameter "$1".');
        $wgMessageCache->addMessage('embedvideo-illegal-height',
                                    'EmbedVideo received the illegal height parameter "$1".');
        $wgMessageCache->addMessage('embedvideo-embed-clause', 
            '<object width="$2" height="$3">'.
            '<param name="movie" value="$1"></param>'.
            '<param name="wmode" value="transparent"></param>'.
            '<embed src="$1" type="application/x-shockwave-flash" '.
            'wmode="transparent" width="$2" height="$3">'.
            '</embed></object>'
        );
    }
    
    /**
     * Adds magic words for parser functions.
     * @param Array $magicWords
     * @param String $langCode
     * @return Boolean Always true
     */
    function parserFunctionMagic( &$magicWords, $langCode='en' ) {
        $magicWords['ev'] = array( 0, 'ev' );
        return true;
    }
    
    /**
     * Embeds video of the chosen service
     * @param Parser $parser  Instance of running Parser.
     * @param String $service Which online service has the video.
     * @param String $id      Identifier of the chosen service
     * @param String $width   Width of video (optional)
     * @param String $height  Height of video (optional)
     * @return String Encoded representation of input params (to be processed later)
     */
    function parserFunction( $parser, $service=null, $id=null, $width=null, $height=null ) {
        if ($service===null || $id===null) return '<div class="errorbox">'.wfMsg('embedvideo-missing-params').'</div>';

        $params = array(
            'service' => trim($service),
            'id'      => trim($id),
            'width'   => ($width===null?null:trim($width)),
            'height'  => ($height===null?null:trim($height))
        );

        global $wgEmbedVideoMinWidth, $wgEmbedVideoMaxWidth;
        if (!is_numeric($wgEmbedVideoMinWidth) || $wgEmbedVideoMinWidth<100) $wgEmbedVideoMinWidth = 100;
        if (!is_numeric($wgEmbedVideoMaxWidth) || $wgEmbedVideoMaxWidth>2048) $wgEmbedVideoMaxWidth = 2048;

        global $wgEmbedVideoMinHeight, $wgEmbedVideoMaxHeight;
        if (!is_numeric($wgEmbedVideoMinHeight) || $wgEmbedVideoMinHeight<10) $wgEmbedVideoMinHeight = 10;
        if (!is_numeric($wgEmbedVideoMaxHeight) || $wgEmbedVideoMaxHeight>2048) $wgEmbedVideoMaxHeight = 2048;
        
        global $wgEmbedVideoServiceList;
        $service = $wgEmbedVideoServiceList[$params['service']];
        if (!$service) return '<div class="errorbox">'.wfMsg('embedvideo-unrecognized-service',
                                                             @htmlspecialchars($params['service'])).'</div>';

        $id = htmlspecialchars($params['id']);
        $idpattern = ( isset($service['id_pattern']) ? $service['id_pattern'] : '%[^A-Za-z0-9_\\-]%' );
        if ($id==null || preg_match($idpattern,$id)) {
            return '<div class="errorbox">'.wfMsgForContent('embedvideo-bad-id', $id,
                                                            @htmlspecialchars($params['service'])).'</div>';
        }

        $defaultWidth  = ( isset($service['default_width'])  ? $service['default_width']  : 425 );
        $defaultHeight = ( isset($service['default_height']) ? $service['default_height'] : 350 );
     
        # Build URL and output embedded flash object
        $ratio = $defaultWidth / $defaultHeight;

        $width = $defaultWidth;
        if ($params['width']!==null) {
            // Check whether $params['width'] is invalid:
            if (!is_numeric($params['width']) || 
                $params['width'] < $wgEmbedVideoMinWidth ||
                $params['width'] > $wgEmbedVideoMaxWidth
            ) return 
                '<div class="errorbox">'.
                wfMsgForContent('embedvideo-illegal-width',
                                @htmlspecialchars($params['width'])
                ).'</div>';
            $width = $params['width'];
        }

        $height = round($width / $ratio);
        if ($params['height']!==null) {
            // Check whether $params['height'] is invalid:
            if (!is_numeric($params['height']) || 
                $params['height'] < $wgEmbedVideoMinHeight ||
                $params['height'] > $wgEmbedVideoMaxHeight
            ) return 
                '<div class="errorbox">'.
                wfMsgForContent('embedvideo-illegal-height',
                                @htmlspecialchars($params['height'])
                ).'</div>';
            $height = $params['height'];
        }

        $url = wfMsgReplaceArgs($service['url'], array($id, $width, $height));
        
        return $parser->insertStripItem(
            wfMsgForContent('embedvideo-embed-clause', $url, $width, $height),
            $parser->mStripState
        );
    }

}

/**
 * Wrapper function for language magic call (hack for 1.6)
 */

# Create global instance and wire it up!
$wgEmbedVideo = new EmbedVideo();
$wgExtensionFunctions[] = array($wgEmbedVideo, 'setup');
if (version_compare($wgVersion, '1.7', '<')) {
    # Hack solution to resolve 1.6 array parameter nullification for hook args
    function wfEmbedVideoLanguageGetMagic( &$magicWords ) {
        global $wgEmbedVideo;
        $wgEmbedVideo->parserFunctionMagic( $magicWords );
        return true;
    }
    $wgHooks['LanguageGetMagic'][] = 'wfEmbedVideoLanguageGetMagic';
} else {
    $wgHooks['LanguageGetMagic'][] = array($wgEmbedVideo, 'parserFunctionMagic');
}

/*
 *  Now starting the list of services.
 *
 *  It may be altered via LocalSettings.php file,
 *  see examples at http://jimbojw.com/wiki/index.php?title=EmbedVideo_Extension#Configuration
 *
 *  Only services used in Traditio (www.traditio.ru) are listed here,
 *  see also the original list at http://jimbojw.com/wiki/index.php?title=EmbedVideo
*/

$wgEmbedVideoServiceList = array(
    'googlevideo' => array(
        'id_pattern'     => '%[^0-9\\-]%',
        'url'            => 'http://video.google.com/googleplayer.swf?docId=$1',
        'default_width'  => 400,
        'default_height' => 326
    ),
    'youtube' => array(
        'url'            => 'http://www.youtube.com/v/$1&rel=1',
        'default_width'  => 425,
        'default_height' => 355
    ),
    'rutube' => array(
        'id_pattern'     => '%[^a-z0-9]%',
        'url'            => 'http://video.rutube.ru/$1',
        'default_width'  => 400,
        'default_height' => 353
    ),
    'imeemtrack' => array(
        'id_pattern'     => '%[^A-Za-z0-9]%',
        'url'            => 'http://media.imeem.com/m/$1/aus=false/',
        'default_width'  => 300,
        'default_height' => 80
    ),
    'imeemsequence' => array(
        'id_pattern'     => '%[^A-Za-z0-9]%',
        'url'            => 'http://media.imeem.com/pl/$1/aus=false/',
        'default_width'  => 300,
        'default_height' => 290
    ),
    'imeemshuffle' => array(
        'id_pattern'     => '%[^A-Za-z0-9]%',
        'url'            => 'http://media.imeem.com/pl/$1/aus=false/autoShuffle=true/',
        'default_width'  => 300,
        'default_height' => 290
    )
);

} # End MW Environment wrapper
?>