Adjust to fit MediaWiki 1.25+ extension format.

- NEW: Use the new extension format introduced by MediaWiki 1.25; the extension will no longer run with older MediaWiki versions.
This commit is contained in:
Daniel Kraus
2016-06-06 23:30:04 +02:00
parent d0c6716346
commit c88ce848e8
44 changed files with 904 additions and 726 deletions

339
COPYING Normal file
View File

@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@ -1,420 +0,0 @@
<?php
/*
* Copyright 2012-2014 Daniel Kraus <krada@gmx.net> ('bovender')
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
/// @file
/// Helper function for development and debugging.
/// @param $var Any variable. Raw content will be dumped to stderr.
/// @return undefined
function dump($var) {
error_log(print_r($var, TRUE) . "\n", 3, 'php://stderr');
};
/// Central class of the extension. Sets up parser hooks.
/// This class contains only static functions; do not instantiate.
class LinkTitles {
/// A Title object for the page that is being parsed.
private static $currentTitle;
/// A Title object for the target page currently being examined.
private static $targetTitle;
/// The content object for the currently processed target page.
/// This variable is necessary to be able to prevent loading the target
/// content twice.
private static $targetContent;
/// Holds the page title of the currently processed target page
/// as a string.
private static $targetTitleText;
/// Delimiter used in a regexp split operation to seperate those parts
/// of the page that should be parsed from those that should not be
/// parsed (e.g. inside pre-existing links etc.).
private static $delimiter;
private static $wordStartDelim;
private static $wordEndDelim;
/// Setup function, hooks the extension's functions to MediaWiki events.
public static function setup() {
global $wgLinkTitlesParseOnEdit;
global $wgLinkTitlesParseOnRender;
global $wgHooks;
if ( $wgLinkTitlesParseOnEdit ) {
$wgHooks['PageContentSave'][] = 'LinkTitles::onPageContentSave';
};
if ( $wgLinkTitlesParseOnRender ) {
$wgHooks['InternalParseBeforeLinks'][] = 'LinkTitles::onInternalParseBeforeLinks';
};
$wgHooks['GetDoubleUnderscoreIDs'][] = 'LinkTitles::onGetDoubleUnderscoreIDs';
self::BuildDelimiters();
}
/// Event handler that is hooked to the PageContentSave event.
public static function onPageContentSave( &$wikiPage, &$user, &$content, &$summary,
$isMinor, $isWatch, $section, &$flags, &$status ) {
if ( ! $isMinor ) {
$title = $wikiPage->getTitle();
$text = $content->getContentHandler()->serializeContent($content);
$newText = self::parseContent( $title, $text );
if ( $newText != $text ) {
$content = $content->getContentHandler()->unserializeContent( $newText );
}
};
return true;
}
/// Event handler that is hooked to the InternalParseBeforeLinks event.
/// @param Parser $parser Parser that raised the event.
/// @param $text Preprocessed text of the page.
public static function onInternalParseBeforeLinks( Parser &$parser, &$text ) {
$title = $parser->getTitle();
$text = self::parseContent( $title, $text );
return true;
}
/// Core function of the extension, performs the actual parsing of the content.
/// @param Title $title Title of the page being parsed
/// @param $text String that holds the article content
/// @returns string: parsed text with links added if needed
private static function parseContent( Title &$title, &$text ) {
// If the page contains the magic word '__NOAUTOLINKS__', do not parse it.
if ( MagicWord::get('MAG_LINKTITLES_NOAUTOLINKS')->match( $text ) ) {
return $text;
}
// Configuration variables need to be defined here as globals.
global $wgLinkTitlesPreferShortTitles;
global $wgLinkTitlesMinimumTitleLength;
global $wgLinkTitlesBlackList;
global $wgLinkTitlesFirstOnly;
global $wgLinkTitlesSmartMode;
global $wgCapitalLinks;
( $wgLinkTitlesPreferShortTitles ) ? $sort_order = 'ASC' : $sort_order = 'DESC';
( $wgLinkTitlesFirstOnly ) ? $limit = 1 : $limit = -1;
LinkTitles::$currentTitle = $title;
$newText = $text;
// Build a blacklist of pages that are not supposed to be link
// targets. This includes the current page.
$blackList = str_replace( '_', ' ',
'("' . implode( '", "',$wgLinkTitlesBlackList ) . '", "' .
LinkTitles::$currentTitle->getDbKey() . '")' );
// Build an SQL query and fetch all page titles ordered by length from
// shortest to longest. Only titles from 'normal' pages (namespace uid
// = 0) are returned. Since the db may be sqlite, we need a try..catch
// structure because sqlite does not support the CHAR_LENGTH function.
$dbr = wfGetDB( DB_SLAVE );
try {
$res = $dbr->select(
'page',
'page_title',
array(
'page_namespace = 0',
'CHAR_LENGTH(page_title) >= ' . $wgLinkTitlesMinimumTitleLength,
'page_title NOT IN ' . $blackList,
),
__METHOD__,
array( 'ORDER BY' => 'CHAR_LENGTH(page_title) ' . $sort_order )
);
} catch (Exception $e) {
$res = $dbr->select(
'page',
'page_title',
array(
'page_namespace = 0',
'LENGTH(page_title) >= ' . $wgLinkTitlesMinimumTitleLength,
'page_title NOT IN ' . $blackList,
),
__METHOD__,
array( 'ORDER BY' => 'LENGTH(page_title) ' . $sort_order )
);
}
// Iterate through the page titles
foreach( $res as $row ) {
LinkTitles::newTarget( $row->page_title );
// split the page content by [[...]] groups
// credits to inhan @ StackOverflow for suggesting preg_split
// see http://stackoverflow.com/questions/10672286
$arr = preg_split( self::$delimiter, $newText, -1, PREG_SPLIT_DELIM_CAPTURE );
// Escape certain special characters in the page title to prevent
// regexp compilation errors
LinkTitles::$targetTitleText = LinkTitles::$targetTitle->getText();
$quotedTitle = preg_quote(LinkTitles::$targetTitleText, '/');
// Depending on the global configuration setting $wgCapitalLinks,
// the title has to be searched for either in a strictly case-sensitive
// way, or in a 'fuzzy' way where the first letter of the title may
// be either case.
if ( $wgCapitalLinks && ( $quotedTitle[0] != '\\' )) {
$searchTerm = '((?i)' . $quotedTitle[0] . '(?-i)' .
substr($quotedTitle, 1) . ')';
} else {
$searchTerm = '(' . $quotedTitle . ')';
}
for ( $i = 0; $i < count( $arr ); $i+=2 ) {
// even indexes will point to text that is not enclosed by brackets
$arr[$i] = preg_replace_callback( '/(?<![\:\.\@\/\?\&])' .
self::$wordStartDelim . $searchTerm . self::$wordEndDelim . '/Su',
array('LinkTitles', 'simpleModeCallback'), $arr[$i], $limit, $count );
if (( $limit >= 0 ) && ( $count > 0 )) {
break;
};
};
$newText = implode( '', $arr );
// If smart mode is turned on, the extension will perform a second
// pass on the page and add links with aliases where the case does
// not match.
if ($wgLinkTitlesSmartMode) {
$arr = preg_split( self::$delimiter, $newText, -1, PREG_SPLIT_DELIM_CAPTURE );
for ( $i = 0; $i < count( $arr ); $i+=2 ) {
// even indexes will point to text that is not enclosed by brackets
$arr[$i] = preg_replace_callback( '/(?<![\:\.\@\/\?\&])' .
self::$wordStartDelim . '(' . $quotedTitle . ')' .
self::$wordEndDelim . '/iuS', array('LinkTitles', 'smartModeCallback'),
$arr[$i], $limit, $count );
if (( $limit >= 0 ) && ( $count > 0 )) {
break;
};
};
$newText = implode( '', $arr );
} // $wgLinkTitlesSmartMode
}; // foreach $res as $row
return $newText;
}
/// Automatically processes a single page, given a $title Title object.
/// This function is called by the SpecialLinkTitles class and the
/// LinkTitlesJob class.
/// @param string $title Page title.
/// @param RequestContext $context Current context.
/// If in doubt, call MediaWiki's `RequestContext::getMain()`
/// to obtain such an object.
/// @returns undefined
public static function processPage($title, RequestContext $context) {
// TODO: make this namespace-aware
$titleObj = Title::makeTitle(0, $title);
$page = WikiPage::factory($titleObj);
$content = $page->getContent();
$text = $content->getContentHandler()->serializeContent($content);
$newText = LinkTitles::parseContent($titleObj, $text);
if ( $text != $newText ) {
$content = $content->getContentHandler()->unserializeContent( $newText );
$page->doQuickEditContent($content,
$context->getUser(),
"Links to existing pages added by LinkTitles bot.",
true // minor modification
);
};
}
/// Adds the two magic words defined by this extension to the list of
/// 'double-underscore' terms that are automatically removed before a
/// page is displayed.
/// @param $doubleUnderscoreIDs Array of magic word IDs.
/// @returns true
public static function onGetDoubleUnderscoreIDs( array &$doubleUnderscoreIDs ) {
$doubleUnderscoreIDs[] = 'MAG_LINKTITLES_NOTARGET';
$doubleUnderscoreIDs[] = 'MAG_LINKTITLES_NOAUTOLINKS';
return true;
}
// Build an anonymous callback function to be used in simple mode.
private static function simpleModeCallback( array $matches ) {
if ( LinkTitles::checkTargetPage() ) {
return '[[' . $matches[0] . ']]';
}
else
{
return $matches[0];
}
}
// Callback function for use with preg_replace_callback.
// This essentially performs a case-sensitive comparison of the
// current page title and the occurrence found on the page; if
// the cases do not match, it builds an aliased (piped) link.
// If $wgCapitalLinks is set to true, the case of the first
// letter is ignored by MediaWiki and we don't need to build a
// piped link if only the case of the first letter is different.
private static function smartModeCallback( array $matches ) {
global $wgCapitalLinks;
if ( $wgCapitalLinks ) {
// With $wgCapitalLinks set to true we have a slightly more
// complicated version of the callback than if it were false;
// we need to ignore the first letter of the page titles, as
// it does not matter for linking.
if ( LinkTitles::checkTargetPage() ) {
if ( strcmp(substr(LinkTitles::$targetTitleText, 1), substr($matches[0], 1)) == 0 ) {
// Case-sensitive match: no need to bulid piped link.
return '[[' . $matches[0] . ']]';
} else {
// Case-insensitive match: build piped link.
return '[[' . LinkTitles::$targetTitleText . '|' . $matches[0] . ']]';
}
}
else
{
return $matches[0];
}
} else {
// If $wgCapitalLinks is false, we can use the simple variant
// of the callback function.
if ( LinkTitles::checkTargetPage() ) {
if ( strcmp(LinkTitles::$targetTitleText, $matches[0]) == 0 ) {
// Case-sensitive match: no need to bulid piped link.
return '[[' . $matches[0] . ']]';
} else {
// Case-insensitive match: build piped link.
return '[[' . LinkTitles::$targetTitleText . '|' . $matches[0] . ']]';
}
}
else
{
return $matches[0];
}
}
}
/// Sets member variables for the current target page.
private static function newTarget( $title ) {
// @todo Make this wiki namespace aware.
LinkTitles::$targetTitle = Title::makeTitle( NS_MAIN, $title);
LinkTitles::$targetContent = null;
}
/// Returns the content of the current target page.
/// This function serves to be used in preg_replace_callback callback
/// functions, in order to load the target page content from the
/// database only when needed.
/// @note It is absolutely necessary that the newTarget()
/// function is called for every new page.
private static function getTargetContent() {
if ( ! isset( $targetContent ) ) {
LinkTitles::$targetContent = WikiPage::factory(
LinkTitles::$targetTitle)->getContent();
};
return LinkTitles::$targetContent;
}
/// Examines the current target page. Returns true if it may be linked;
/// false if not. This depends on the settings
/// $wgLinkTitlesCheckRedirect and $wgLinkTitlesEnableNoTargetMagicWord
/// and whether the target page is a redirect or contains the
/// __NOAUTOLINKTARGET__ magic word.
/// @returns boolean
private static function checkTargetPage() {
global $wgLinkTitlesEnableNoTargetMagicWord;
global $wgLinkTitlesCheckRedirect;
// If checking for redirects is enabled and the target page does
// indeed redirect to the current page, return the page title as-is
// (unlinked).
if ( $wgLinkTitlesCheckRedirect ) {
$redirectTitle = LinkTitles::getTargetContent()->getUltimateRedirectTarget();
if ( $redirectTitle && $redirectTitle->equals(LinkTitles::$currentTitle) ) {
return false;
}
};
// If the magic word __NOAUTOLINKTARGET__ is enabled and the target
// page does indeed contain this magic word, return the page title
// as-is (unlinked).
if ( $wgLinkTitlesEnableNoTargetMagicWord ) {
if ( LinkTitles::getTargetContent()->matchMagicWord(
MagicWord::get('MAG_LINKTITLES_NOTARGET') ) ) {
return false;
}
};
return true;
}
/// Builds the delimiter that is used in a regexp to separate
/// text that should be parsed from text that should not be
/// parsed (e.g. inside existing links etc.)
private static function BuildDelimiters() {
// Configuration variables need to be defined here as globals.
global $wgLinkTitlesParseHeadings;
global $wgLinkTitlesSkipTemplates;
global $wgLinkTitlesWordStartOnly;
global $wgLinkTitlesWordEndOnly;
// Use unicode character properties rather than \b escape sequences
// to detect whole words containing non-ASCII characters as well.
// Note that this requires the use of the '/u' switch, and you need
// to have PHP with a PCRE library that was compiled with
// --enable-unicode-properties
( $wgLinkTitlesWordStartOnly ) ? self::$wordStartDelim = '(?<!\pL)' : self::$wordStartDelim = '';
( $wgLinkTitlesWordEndOnly ) ? self::$wordEndDelim = '(?!\pL)' : self::$wordEndDelim = '';
if ( $wgLinkTitlesSkipTemplates )
{
$templatesDelimiter = '{{[^}]+}}|';
} else {
// Match template names (ignoring any piped [[]] links in them)
// along with the trailing pipe and parameter name or closing
// braces; also match sequences of '|wordcharacters=' (without
// spaces in them) that usually only occur as parameter names in
// transclusions (but could also occur as wiki table cell contents).
// TODO: Find a way to match parameter names in transclusions, but
// not in table cells or other sequences involving a pipe character
// and equal sign.
$templatesDelimiter = '{{[^|]*?(?:(?:\[\[[^]]+]])?)[^|]*?(?:\|(?:\w+=)?|(?:}}))|\|\w+=|';
}
// Build a regular expression that will capture existing wiki links ("[[...]]"),
// wiki headings ("= ... =", "== ... ==" etc.),
// urls ("http://example.com", "[http://example.com]", "[http://example.com Description]",
// and email addresses ("mail@example.com").
// Since there is a user option to skip headings, we make this part of the expression
// optional. Note that in order to use preg_split(), it is important to have only one
// capturing subpattern (which precludes the use of conditional subpatterns).
( $wgLinkTitlesParseHeadings ) ? $delimiter = '' : $delimiter = '=+.+?=+|';
$urlPattern = '[a-z]+?\:\/\/(?:\S+\.)+\S+(?:\/.*)?';
self::$delimiter = '/(' . // exclude from linking:
'\[\[.*?\]\]|' . // links
$delimiter . // titles (if requested)
$templatesDelimiter . // templates (if requested)
'^ .+?\n|\n .+?\n|\n .+?$|^ .+?$|' . // preformatted text
'<nowiki>.*?<.nowiki>|<code>.*?<\/code>|' . // nowiki/code
'<pre>.*?<\/pre>|<html>.*?<\/html>|' . // pre/html
'<script>.*?<\/script>|' . // script
'<div.+?>|<\/div>|' . // attributes of div elements
'<span.+?>|<\/span>|' . // attributes of span elements
'<file>[^<]*<\/file>|' . // stuff inside file elements
'style=".+?"|class=".+?"|' . // styles and classes (e.g. of wikitables)
'\[' . $urlPattern . '\s.+?\]|'. $urlPattern . '(?=\s|$)|' . // urls
'(?<=\b)\S+\@(?:\S+\.)+\S+(?=\b)' . // email addresses
')/ismS';
}
}
// vim: ts=2:sw=2:noet:comments^=\:///

View File

@ -1,13 +0,0 @@
<?php
/*! @file LinkTitles.i18n.magic.php
*/
/// Holds the two magic words that the extension provides.
$magicWords = array();
/// Default magic words in English.
$magicWords['en'] = array(
'MAG_LINKTITLES_NOAUTOLINKS' => array(0, '__NOAUTOLINKS__'),
'MAG_LINKTITLES_NOTARGET' => array(0, '__NOAUTOLINKTARGET__')
);

