Jump to content

Extension talk:AutoLink

Add topic
From mediawiki.org
Latest comment: 12 years ago by Bovender in topic Alternative extension in the works

No Replacment Rules?

[edit]

Hi! Thanks for that useful extension. But there seem to be some problems. i'll try to describe. In my AutoLinkPages List are listed the sites like

Stefan Heinz|Peter Meier|Torsten Frings

and so on.

If there are also Entries like

Stefan|Peter|Torsten|Stefan Heinz|Peter Meier|Torsten Frings

AutoLinkPages will replace the Links twice and the sum of that twice replacement is a link like

[[[[Torsten]] Frings]] - and that will not work. :( --85.16.52.199 16:08, 13 May 2008 (UTC)Reply

Potential Bug Fix/Feature (!5-Feb-08)

[edit]

I changed the code slightly to make sure that where you have page names that contain other page names like on my site and you want AutloLink to pick up the bigger page name, than I found this worked well

Exaples:

I have Pages called "Kidney" and "Cancer" and I also have a page called "Kidney Cancer". In the original code if I had a sentence that had Kidney Cancer in it, the Autolink would always pick up "Kidney" and "Cancer" as 2 separate words. With the code bellow it always picks up "Kidney Cancer" now.

The code below just sorts the pages by Descending length

#Function to return page names from AutoLinkPages as an array()
 function getPages()
{
        $dbr = &wfGetDB(DB_SLAVE);
        $result_set = $dbr->select('page', array('page_title'), array('page_namespace' => 0), __METHOD__, array('ORDER BY' =>'page_title desc'));
        $titles = array();
        while (($row = $dbr->fetchObject($result_set)))
	{
                array_push($titles, $row->page_title);
        }
        
	usort($titles, "Ascii_sort");

        $dbr->freeResult($result_set);
        return $titles;
}


function Ascii_sort($val_1, $val_2)
{
	// initialize the return value to zero
	$retVal = 0;

	// compare lengths
	$firstVal = strlen($val_1);
	$secondVal = strlen($val_2);

	if($firstVal < $secondVal)
	{
		$retVal = 1;
	}
	else if($firstVal > $secondVal)
	{
		$retVal = -1;
	}
	
	return $retVal;	
}

Hope this helps

Andy


Help 04-Jan-2008

[edit]

Hi Sanjeev

Great program thanks!! Is there anyway of making it work with larger pages? We're using it in anger on our website http://www.kidneycancerresource.com/wiki and quite a few of our pages go well over the 25K mark and what we've found is that it tries to save and then just comes up with a blank page. When you refresh the saved page it goes back to the original and you lose the changes.

I guess it has something to do with the maximum Text size?

Thanks

Andy

help

[edit]

I have made AutoLink.php in extensions directory, added require_once("$IP/extensions/AutoLink.php"); to LocalSettings.php, and made an AutoLinkPages (http://zimwiki.com/index.php?title=AutoLinkPages). What am I doing wrong?

  • you have to separathe the namepages with ':' ... example: Page1:Page2:Page3

Finally

[edit]

I've been wanting an extension like this forever, but had no idea how to do it. Thanks for tackling this, can't wait to try and implement it on my wiki.--24.250.230.243 01:44, 15 June 2007 (UTC)Reply

Big Bug (Resolved)

[edit]

If for example you have the word "animal" in your wordlist AutoLinkPages and you have an images called animal.jpg in your curently edited artikel you get animal.jpg as a result. That ist bad in the "image-" Tag. I think with categories it is the same problem. Anyone here, who can change the code? 89.52.133.99 15:55, 2 July 2007 (UTC)Reply

Thankyou very much for drawing my attention to this point.I have just started working with wikis,so as soon as i was done with this extension i put it here.But i'll definitely re-work on this extension keeping all your suggestions in mind.Please wait for some time so that i can make it perfect and then submit.--Sanjeev 08:41, 3 July 2007 (UTC)Reply
Sadly to say - it isn't resolved.89.52.189.171 21:22, 9 July 2007 (UTC)Reply
Is it too difficult to make this little change? If yes - this tool is not helpfull for me - I am sorry.89.52.164.171 23:47, 10 July 2007 (UTC)Reply
In Next two dayz i'll do that.--Sanjeev 08:28, 16 July 2007 (UTC)Reply
This bug has not been resolved... With the following code:
{{ Infobox 
| name= animal
| image = [[Image:animal.jpg|400px]]
}}
It is automatically changed to...
{{ Infobox 
| name= animal
| image = }}[[Image:animal.jpg|400px]]
}}
Caues massive issues. --68.197.175.128 23:08, 17 August 2008 (UTC)Reply

one bug, one "feature"

[edit]

I edited the script so that if you have "animal" in the dictionary page, it will create a link to it from either "animal" or "Animal". Also, there was a bug in the code that did not autolink text if it appeared in position 0 in the content string. It had to do with the return value of the strpos() function. You have to use "!== false" to evaluate properly. Anyway -- that was kind of eliminated when I switched to using preg_replace and preg_match. Feel free to roll back if it's not appropriate. I'm currently using the script as I've edited it on my own server. I was planning to address the issue with replacing words that appear inside of square brackets.

Thanks for the idea and for putting the original code together. --Flanagana 19:48, 3 July 2007 (UTC)Reply

Hi Flanagana.
As,I said i was re-working on this extension,even i was planning to use preg_match/replace functions.And regarding !==false condition, this bug can also be removed if instead of strpos, strstr is used.But nywayz as you said preg_match if used then no need to worry about !==false condition.So the changes made by you to the code contribute towards it's perfection.Thankyou very much for that.Please try to find out if any other problem lies in that,so that we can work together on it. :)
Your changes to code and suggestions encourage me to think out of the box and to develop and contribute more extensions for our people.Thanks once again.--Sanjeev 04:50, 4 July 2007 (UTC)Reply


Put all articles automatically into the article "AutoLinkPages" (resolved)

[edit]

I want to have all my article put automaticaly into AutoLinkPages. Is it possible when opening the article "AutoLinkPages" to be asked "Do you want to have all your articles put into this page?" and when I answer "yes" the script will put all of them automatically into thte page?? 89.52.189.233 10:23, 6 July 2007 (UTC)Reply

Hi!!!
Yes,it is very much possible to put all the Articles in AutoLink Page.
But when i wrote this extension, my requirement was for selective words in a page content.
I will definitely work on this to allow, putting all the Articles in that page
automatically,but can you please give some more details about your requirement.
For example,one case is that from now onwards any page/article you create will have an auto
entry in AutoLink page..,or else all the existing article names have to be added to
AutoLinkPage.So, Please give me some more details and time to prepare that.
Thankyou very much --Sanjeev 06:18, 9 July 2007 (UTC)Reply
It's a good idea from you to allow the alternatives: give the user the possibillity ...
1. ... to put single words into AutoLinkPages (as you did before)
2. ... to abandon the AutoLinkPages and automatically use all the article-names
Thanks for your work
89.52.189.171 21:16, 9 July 2007 (UTC)Reply

Samuel Gelineau resolved wish 2. 89.52.154.165 09:38, 29 July 2007 (UTC)Reply

Content is wiped out

[edit]

Hi, I've tried this extension on my wiki, and I always get the content wiped out. I've just started trying editing it myself. If anybody has had the same issue, please suggest a solution. Thanks.--Cartoro 09:16, 11 July 2007 (UTC)Reply

Hi Cartoro.

