Manual talk:Tag extensions
Any user names refer to users of that site, who are not necessarily users of MediaWiki.org (even if they share the same username).
Subclusion
editOk, I've written my extension, and it works. But what if I want to use it in a template or with other subclusion? For example:
Example munges "{{{1}}}" into "<example>{{{1}}}</example>"
As is, the example tag acts very nearly like the nowiki tag. --Ssd 02:02, 3 Mar 2005 (UTC)
There is an answer to this in the FAQ: MediaWiki extensions FAQ. See: 'How do I render wikitext in my extension?'
- I cannot see an answer to the template paramter problem in the FAQ. I tried both recipes from this FAQ in my extension but the parameter kept {{{1}}} instead of been rewritten with the given template parameter --Rrosenfeld 19:34, 27 July 2005 (UTC)
Must an extension be in php? How could I include python code, for example, within a page?
- You'd have to write PHP code which calls an external program. --brion 02:38, 18 Mar 2005 (UTC)
Templates and Extensions
editHi All, i had the same problems as Rrosenfeld, i needed template parameters to be replaced when you use extensions in templates. It took me a whole day to figure out where to do it, but i've hacked the parser to replace template parameters also in extensions ( and i guess also everywhere else where it not worked... don't know that... ) If you want to take that into your main branch or for every body else who needs this, have a look at the Parser.php in the includes directory and replace
function replaceVariables( $text, $args = array() ) { [...] if ( $this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI ) { # Argument substitution $text =preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text ); } [...] }
with
function replaceVariables( $text, $args = array() ) { [...] if ( $this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI ) { # Argument substitution $text =preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text ); # Replace also everywhere in stripped states. foreach ( $this->mStripState as $sectionKey => $sectionVal ) { foreach ( $sectionVal as $stripKey => $stripVal ) { $this->mStripState[$sectionKey][$stripKey] = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $stripVal ); } } } [...] }
Of course, i've not tested that very much and I did not dig so deep into all the code to eleminiate the possibility that this will fuck up all your other stuff, so be warned and have fun... :) Regards, Andreas Neumann 62.109.78.120 16:13, 20 December 2005 (UTC)
Great bit of code but it works on the stuff being passed back INTO wiki so if you pass a variable called fred into the extension then inside the extension you get fred rather than the contents of fred - which means you can't manipulate the contents of a variable within the extension. Steve A I've been thinking about this. What needs to be done is for the external function to be able to parse variables - so I'm off on a search of the code trying to work out if its possible to access the variable contents so it can parse them Steve A
I finally managed to tweak the parser class to allow template arguments handling INSIDE extensions. BTW I made another interesting tweak that allows an extension to parse possible nested extensions output. Everything is done inside 'Strip()' and 'BraceSubstitution()' constructors. It works well but it is still in testing (with MW 1.5.7). I'll publish the code within a week or two. Regards, RG 82.230.94.149
What happened to this? I've just gone through the same process and also am stuck at the point where I can't actually use variable content inside my extension. Anyone know of the code? or if this got addressed in more recent versions of MW? --Fizik aka Chris E 20:42, 14 July 2006 (UTC)
- I'm not precisely sure what you guys are trying to fix. What version of MW are you using? — Ambush Commander(Talk) 23:55, 14 July 2006 (UTC)
- I am sorry, I was long in publishing the parser tweaks I made on the 1.5.7 version (and then more recently to the 1.6.3). You can find them here : User:Guilrom/ParserRGVersion. Regards, RG 10:09, 16 July 2006 (UTC)
- It's exactly the extension for my need. I try to test it to MW 1.7.1 but it seems the strip methode has a lot of change. have you planned to make a port for this release of Mediawilki ? thx. --Ctof 10:24, 4 August 2006 (UTC)
Attributes
editIs there any support for putting attributes on the start tag to control the details of the transformation? Bovlb 17:05, 25 Mar 2005 (UTC)
- According to Brion Vibber, "Not yet."[1] bug #684 Bovlb 05:02, 6 Jul 2005 (UTC)
- You can use div elements to be invisible and contain attributes and match them in your extension code. This example will extract all the attributes from a named div class: Nad
if (preg_match('/<div\\s+class="MyExtension"\\s+(.+?)\\s*\\/?>/', $article, $match)) { preg_match_all('/(\\w+?)="(.+?)"/', $match[1], $match, PREG_SET_ORDER); foreach ($match as $i) echo "attribute $i[1] contains $i[2]"; }
More than one?
editI'm making simple extensions, and the first one works great, but I'm wondering how to do more from here.
response
You declare them on the function wfExampleExtension and simply create the respective functions:
... $wgParser->setHook( "example1", "renderExample1" ); $wgParser->setHook( "example2", "renderExample2" ); $wgParser->setHook( "example3", "renderExample3" ); ... function renderExample1 {... # responds to <example1> function renderExample2 {... # responds to <example2> function renderExample3 {... # responds to <example3>
- Abdon
What links here
editIf an XML tag extension transforms the content into regular Wiki markup and passes it to the parser, will this get picked up by "What links here"? Bovlb 14:08, 24 Apr 2005 (UTC)
- According to Brion Vibber, "It should, I think, but no guarantees. Try it and see."[2] Bovlb 05:02, 6 Jul 2005 (UTC)
- All the link-tables are calculated from the links in the wikitext during parsing, and updated in the database when articles are saved. So as long as the parser finds valid link syntax in the text it will work regardless of how those links got there.
- Nad 19:53, 7 March 2006 (UTC)
Caching output example?
editI'd like to see an example of how to cache extension output into a /tmp/ directory.
- I guess my biggest question is how to program a filename for the output. My extension can turn a list of .mp3 urls into an .m3u playlist for streaming. Some extensions make filenames that look like checksums, is that right? What is the best practice? --Forresto 13:01, 1 May 2005 (UTC)
- You can use sha1 if you want
Here is a sample cache disable stuff. But this is not working. This stuff is trying to update the page last seen time to force the cache to be outdated (so it will not use the cache). But the $wgTitle object is empty. Why the hell isn't it feeded with the current page values ? I can't answer this.
function wfShadowTalk() {
global $wgParser;
global $wgTitle; $dbw =& wfGetDB( DB_MASTER );
$dbw->update( 'cur', array( 'cur_touched' => $dbw->timestamp( time() + 120 ) ), array( 'cur_namespace' => $wgTitle->getNamespace(), 'cur_title' => $wgTitle->getDBkey() ),'shadowtalk' );
# register the extension with the WikiText parser # the first parameter is the name of the new tag. # In this case it defines the tag <example> ... </example> # the second parameter is the callback function for # processing the text between the tags $wgParser->setHook( "shadowtalk", "st_render" ); }
How can I process the page title in an extension?
editI am working on an extension that needs the page title in link format, for example if used in en:Fernán Caballero it could return "Fern%E1n_Caballero" and if used on en:Category:Spanish novelists it would return "Category:Spanish_novelists" ... what variable is that and how can I access it from my extension? --Forresto 13:06, 18 May 2005 (UTC)
I was able to get this to work by adding this code to the hook function:
global $wgTitle; $output=$wgTitle->mPrefixedText;
--Boone 22:26, 17 September 2005 (UTC)
Disable Caching?
editI wrote a simple extention to show the dynamic content, for example, showing the current time. But it seems the wiki page is cached, so even if I refresh the page, the time doesn't get refreshed!
It happens even with the { { CURRENTTIME } } 13:49 - try refresh this page see if the time changes!
Anyway to disable the caching for the page/extentions?
- Yes. Have a look there: MediaWiki_extensions_FAQ. You might write an extension which does nothing else but disable/expire the cache on every view of the page. --Klaws 13:04, 23 September 2005 (UTC)
Additional input box in article submit
editOk - this may be simple to all you guys, But I cant get my head around it - but I think it would be a great Idea.
Im looking for a way to add an additional textbox to the article add/edit form. This should throw this into the database or somewheer else closeby.
The article page should then, when called, show a googlemap, using the contents of the textbox as its main point of reference.
And possibly, a main googlemap on the main page showing all the opints colected so far.
Any ideas on where to start?
Cheers! Nick
- This is totally beyond extending wiki markup: you'll have to change the database schema and all sorts of other nasty things. Ambush Commander 02:47, 1 March 2006 (UTC)
$parser parameter
editI decided to go back to the start as I'd messed things up so I did a cut and paste of the latest code from the content page. This includes the $parser parameter in the function definition but not in the call so you get a warning about Missing argument 3. Obviously being able to get to parser objects in the external functions should allow much more "interaction" between wiki and the extension. Steve A
- It seems that you're still running an older version of MediaWiki. I suggest you upgrade. Ambush Commander 21:22, 5 March 2006 (UTC)
- I downloaded the latest wiki code release. Did a clean install. Cut and pasted the code from the page here into the right place. Edited the LocalSettings.php file, created my test page and it happily reports (with PHP errors turned on) "Warning: Missing argument 3 for renderexample() in /webstuff/wiki/extensions/pncextensions.php on line 26" where line 26 contains function renderExample( $input, $argv, &$parser ) {
Has anyone managed to get this to work? (the third parameter)? I've hacked together something using globals so that I can use the parser functions but I can't get my function to produce a string which contains expanded template values. It doesn't help that the documentation is all over the place and as things have changed from version to version its not all valid.
- It doesn't work. I checked myself too. The quickest way to get around it is to declare
global $wgParser;
which (theoretically) is equivalent to what the third parameter would pass. I'm going to add a disclaimer. Ambush Commander 20:51, 15 March 2006 (UTC)
A backport has been made in the code for 1.5 branch which will cause this to start working in 1.5.8, among other hooks. Rob Church Talk 19:09, 24 March 2006 (UTC)
- Article text accordingly updated. Ambush Commander 22:12, 24 March 2006 (UTC)
OK I'm now on 1.6.6 and I've been told that I should use the parser object that is passed in. I've recoded my extensions but I'm still finding something odd which suggests the parser object gets lost. If I have an extension that takes lots of fields and I decide to create "short" versions of some of the more complex functions then when the short version calls the full version the parser object seems to get lost even though I pass it into the first extension which passes it into the second.... Don't tell me... I can't do that ;)
Well I just got the latest version of Wikimedia..I'd been stuck on an earlier version due to me not having PHP5.. .but now I've compiled it and switched Apache2 to using the php5 library I took the plunge and upgraded a development wiki... Bad news... I see that the method to parse ouptut has changed, yet again, and all I've got now is piles of UNIQ..... QINU blocks... Has anyone actually documented in a clear and consise method the way of moving from using global $wgparser to the new method? --Steve A 12:47, 10 March 2007 (UTC)
How to create a simple new page from a 'hook'ed in PHP program?
editI'm doing fine customizing output etc. from within my PHP program but can't seem to find simple examples or documentation about how to create a new page and write something to it directly from within PHP. Spent too many hours looking at the source code and finally came to the conclusion it can't be as difficult as I'm making it. I must be missing something. Could some kind soul point me in the direction of a simple example or documentation that shows how to write "Hello world" to a new page? Or just outline the general flow of calls from here and I should be able to figure it out. Thanks! Jimkloss 10:54, 21 March 2006 (UTC)
- Had you read the mailing list archives for MediaWiki, you'd know this was a question I answered quite often. The response is to look at the code in maintenance/InitialiseMessages.inc which has quite a nice example of programmatically creating pages. Basically, create a new title, create an article with that title, set up the revision, then save the page and the revision and update the revision on the page record. Rob Church Talk 19:08, 24 March 2006 (UTC)
- Hmm... no link to a page on meta means that we should probably right a page on that. I'll try my hand at it some time. Ambush Commander 21:53, 24 March 2006 (UTC)
- Thanks. I did eventually figure it out and also started subscribing to the mailing list. I hope to write a simplified page on our site describing some of the ways I'm creating a dynamic wiki chat room and dynamic webcast playlists in case anyone who's just getting started, as I am, would find a "Dummies guide to quick mediawiki hacks and system calls" helpful. By the way, the reason that creating a new page was so problematic for me (yes, I'd used example code from 2 or 3 different sources, generally understood the flow, yet never got a new page created) was because I was trying to create a new page called "test". The problem? As per wikimedia rules, I needed to create "Test". I had (falsely and stupidly) assumed the mediawiki code would correct this breach of rules. Anyway, thanks for the guidance. Jimkloss 03:44, 27 March 2006 (UTC)
How to display html file inside a Wiki page
editI am trying to figure out how to do this. Call the file test.html and store it in wiki/extensions folder. When I do a fopen it returns:
No such file or directory in /home/elvis/public_html/wiki/extensions/YourExtensionName.php
Where should I store the folder and/or how do I open it? Maybe there is a simpler way of doing this even. -- Thanks, JohnE
- Your probably best off creating a new configuration directive like
$wgHTMLFilesDirectory
which contains the full path to the folder you want. However, you can probably keep it the way it is... but I need to see some more code. Ambush Commander 22:12, 24 March 2006 (UTC)
- Thanks for the quick response. I have been trying but still haven't got anywhere. I have used the code from the article page, and only changed the function renderExample as follows:
# The callback function for converting the input text to HTML output function renderExample( $input, $argv ) { # $argv is an array containing any arguments passed to the # extension like <example argument="foo" bar>.. # Put this on the sandbox page: (works in MediaWiki 1.5.5) # <example argument="foo" argument2="bar">Testing text **example** in between the new tags</example> $filename2 = "/wiki/extensions/recent_tour.html"; $fp = fopen($filename2,"r") or die("Couldn't open $filename"); while ( ! feof( $fp ) ) { $line = fgets( $fp, 1024 ); $output .= $line; } return $output; } ?>
- The file recent_tour.html is a standard html table containing recent tour information. It contains multiple columns and rows. - Thanks, JohnE, 202.49.72.33 00:54, 31 March 2006 (UTC)
I did something similar :
function renderCode( $input, $argv ) { $lines = file('./extras/file.code'); $output=''; foreach ($lines as $line_num => $line) { $output.=$line; } return $output; }
where extras is a directory under my wiki install. However I cannot stop the wiki parser from parsing it and messing stuff up. I had a bit of Javascript in there and wiki didn't like the double ampersand logic code and replaced it with && Also if there was a leading space on a line it decided it was enclosed in a pre. Is there any easy way of telling the parser to leave the stuff inside a specific extension well alone? Steve A 14:48, 24 April 2006 (UTC)
I've solved this now by basically forcing the code through the wiki parser as HTML :
$lines = file($filename); $output=''; foreach ($lines as $line_num => $line) { $output.=$line; } $output=$wgOut->addHTML($output); return $output;
Most Linked to page
editIf your extension produces wiki style links then I used to find that if I wanted those links to be picked up in the Special:Mostlinked page then all I needed to do was touch the page with the extension in it and those links would be counted in the Most Linked to Page - it was as the final rendered page was scanned for links. Under Mediawiki 1.6.6 this no longer seems to be the case and only hard coded links in the page are now included. Is there any way of making it so that these "soft" links are included? Steve A
- Update: I double checked this with two installations (1.6.6 and 1.5.5 side by side) and 1.5.5 happily finds links created by extensions when the page is rendered after editing and records them in the pagelinks table. 1.6.6 doesn't. So if anyone else has found this I though I'd let you know that I've raised it as a minor bug. Steve A
Form Processing
editIf I wanted to add a feedback form or something like that, would it be possible to use this? If so, how would I handle the form processing? Would that just go in a regular php file like form_processing.php?
- I've done this before, it's a useful way of adding forms to pages without allowing HTML. Simply hard-code the form HTML into the tag output, and ignore anything inside. — Ambush Commander(Talk) 23:00, 21 July 2006 (UTC)
Passing extension-parsed data to templates
editI wrote an extension to rewrite a date format (not a normal calendar) and it works great, but when I tried to use the <date>...</date> tag as input to a template, instead of my nice, formatted wikitext, I get strings like "UNIQ7dcd9aca33200a81-date-14c1dc322856b22b00000001-QINU". If it's not in the template, it seems to work fine. I've included the code on my user page (User:Socoljam/ardaDates-code).
All the extension does is take a date like $1 $2 $3 $4
and return something formatted like
[[$1 $2|$1]] [[$2]] [[$3 $4|$3]] [[$4]]
I'm not sure if this is the same problem Andreas had earlier (see #Templates and Extensions) but I don't think that it is.
I go into much more detail on my user page.
(Sorry, forgot to sign) Socoljam 09:47, 22 July 2006 (UTC)
- I have a similar problem but it's not related to templates. I get the above mentioned type of string if I use my new tag more than once on a page. Only the last instance of the tag will render correctly all the previous once will be rendered as those placeholder strings. Any ideas what might be causing it?
- Thanks to some conversation on Extension_talk:NiceCategoryList, I found the fix for this. It had nothing to do with templates. I'm including the fix on its own page.
The solution to this is to use a parser function instead. I'll add some docs to the page about it. -- Tim Starling 08:16, 30 September 2006 (UTC)
Caching Issue?
editI know this is a caching issue but I don't know if the above code will solve it. We're running the newest version of wikimedia. I have a page which displays content from an SQL query with the hope that the content will update dynamically. However, what I have now is something that updates only when a user goes in and hits edit -- resubmit. I installed the disable caching hack to the code but it hasn't helped. Any ideas on how to make it requery the database everytime someone loads the page?
- Extensions_FAQ#How_do_I_disable_caching_for_pages_using_my_extension.3F --91.12.18.129 20:40, 27 January 2010 (UTC)
Non - Ascii characters in arguments.
editHi. I quest that my problem is rather php-type then MediaWiki-type, but I hope I will find some answers here.
When I do my on extension, is there a way to manage non-ascii characters names?
I mean, I would like to users be able to write something like:
<postać siła='9'>Soem text here</postać>
instead of
<postac sila='9'>Some text here</postac>
I manage to make extension which response to <postać> tag (by simply having source code written in UTF-8), but arguments seams not work in this way. I mean, the code:
function wfExampleExtension() { global $wgParser; $wgParser->setHook( "character", "renderCharacter" ); $wgParser->setHook( "postać", "renderPostac" ); } function renderCharacter( $input, $argv, &$parser ) { $output = "Input:". $input; $output .= "<br /><br />Argument:" . $argv["straight"]; return $output; } function renderPostac($input, $argv, &$parser ){ $argv["straight"] = $argv['siła']; return renderCharacter($input, $argv, &$parser ); }
reacts on:
<postać siła='10'>Test input</postać>
like thits:
Input: Test input Argument:
Egon 13:06, 9 October 2006 (UTC)
Debugging
editSo what's the accepted way of adding debugging output to an extension? —Sledged (talk) 17:14, 24 May 2007 (UTC)
Note that the above conversation may have been edited or added to since the transfer. If in doubt, check the edit history.
New Tables
editWhat is the recommended way of writing an extension that stores some additional information in the database? Is there some form of API to register “I want a new table foo with the following layout: …“ or would I have to write the setup code myself? --217.84.104.47 15:47, 9 July 2007 (UTC)
Parser functions vs. tag functions
editThe intro to the parser functions section states that one has to expand templates by hand. For what MediaWiki versions is this true? I am running 1.10 and I seem to be able to expand templates just fine if I pass the text between the tags to $parser->recursiveTagParse(). No manual parsing needed. Should we correct the article? Egfrank 05:56, 8 August 2007 (UTC)
Table of Contents Extension
editI've been writing up a couple extensions to power certain aspects of my own site (family of sites, eventually), and one (albeit minor) roadblock I've run into is adding an item to the table of contents (as on [3]) - I would be able to simply call $wgOut->addWikiText('==Items Dropped==')
, but I need the [edit] link to be custom - I can't simply have it opening the MediaWiki editor for a section of that page; I need it to point to a special page.
I've done some looking through the code, but I can't find any way to easily add an anchor link to the table of contents. I was trying to add a little hack for it, but it seems that Parser::formatHeadings() is not even being called, and that's the only place I could find to look. Could anyone point me in the right direction? ;) 68.80.149.10 05:15, 10 August 2007 (UTC)
Moving this article...need to rethink the title and/or the organization of this topic
editI'm still feeling too new to "be bold" here, but, I think this article would be better named "Manual:Extending wiki markup". The title "Tag extensions" is too narrow and misleading - the article also has an extensive discussion of how to write parser functions and parser functions and tags are quite different both in syntax and timing of processing. This article really is an overview, not just a discussion of tag extensions.
I'd like to propose the following change: Option 1: rename *this* article to Manual:Extending wiki markup Option 2: leave *this* article as is, BUT
- redirect the old Extending wiki markup to a general overview article [[Manual::Extending wiki markup]]. This should discuss, compare and contrast the different kinds of wiki language extensions (custom variables, parser functions, tags, templates). It should act as a gateway and link to more specialized articles on different kinds of mediawiki extensions.
- split the material in this article into at least three articles:
- one on writing tag extensions (can keep this name of course)
- one on writing parser functions
- one on writing custom variables (Extension:Variables is an example, but it doesn't explain the principles behind it or why each hook is needed).
Egfrank 00:48, 3 September 2007 (UTC)
- There are a couple of overview pages right now that are slowly being merged. Manual:Extensions is the best one. Developer hub also has some good information. All the parser function specific stuff should be moved to Manual:Parser functions. Also, Extension:Variables is an extension, not really guidance. Manual:Magic words is probably closer to what you are talking about but it isn't very fleshed out. The intention with the page name was to follow the structure of the navigation template at the top of the page. There probably is a better name that is still different from parser functions, special pages, hooks, etc, but I couldn't think of one. --Cneubauer 15:04, 4 September 2007 (UTC)
- Thanks for the response. I've fleshed out Manual:Magic words and written some fuller documentation on variables - your feedback and others would be most welcome.
- Egfrank 05:44, 5 September 2007 (UTC)
Info for Older Versions
editI propose keeping the FAQ information on this page concise and relevant to the current version of MediaWiki at all times and pointing people of other pages (like Extensions FAQ) for older information. If we keep info for older versions this page is eventually going to be huge. Hopefully, this would also encourage people to upgrade to a newer version of MediaWiki if possible. We could point people to older info with a template that says something like: For information specific to MediaWiki version {{{1}}} please see {{{2}}}. --Cneubauer 14:58, 4 September 2007 (UTC)
- Legacy info could be kept on subpages -- Duesentrieb ⇌ 00:19, 5 September 2007 (UTC)
Conflicting Anchor Names
editSo I'm putting together an extension that creates anchors in pages (via <span id="someAnchorName"/>
), and I want to make sure the id attributes do not conflict with anchor names created by wiki-syntax headers (i.e. =, ==, ===, ====, =====, and ======). Is there a variable or function to retrieve all the names/ids of the current destination anchors? —Sledged (talk) 20:48, 4 October 2007 (UTC)
This is a small thing, I think it is better to reduce indentation and readablility with;
if (!defined('MEDIAWIKI')) {
echo( "This file is an extension to the MediaWiki software and cannot be used standalone.\n" );
exit( 1 );
}
/**
* Unindented extension code follows
*/
rather than
if( defined( 'MEDIAWIKI' ) ) {
/**
* Indented extension code
*/
} else {
echo( "This file is an extension to the MediaWiki software and cannot be used standalone.\n" );
exit( 1 );
}
Thought I would put it here for other peoples opinions before changing the article--Zven 00:47, 13 February 2008 (UTC)
Variables from Templates don't work
editI wrote a little extension to include Screenshots via websnapr.com. I like to use my extension in a template and include a variable like <mytag>{{{Var}}}</mytag>. Now the variable is not parsed, the output is simply {{{Var}}} and not the worth in this variable.
I tried to use recursiveTagParse but it is still not parsed. Is there any workaround?
- This is a well known problem, the solution to this is to use the #tag parser function. This solves.
- --DonGiulio 19:28, 12 May 2008 (UTC)
#tag parser function translates <> into & lt; & gt;
editHi,
I'm using the #tag parser function in a template to highglight some programming code using Extension:SyntaxHighlight_GeSHi. The problem is that #tag passes the strings with the < and > converted to & lt; and & gt;. and they don't get highlighted properly.
Does anyone have an idea on how to correct this problem?
Thank you,
Extension Output on Wrong Place
editMy Extensions put their output on just top of the page instead of the content division. What may the reason be?--88.226.171.181 18:21, 30 September 2008 (UTC)
- Start with the sample code. The sample code should be working correctly, at least that was my experience the last time I tried. If the :sample code works, you can compare it to your current code to decipher the problem. -- Emceelam 18:22, 1 October 2008 (UTC)
How can I parse output to wikitext?
editIn this code I want $playRfile to be passed to a template:
function aoRandomPagesHook($text, $params, $parser) {
global $wgDBprefix, $wgContLang;
// prevent caching for this wiki page
$parser->disableCache();
// get parameters
$limit = isset($params['limit']) ? (int)$params['limit'] : 50;
// build sql query.
$sql = sprintf('SELECT " . NS_IMAGE . " AS namespace, img_name FROM image WHERE img_minor_mime =
CONVERT( _utf8 \'mp3\' USING latin1 ) COLLATE latin1_swedish_ci ', $wgDBprefix);
$sql .= sprintf('ORDER BY RAND() LIMIT %d', $limit);
// execute that.
$dbr = wfGetDB( DB_SLAVE );
$rs = $dbr->query( $sql );
$playRfile = '<div>';
while( $row = $rs->fetchObject( $rs ) ) {
$title = Title::makeTitleSafe($row->namespace, $row->img_name);
$text = $wgContLang->convert( $title->getText() );
$playRfile .= '{{Media|$text}}';
}
return $playRfile . '</div>';
}
I just dunno how :/ Thanks! --Subfader 16:56, 6 November 2008 (UTC)
Bug in example code (avoiding modification of output)
editIn the section How can I avoid modification of my extension's HTML output? this function is given:
function myextParserAfterTidy(&$parser, &$text) {
// find markers in $text
// replace markers with actual output
global $markerList;
for ($i = 0; $i<count($markerList); $i++)
$text = preg_replace('/xx-marker'.$i.'-xx/',$markerList[$i],$text);
return true;
}
If however, the output code contains an expression that preg_replace() interprets, this will appear in the output. For example, if $output
was set to "value = $0A" then after this function is called, the HTML will show "value = xx-marker0-xxA" - the $0
is being interpreted by preg_replace().
Here is an alternate version of the function which avoids the bug, and IMHO is slightly more efficient as the page content only gets scanned once overall instead of once for each occurrence of the tag:
function myextParserAfterTidy(&$parser, &$text) {
// find markers in $text
// replace markers with actual output
global $markerList;
$k = array();
for ($i = 0; $i < count($markerList); $i++)
$k[] = 'xx-marker' . $i . '-xx';
$text = str_replace($k, $markerList, $text);
return true;
}
-- Malvineous 06:39, 10 January 2009 (UTC)
How do you disable a particular tag?
editI tried to get math tags working before I realized that my hosting service will not let me compile texvc. I am now using the mimetex alternative. However, I want this to work with math tags, instead of tex tags, so that I can copy content directly from other wikis. Looking at my special:version page, I see that math tags are not enabled, but I still get a "Failed to parse (Missing texvc executable)" error for math tags. Where can I go to disable the use of math tags, so that I can manually link them to my mimetex extension?
Tag extensions with attributes values from templates
editI've been wrestling a bit with, but I've not been able to find a way to pass template values into tag attributes values (using MW 1.16). I imagine it's possible with tag values, but not with tag attribute values, isn't?
Example:
<example attribute="{{{1}}}" />
--Toniher 15:05, 6 September 2010 (UTC)
The parser extension tags break after several days
editAt WikID we're having a strange issue with the extension parser tags from Videoflash and Cite. They always function when they are first added to a page, but on a sub-set of pages they stop being parsed after several days. At this point the syntax just appears on the page, but performing any edit and saving the page causes the tags to be parsed correctly again. Then they break again after a while. What is so strange to me is that some pages do not suffer from this issue at all, but I can't find out what's so special about these pages. Could anyone point me in the right direction? Many thanks in advance!
Text to trim from this page
editFor consistency, I'd like to trim text from this page and replace it with links to 'the canonical extension docs' here: Manual:Developing extensions. However, I don't wan't to just zap the good text here. --Dmb 15:05, 23 April 2011 (UTC)
Extension brokes previous tas
editI wrote an extension to add a <spoiler> tag, but it brokes other extension tags as well as some HTML (like the TOC) and links are displayed like this:
1 ?UNIQ72c1b0505aa8a0f4-h-0--QINU?Crónicas antiguas 2 ?UNIQ72c1b0505aa8a0f4-h-1--QINU?Edad preespacial (edad oscura)
Any ideas?--Krusher 01:36, 16 September 2011 (UTC)
- This is a common issue caused by calling the parser recursively. This can happen by doing things like $wgParser->parse, $parser->parse, or some $wgOut methods (Never ever use $wgOut in a tag extension, it won't do what your expect). On older mediawiki this can happen with some of the wfMsg related functions as well (this is fixed since 1.16 or 1.17 I think). If you need to parse anything, you should use
$parser->recursiveTagParse( 'text to parse', $frame );
where $parser and $frame come from the arguments passed to your tag extension. Bawolff (talk) 03:50, 6 March 2012 (UTC)
<center>
editI can't figure out what extension, if any, has the center tag? Schalice (talk) 04:37, 5 March 2012 (UTC)
- I figured it out. Its deprecated in favor of <div>. Schalice (talk) 03:46, 6 March 2012 (UTC)
<dot-separator>
editlol, now I'm trying to figure this one out. Doesn't work on my wiki. Schalice (talk) 19:49, 8 March 2012 (UTC)
- This uses MediaWiki:Dot-separator. Mine was misspelled (MediaWiki:Dot-seperator). Schalice (talk) 23:22, 8 March 2012 (UTC)
Parser::setFunctionTagHook
editI was in the parser the other day and came across setFunctionTagHook()
. Is there a reason to use this method over the existing setHook()
? It seems that this method was added back in 2009, and is rarely used (by the extensions I have installed at least.) Should the documentation be updated to reflect this method and it's (possible) advantages? ( Part of a discusion can be found on-list at http://lists.wikimedia.org/pipermail/wikitech-l/2011-January/051432.html )
How to handle the typos from the editors
editI met a problem that is sometimes when editors use the tags, they might have typos, for example:<sample>something</sample>, but the ending tag </sample> was replaced with <sample>. It is <sample>something<sample>. How to handle this plz? thanks --Michaelhuo (talk) 19:04, 24 March 2013 (UTC)
Add code on every page load
editBasically, I have a dynamic php function that get's a Minecraft Server's status (using packets etc). The main problem is that the code is parsed when edited (I can see it in the logs) and not when the page is loaded. The plugin checks for the status />
tag and replaces it with the status (a div with contents).
The source code that matters:
$wgExtensionCredits['parsehook'][] = array(
'name' => 'MCStatusTag',
'author' => 'ZephireNZ',
'url' => '/* Redacted */',
);
$wgHooks['ParserFirstCallInit'][] = 'registerStatusTag';
function registerStatusTag(Parser $parser) {
$parser->setHook('status','printStatusTag');
return true;
}
function printStatusTag($input, array $args, Parser $parser, PPFrame $frame) {
$parser->disableCache(); // I tried disabling cache as suggested, but it doesn't work.
// Return constructed html;
}
How can I get it to replace the tag each time a page with that tag is viewed? Is there a hook that will allow this? 101.98.181.157 10:15, 22 April 2013 (UTC)
Use Sanitizer::removeHTMLtags instead htmlspecialchars
editIs it safe to use Sanitizer::removeHTMLtags instead htmlspecialchars in function wfSampleRender of example Manual:Tag_extensions#Example?
// Execute
function wfSampleRender( $input, array $args, Parser $parser, PPFrame $frame ) {
// Nothing exciting here, just escape the user-provided
// input and throw it back out again
return Sanitizer::removeHTMLtags( $input );
}
About The First Paragraph
editShould it still be saying
You should always check the matrix before you start work on an extension to make sure someone else hasn't done exactly what you are trying to do.
without giving a proper link to a list of extensions? The term “matrix” leads to Extension Matrix/AllExtensions, which is openly obsolete by now. Eduardogobi (talk) 07:14, 8 December 2017 (UTC)
How to addHeadItem
editI am trying to add some meta tags using addHeadItem() inside my tag function. Attaching it to $wgOut doesn't work as it is not cached and adding it to $parser->getOutput() is not working.
Retrieving the tag name inside of the callback for newer versions
editTo make this work for newer version, the example given should be modified: From:
return sharedFunctionality( $input, $args, $parser, $frame, $tagName );
To:
return self::sharedFunctionality( $input, $args, $parser, $frame, $tagName );
Example Tag extension
editIs there an exmple of a parser tag extension using the HookHandler? Alexander Mashin talk 03:43, 26 August 2022 (UTC)
Wrong configuration?
editSo, i followed the Documentation and I got the followin:
extension.json
"AutoloadClasses": { "PromotedArticle": "src/PromotedArticle.php", "PromotedArticleHooks": "src/Hooks/PromotedArticleHooks.php" }, "AutoloadNameSpaces": { "Mediawiki\\Extension\\PromotedArticle": "src/" }, "HookHandlers": { "default": { "class": "PromotedArticleHooks" } }, "Hooks": { "GetPromotedArticle": { "handler": "default" }, "ParserFirstCallInit": { "handler": "default" } }
PromotedArticleHooks.php
public static function onParserFirstCallInit( Parser $parser ) { // When the parser sees the <promotedArticle> tag, it executes getPromotedArticle (see below) $parser->setHook( 'promotedArticle', [__CLASS__, "getPromotedArticle"]); return true; }
public static function getPromotedArticle($input, array $args, Parser $parser, PPFrame $frame) { //Do things return 'This is the promoted article"; }
But even though I have the tag <promotedArticle> in one Article, the function getPromotedArticle does not seem to be called. I debugged local and it goes into onParserFirstCallInit but is not executing the callable. Any ideas? Grandeescanciano (talk) 06:57, 11 May 2023 (UTC)
In the FAQ "How do I get my extension to show up on Special:Version?"
editIn the body text myextensionmsg
is mentioned, but does not appear in the code sample. In the code sample descriptionmsg
is used. My guess is that these are supposed to be the same thing. If so, which one is current? Jsaiya (talk) 00:17, 20 December 2023 (UTC)
onParserFirstCallInit cannot be static if implementing ParserFirstCallInitHook interface
editThe examples given show defining onParserFirstCallInit as static, however the MediaWiki\Hook\ParserFirstCallInitHook interface does not define onParserFirstCallInit as static, see https://github.com/wikimedia/mediawiki/blob/f338ac3295f1514e0c7b74422ed168decd8e679a/includes/parser/Hook/ParserFirstCallInitHook.php#L23 . So either we shouldn't implement the interface, or if implementing the interface we shouldn't define the function as static, or the interface needs to be updated to define the function as static. Lwangaman (talk) 23:08, 30 July 2024 (UTC)
- @Lwangaman: I don't think any examples should be using static methods any more; let's update them to all be implementing the interface. Sam Wilson 01:30, 31 July 2024 (UTC)