View File

@ -1,17 +0,0 @@
<?php
/** @file LinkTitles.i18n.php
*/
/// Holds messages that the extension provides.
$messages = array();
/// English messages.
$messages['en'] = array(
'linktitles' => 'LinkTitles',
'linktitles-desc' => 'Automatically adds links to existing pages whenever a page is saved.',
);
/// German messages.
$messages['de'] = array(
'linktitles-desc' => 'Fügt beim Speichern von Seiten automatisch Querverweise zu vorhandenen Seiten ein.',
);

239
LinkTitles.php Executable file → Normal file
View File

@ -1,226 +1,15 @@
<?php <?php
/* if ( function_exists( 'wfLoadExtension' ) ) {
* Copyright 2012-2014 Daniel Kraus <krada@gmx.net> ('bovender') wfLoadExtension( 'LinkTitles' );
* // Keep i18n globals so mergeMessageFileList.php doesn't break
* This program is free software; you can redistribute it and/or modify $wgMessagesDirs['LinkTitles'] = __DIR__ . '/i18n';
* it under the terms of the GNU General Public License as published by $wgExtensionMessagesFiles['LinkTitlesMagic'] = __DIR__ . '/includes/LinkTitles_Magic.php';
* the Free Software Foundation; either version 2 of the License, or wfWarn(
* (at your option) any later version. 'Deprecated PHP entry point used for LinkTitles extension. ' .
* 'Please use wfLoadExtension instead, ' .
* This program is distributed in the hope that it will be useful, 'see https://www.mediawiki.org/wiki/Extension_registration for more details.'
* but WITHOUT ANY WARRANTY; without even the implied warranty of );
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the return;
* GNU General Public License for more details. } else {
* die( 'This version of the LinkTitles extension requires MediaWiki 1.25+' );
* You should have received a copy of the GNU General Public License }
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
/// @file
/// This file will be loaded by MediaWiki if the extension is included in
/// `LocalSettings.php`. It sets up the classes for auto-loading,
/// announces metadata, and defines a number of @link config configuration
/// variables @endlink.
/// @cond
if ( !defined( 'MEDIAWIKI' ) ) {
die( 'Not an entry point.' );
}
/// @endcond
/*
error_reporting(E_ALL);
ini_set('display_errors', 'On');
ini_set('error_log', 'php://stderr');
$wgMainCacheType = CACHE_NONE;
$wgCacheDirectory = false;
*/
/// @defgroup config Configuration
/// The global configuration variables can be overriden in the local
/// `LocalSettings.php` file just like with any other extension.
/// These variables are all defined in LinkTitles.php.
/// Controls precedence of page titles. If true, pages with shorter titles
/// are given preference over pages with longer titles (e.g., link to
/// 'Media' rather than 'MediaWiki'). If false (default), longer titles
/// (which tend to be more specific) are given precedence (e.g., link to
/// 'MediaWiki' rather than 'Media' if both pages exist).
/// @ingroup config
$wgLinkTitlesPreferShortTitles = false;
/// The minimum number of characters in a title that is required for it to
/// be automatically linked to.
/// @ingroup config
$wgLinkTitlesMinimumTitleLength = 3;
/// Determines whether or not to insert links into headings.
/// @ingroup config
$wgLinkTitlesParseHeadings = false;
/// Important configuration variable that determines when the extension
/// will process a page. If set to true in `LocalSettings.php`, links will
/// be inserted whenever a page is edited and saved (unless 'minor
/// modifications' is checked). If set to false, the extension will not do
/// anything when a page is edited and saved. Because saving a page
/// automatically invalidates the cache, the next time the page is
/// displayed (i.e., immediately after saving it), the extension might add
/// links if $wgLinkTitlesParseOnRender is set to true.
/// @ingroup config
$wgLinkTitlesParseOnEdit = true;
/// Important configuration variable that determines when the
/// extension will process a page. If set to true in LocalSettings.php,
/// links will be added whenever a page is rendered for viewing, after
/// templates have been expanded.
/// @note Since pages are cached, links may not appear immediately.
/// When links are added during the rendering process, they do not appear
/// as markup when the page is edited. This may or may not be the behavior
/// that you desire. Also note that if lots of templates or parser
/// functions are included, processing time may increase quite a bit,
/// causing gateway time-out errors of the web server.
/// @ingroup config
$wgLinkTitlesParseOnRender = false;
/// Determines whether to parse text inside templates. If this is set to
/// true in LocalSettings.php, the parameters in a template will be parsed
/// (e.g., {{myTemplate|template parameter that may contain a page
/// title}}).
/// @note If pages are parsed when they are rendered (see
/// $wgLinkTitlesParseOnRender setting), this setting does not take
/// effect.
/// @ingroup config
$wgLinkTitlesSkipTemplates = false;
/// Blacklist of page titles that should never be linked.
/// @note See also: __NOAUTOLINKTARGET__ magic word to allow wiki users to
/// blacklist a page dynamically.
/// @ingroup config
$wgLinkTitlesBlackList = array();
/// Determines whether to link only the first occurrence of a page
/// title on a page or all occurrences. Default is false: All occurrences
/// on a page are linked.
/// @ingroup config
$wgLinkTitlesFirstOnly = false;
/// Determines whether a page title must occur at the start of a word in
/// order for it to be linked. Example: Given a page 'Media' and an
/// article that contains the word 'Multimedia', the default setting
/// (`true`) will prevent the page from being linked. If this setting is
/// overriden in `LocalSettings.php` to be `false`, a link would be
/// inserted: `Multi[[media]]`.
/// @note If both $wgLinkTitlesWordStartOnly and $wgLinkTitlesWordEndOnly
/// are overriden to `false` in `LocalSettings.php`, you may get weird
/// linking. As a (contrieved) example, consider a wiki that has a page
/// "spa", then the word "namespace" in a technical article would be
/// linked as `name[[spa]]ce`, which is likely not what you want.
/// @ingroup config
$wgLinkTitlesWordStartOnly = true;
/// Determines whether a page title must end with the end of a word in
/// order for it to be linked. Example: Given a page 'Media' and an
/// article that contains the word 'MediaWiki', the default setting
/// (`true`) will prevent the page from being linked, because both words
/// have different endings. If this setting is overriden in
/// `LocalSettings.php` to be `false`, a link would be inserted:
/// `[[Media]]wiki`.
/// @note Setting this to false may have undesired effects because there
/// are many short words that may randomly occur in longer words, but are
/// semantically unrelated.
/// @note If both $wgLinkTitlesWordStartOnly and $wgLinkTitlesWordEndOnly
/// are overriden to `false` in `LocalSettings.php`, you may get weird
/// linking. As a (contrieved) example, consider a wiki that has a page
/// "spa", then the word "namespace" in a technical article would be
/// linked as `name[[spa]]ce`, which is likely not what you want.
/// @ingroup config
$wgLinkTitlesWordEndOnly = true;
/// Important setting that controls the extension's smart mode of
/// operation. With smart mode turned on (default), the extension will
/// first link all occurrences of a page title on a page in a
/// case-sensitive manner (but see note). It will then perform a second
/// pass in a case-__in__sensitive manner. For example, if you have a page
/// called "IgAN" (abbreviation for IgA nephritis, a kidney disease) and
/// someone writes the alternative form "Igan" in their article, then the
/// page would not be linked if smart mode is turned off.
/// @note Because smart mode constitutes two-pass processing of a page,
/// rather than single-pass, the processing time will increase. This may
/// not be noticeable on single page saves, but may play a role during
/// @link batch batch processing @endlink.
/// @ingroup config
$wgLinkTitlesSmartMode = true;
/// Determines whether or not to check if a page redirects to the current
/// page. This check requires that the extension fetches the page content
/// of a potential target page from the database, which costs time.
/// @note For maximum performance, set both $wgLinkTitlesCheckRedirect and
/// $wgLinkTitlesEnableNoTargetMagicWord to false in LocalSettings.php.
/// On the developer's machine, fetching the target page content increased
/// the run time from about 50 ms to about 500 ms on a wiki with 90 pages
/// (Intel Core i5-3320M, 2x 2.6 GHz, 16 GB RAM, PHP 5.5.9, Apache 2.4.7,
/// MySQL 5.5.37, MediaWiki 1.23.0). If any of the two mentioned variables
/// is set to true, a page content request will be performed for every
/// page whose title occurs on a given page.
/// @ingroup config
$wgLinkTitlesCheckRedirect = true;
/// Determines whether or not the magic word __NOAUTOLINKTARGET__ is
/// enabled or not. If __NOAUTOLINKTARGET__ is included in a page, this
/// page will never be linked to by the extension. The default is enabled
/// (true), but it comes at the cost of performance.
/// @note For maximum performance, set both $wgLinkTitlesCheckRedirect and
/// $wgLinkTitlesEnableNoTargetMagicWord to false in LocalSettings.php.
/// On the developer's machine, fetching the target page content increased
/// the run time from about 50 ms to about 500 ms on a wiki with 90 pages
/// (Intel Core i5-3320M, 2x 2.6 GHz, 16 GB RAM, PHP 5.5.9, Apache 2.4.7,
/// MySQL 5.5.37, MediaWiki 1.23.0). If any of the two mentioned variables
/// is set to true, a page content request will be performed for every
/// page whose title occurs on a given page.
/// @ingroup config
$wgLinkTitlesEnableNoTargetMagicWord = true;
/// Time limit for online batch processing. This determines the maximum
/// amount of time in seconds that page processing will take before a
/// refresh of the special page is issued.
/// @note See SpecialLinkTitles class.
/// @ingroup config
$wgLinkTitlesTimeLimit = 0.2;
/// @cond
$wgExtensionCredits['parserhook'][] = array(
'path' => __FILE__,
'name' => 'LinkTitles',
'author' => '[https://www.mediawiki.org/wiki/User:Bovender Daniel Kraus]',
'url' => 'https://www.mediawiki.org/wiki/Extension:LinkTitles',
'version' => '3.1.0',
'descriptionmsg' => 'linktitles-desc'
);
$wgExtensionMessagesFiles['LinkTitles'] = dirname( __FILE__ ) . '/LinkTitles.i18n.php';
$wgExtensionMessagesFiles['LinkTitlesMagic'] = dirname( __FILE__ ) . '/LinkTitles.i18n.magic.php';
$wgAutoloadClasses['LinkTitles'] = dirname( __FILE__ ) . '/LinkTitles.body.php';
$wgAutoloadClasses['SpecialLinkTitles'] = dirname( __FILE__ ) . '/SpecialLinkTitles.php';
$wgExtensionFunctions[] = 'LinkTitles::setup';
// Settings for the batch-processing special page
$wgSpecialPages['LinkTitles'] = 'SpecialLinkTitles';
$wgSpecialPageGroups['LinkTitles'] = 'other';
/// @endcond
/// The @link SpecialLinkTitles special page @endlink provides a distinct
/// right `linktitles-batch`. A user must be granted this right in order
/// to be able to visit this page.
$wgAvailableRights[] = 'linktitles-batch';
/// Grants the `linktitles-batch` right to sysops by default.
/// Override this only with care. If anybody can execute the
/// @link SpecialLinkTitles special page @endlink the server might
/// experience high loads.
/// @ingroup config
$wgGroupPermissions['sysop']['linktitles-batch'] = true;
// vim: ts=2:sw=2:noet:comments^=\:///