Please do not use the extension now as it's under re-work.Very soon i'll be replacing the code with one which will work perfectly.Sorry for inconvenience.--Sanjeev 13:16, 11 July 2007 (UTC)Reply

Woohoo! Thanks Cartoro for making this point and thanks to Sanjeev for letting us know what is happening. I had thought it was something I was doing when I had the same problem as nobody else mentioned it. I look forward to the new version.

New Version of This Extension

[edit]

Hi frenzz!!!

The code for this extension is updated latest(version1.2) and take cares of the above specified "animal.jpg" problem.Before you use this extension let me make you aware of something.This extension is re-worked to remove the bug like animal.jpg,but i won't say that a bug, coz it depends on once requirements.So this extension may satisfy certain requirements and others not, so all of you feel free to take the code and customize it as per your requirements.This Extension can be made more specific to include other conditions also,so please keep on adding more functionality to it.Ideas are appreciated and will definitely be taken care of.Now about including all Article names in AutoLinkPages,i tried that but it harms the performance badly as my wiki app has many articles.So i thought, not to include it.Please let me know if any issues.Thanks a lot. --Sanjeev 11:31, 16 July 2007 (UTC)Reply

New issue

[edit]

Sanjeev: I've only used this a little bit more, but I've hit the problem that the matching does not take place when the word is near other punctuation. For example if the word is "animal" then the sentence

 "This is an animal!"

won't link properly, where

 "This is an animal !"

will link... Anyway -- thanks for your efforts on making this better... I'm swamped with other tasks but if I get around to resolving any of these issues, I'll post my updated code. --70.21.34.164 02:26, 18 July 2007 (UTC)Reply

Problems with pictures

[edit]

"dogs" is put into AutoLinkPage. The following then is changed from:


[[Bild:dogs and cats.gif|thumb|500px|animals]]

into:

[[Bild:dogs and cats.gif|thumb|500px|animals]]</nowiki>


It is assumed that name of the images won't be having spaces between them.
For example if 'dogs and cat.gif' is 'dogs_and_cat.gif', extension will work and 'dogs' will not be linked.Thanks!!!!Sanjeev


You are right - it is no good idea to have spaces in filenames. But we have lots of spaces in names of pictures in our wiki. Nearly impossible to rename them all.
Suggestion: Wy not just stop replacing between "[[" ... and ... "]]" and also between "[" ... and ... "]"? 89.52.168.70 11:24, 27 July 2007 (UTC)Reply

New version

[edit]

Hi, I (not the original Author) wrote a new version which didn't rely on an AutoLinkPage word list. I also rewrote the substitution code so it wouldn't depend on spaces (see "New issue" above), and added an easy-to-edit list of "exception blocks" within which words should not be substituted. There's a regression though: the so-called "animal" problem will probably reoccur.

Thank you very much for the further development of the extension.
Would it be possible to have both versions in one script? Maybe with a parameter for "wordlist" or "all pages"? Or if there is no article "AutoLinkPages" take all artikels.
Otherwise we'll get a third/forth/... version in a few months. 89.52.191.150 19:53, 28 July 2007 (UTC)Reply

Two wishes:
Don't touch the hyperlinks I wrote by hand myself. E.g.: There is an article "Animals" but no article "Animalfarm". Now [[Animals|animal]]farm would result in "animalfarm" but it shouldn't be touched. 89.52.154.165 10:28, 29 July 2007 (UTC)Reply

wiki links are already exception blocks, so the extension won't touch your hand-made hyperlinks. Besides, there's no way the regular expression /animalfarm/ will match the text "animal]]farm", so I'm deeply convinced that this already works as expected. Gelisam
Thanks for this great extension. My problem: the extension handel german-umlaut like an end of a word.
for example: if there is an article named "F" and i write an "fßr" in my text the extension replace "[[F|f]]ßr". try to fix it, but my php-knowlegth is not deep enough. may its because wiki write umlaut in latin-Kollation. for example: "ß" instate of "ß". 85.232.26.207 16:06, 9 October 2007 (UTC)Reply


Don't hyperlink the articlename itself more than once. E.g.: If the article is called "Animal" then mark only the first "Animal" otherwise there are a lot of bold "Animals". 10:28, 29 July 2007 (UTC)

I've just noticed; and I've just fixed it. Although I don't mark the first self-loop either. Gelisam

Added only a little to the "Gelineau"-version and now it is workin fine - thank you very much.89.52.176.161 16:52, 30 July 2007 (UTC)Reply

Bracket bug

[edit]

If you have an article "PHP" and you write an hyperlink in an other article [http://xyz.com/help.php?parameter=3 Only an example] then .php? gets [http://xyz.com/help.[[PHP|php]]?parameter=3 Only an example].

I tried to put [ ] into the mapIgnoringBlocks and got further errors. -89.52.168.59 16:08, 5 August 2007 (UTC)Reply

I have asked here for an answer. -89.52.137.94 07:00, 21 August 2007 (UTC)Reply

Etiquette violation?

[edit]

I just posted a new version of this extension, and then I realized I might have committed some MediaWiki etiqutte violation. If so, I apologize and urge you to feel free to pull down my code. I probably should have contacted the author before posting a mod on the same page. --Vjg 16:50, 24 August 2007 (UTC)Reply

I just installed the version written by you that prefers longer names. After having tried it a short while I come across my first question. Is there any way to define an exclusion list of certain words that shall not automatically be converted to links? I found that words such as help and contact normally tend to create "strange" link targets given the context of the article being modified.
OK - changed the function called getPages to exclude pages listed in a special article. In my version it looks like below.
function getPages()
{
        $dbr = &wfGetDB(DB_SLAVE);
        $result_set = $dbr->select('page', array('page_title'), array('page_namespace' => 0), __METHOD__, array('ORDER BY' =>'page_title desc'));
        $titles = array();
        while (
                ($row = $dbr->fetchObject($result_set))
        ) {
                array_push($titles, $row->page_title);
        }
        $dbr->freeResult($result_set);


        $title = Title::newFromURL('AutoLinkExcludePages');
        $article = new Article($title);
        $pagenames = $article->getContent();
        $excludepages = explode(':',$pagenames); 


        $netpages = array_diff($titles, $excludepages);

        return $netpages;

}

In addition I added an if-statement in the function wfAddAutoLinks to exclude the exclusion page from being autoLinked. This seems to work quite well.

However, I also have the umlaut-problem referred to above where umlaut-letters seem to trigger word-ending. Fatboy45 14:41, 5 December 2007 (UTC)Reply

nowiki bug

[edit]

I discovered a bug in both versions that work with all pages. At first I thought I'd introduced it in my version, but I've confirmed it is present in the code I used as the basis of my change. I don't know if it is also present in the code that used the AutoLinkPage.

If you have a page with the text:

Page <nowiki> reference [[Main Page]] is in a nowiki </nowiki> block.

the text that actually gets saved is:

Page <nowiki> reference </nowiki>[[Main Page]] is in a nowiki </nowiki> block.

Note the extra terminating </nowiki> that was inserted immediately before the first nested wiki link tag. The nowiki block isn't being handled quite right. If I resolve the issue, I'll post changes, but it's low on my priority list. --Vjg 15:03, 27 August 2007 (UTC)Reply

Please put it higher in your priority list ;-) 89.52.160.92 18:34, 17 September 2007 (UTC)Reply
Workaround erase the line "<nowiki>", "</nowiki>"; it works better. Thomas 12. March 2008

Delimiter warning (if not bug)

[edit]

