Go to the documentation of this file.
23 use Wikimedia\ScopedCallback;
38 'originalwidth' =>
'ImageWidth',
39 'originalheight' =>
'ImageLength',
40 'description' =>
'ImageDescription',
41 'title' =>
'ObjectName',
47 wfDebug(
"\$wgSVGConverter is invalid, disabling SVG rendering.\n" );
68 # @todo Detect animated SVGs
69 $metadata = $file->getMetadata();
72 if ( isset( $metadata[
'animated'] ) ) {
73 return $metadata[
'animated'];
97 if ( isset( $metadata[
'translations'] ) ) {
98 foreach ( $metadata[
'translations']
as $lang => $langType ) {
137 # Don't make an image bigger than wgMaxSVGSize on the smaller side
169 $clientWidth =
$params[
'width'];
170 $clientHeight =
$params[
'height'];
171 $physicalWidth =
$params[
'physicalWidth'];
172 $physicalHeight =
$params[
'physicalHeight'];
175 if (
$flags & self::TRANSFORM_LATER ) {
180 if ( isset( $metadata[
'error'] ) ) {
181 $err =
wfMessage(
'svg-long-error', $metadata[
'error'][
'message'] );
188 wfMessage(
'thumbnail_dest_directory' ) );
191 $srcPath =
$image->getLocalRefPath();
192 if ( $srcPath ===
false ) {
194 sprintf(
'Thumbnail failed on %s: could not get local copy of "%s"',
207 $lnPath =
"$tmpDir/" . basename( $srcPath );
208 $ok = mkdir( $tmpDir, 0771 ) && symlink( $srcPath, $lnPath );
210 $cleaner =
new ScopedCallback(
function ()
use ( $tmpDir, $lnPath ) {
211 MediaWiki\suppressWarnings();
214 MediaWiki\restoreWarnings();
218 sprintf(
'Thumbnail failed on %s: could not link %s to %s',
245 public function rasterize( $srcPath, $dstPath, $width, $height,
$lang =
false ) {
253 $args = array_merge( [ $srcPath, $dstPath, $width, $height,
$lang ],
255 if ( !is_callable( $func ) ) {
258 $err = call_user_func_array( $func,
$args );
263 [
'$path/',
'$width',
'$height',
'$input',
'$output' ],
273 if (
$lang !==
false ) {
274 $env[
'LANG'] =
$lang;
277 wfDebug( __METHOD__ .
": $cmd\n" );
282 if (
$retval != 0 || $removed ) {
291 $im =
new Imagick( $srcPath );
292 $im->setImageFormat(
'png' );
293 $im->setBackgroundColor(
'transparent' );
294 $im->setImageDepth( 8 );
296 if ( !$im->thumbnailImage( intval( $width ), intval( $height ),
false ) ) {
297 return 'Could not resize image';
299 if ( !$im->writeImage( $dstPath ) ) {
300 return "Could not write to $dstPath";
311 if ( $metadata ===
false && $file instanceof
File ) {
312 $metadata = $file->getMetadata();
316 if ( isset( $metadata[
'width'] ) && isset( $metadata[
'height'] ) ) {
317 return [ $metadata[
'width'], $metadata[
'height'],
'SVG',
318 "width=\"{$metadata['width']}\" height=\"{$metadata['height']}\"" ];
320 return [ 0, 0,
'SVG',
"width=\"0\" height=\"0\"" ];
325 return [
'png',
'image/png' ];
341 if ( isset( $metadata[
'error'] ) ) {
342 return wfMessage(
'svg-long-error', $metadata[
'error'][
'message'] )->text();
345 $size =
$wgLang->formatSize( $file->getSize() );
348 $msg =
wfMessage(
'svg-long-desc-animated' );
353 $msg->numParams( $file->getWidth(), $file->getHeight() )->params( $size );
355 return $msg->parse();
367 }
catch ( Exception
$e ) {
369 $metadata[
'error'] = [
370 'message' =>
$e->getMessage(),
371 'code' =>
$e->getCode()
373 wfDebug( __METHOD__ .
': ' .
$e->getMessage() .
"\n" );
380 MediaWiki\suppressWarnings();
382 MediaWiki\restoreWarnings();
383 if ( isset( $unser[
'version'] ) && $unser[
'version'] == self::SVG_METADATA_VERSION ) {
396 if ( $meta ===
false ) {
399 if ( !isset( $meta[
'originalWidth'] ) ) {
408 $fields = [
'objectname',
'imagedescription' ];
423 $metadata = $file->getMetadata();
428 if ( !$metadata || isset( $metadata[
'error'] ) ) {
443 if ( isset( self::$metaConversion[
$tag] ) ) {
444 $tag = strtolower( self::$metaConversion[
$tag] );
451 in_array(
$tag, $visibleFields ) ?
'visible' :
'collapsed',
458 return $showMeta ?
$result :
false;
467 if ( in_array(
$name, [
'width',
'height' ] ) ) {
470 } elseif (
$name ==
'lang' ) {
473 wfDebug(
"Invalid user language code\n" );
493 $lang =
"lang{$params['lang']}-";
495 if ( !isset(
$params[
'width'] ) ) {
499 return "$lang{$params['width']}px";
504 if ( preg_match(
'/^lang([a-z]+(?:-[a-z]+)*)-(\d+)px$/', $str, $m ) ) {
505 return [
'width' => array_pop( $m ),
'lang' => $m[1] ];
506 } elseif ( preg_match(
'/^(\d+)px$/', $str, $m ) ) {
507 return [
'width' => $m[1],
'lang' =>
'en' ];
514 return [
'img_lang' =>
'lang',
'img_width' =>
'width' ];
522 $scriptParams = [
'width' =>
$params[
'width'] ];
523 if ( isset(
$params[
'lang'] ) ) {
524 $scriptParams[
'lang'] =
$params[
'lang'];
527 return $scriptParams;
536 if ( !$metadata || isset( $metadata[
'error'] ) ) {
542 if (
$tag ===
'originalwidth' ||
$tag ===
'originalheight' ) {
547 if ( isset( self::$metaConversion[
$tag] ) ) {
validateParam( $name, $value)
static rasterizeImagickExt( $srcPath, $dstPath, $width, $height)
Media transform output for images.
error also a ContextSource you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
static array $metaConversion
A list of metadata tags that can be converted to the commonly used exif tags.
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
getMetadata()
Get handler-specific metadata Overridden by LocalFile, UnregisteredLocalFile STUB.
parseParamString( $str)
Parse a param string made with makeParamString back into an array.
if(!isset( $args[0])) $lang
formatMetadata( $file, $context=false)
getMetadataType( $image)
Get a string describing the type of metadata, for display purposes.
$wgSVGMaxSize
Don't scale a SVG larger than this.
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
mustRender( $file)
True if handled types cannot be displayed directly in a browser but can be rendered.
unserialize( $serialized)
wfHostname()
Fetch server name for use in error reporting etc.
Allows to change the fields on the form that will be generated $name
getThumbType( $ext, $mime, $params=null)
Get the thumbnail extension and MIME type for a given source MIME type.
getScriptParams( $params)
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
getMetadata( $file, $filename)
rasterize( $srcPath, $dstPath, $width, $height, $lang=false)
Transform an SVG file to PNG This function can be called outside of thumbnail contexts.
getLongDesc( $file)
Subtitle for the image.
Implements some public methods and some protected utility functions which are required by multiple ch...
$wgSVGConverterPath
If not in the executable PATH, specify the SVG converter path.
normaliseParams( $image, &$params)
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books $tag
isEnabled()
False if the handler is disabled for all files.
Media handler abstract base class for images.
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as $wgLang
when a variable name is used in a it is silently declared as a new masking the global
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check $image
doTransform( $image, $dstPath, $dstUrl, $params, $flags=0)
if( $ext=='php'|| $ext=='php5') $mime
static isValidBuiltInCode( $code)
Returns true if a language code is of a valid form for the purposes of internal customisation of Medi...
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account incomplete not yet checked for validity & $retval
wfEscapeShellArg()
Version of escapeshellarg() that works better on Windows.
canAnimateThumbnail( $file)
We do not support making animated svg thumbnails.
getAvailableLanguages(File $file)
Which languages (systemLanguage attribute) is supported.
getImageSize( $file, $path, $metadata=false)
static scaleHeight( $srcWidth, $srcHeight, $dstWidth)
Calculate the height of a thumbnail using the source and destination width.
getCommonMetaArray(File $file)
Get an array of standard (FormatMetadata type) metadata values.
wfTempDir()
Tries to get the system directory for temporary files.
getDefaultRenderLanguage(File $file)
What language to render file in if none selected.
visibleMetadataFields()
Get a list of metadata items which should be displayed when the metadata table is collapsed.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
$wgSVGConverters
Scalable Vector Graphics (SVG) may be uploaded as images.
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "<
const SVG_METADATA_VERSION
unpackMetadata( $metadata)
makeParamString( $params)
getParamMap()
Get an associative array mapping magic word IDs to parameter names.
$wgSVGConverter
Pick a converter defined in $wgSVGConverters.
isVectorized( $file)
The material is vectorized and thus scaling is lossless.
it s the revision text itself In either if gzip is the revision text is gzipped $flags
isMetadataValid( $image, $metadata)
Check if the metadata string is valid for this handler.
the array() calling protocol came about after MediaWiki 1.4rc1.
wfShellExecWithStderr( $cmd, &$retval=null, $environ=[], $limits=[])
Execute a shell command, returning both stdout and stderr.
wfRandomString( $length=32)
Get a random string containing a number of pseudo-random hex characters.