64
extension.json Normal file
View File

@ -0,0 +1,64 @@
{
"name": "LinkTitles",
"author": "[https://www.mediawiki.org/wiki/User:Bovender Daniel Kraus (bovender)]",
"type": "parserhook",
"url": "https://www.mediawiki.org/wiki/Extension:LinkTitles",
"version": "4.0.0",
"license-name": "GPL-2.0+",
"descriptionmsg": "linktitles-desc",
"requires": {
"MediaWiki": ">= 1.25.0"
},
"config": {
"LinkTitlesParseOnEdit": true,
"LinkTitlesParseOnRender": false,
"LinkTitlesParseHeadings": false,
"LinkTitlesSkipTemplates": true,
"LinkTitlesPreferShortTitles": true,
"LinkTitlesCheckRedirect": true,
"LinkTitlesEnableNoTargetMagicWord": false,
"LinkTitlesMinimumTitleLength": 4,
"LinkTitlesBlackList": [],
"LinkTitlesFirstOnly": true,
"LinkTitlesSmartMode": true,
"LinkTitlesWordStartOnly": true,
"LinkTitlesWordEndOnly": true,
"LinkTitlesBatchTimeLimit": 1
},
"AutoloadClasses": {
"LinkTitles\\Extension": "includes/LinkTitles_Extension.php",
"LinkTitles\\Special": "includes/LinkTitles_Special.php"
},
"SpecialPages": {
"LinkTitles": "LinkTitles\\Special"
},
"AvailableRights": [
"linktitles-batch"
],
"GroupPermissions": {
"sysop": {
"linktitles-batch": true
}
},
"Hooks": {
"PageContentSave": [
"LinkTitles\\Extension::onPageContentSave"
],
"InternalParseBeforeLinks": [
"LinkTitles\\Extension::onInternalParseBeforeLinks"
],
"GetDoubleUnderscoreIDs": [
"LinkTitles\\Extension::onGetDoubleUnderscoreIDs"
]
},
"callback": "LinkTitles\\Extension::setup",
"ExtensionMessagesFiles": {
"LinkTitlesMagic": "includes/LinkTitles_Magic.php"
},
"MessagesDirs": {
"LinkTitles": [
"i18n"
]
},
"manifest_version": 1
}