Be cautious with the use of the delimiter pair array. For instance, the categorytree tag won't be recognized if you have parameters set in the opening tag. Dropping the trailing > on the opening tag will make it work again, but you need to consider this behavior for any delimiter pair you introduce. --Vjg 17:21, 27 August 2007 (UTC)Reply

Help translating

[edit]

Hello, I want to help translate something (because you wrote it). My only question now is how to do that. (I can speak German, French and Italian) Could you give me a hint? --Iiiiiichdenk 16:23, 1 September 2007 (UTC)Reply

Conflict with other extensions

[edit]

I added a tag to the function wfAddAutoLinks (in autolink.php), because autolink got in trouble with the extension dirlist.

"<nowiki>", "</nowiki>",
"<dirlist","</dirlist>"

Now it works fine. This should also work with other extensions which are manipulating the sourccode during site-saving/editing.--217.5.220.106 09:26, 10 September 2007 (UTC)Reply


[edit]

Hi Sanjeev and everyone else -

Do you know of any way to get this awesome script to create links to categories instead of page titles? I don't know PHP, but I believe that all it would need to do is instead of transforming the text "cheese" into "cheese" it would only need to transform it into "[[:category:cheese | cheese]]" though I have no idea how to do this. Thanks!

dwh2103@columbia.edu / David Dwharrington 18:31, 14 November 2007 (UTC)Reply

SVN access

[edit]

Why this extension is not included in the SVN?

I added a bit modified Version to SVN for my Wiki[1]. It can be found here[2], anybody who wants to work on this extension just tell me the name of your sourceforge-account. --DaSch 22:19, 1 April 2009 (UTC)Reply

Another amended version

[edit]

I have mashed up the two code sets, taking bits from each.

I took the performance optimised code from the third code extract. However, I found that including every page was not desirable, so I used the autolinkpages approach (i.e. getpages()) from the first extract.

I have also included a fix with the page matching regex. This was done because I had pages with () brackets in them which weren't being matched. Neilkt 22:56, 19 December 2007 (UTC)Reply

Neilkt 12:49, 8 January 2008 (UTC) Update to fix a bug with the sorting and limit autolinking to the MAIN namespace (the prior version caused problems in the Mediawiki and Special namespaces). Mediawiki:Sidebar is formatted unusually and this extension previously was not able to parse it correctly.Reply

<?php
# turn ordinary words into page links, if the name matches. to match plurals and variations,
# write lots and lots of redirection pages.
#
# the original version, by [http://www.mediawiki.org/wiki/User:Sanjualone Sanjeev], required
# users to manually enter all the page names they wanted to match.
# [http://www.mediawiki.org/wiki/User:Gelisam] completely rewrote the script (minus the
# boilerplate) to match any page.
#
# On 08/24/2007, a new version was created by [http://www.mediawiki.org/wiki/User:Vjg] which
# gives preference to longer page names. It switches the order of processing, handling the
# article for each page, but only building the page array once. The previous version handled
# the article once, but built the page array on each pass. I haven't fully explored all the
# performance implications. This was for use on a relatively small site.

#This version has been amended by [[User:Neilkt|Neilkt]] to only work using explicitly added 
#terms, but takes optimisations from the [[User:Vjg]] version.  Articles with longer names 
#are linked first.  
if ( ! defined( 'MEDIAWIKI' ) )
        die();
 
$wgExtensionCredits['other'][] = array(
    'name' => "AutoLink (version-2.3)",
    'author' => 'Virgil Green'
);
 
$wgHooks['ArticleSave'][] = 'wfAddAutoLinks';
 
#Event Handler for ArticleSave Event.
function wfAddAutoLinks(&$article,&$user,&$text)
{
	if($article->mTitle->mTextform != 'AutoLinkPages' && ($article->mTitle->getNamespace() == NS_MAIN) )
	{
	        global $autolink__current_page;
	        $autolink__current_page = preg_replace('/ /', '_', $article->mTitle->mTextform);
	 
	        $text = autoLinkWords(
	                array(
	                        "<createbox>", "</createbox>",
	                        "<categorytree>", "</categorytree>",
	                        "<DPL>", "</DPL>",
	                        "{{#ask:", "}}",
	                        "[[Image:", "]]",
	                        "[[", "]]",
	                        "{{", "}}",
	                        "[", "]",
	                        "<nowiki>", "</nowiki>"
	                ),
	                $text
	        );
	}
        return true;
}
 
function mapIgnoringBlocks($delimiters, $text, $pattern, $replacement) {
        if (count($delimiters) == 0) {
                return preg_replace($pattern, $replacement, $text);
        }
 
        $block_start = array_shift($delimiters);
        $block_end = array_shift($delimiters);
 
        $result = "";
        $post_headers = explode($block_start, $text);
 
        $first_inter_block = array_shift($post_headers);
        $result = $result . mapIgnoringBlocks($delimiters, $first_inter_block, $pattern, $replacement);
 
        foreach($post_headers as $post_header) {
                $block_and_inter_block = explode($block_end, $post_header, 2);
 
                $block = array_shift($block_and_inter_block);
                $result = $result . $block_start . $block . $block_end;
 
                $inter_block = array_shift($block_and_inter_block);
                $result = $result . mapIgnoringBlocks($delimiters, $inter_block, $pattern, $replacement);
        }
 
        return $result;
}
 
function autoLinkWords($delimiters, $text) {
        global $autolink__current_page;
 				$tmp = "";
        $patternMap = array();
      
        foreach(getPages() as $page) 
        {
        	if ($page != $autolink__current_page) 
        	{
	        	$pattern = preg_replace('/_/', '[_ ]', preg_quote($page, '/'));
				
						if (strpos($page,"(")+strpos($page,")") > 0)
						{
							$pattern = '/\b((?<!\[)(?<!\/\/)' . $pattern . '(?!\]))/';
						}
						else
						{
							$pattern = '/\b((?<!\[)(?<!\/\/)' . $pattern . '(?!\]))\b/i';
						}
          	$patternMap[$pattern] = '[[' . $page . '|\1]]';
          }
        }
        foreach($patternMap as $pattern=>$replacement) {
                $text = mapIgnoringBlocks($delimiters, $text, $pattern, $replacement);
        }

        return $tmp.$text;
}
 
#Function to return page names from AutoLinkPages as an array()
function getPages()
{
        $title = Title::newFromURL('AutoLinkPages');
        $article = new Article($title);
        $pagenames = $article->getContent();
        $pages = explode(':',$pagenames);
        uasort($pages,"Ascii_sort"); //Longest page titles first
        return $pages;
}

function Ascii_sort($val_1, $val_2)
{
	// initialize the return value to zero
	$retVal = 0;

	// compare lengths
	$firstVal = strlen($val_1);
	$secondVal = strlen($val_2);

	if($firstVal > $secondVal)
	{
		$retVal = -1;
	}
	else if($firstVal < $secondVal)
	{
		$retVal = 1;
	}
	return $retVal;
}


Hi Neilkt, I like the idea very much of having links in all namespaces, not only in my main namespace. Do you have any idea, how one can solve this Sidebar problem? Ben --84.186.215.218 08:40, 18 January 2008 (UTC)Reply

Neilkt 00:09, 17 February 2008 (UTC) Sure, the line to change is the following.Reply

if($article->mTitle->mTextform != 'AutoLinkPages' && ($article->mTitle->getNamespace() == NS_MAIN) )

You could either change it so that it checked the title (i.e. mTextform != 'Sidebar') or just apply it to the mediawiki namespace. I admit to being lazy on this one. Soz