6
i18n/de.json Normal file
View File

@ -0,0 +1,6 @@
{
"linktitles": "LinkTitles",
"linktitles-desc": "Fügt beim Speichern von Seiten automatisch Querverweise zu vorhandenen Seiten ein.",:w
"right-linktitles-batch": "LinkTitles-Stapelverarbeitung ausführen",
"action-linktitles-batch": "LinkTitles-Stapelverarbeitung auszuführen"
}

6
i18n/en.json Normal file
View File

@ -0,0 +1,6 @@
{
"linktitles": "LinkTitles",
"linktitles-desc": "Automatically adds links to existing pages whenever a page is saved.",
"right-linktitles-batch": "Perform a LinkTitles batch operation",
"action-linktitles-batch": "perform a LinkTitles batch operation"
}

6
i18n/qqq.json Normal file
View File

@ -0,0 +1,6 @@
{
"linktitles": "Title of the LinkTitles extension; also used for the special page.",
"linktitles-desc": "Description of the LinkTitles extension.",
"right-linktitles-batch": "Describes the right to perform a LinkTitles batch operation.",
"action-linktitles-batch": "Describes the action of performing a LinkTitles batch operation."
}

View File

@ -0,0 +1,410 @@
<?php
/*
* Copyright 2012-2016 Daniel Kraus <bovender@bovender.de> ('bovender')
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
/// @file
namespace LinkTitles;
/// Helper function for development and debugging.
/// @param $var Any variable. Raw content will be dumped to stderr.
/// @return undefined
function dump($var) {
error_log(print_r($var, TRUE) . "\n", 3, 'php://stderr');
};
/// Central class of the extension. Sets up parser hooks.
/// This class contains only static functions; do not instantiate.
class Extension {
/// A Title object for the page that is being parsed.
private static $currentTitle;
/// A Title object for the target page currently being examined.
private static $targetTitle;
/// The content object for the currently processed target page.
/// This variable is necessary to be able to prevent loading the target
/// content twice.
private static $targetContent;
/// Holds the page title of the currently processed target page
/// as a string.
private static $targetTitleText;
/// Delimiter used in a regexp split operation to seperate those parts
/// of the page that should be parsed from those that should not be
/// parsed (e.g. inside pre-existing links etc.).
private static $delimiter;
private static $wordStartDelim;
private static $wordEndDelim;
/// Setup method
public static function setup() {
self::BuildDelimiters();
}
/// Event handler that is hooked to the PageContentSave event.
public static function onPageContentSave( &$wikiPage, &$user, &$content, &$summary,
$isMinor, $isWatch, $section, &$flags, &$status ) {
if ( !$isMinor && !\MagicWord::get('MAG_LINKTITLES_NOAUTOLINKS')->match( $text ) ) {
$title = $wikiPage->getTitle();
$text = $content->getContentHandler()->serializeContent($content);
$newText = self::parseContent( $title, $text );
if ( $newText != $text ) {
$content = $content->getContentHandler()->unserializeContent( $newText );
}
};
return true;
}
/// Event handler that is hooked to the InternalParseBeforeLinks event.
/// @param Parser $parser Parser that raised the event.
/// @param $text Preprocessed text of the page.
public static function onInternalParseBeforeLinks( \Parser &$parser, &$text ) {
// If the page contains the magic word '__NOAUTOLINKS__', do not parse it.
if ( !isset($parser->mDoubleUnderScores[$text] )) {
$text = self::parseContent( $parser->getTitle(), $text );
}
return true;
}
/// Core function of the extension, performs the actual parsing of the content.
/// @param Parser $parser Parser instance for the current page
/// @param $text String that holds the article content
/// @returns string: parsed text with links added if needed
private static function parseContent( $title, &$text ) {
// Configuration variables need to be defined here as globals.
global $wgLinkTitlesPreferShortTitles;
global $wgLinkTitlesMinimumTitleLength;
global $wgLinkTitlesBlackList;
global $wgLinkTitlesFirstOnly;
global $wgLinkTitlesSmartMode;
global $wgCapitalLinks;
( $wgLinkTitlesPreferShortTitles ) ? $sort_order = 'ASC' : $sort_order = 'DESC';
( $wgLinkTitlesFirstOnly ) ? $limit = 1 : $limit = -1;
self::$currentTitle = $title;
$newText = $text;
// Build a blacklist of pages that are not supposed to be link
// targets. This includes the current page.
$blackList = str_replace( '_', ' ',
'("' . implode( '", "',$wgLinkTitlesBlackList ) . '", "' .
self::$currentTitle->getDbKey() . '")' );
// Build an SQL query and fetch all page titles ordered by length from
// shortest to longest. Only titles from 'normal' pages (namespace uid
// = 0) are returned. Since the db may be sqlite, we need a try..catch
// structure because sqlite does not support the CHAR_LENGTH function.
$dbr = wfGetDB( DB_SLAVE );
try {
$res = $dbr->select(
'page',
'page_title',
array(
'page_namespace = 0',
'CHAR_LENGTH(page_title) >= ' . $wgLinkTitlesMinimumTitleLength,
'page_title NOT IN ' . $blackList,
),
__METHOD__,
array( 'ORDER BY' => 'CHAR_LENGTH(page_title) ' . $sort_order )
);
} catch (Exception $e) {
$res = $dbr->select(
'page',
'page_title',
array(
'page_namespace = 0',
'LENGTH(page_title) >= ' . $wgLinkTitlesMinimumTitleLength,
'page_title NOT IN ' . $blackList,
),
__METHOD__,
array( 'ORDER BY' => 'LENGTH(page_title) ' . $sort_order )
);
}
// Iterate through the page titles
foreach( $res as $row ) {
self::newTarget( $row->page_title );
// split the page content by [[...]] groups
// credits to inhan @ StackOverflow for suggesting preg_split
// see http://stackoverflow.com/questions/10672286
$arr = preg_split( self::$delimiter, $newText, -1, PREG_SPLIT_DELIM_CAPTURE );
// Escape certain special characters in the page title to prevent
// regexp compilation errors
self::$targetTitleText = self::$targetTitle->getText();
$quotedTitle = preg_quote(self::$targetTitleText, '/');
// Depending on the global configuration setting $wgCapitalLinks,
// the title has to be searched for either in a strictly case-sensitive
// way, or in a 'fuzzy' way where the first letter of the title may
// be either case.
if ( $wgCapitalLinks && ( $quotedTitle[0] != '\\' )) {
$searchTerm = '((?i)' . $quotedTitle[0] . '(?-i)' .
substr($quotedTitle, 1) . ')';
} else {
$searchTerm = '(' . $quotedTitle . ')';
}
$regex = '/(?<![\:\.\@\/\?\&])' . self::$wordStartDelim .
$searchTerm . self::$wordEndDelim . '/Su';
for ( $i = 0; $i < count( $arr ); $i+=2 ) {
// even indexes will point to text that is not enclosed by brackets
$arr[$i] = preg_replace_callback( $regex,
'LinkTitles\Extension::simpleModeCallback', $arr[$i], $limit, $count );
if (( $limit >= 0 ) && ( $count > 0 )) {
break;
};
};
$newText = implode( '', $arr );
// If smart mode is turned on, the extension will perform a second
// pass on the page and add links with aliases where the case does
// not match.
if ($wgLinkTitlesSmartMode) {
$arr = preg_split( self::$delimiter, $newText, -1, PREG_SPLIT_DELIM_CAPTURE );
for ( $i = 0; $i < count( $arr ); $i+=2 ) {
// even indexes will point to text that is not enclosed by brackets
$arr[$i] = preg_replace_callback( '/(?<![\:\.\@\/\?\&])' .
self::$wordStartDelim . '(' . $quotedTitle . ')' .
self::$wordEndDelim . '/iuS', 'LinkTitles\Extension::smartModeCallback',
$arr[$i], $limit, $count );
if (( $limit >= 0 ) && ( $count > 0 )) {
break;
};
};
$newText = implode( '', $arr );
} // $wgLinkTitlesSmartMode
}; // foreach $res as $row
return $newText;
}
/// Automatically processes a single page, given a $title Title object.
/// This function is called by the SpecialLinkTitles class and the
/// LinkTitlesJob class.
/// @param string $title Page title.
/// @param RequestContext $context Current context.
/// If in doubt, call MediaWiki's `RequestContext::getMain()`
/// to obtain such an object.
/// @returns undefined
public static function processPage( $title, \RequestContext $context ) {
// TODO: make this namespace-aware
$titleObj = \Title::makeTitle(0, $title);
$page = \WikiPage::factory($titleObj);
$content = $page->getContent();
$text = $content->getContentHandler()->serializeContent($content);
$newText = self::parseContent($titleObj, $text);
if ( $text != $newText ) {
$content = $content->getContentHandler()->unserializeContent( $newText );
$page->doQuickEditContent($content,
$context->getUser(),
"Links to existing pages added by LinkTitles bot.", // TODO: i18n
true // minor modification
);
};
}
/// Adds the two magic words defined by this extension to the list of
/// 'double-underscore' terms that are automatically removed before a
/// page is displayed.
/// @param $doubleUnderscoreIDs Array of magic word IDs.
/// @return true
public static function onGetDoubleUnderscoreIDs( array &$doubleUnderscoreIDs ) {
$doubleUnderscoreIDs[] = 'MAG_LINKTITLES_NOTARGET';
$doubleUnderscoreIDs[] = 'MAG_LINKTITLES_NOAUTOLINKS';
return true;
}
// Build an anonymous callback function to be used in simple mode.
private static function simpleModeCallback( array $matches ) {
if ( self::checkTargetPage() ) {
return '[[' . $matches[0] . ']]';
}
else
{
return $matches[0];
}
}
// Callback function for use with preg_replace_callback.
// This essentially performs a case-sensitive comparison of the
// current page title and the occurrence found on the page; if
// the cases do not match, it builds an aliased (piped) link.
// If $wgCapitalLinks is set to true, the case of the first
// letter is ignored by MediaWiki and we don't need to build a
// piped link if only the case of the first letter is different.
private static function smartModeCallback( array $matches ) {
global $wgCapitalLinks;
if ( $wgCapitalLinks ) {
// With $wgCapitalLinks set to true we have a slightly more
// complicated version of the callback than if it were false;
// we need to ignore the first letter of the page titles, as
// it does not matter for linking.
if ( self::checkTargetPage() ) {
if ( strcmp(substr(self::$targetTitleText, 1), substr($matches[0], 1)) == 0 ) {
// Case-sensitive match: no need to bulid piped link.
return '[[' . $matches[0] . ']]';
} else {
// Case-insensitive match: build piped link.
return '[[' . self::$targetTitleText . '|' . $matches[0] . ']]';
}
}
else
{
return $matches[0];
}
} else {
// If $wgCapitalLinks is false, we can use the simple variant
// of the callback function.
if ( self::checkTargetPage() ) {
if ( strcmp(self::$targetTitleText, $matches[0]) == 0 ) {
// Case-sensitive match: no need to bulid piped link.
return '[[' . $matches[0] . ']]';
} else {
// Case-insensitive match: build piped link.
return '[[' . self::$targetTitleText . '|' . $matches[0] . ']]';
}
}
else
{
return $matches[0];
}
}
}
/// Sets member variables for the current target page.
private static function newTarget( $title ) {
// @todo Make this wiki namespace aware.
self::$targetTitle = \Title::makeTitle( NS_MAIN, $title);
self::$targetContent = null;
}
/// Returns the content of the current target page.
/// This function serves to be used in preg_replace_callback callback
/// functions, in order to load the target page content from the
/// database only when needed.
/// @note It is absolutely necessary that the newTarget()
/// function is called for every new page.
private static function getTargetContent() {
if ( ! isset( $targetContent ) ) {
self::$targetContent = \WikiPage::factory(
self::$targetTitle)->getContent();
};
return self::$targetContent;
}
/// Examines the current target page. Returns true if it may be linked;
/// false if not. This depends on the settings
/// $wgLinkTitlesCheckRedirect and $wgLinkTitlesEnableNoTargetMagicWord
/// and whether the target page is a redirect or contains the
/// __NOAUTOLINKTARGET__ magic word.
/// @returns boolean
private static function checkTargetPage() {
global $wgLinkTitlesEnableNoTargetMagicWord;
global $wgLinkTitlesCheckRedirect;
// If checking for redirects is enabled and the target page does
// indeed redirect to the current page, return the page title as-is
// (unlinked).
if ( $wgLinkTitlesCheckRedirect ) {
$redirectTitle = self::getTargetContent()->getUltimateRedirectTarget();
if ( $redirectTitle && $redirectTitle->equals(self::$currentTitle) ) {
return false;
}
};
// If the magic word __NOAUTOLINKTARGET__ is enabled and the target
// page does indeed contain this magic word, return the page title
// as-is (unlinked).
if ( $wgLinkTitlesEnableNoTargetMagicWord ) {
if ( self::getTargetContent()->matchMagicWord(
\MagicWord::get('MAG_LINKTITLES_NOTARGET') ) ) {
return false;
}
};
return true;
}
/// Builds the delimiter that is used in a regexp to separate
/// text that should be parsed from text that should not be
/// parsed (e.g. inside existing links etc.)
private static function BuildDelimiters() {
// Configuration variables need to be defined here as globals.
global $wgLinkTitlesParseHeadings;
global $wgLinkTitlesSkipTemplates;
global $wgLinkTitlesWordStartOnly;
global $wgLinkTitlesWordEndOnly;
// Use unicode character properties rather than \b escape sequences
// to detect whole words containing non-ASCII characters as well.
// Note that this requires the use of the '/u' switch, and you need
// to have PHP with a PCRE library that was compiled with
// --enable-unicode-properties
( $wgLinkTitlesWordStartOnly ) ? self::$wordStartDelim = '(?<!\pL)' : self::$wordStartDelim = '';
( $wgLinkTitlesWordEndOnly ) ? self::$wordEndDelim = '(?!\pL)' : self::$wordEndDelim = '';
if ( $wgLinkTitlesSkipTemplates )
{
$templatesDelimiter = '{{[^}]+}}|';
} else {
// Match template names (ignoring any piped [[]] links in them)
// along with the trailing pipe and parameter name or closing
// braces; also match sequences of '|wordcharacters=' (without
// spaces in them) that usually only occur as parameter names in
// transclusions (but could also occur as wiki table cell contents).
// TODO: Find a way to match parameter names in transclusions, but
// not in table cells or other sequences involving a pipe character
// and equal sign.
$templatesDelimiter = '{{[^|]*?(?:(?:\[\[[^]]+]])?)[^|]*?(?:\|(?:\w+=)?|(?:}}))|\|\w+=|';
}
// Build a regular expression that will capture existing wiki links ("[[...]]"),
// wiki headings ("= ... =", "== ... ==" etc.),
// urls ("http://example.com", "[http://example.com]", "[http://example.com Description]",
// and email addresses ("mail@example.com").
// Since there is a user option to skip headings, we make this part of the expression
// optional. Note that in order to use preg_split(), it is important to have only one
// capturing subpattern (which precludes the use of conditional subpatterns).
( $wgLinkTitlesParseHeadings ) ? $delimiter = '' : $delimiter = '=+.+?=+|';
$urlPattern = '[a-z]+?\:\/\/(?:\S+\.)+\S+(?:\/.*)?';
self::$delimiter = '/(' . // exclude from linking:
'\[\[.*?\]\]|' . // links
$delimiter . // titles (if requested)
$templatesDelimiter . // templates (if requested)
'^ .+?\n|\n .+?\n|\n .+?$|^ .+?$|' . // preformatted text
'<nowiki>.*?<.nowiki>|<code>.*?<\/code>|' . // nowiki/code
'<pre>.*?<\/pre>|<html>.*?<\/html>|' . // pre/html
'<script>.*?<\/script>|' . // script
'<div.+?>|<\/div>|' . // attributes of div elements
'<span.+?>|<\/span>|' . // attributes of span elements
'<file>[^<]*<\/file>|' . // stuff inside file elements
'style=".+?"|class=".+?"|' . // styles and classes (e.g. of wikitables)
'\[' . $urlPattern . '\s.+?\]|'. $urlPattern . '(?=\s|$)|' . // urls
'(?<=\b)\S+\@(?:\S+\.)+\S+(?=\b)' . // email addresses
')/ismS';
}
}
// vim: ts=2:sw=2:noet:comments^=\:///

View File

@ -0,0 +1,31 @@
<?php
/*
* Copyright 2012-2016 Daniel Kraus <bovender@bovender.de> ('bovender')
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
/*! @file LinkTitles_Magic.php
*/
/// Holds the two magic words that the extension provides.
$magicWords = array();
/// Default magic words in English.
$magicWords['en'] = array(
'MAG_LINKTITLES_NOAUTOLINKS' => array(0, '__NOAUTOLINKS__'),
'MAG_LINKTITLES_NOTARGET' => array(0, '__NOAUTOLINKTARGET__')
);