It seems that this amended version (or whole original extension) destroys templates which have pictures or other templates inside them (it inserts }} just before [[Image:... or before template's {{) - no matter what the file name of the page or the picture is. --212.149.204.218 02:42, 10 March 2008 (UTC)Reply

Try testing it with this footballer infobox-template code. If it replicates like mine, the box won't stay together until those flag-templates and picture is removed. --212.149.204.218 02:51, 10 March 2008 (UTC)Reply


Neilkt 11:43, 20 March 2008 (UTC) Sorry, just noticed your post...Reply

Worst case, consider using Dirk Kreisel's new version which does essentially the same thing, but doesn't seem to handle templates parser functions gracefully.

Try reordring them as follows (worked for me). Essentially, you put the more complex blocks first. Would love for some help implementing this in a more clever way. You can always visit my website (click my profile) and send me an email using the address posted there to let me know how you get on. It's unpleasant to have to do this, but I can't see a better way (the "ignore terms" piece was taken from somebody else's code and I don't fully understand it).

    "<createbox>", "</createbox>",
    "<categorytree>", "</categorytree>",
    "<DPL>", "</DPL>",
    "{{#ask:", "}}",
    "[[Image:", "]]",
    "[[", "]]",
    "{{", "}}",
    "[", "]",
    "<nowiki>", "</nowiki>"

Correction of version with restricted wordlist

[edit]

The lines:
$textlines = explode('\n',$content);
$content = implode('\n',$newlines);
must be changed to
$textlines = explode("\n",$content);
$content = implode("\n",$newlines);

otherwise the \n character is not recognized as a newline character by php.

<?php
# Adds Auto Links in A page.
# Reads page 'AutoLinkPages', which works as Dictonary.

if ( ! defined( 'MEDIAWIKI' ) )
        die();

$wgExtensionCredits['other'][] = array(
    'name' => "AutoLink (version-1.2)",
    'author' => '[http://www.mediawiki.org/wiki/User:Sanjualone Sanjeev]'
);

$wgHooks['ArticleSave'][] = 'wfAddAutoLinks';

#Event Handler for ArticleSave Event.
function wfAddAutoLinks(&$article,&$user,&$text)
{
        $content = $text;
        $pages = array();
        #This should not work for the Page AutoLinkPages.

        if($article->mTitle->mTextform != 'AutoLinkPages')
        {
                $pages = getPages();
                $textlines = array();
                $textlines = explode("\n",$content);
                $newlines = array();
                foreach($textlines as $line)
                {
                        $textword = array();
                        $textword = explode(' ',$line);
                        $newwords = array();
                        foreach($textword as $word)
                        {
                                if(strpos($word,'[') == false &&
                                   strpos($word,']') == false &&
                                   strpos($word,'<') == false &&
                                   strpos($word,'>') == false)
                                {
                                      if(strstr($word,'.') == false || strstr($word,'.')== '.')
                                      {
                                        foreach($pages as $page)
                                        {
                                                if(strstr($word,$page))
                                                 $word=str_replace($page,"[[".$page."]]",$word);
                                        }
                                      }
                                }
                                $newwords[] = $word;
                        }

                        $newlines[] = implode(' ',$newwords);
                }
                $content = implode("\n",$newlines);
                $text = $content;
        }
        return true;
}

#Function to return page names from AutoLinkPages as an array()
function getPages()
{
        $title = Title::newFromURL('AutoLinkPages');
        $article = new Article($title);
        $pagenames = $article->getContent();
        $pages = explode(':',$pagenames);
        return $pages;
}

--Effco 09:15, 21 January 2008 (UTC)Reply

Request 22-Jan-2008

[edit]

Hi Sanjeev, many thanks for the extension. I wonder if there's a chance to add this to the "AutoLinkPages" article:

[[John Jackson|John]]:[[Jack Johnson|Jack]]

And let AutoLink create a link to the "John Jackson" article when I write just John. Cheers

Yes this can be done.But please provide some more details of the requirement. For eg:- Jackson is fixed or it may change.Plz elaborate.Thanks :-) Sanjeev
Thanks for the reply! I'm afraid I don't get your point... let's say the AutoLinkPages article is:

[[Jack Johnson|Jack]]

Whenever I write Jack is reading a book on a new article, the output will be:

Jack is reading a book

Is that possible? Cheers


Neilkt 14:54, 26 February 2008 (UTC)Reply

A workaround might be

#Redirect Jack Johnson

on the Jack page
Yes, I know of redirects, thanks. I wonder if it's possible to do it via the AutoLink extension. Cheers
Neilkt 15:33, 2 April 2008 (UTC)Well, not something I'm planning on building, but would be handy I guess. Sorry (it's working exactly how I need it to at this stage).Reply

Won't work anymore?

[edit]

Hi,

I've just installed the extension and at first it also did work without a problem. However, after some testing it won't work anymore. Any idea how to fix this? Link

Can't get it to work.

[edit]

I did everything according to the instruction. Does it work for Chinese characters? This would be a great value-added extension. Thank you. Here is what I did:

1. Uploaded AutoLink.php to the extension page
2. Created AutoLinkPages on wiki with names of existing pages separated by :
3. Tested a page with words which is the title of an existing page. No link is created on this page.

Could you tell me what I did wrong.

can someone show how AutoLinkPages need to look like

[edit]

i mean...someone can tell how the page we need to create which his name is- "AutoLinkPages" need to be look like. a simple format of the page for dummies like me.

Page 1|Page 2|Page 3--85.16.52.199 16:03, 13 May 2008 (UTC)Reply

wont work with hebrew

[edit]

i tried this extension and it wint work with hebrew


Prevent from Replacement in <style>-tags of tables

[edit]

If you have pagenames like "1" or "2" and so on, it could happen, that style-tags are changed without your willing. To Prevent Replacement in style-tags in tables, just add the following line to AutoLink.php to the function wfAddAutoLinks(). Add

  "=\"","\""

to the $text array.

Greeting--91.96.121.57 20:13, 6 June 2008 (UTC)Reply

How to use the extension?

[edit]

An example: I have articles with words like (bairro centro) and (centro) and i want this words be linked to this [[Logradouros:Bairro Centro]]. Where Logradouros is a namespace. What i need to add on AutoLinksPage to work like this? What version of autolink i need to use?

[edit]

Is there a way to also make the autolinking show up in preview? Would it be as simple as adding $wgHooks['ArticlePreview'][] = 'wfAddAutoLinks'; below $wgHooks['ArticleSave'][] = 'wfAddAutoLinks'; ?

ALSO:

I noticed that it will not check text within wiki tags, for example, it won't replace words in image tag descriptions. Is there any work around for this?

Thanks.

[edit]

We're a web dev company that uses a wiki to track our changes, I thought this would be a helpful extension so I installed it and immediately noticed a problem. I'm using the version that checks for page titles, though I assume this is an issue either way. Lets say we have a page entitled qqwwer for qqwwer.com and on that page, or in other pages on the wiki, have a reference to a page on that site like http://www.qqwwer.com/contact_us.php. It leaves it alone if it's an explicitly "wikied" external link but if it's just text it links just the qqwwer part to the internal page.

In my opinion it should detect and exclude urls.

No bot yet??

[edit]

I LOVE this Extension! I can't believe we do not have a way yet to auto update the AutoLinkPage. I figured I would have seen someone at least create a bot that could be ran that gets all articles and formats in Page:Page:Page format for easy updating of the page???? Am I going to have to teach myself Python or what!

GobleS 11:49, 23 August 2008 (UTC)Reply

Bot Question

[edit]

Following up on the above, I would LOVE to know how to get a bot of some sort to use this. It would make my wiki as beautiful as the love between man and computer can be. But seriously, any ideas? Also, I found a way to modify this to autocategorize pages based on key words. The autocategory script runs in tandem with autolink so that, if I have the page "Yale" and the category "Yale," any page containing the word "Yale" will link to and be categorized as "Yale." If the page "Yale" is a redirect to the category "Yale," it becomes really easy to see who, in my wiki, went to Yale. Anyone interested? Dwharrington

I'd be happy with a script that ran every 24 hours that scanned all pages in the wiki and autolinked any key words it found... This would probably take a while on massive wiki's but mine is relatively small so I don't mind. --82.110.63.15 14:02, 20 October 2010 (UTC)Reply
I would love it, is there any possibility to do it?

Notes on Version 3.7

[edit]
  • MediaWiki 1.13.2
  • PHP 5.2.42-servage7 (apache2handler)
  • MySQL 5.0.51a
  • URL DishiWiki

Have only tried version 3.7, which was the latest version at the time of install (1/1/2009). The Extension page for this extension was a little unclear about the state of the extension, but reading the entire Discussion page will help you to be clear. (I will add a couple clarifications to the extension page.)

So read the version history and choose and install only the code for the version that you think will meet your needs. So if you choose a later version, you will not need to create the page AutoLinkPage talked about in earlier versions.

Version 3.7 installed without a hitch. The recently added feature to "create links on page view" certainly worked. Immediately upon simply viewing a page, links were now present on the page that correctly linked to other pages having titles matching the word links. If you're not yet clear what that means, continue reading.

Our wiki is about food and recipes. So we have pages dedicated to ingredients such as "Onions" or "Saffron," and so forth. And sure enough, each recipe page that called for, say, the ingredient "saffron" would have the word "saffron" as an AutoLink. Trouble is, the word would be capitalized. So a list of ingredients on a recipe page would look like this:

  • 1 cup rice
  • 1 teaspoon Saffron (notice the capital S)
  • 1 cup broccoli

The capitalized ingredient just doesn't fit in with our style manual. One other small problem: We have a page titled "Sage." When this extension found the word "sausage" on other pages, it would create links to the Sage page, and the links looked like this: "sauSage," with just the Sage part being a link. So that's another deal breaker. So for the time being, we have uninstalled this extension.

Now, you guys and gals who write extensions are our heroes! Our Web site (DishiWiki) would be not nearly as good without the extensions we use!

So if you think this extension might work for you, I am happy to report that removing the extension by remarking-out or removing the line in your LocalSettings.php page will immediately revert your pages back to the way they were, if the extension didn't work like you expected. We were very surprised and happy to learn that those links were not permanent edits but were being generated real-time, upon viewing. So try version 3.7 and see if it works for you. I think this extension will be perfected soon. We thank everyone for their time and efforts so far. Brian7632416 02:07, 2 January 2009 (UTC)Reply

Conflict With Semantic media wiki

[edit]

Conflict With Semantic media wiki. It doesn't display the proper query after install.

[edit]

I'd prefer pseudo-links so they only appear on watching the page. When you edit it, only manually set article links appear.
This would properly solve the backward-problem and safe you from ruining all your pages with article links. Could be an own extension though. --Subfader 00:13, 27 February 2009 (UTC)Reply

Possible fix for 3.7 issue

[edit]

I've been struggling to remove an autolink to an article called "EDIA" from the text "MediaWiki" - and I think this will work. It is the same problem that Brian7632416 reported above, getting a link to "sage" in the text "sausage." In the function AutoLink_MakeLink, find

 $region[$i] = preg_replace('/'.$pattern.'/i', $replace, $region[$i]);

and change it to

 $region[$i] = preg_replace('/\b'.$pattern.'\b/i', $replace, $region[$i]);

For 3.7, that change Worked For MeÂŽ. 2009-03-25 9:51pm EDT User:Cherron

Thanks man! It worked for me! --Tango granada 03:15, 27 March 2010 (UTC)Reply

ATTENTION! Breaks everything

[edit]

This extensions needs a BIG rework. It links inside of div, span etc. breaks magic word like __NOTOC__ and makes Links that really are far away from making sense. Wilkommen to WilkOMmen. WTF? --DaSch 14:49, 1 April 2009 (UTC)Reply

Well I thought I could fix a bit of the problem with this extension. But on problem still remains. When having __NOEDITSECTION__ and __NOTOC__ in one page the last one is mixed up and the result ist something like __NOTOCTOC_CTOCTOC_CCTOC_COC_C_C__ . If somebody wants to enchance this Extenstion, I put it into SVN[3]. You could post patches here or register to sourceforge and I could give you SVN access. Bugs could also be posted here[4]. --DaSch 15:13, 1 April 2009 (UTC)Reply

<noautolink>

[edit]

Moin,

for me, v.2.4 was very clever, but using the new tag <noautolink> it shows up <noautolink> in text, which isn´t really great...

Avoiding that, in section $htmlpairs of sanitizer.php you have to add 'noautolink'

usteck 2009-04-01


[edit]

Hi there, great work, but i have a little problem. is it possible, that only the first occurence of an phrase is linked to that responding article? --80.228.180.119 13:44, 12 May 2009 (UTC)Reply

Ignore specified words

[edit]

Hi, this is a great extension. Is it possible to make AutoLink always ignore some specified words (not make link)?

3.7 doesnt work when logged in

[edit]

When using 3.7 it works perfectly for anonymous users, but once i log in the on-the-fly links dont work.

Any suggestions?


--- I am having the same problem, any ideas would be great.

Help Installed 2.2 and content is wiped

[edit]

Hi I installed version 2.2 today and my site no longer comes up. www.ipornwiki.com/wiki

I removed the extension and the localsettings.php entry but site is still blank. I looked in SQLmanager I am with lunarpages so only have GUI. It shows tables still there, so I dont know what to do.

How can I recover my site?

please email me if possible at owngeek@gmail.com


Fixed it, thanks :)

Get a blank page when I activate the Extension

[edit]

When I activate this extension then I get just a blank page instead of my wiki. As soon as I deactivate it, it works perfectly again.83.79.163.69 18:04, 2 February 2010 (UTC)Reply

Now it works, with autolink activated after editing pages.

Is it possible to make a blacklist? Because I don't want a link to article "C" in every word that contains "c". 83.79.163.69 18:17, 2 February 2010 (UTC)Reply

3.7 not working with logged in users on MW 1.15

[edit]

(02-15-2010) This extension works great for anonymous users, but not for logged in users. Only in onafteredit-mode it works. Anyone nows who supports this extension?

3.7 also not working with logged in users on MW 1.16.2

[edit]

(02-23-2011) If anyone has a solution please send info also to info@mssc.biz

Seems to work but with a Deprecated error?

[edit]

Deprecated: Call-time pass-by-reference has been deprecated in C:\Program Files\wamp\www\bos\extensions\AutoLink.php on line 94

Hello I just installed this extension on my wiki install (version 1.16.2. The extension is version 3.7) and I get the above error. It seems to work as intended for my small Wiki, but that error kinda messes up the page layout. Anyone have a suggestion of how to fix? Thanks!