View File

@ -1,6 +1,6 @@
<?php <?php
/* /*
* Copyright 2012-2014 Daniel Kraus <krada@gmx.net> ('bovender') * Copyright 2012-2016 Daniel Kraus <bovender@bovender.de> ('bovender')
* *
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -17,18 +17,19 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA. * MA 02110-1301, USA.
*/ */
namespace LinkTitles;
/// @defgroup batch Batch processing /// @defgroup batch Batch processing
/// @cond /// @cond
if ( !defined( 'MEDIAWIKI' ) ) { if ( !defined( 'MEDIAWIKI' ) ) {
die( 'Not an entry point.' ); die( 'Not an entry point.' );
} }
/// @endcond /// @endcond
/// Provides a special page that can be used to batch-process all pages in /// Provides a special page that can be used to batch-process all pages in
/// the wiki. By default, this can only be performed by sysops. /// the wiki. By default, this can only be performed by sysops.
/// @ingroup batch /// @ingroup batch
class SpecialLinkTitles extends SpecialPage { class Special extends \SpecialPage {
/// Constructor. Announces the special page title and required user right /// Constructor. Announces the special page title and required user right
/// to the parent constructor. /// to the parent constructor.
@ -36,17 +37,21 @@ class SpecialLinkTitles extends SpecialPage {
// the second parameter in the following function call ensures that only // the second parameter in the following function call ensures that only
// users who have the 'linktitles-batch' right get to see this page (by // users who have the 'linktitles-batch' right get to see this page (by
// default, this are all sysop users). // default, this are all sysop users).
parent::__construct('LinkTitles', 'linktitles-batch'); parent::__construct( 'LinkTitles', 'linktitles-batch' );
}
function getGroupName() {
return 'pagetools';
} }
/// Entry function of the special page class. Will abort if the user does /// Entry function of the special page class. Will abort if the user does
/// not have appropriate permissions ('linktitles-batch'). /// not have appropriate permissions ('linktitles-batch').
/// @returns undefined /// @return undefined
function execute($par) { function execute($par) {
// Prevent non-authorized users from executing the batch processing. // Prevent non-authorized users from executing the batch processing.
if ( !$this->userCanExecute( $this->getUser() ) ) { if ( !$this->userCanExecute( $this->getUser() ) ) {
$this->displayRestrictionError(); $this->displayRestrictionError();
return; return;
} }
$request = $this->getRequest(); $request = $this->getRequest();
@ -57,17 +62,17 @@ class SpecialLinkTitles extends SpecialPage {
// If GET, display information and a button to start linking. // If GET, display information and a button to start linking.
// If POST, start or continue the linking process. // If POST, start or continue the linking process.
if ( $request->wasPosted() ) { if ( $request->wasPosted() ) {
if ( array_key_exists('s', $request->getValues()) ) { if ( array_key_exists( 's', $request->getValues() ) ) {
$this->process($request, $output); $this->process( $request, $output );
} }
else else
{ {
$this->buildInfoPage($request, $output); $this->buildInfoPage( $request, $output );
} }
} }
else else
{ {
$this->buildInfoPage($request, $output); $this->buildInfoPage( $request, $output );
} }
} }
@ -77,7 +82,7 @@ class SpecialLinkTitles extends SpecialPage {
/// @param WebRequest $request WebRequest object that is associated with the special /// @param WebRequest $request WebRequest object that is associated with the special
/// page. /// page.
/// @param OutputPage $output Output page for the special page. /// @param OutputPage $output Output page for the special page.
private function process( WebRequest &$request, OutputPage &$output) { private function process( \WebRequest &$request, \OutputPage &$output) {
global $wgLinkTitlesTimeLimit; global $wgLinkTitlesTimeLimit;
// Start the stopwatch // Start the stopwatch
@ -125,7 +130,7 @@ class SpecialLinkTitles extends SpecialPage {
// Iterate through the pages; break if a time limit is exceeded. // Iterate through the pages; break if a time limit is exceeded.
foreach ( $res as $row ) { foreach ( $res as $row ) {
$curTitle = $row->page_title; $curTitle = $row->page_title;
LinkTitles::processPage($curTitle, $this->getContext()); Extension::processPage( $curTitle, $this->getContext() );
$start += 1; $start += 1;
// Check if the time limit is exceeded // Check if the time limit is exceeded
@ -155,7 +160,7 @@ class SpecialLinkTitles extends SpecialPage {
/// Adds WikiText to the output containing information about the extension /// Adds WikiText to the output containing information about the extension
/// and a form and button to start linking. /// and a form and button to start linking.
private function buildInfoPage(&$request, &$output) { private function buildInfoPage( &$request, &$output ) {
$url = $request->getRequestURL(); $url = $request->getRequestURL();
// TODO: Put the page contents in messages in the i18n file. // TODO: Put the page contents in messages in the i18n file.
@ -189,7 +194,7 @@ EOF
/// @param $index Index of the currently processed page. /// @param $index Index of the currently processed page.
/// @param $end Last index that will be processed (i.e., number of /// @param $end Last index that will be processed (i.e., number of
/// pages). /// pages).
private function addProgressInfo(&$output, $curTitle, $index, $end) { private function addProgressInfo( &$output, $curTitle, $index, $end ) {
$progress = $index / $end * 100; $progress = $index / $end * 100;
$percent = sprintf("%01.1f", $progress); $percent = sprintf("%01.1f", $progress);
@ -231,7 +236,7 @@ EOF
/// @param $reloads Counter that holds the number of reloads so far. /// @param $reloads Counter that holds the number of reloads so far.
/// @returns String that holds the HTML for a form and a /// @returns String that holds the HTML for a form and a
/// JavaScript command. /// JavaScript command.
private function getReloaderForm($url, $start, $end, $reloads) { private function getReloaderForm( $url, $start, $end, $reloads ) {
return return
<<<EOF <<<EOF
<form method="post" name="linktitles" action="${url}"> <form method="post" name="linktitles" action="${url}">
@ -252,7 +257,7 @@ EOF
/// @param $end Index of the last processed page. /// @param $end Index of the last processed page.
/// @param $reloads Number of reloads of the page. /// @param $reloads Number of reloads of the page.
/// @returns undefined /// @returns undefined
private function addCompletedInfo(&$output, $start, $end, $reloads) { private function addCompletedInfo( &$output, $start, $end, $reloads ) {
global $wgLinkTitlesTimeLimit; global $wgLinkTitlesTimeLimit;
$pagesPerReload = sprintf('%0.1f', $end / $reloads); $pagesPerReload = sprintf('%0.1f', $end / $reloads);
$output->addWikiText( $output->addWikiText(
@ -275,7 +280,7 @@ EOF
/// Counts the number of pages in a read-access wiki database ($dbr). /// Counts the number of pages in a read-access wiki database ($dbr).
/// @param $dbr Read-only `Database` object. /// @param $dbr Read-only `Database` object.
/// @returns Number of pages in the default namespace (0) of the wiki. /// @returns Number of pages in the default namespace (0) of the wiki.
private function countPages(&$dbr) { private function countPages( &$dbr ) {
$res = $dbr->select( $res = $dbr->select(
'page', 'page',
'page_id', 'page_id',

View File

@ -1,28 +0,0 @@
#!/bin/bash
# This script packs the relevant files of the LinkTitles
# extension into two archive files that contain the current
# git tag as the version number.
if [[ -z $1 ]]; then
echo "Usage: $(basename $0) VERSION."
echo "Missing VERSION!"
exit 1
fi
FILENAME="release/LinkTitles-$1.tar.gz"
# Pack the relevant files into at tarball, renaming the paths to include the
# root path "LinktTitles".
tar cvzf $FILENAME gpl-*.txt README.md NEWS *.php --exclude '*~' --transform 's,^,LinkTitles/,'
# if [[ $? -eq 0 ]]; then
# # Add the tarball to the repository, commit it, then tag the commit and push to origin.
# git add $FILENAME
# git commit -m --amend
# git tag -a $1 -m "Version $1."
# git push
# git push --tags
# else
# echo "tar had errors, did not push."
# fi

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.