(This error pops up whether or not I'm logged in.)

Version 2.4

[edit]

I don't understand v. 3.7 but will support v. 2.4 as that is still in use at Hindupedia. Let me know if you come across any problems with v2.4. It works on Mediawiki v.1.15.2 as that is the version Hindupedia.com is currently running.

Krishna

Fix: 3.7 in page view mode not working unless page is purged from cache

[edit]

I'm running MediaWiki 1.12.0-2lenny7 on Debian 5.0.7 (i.e., the default version supplied with the OS). I had the problem that AutoLink (in page view mode) would not work, unless the page had been removed from the cache after the last edit (can be done manually by adding ?action=purge to the URL).

In case anyone else encounters this problem as well, I was able to fix it by adding $wgParserCacheType = CACHE_NONE; to my LocalSettings.php. --80.108.218.34 11:00, 21 May 2011 (UTC)Reply

[edit]
<?php
/**
 * AutoLink extension
 * Turn ordinary words into page links, if the name matches. to match plurals and variations,
 * write lots and lots of redirection pages.
 * The original version, by [http://www.mediawiki.org/wiki/User:Sanjualone Sanjeev], required
 * users to manually enter all the page names they wanted to match.
 * [http://www.mediawiki.org/wiki/User:Gelisam] completely rewrote the script (minus the
 * boilerplate) to match any page.
 *
 * On 08/24/2007, a new version was created by [http://www.mediawiki.org/wiki/User:Vjg] which
 * gives preference to longer page names. It switches the order of processing, handling the
 * article for each page, but only building the page array once. The previous version handled
 * the article once, but built the page array on each pass. I haven't fully explored all the
 * performance implications. This was for use on a relatively small site.
 *
 * on 09/10/2008, a new version was created by Krishna Maheshwari
 * which doesn't add a pipe & link if the page name matches the text (longest matches first).  It also strips all links 
 * prior to regenerating them, ensuring if changes or other articles are created with longer names
 * that match, than they are used.  Ie: This Text could be transformed to This [[Text]] than on a
 * subsequent edit become [[This Text]]. In addition, it only allows the first occurance of a page
 * to be linked instead of each occurance. This extension is used on Hindupedia (www.hindupedia.com)
 * New Tags: __NOAUTOLINK__ => this extension doesn't try to generate any links for page
 *           __NOREGENERATELINKS__ => don't try to regenerate links
 *           <noautolink> ... </noautolink> => don't generate links on content inside these tags
 *
 * On 12/25/2008, a new version was created by Hyunsik Kim
 * completly rewritten version. Main function refer to the version 2.4
 * magic word function has been removed because I don't know what it is.
 * reduce regex functions and replace faster one, improve getting title function.
 * consider nested tag structure.
 * longest match uses first.
 *    -- v3.2 : Bug fix - MakeRegion
 *    -- v3.3 : Improve Regioning function - Increase speed.
 *    -- v3.5 : Feature added Autolink execute when view page.
 *    -- 12/26/2008, v3.6 : Increse Parse speed.
 *    -- 12/27/2008, v3.7 : Bug fix - Prevent link strip at protected block.
 *    -- 10/26/2011, v3.8 : <darren@cwebd.co.uk> Updated replace to keep existing matched text rather than replacing with page title so case sensitivity is retained
 *
 * @author Hyunsik Kim (E-mail:weatherbless.story@gmail.com)
 * @version 3.8
 * @url http://www.mediawiki.org/wiki/Extension:AutoLink
 */
 
if (!defined('MEDIAWIKI')) die();
 
$wgExtensionCredits['other'][] = array(
    'name' => 'AutoLink',
    'version' => '3.8',
    'author' => 'Hyunsik Kim',
    'url' => 'http://www.mediawiki.org/wiki/Extension:AutoLink',
);
 
########################## Enable Autolink ###########################
# We don't recommend both options has been enabled at the same time. #

# To activate Autolink after edit page, uncomment this:
# $wgHooks['ArticleSave'][] = 'wfAutoLink_ArticleSave';

# To activate Autolink during page view, uncomment this:
$wgHooks['ArticleAfterFetchContent'][] = 'wfAutoLink_ArticleAfterFetchContent';
 
# Event Handler for ArticleAfterFetchContent Event.
function wfAutoLink_ArticleAfterFetchContent(&$article, &$text)
{
        global $action;
        $currentPage = $article->mTitle->mTextform;
 
        # Actions : view, watch, unwatch, delete, revert, rollback, protect, unprotect,
 #           info, markpatrolled, render, deletetrackback, purge, print, dublincore,
 #           creativecommons, credits, submit, edit, editredlink, history, raw, ajax
 # Refer to [http://www.mediawiki.org/wiki/Manual:Page_action#Actions]
 switch( $action )
        {
                case '':
                case 'view':
                case 'render':
                case 'purge':
                case 'print':
                        AutoLink_Parse($currentPage, $text);
                        break;
                case 'edit':
                case 'editredlink':
                        break;
                default:
                        break;
        }
 
        return true;
}
 
# Event Handler for ArticleSave Event.
function wfAutoLink_ArticleSave(&$article, &$user, &$text)
{
        return AutoLink_Parse($article->mTitle->mTextform, &$text);
}
 
function AutoLink_Parse($title, &$text)
{
        # Set ignoring blocks. It must include "[[" and "]]"
 # Otherwise, It may cause endless recursion.
 $ignoreBlocks = array(
                array("[[", "]]"),
                array("[", "]"),
                array("{{", "}}"),
                array("<pre", "</pre>"),
                array("<nowiki>", "</nowiki>"),
                array("<noautolink>","</noautolink>"),
                array("<createbox>", "</createbox>"),
                array("<categorytree>", "</categorytree>"),
                array("<dirlist>","</dirlist"),
                array("<DPL>", "</DPL>"),
                array("#REDIRECT", "]]"),
                );
 
        $currentPage = str_replace(" ", "_", $title);
 
        # If we specificy no autolink, than don't autolink
 if (stripos($text, '__NOAUTOLINK__') !== false) { return true; } 
 
        # As long as we are allowed to regenerate links...
 if (stripos($text, '__NOREGENERATELINKS__') === false)
        {
                # Strip links so that all links are regenerated except those that are custom links
         # ie have a '|' or ')' or '(' in them
         # It only work for odd number region(Protected area).
         $region = AutoLink_MakeRegion($text, $ignoreBlocks);
 
                for ( $i = 1; $i < count($region); $i += 2)
                {
                        $region[$i] = preg_replace('/^\[\[([^|:\(\)\]]*)\]\]$/','\1',$region[$i]);
                }
 
                # Merge regions so that all stripped links are unprotected.
         $text = implode($region);
        }
 
        $titles = AutoLink_GetTitleList($currentPage);
        AutoLink_MakeLink($titles, $text, $ignoreBlocks);
 
        return true;
}
 
function AutoLink_GetTitleList($currentPage)
{
        $dbr = &wfGetDB(DB_SLAVE);
        $result = $dbr->select('page', array('page_title'), 'page_namespace=0 AND page_title <> "'.$currentPage.'"', __METHOD__, array('ORDER BY' =>'CHAR_LENGTH(page_title) DESC'));
 
        $titles = array();
 
        while (($row = $dbr->fetchObject($result)))
        {
                $titles[] = $row->page_title;
        }
        $dbr->freeResult($result);
 
        return $titles;
}
 
function AutoLink_FindFirstSkipBlock(&$ignoreBlocks, &$text)
{
        $startTag = "";
        $endTag = "";
        $firstTag_start = strlen($text) + 1; # sentinel value

        foreach($ignoreBlocks as $tagPair)
        {
                $curTag_start = stripos($text, $tagPair[0]);
                if ( $curTag_start !== false && $firstTag_start > $curTag_start )
                {
                        $startTag = $tagPair[0];
                        $endTag = $tagPair[1];
                        $firstTag_start = $curTag_start;
                }
        }
 
        if ( $firstTag_start > strlen($text) ) return false;
 
        $startTagLength = strlen($startTag);
        $endTagLength = strlen($endTag);
        $firstTag_end = stripos($text, $endTag, $firstTag_start + $startTagLength);
        $nextPosition = $firstTag_start + $startTagLength;
        $tagDepth = 0;
        while ( true )
        {
                $findPosition = stripos($text, $startTag, $nextPosition);
                if ( $findPosition === false || $findPosition > $firstTag_end )
                {
                        break;
                }
 
                $nextPosition = $findPosition + $startTagLength;
                ++$tagDepth;
        }
 
        $nextPosition = $firstTag_end + $endTagLength;
 
        while ( $tagDepth > 0 )
        {
                $findPosition = stripos($text, $endTag, $nextPosition);
 
                # If orpant tag has been detected, whole block is selected.
         if ( $findPosition === false )
                {
                        $nextPosition = strlen($text);
                        break;
                }
 
                $nextPosition = $findPosition + $endTagLength;
                --$tagDepth;
        }
 
        $firstTag_end = $nextPosition;
 
        return array($firstTag_start, $firstTag_end);
}
 
function AutoLink_MakeRegion(&$text, &$ignoreBlocks)
{
        $textLength = strlen($text);
 
        # Region :: Even : Normal text area, Odd : Protected area(skip autolink)
 $region = array();
 
        $skipBlock = AutoLink_FindFirstSkipBlock($ignoreBlocks, $text);
 
        # Recursion Terminate condition
 if ( $skipBlock === false )
        {
                return array($text);
        }
 
        $splitBegin = $skipBlock[0];
        $splitEnd = $skipBlock[1];
 
        $region = array_merge(
                array(substr($text, 0, $splitBegin),
                substr($text, $splitBegin, $splitEnd - $splitBegin)),
                AutoLink_MakeRegion(substr($text, $splitEnd  , $textLength - $splitEnd), $ignoreBlocks)
                );
 
        return $region;
}
 
function AutoLink_MakeLink(&$titles, &$text, &$ignoreBlocks)
{
        $autoLinkTag = array(array("[[","]]"));
        $region = AutoLink_MakeRegion($text, $ignoreBlocks);
 
        foreach($titles as $page)
        {
                $pattern = str_replace('_','[_ ]', preg_quote($page, '/'));
                $patternLength = strlen($page);
                $replace = '[['.str_replace('_', ' ', $page);

                # Make links. It only work for even number region.
         # Odd number region is ignoring block(include already linked text)
         for ( $i = 0; $i < count($region); )
                {
                        if ( strlen($region[$i]) < $patternLength )
                        {
                                $i += 2;
                                continue;
                        }
 
                        $region[$i] = preg_replace('/('.$pattern.')/i', $replace.'|$1]]', $region[$i]);
                        $newRegion = AutoLink_MakeRegion($region[$i], $autoLinkTag);
                        array_splice($region, $i, 1, $newRegion);
                        $i += count($newRegion) + 1;
                }
        }
 
        $text = implode($region);
}

Further enhancements on v3.7 enhancement to allow for a configuration option to exclude pages from being auto linked

[edit]
<?php
/**
 * AutoLink extension
 * Turn ordinary words into page links, if the name matches. to match plurals and variations,
 * write lots and lots of redirection pages.
 * The original version, by [http://www.mediawiki.org/wiki/User:Sanjualone Sanjeev], required
 * users to manually enter all the page names they wanted to match.
 * [http://www.mediawiki.org/wiki/User:Gelisam] completely rewrote the script (minus the
 * boilerplate) to match any page.
 *
 * On 08/24/2007, a new version was created by [http://www.mediawiki.org/wiki/User:Vjg] which
 * gives preference to longer page names. It switches the order of processing, handling the
 * article for each page, but only building the page array once. The previous version handled
 * the article once, but built the page array on each pass. I haven't fully explored all the
 * performance implications. This was for use on a relatively small site.
 *
 * on 09/10/2008, a new version was created by Krishna Maheshwari
 * which doesn't add a pipe & link if the page name matches the text (longest matches first).  It also strips all links 
 * prior to regenerating them, ensuring if changes or other articles are created with longer names
 * that match, than they are used.  Ie: This Text could be transformed to This [[Text]] than on a
 * subsequent edit become [[This Text]]. In addition, it only allows the first occurance of a page
 * to be linked instead of each occurance. This extension is used on Hindupedia (www.hindupedia.com)
 * New Tags: __NOAUTOLINK__ => this extension doesn't try to generate any links for page
 *           __NOREGENERATELINKS__ => don't try to regenerate links
 *           <noautolink> ... </noautolink> => don't generate links on content inside these tags
 *
 * On 12/25/2008, a new version was created by Hyunsik Kim
 * completly rewritten version. Main function refer to the version 2.4
 * magic word function has been removed because I don't know what it is.
 * reduce regex functions and replace faster one, improve getting title function.
 * consider nested tag structure.
 * longest match uses first.
 *    -- v3.2 : Bug fix - MakeRegion
 *    -- v3.3 : Improve Regioning function - Increase speed.
 *    -- v3.5 : Feature added Autolink execute when view page.
 *    -- 12/26/2008, v3.6 : Increse Parse speed.
 *    -- 12/27/2008, v3.7 : Bug fix - Prevent link strip at protected block.
 *    -- 10/26/2011, v3.8 : <darren@cwebd.co.uk> Updated replace to keep existing matched text rather than replacing with page title so case sensitivity is retained
 *    -- 10/26/2011, v3.9 : <darren@cwebd.co.uk> Added in configuration option to exclude pages from being autolinked
 *
 * @author Hyunsik Kim (E-mail:weatherbless.story@gmail.com)
 * @version 3.9
 * @url http://www.mediawiki.org/wiki/Extension:AutoLink
 */
 
if (!defined('MEDIAWIKI')) die();
 
$wgExtensionCredits['other'][] = array(
    'name' => 'AutoLink',
    'version' => '3.9',
    'author' => 'Hyunsik Kim',
    'url' => 'http://www.mediawiki.org/wiki/Extension:AutoLink',
);
 
########################## Enable Autolink ###########################
# We don't recommend both options has been enabled at the same time. #

# To activate Autolink after edit page, uncomment this:
# $wgHooks['ArticleSave'][] = 'wfAutoLink_ArticleSave';

# To activate Autolink during page view, uncomment this:
$wgHooks['ArticleAfterFetchContent'][] = 'wfAutoLink_ArticleAfterFetchContent';

# To exclude pages from being autolinked
# set the configuration directive $wgAutoLinkExcludePages in LocalSettings.php
# e.g $wgAutoLinkExcludePage = array('About','Main_Page');
#
if (empty($wgAutoLinkExcludePages)) {
    $wgAutoLinkExcludePages = array();
}
 
# Event Handler for ArticleAfterFetchContent Event.
function wfAutoLink_ArticleAfterFetchContent(&$article, &$text)
{
        global $action;
        $currentPage = $article->mTitle->mTextform;
 
        # Actions : view, watch, unwatch, delete, revert, rollback, protect, unprotect,
 #           info, markpatrolled, render, deletetrackback, purge, print, dublincore,
 #           creativecommons, credits, submit, edit, editredlink, history, raw, ajax
 # Refer to [http://www.mediawiki.org/wiki/Manual:Page_action#Actions]
 switch( $action )
        {
                case '':
                case 'view':
                case 'render':
                case 'purge':
                case 'print':
                        AutoLink_Parse($currentPage, $text);
                        break;
                case 'edit':
                case 'editredlink':
                        break;
                default:
                        break;
        }
 
        return true;
}
 
# Event Handler for ArticleSave Event.
function wfAutoLink_ArticleSave(&$article, &$user, &$text)
{
        return AutoLink_Parse($article->mTitle->mTextform, &$text);
}
 
function AutoLink_Parse($title, &$text)
{
        # Set ignoring blocks. It must include "[[" and "]]"
 # Otherwise, It may cause endless recursion.
 $ignoreBlocks = array(
                array("[[", "]]"),
                array("[", "]"),
                array("{{", "}}"),
                array("<pre", "</pre>"),
                array("<nowiki>", "</nowiki>"),
                array("<noautolink>","</noautolink>"),
                array("<createbox>", "</createbox>"),
                array("<categorytree>", "</categorytree>"),
                array("<dirlist>","</dirlist"),
                array("<DPL>", "</DPL>"),
                array("#REDIRECT", "]]"),
                );
 
        $currentPage = str_replace(" ", "_", $title);
 
        # If we specificy no autolink, than don't autolink
 if (stripos($text, '__NOAUTOLINK__') !== false) { return true; } 
 
        # As long as we are allowed to regenerate links...
 if (stripos($text, '__NOREGENERATELINKS__') === false)
        {
                # Strip links so that all links are regenerated except those that are custom links
         # ie have a '|' or ')' or '(' in them
         # It only work for odd number region(Protected area).
         $region = AutoLink_MakeRegion($text, $ignoreBlocks);
 
                for ( $i = 1; $i < count($region); $i += 2)
                {
                        $region[$i] = preg_replace('/^\[\[([^|:\(\)\]]*)\]\]$/','\1',$region[$i]);
                }
 
                # Merge regions so that all stripped links are unprotected.
         $text = implode($region);
        }
 
        $titles = AutoLink_GetTitleList($currentPage);
        AutoLink_MakeLink($titles, $text, $ignoreBlocks);
 
        return true;
}
 
function AutoLink_GetTitleList($currentPage)
{
        $dbr = &wfGetDB(DB_SLAVE);
        $result = $dbr->select('page', array('page_title'), 'page_namespace=0 AND page_title <> "'.$currentPage.'"', __METHOD__, array('ORDER BY' =>'CHAR_LENGTH(page_title) DESC'));
 
        $titles = array();
 
        while (($row = $dbr->fetchObject($result)))
        {
                $titles[] = $row->page_title;
        }
        $dbr->freeResult($result);
 
        return $titles;
}
 
function AutoLink_FindFirstSkipBlock(&$ignoreBlocks, &$text)
{
        $startTag = "";
        $endTag = "";
        $firstTag_start = strlen($text) + 1; # sentinel value

        foreach($ignoreBlocks as $tagPair)
        {
                $curTag_start = stripos($text, $tagPair[0]);
                if ( $curTag_start !== false && $firstTag_start > $curTag_start )
                {
                        $startTag = $tagPair[0];
                        $endTag = $tagPair[1];
                        $firstTag_start = $curTag_start;
                }
        }
 
        if ( $firstTag_start > strlen($text) ) return false;
 
        $startTagLength = strlen($startTag);
        $endTagLength = strlen($endTag);
        $firstTag_end = stripos($text, $endTag, $firstTag_start + $startTagLength);
        $nextPosition = $firstTag_start + $startTagLength;
        $tagDepth = 0;
        while ( true )
        {
                $findPosition = stripos($text, $startTag, $nextPosition);
                if ( $findPosition === false || $findPosition > $firstTag_end )
                {
                        break;
                }
 
                $nextPosition = $findPosition + $startTagLength;
                ++$tagDepth;
        }
 
        $nextPosition = $firstTag_end + $endTagLength;
 
        while ( $tagDepth > 0 )
        {
                $findPosition = stripos($text, $endTag, $nextPosition);
 
                # If orpant tag has been detected, whole block is selected.
         if ( $findPosition === false )
                {
                        $nextPosition = strlen($text);
                        break;
                }
 
                $nextPosition = $findPosition + $endTagLength;
                --$tagDepth;
        }
 
        $firstTag_end = $nextPosition;
 
        return array($firstTag_start, $firstTag_end);
}
 
function AutoLink_MakeRegion(&$text, &$ignoreBlocks)
{
        $textLength = strlen($text);
 
        # Region :: Even : Normal text area, Odd : Protected area(skip autolink)
 $region = array();
 
        $skipBlock = AutoLink_FindFirstSkipBlock($ignoreBlocks, $text);
 
        # Recursion Terminate condition
 if ( $skipBlock === false )
        {
                return array($text);
        }
 
        $splitBegin = $skipBlock[0];
        $splitEnd = $skipBlock[1];
 
        $region = array_merge(
                array(substr($text, 0, $splitBegin),
                substr($text, $splitBegin, $splitEnd - $splitBegin)),
                AutoLink_MakeRegion(substr($text, $splitEnd  , $textLength - $splitEnd), $ignoreBlocks)
                );
 
        return $region;
}
 
function AutoLink_MakeLink(&$titles, &$text, &$ignoreBlocks) {
    $autoLinkTag = array(array("[[","]]"));
    $region = AutoLink_MakeRegion($text, $ignoreBlocks);
    global $wgAutoLinkExcludePages;

    foreach($titles as $page) {
        if (!in_array($page,$wgAutoLinkExcludePages)) {
            $pattern = str_replace('_','[_ ]', preg_quote($page, '/'));
            $patternLength = strlen($page);
            $replace = '[['.str_replace('_', ' ', $page);
            
            # Make links. It only work for even number region.
            # Odd number region is ignoring block(include already linked text)
            for ( $i = 0; $i < count($region); )
                {
                    if ( strlen($region[$i]) < $patternLength )
                        {
                            $i += 2;
                            continue;
                        }
                    
                    $region[$i] = preg_replace('/('.$pattern.')/i', $replace.'|$1]]', $region[$i]);
                    $newRegion = AutoLink_MakeRegion($region[$i], $autoLinkTag);
                    array_splice($region, $i, 1, $newRegion);
                    $i += count($newRegion) + 1;
                }
        }
        $text = implode($region);
    }
}

Version 3 install

[edit]

I see here AutoLink Installation for version 1 only. Where is the instructions to install Ver 3?

partial word match bug

[edit]

I happened upon this last and couldn't wait to install it. Unfortunately for categories like "IT" it will create an auto link in words like "Repository". Not only is it incorrectly linking the wrong words but it also highlights (the hyperlink) incorrectly. "Repository" is highlighted as Repos_ITory_ (hyperlink added to "itory") which will take you to the "IT" category page. We have no article called "Repository" and this is happening on multiple different situations with similar results. Is there a flag or something i am missing in the code to make sure it only links full text strings instead of partial segments within the text strings? --edited for clarity--

Alternative extension in the works

[edit]

Since I find the automatic linking of page titles very useful, I have written an alternative extension (this one no longer seems to be maintained?): Extension:LinkTitles. Bovender (talk) 13:17, 20 May 2012 (UTC)Reply