MediaWiki HOWTOs

From Zedomax Wiki

Revision as of 18:51, 2 February 2008; Max (Talk | contribs)
(diff) ←Older revision | Current revision | Newer revision→ (diff)
Jump to: navigation, search

Password change

UPDATE user SET user_password = MD5(CONCAT(user_id, '-', MD5('somepass'))) WHERE user_name = 'whatever';

==Install MediaWiki Steps to installing MediaWiki:

Download Media Wiki here

Requirements

Some users find it helpful to install an additional software package such as phpMyAdmin (MySQL) or phpPgAdmin (Postgres) to help administer the database server.

1. copy the tar.gz file and untar using "tar xvf mediaXXX.tar.gz"

2. you can do "cp mediawikiXXX/* . -rf" to copy to root directory if untarred to a directory

3. Open your website now such as FiveDollarWiki.com

4. Follow instructions

Recommended Installs

Turck MMCACHE

Remove Robot NoFollow

Remove Robot NoFollow from MediaWiki

Category Cloud

here

Voting AJAX MediaWiki Extension

Voting AJAX MediaWiki Extension

eliminate index in mediawiki

1. Add this to your LocalSettings.php $wgArticlePath = "/$1";

2. Make a new .htaccess file and add this:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?title=$1 [PT,L,QSA]

Problems with MediaWiki 1.11 / "Index.php" article

If you find yourself editing a page called "Index.php", try adding this to LocalSettings.php:

 $wgUsePathInfo = false;

Note that setting this global to false means that the semi-friendly solutions described above for handling ampersands etc will no longer work. To temporarily fix this 1.11 bug before the developers have released a fixed version, see OrganicDesign:MediaWiki 1.11 title extraction bug for details about how to revert 1.11's title handling code to the 1.10 version.


Get rid of No-Follow

source

$wgNoFollowLinks = false;

Install WikiScript

WikiScript

Allowing external image links

Add this to LocalSettings.php:

$wgAllowExternalImages = true;

Add this to Template:Clickpic page:

<span class="plainlinks">[{{SERVER}}{{localurl:{{{1}}}}} {{{2}}}]</span>

Install GoogleMaps Extension

Install GoogleMaps!

Who's Online Extension

Who's Online Extension!

Install websiteFrame Extension

Install websiteFrame Extension

Install ImageMap Extension

ImageMap Installation directions

<?php
# ImageMap Mediawiki extension
#
# original by smcnaught 29.06.2005
# Installation:
#  * put this file (ImageMap.php) into the extension directory of your mediawiki installation
#  * add the following to the end of LocalSettings.php: include("extensions/ImageMap.php");
#
# Usage:
#  Use one section between <ImageMap>-tags for each feed. The ImageMap section may contain parameters
#  separated by a pipe ("|"), just like links and templates. These parameters are supported:
#
# Example:
#    <ImageMap>Image=ImageURL|Map=MapURL</ImageMap>
#


#install extension hook
$wgExtensionFunctions[] = "wfImageMapExtension";

#extension hook callback function
function wfImageMapExtension() {
  global $wgParser;

  #install parser hook for <ImageMap> tags
  $wgParser->setHook( "ImageMap", "renderImageMap" );
}

#parser hook callback function
function renderImageMap( $input ) {
  global $wgServer, $wgScriptPath, $wgTitle, $wgUrlProtocols, $wgUser, $IP;
#  global $wgOutputEncoding;

  if (!$input) return "";

  $fields= explode("|",$input);
  $args= array();
  for ($i=0; $i<sizeof($fields); $i++) {
    $f= $fields[$i];

    if (strpos($f,"=")===False) $args[strtolower(trim($f))]= False;
    else {
      list($k,$v)= explode("=",$f,2);
      if (trim($v)==False) $args[strtolower(trim($k))] = False;
      else $args[strtolower(trim($k))]= trim($v);
    }
  }
  $timestamp = mktime() . rand(1,29);

  #get title from argument-array

  $ImageURL= @$args["image"];
  $ImageURL= trim($ImageURL);
  if ($ImageURL=='') {
    return "No Image";
  }

  $MapURL= @$args["map"];
  $MapURL= trim($MapURL);
  if ($MapURL=='') {
    return "No Map";
  }
  $localParser = new Parser();
  $parserOptions = ParserOptions::newFromUser( $wgUser );

  $html = $localParser->parse($ImageURL,$wgTitle,$parserOptions);
  $Imageurl = preg_replace('/^.*<a[\s]+href=*"(.*?)".*$/is', '\1' , $html->mText);
  $html = $localParser->parse($MapURL,$wgTitle,$parserOptions);
  $Mapurl = preg_replace('/^.*<a[\s]+href=*"(.*?)".*$/is', '\1' , $html->mText);
  $mapfile = "$IP/../$Mapurl";
  $lines = array_map('rtrim',file("$mapfile"));

  $output="<img src=\"$Imageurl\" usemap=\"#$timestamp\">";

  if (!file_exists($mapfile)) {
    $output = $output . "Path to mapfile is incorrect or file does not exist. mapfile should look like: /var/www/html/wiki/images/4/4d/Fish.map";

    # Enable for troubleshooting, otherwise comment to hide directory path.
    #   $output = $output . "$mapfile";
  }


  // Loop through our array, show HTML source as HTML source; and line numbers too.
  foreach ($lines as $line_num => $line) {
    if (preg_match ("/\sname=/i", $line)) {
      $replacestr = " name=\"$timestamp\"";
      $line = preg_replace('/\sNAME=\"[a-zA-Z0-9 ]+\"/i',$replacestr,$line);    
    }
    $line = preg_replace(array('/\s{2,}/','/^\s+/','/\s+$/'),array(' ','',''),$line);
    $output = $output . $line . "\n";
  }
  return $output;

}

?>


prevent new users

prevent new users mediawiki

Useful MediaWiki Resources

MediaWiki installation and twiks

prevent new users

prevent new users mediawiki

Making search for keywords

include utils.php from Pligg



Welcome <?php echo $_POST["words"]; ?>.<br />

<?php

$words=$_POST["words"];
//$foo = new Title;

//$test = $foo->cleanUp($_POST["words"]);
//$test = $foo->NFC($_POST["words"]);
//$test = Title::getInterwikiLink( $_POST["words"]);
//$test = Title::newFromText( $_POST["words"]);
//$test = urlencode("hello-there");
//$test = Sanitizer::stripAllTags("Hello there");
//$test = strip_tags(trim($words));
//$test = makeUrlFriendly($test);
//$test = utf8_substr($test);

$words = stripslashes(strip_tags(trim($words)));
$words = ucwords(strtolower($words));
$words = makeUrlFriendly($words);


//$test = utf8_substr($input, 0, 240);
//class foo extends UtfNormal {
//}
//$urlfriendly = toNFC($_POST["words"]);
?>

URL friendly: <?php echo $urlfriendly; ?>

<?php echo $words; ?>

<br />

<?php

$db = mysql_connect("localhost", "asdasd", "asdasd");

if (!$db) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db("asdasd",$db);

$result = mysql_query("SELECT count(page_title) from page where page_title='".$words."'",$db);

if (mysql_result($result,0) == 0) {
        printf("NONE!");
}


printf("Records: %s\n", mysql_result($result,0));


Install PageFunctions Extension

PageFunctions MediaWiki Extension HOWTO


*/
$wgExtensionCredits[PageFunctions::thisType][] = array( 
        'name'        => PageFunctions::thisName, 
        'version'     => StubManager::getRevisionId( '$Id: PageFunctions.php 634 2007-08-10 00:58:50Z jeanlou.dupont $' ),
        'author'      => 'Jean-Lou Dupont', 
        'description' => 'Provides page scope functions',
        'url'          => StubManager::getFullUrl(__FILE__),                                            
);
 
class PageFunctions
{
        const thisName = 'PageFunctions';
        const thisType = 'other';
 
        var $pageVars;
 
        // Our class defines magic words: tell it to our helper class.
        public function __construct()
        { 
                $this->pageVars = array();
        }
 
        // ===============================================================
        public function mg_pagetitle( &$parser )
        {
                $params = StubManager::processArgList( func_get_args(), true );
                return $this->setTitle( $params[0] );
        }
        private function setTitle( &$title )
        {
                global $wgOut;
                $wgOut->setPageTitle( $title );
        }
 
        // ===============================================================
        public function mg_pagesubtitle( &$parser )
        {
                $params = StubManager::processArgList( func_get_args(), true );
                $this->setSubTitle( $params[0] );
        }
        private function setSubTitle( &$title )
        {
                global $wgOut;
                $wgOut->setSubtitle( $title );
        } 
 
        // ===============================================================
        public function mg_pageexists( &$parser )
        {
                $params = StubManager::processArgList( func_get_args(), true );
                return $this->doesPageExists( $params[0] );
        }
 
        private function doesPageExists( &$title ) 
        {
                $a = StubManager::getArticle( $title );
                if (is_object($a)) 
                        $id=$a->getID();
                else $id = 0;
 
                return ($id == 0 ? false:true);             
        }
 
        // ===============================================================
        /**
                Hook based Page Variable 'get'
                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
         */
        public function hPageVarGet( &$varname, &$value )
        {
                $value = @$this->pageVars[ $varname ];         
                return true; // continue hook-chain.
        }
        /**
                Hook based Page Variable 'set'
                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
         */
        public function hPageVarSet( &$varname, &$value )
        {
                $this->pageVars[ $varname ] = $value;          
                return true; // continue hook-chain.
        }
        public function mg_varset( &$parser ) 
        {
                $params = StubManager::processArgList( func_get_args(), true );
                $this->pageVars[ $params[0] ] = $params[1];              
        }
        public function mg_varget( &$parser ) 
        {
                $params = StubManager::processArgList( func_get_args(), true );
                return @$this->pageVars[ $params[0] ];              
        }
        /**
                Captures a variable
 
                Useful when building complex HTML pages.
 
                {{#varcapset: variable name|value }}
                ((#varcapset: variable name|value )) 
         */
        public function mg_varcapset( &$parser )
        {
                $params = StubManager::processArgList( func_get_args(), true );
                @$this->pageVars[ $params[0] ] = $params[1];
                return $params[1];
        }  
        /**
                Sets a variable to an array.
                param 0: variable name
                param 1: array key
                param 2: array value corresponding to key.
         */http://zedomax.com/wiki/index.php/Main_Page
http://zedomax.com/wiki/index.php/Main_Page
        public function mg_varaset( &$parser )
        {
                $params = StubManager::processArgList( func_get_args(), true );
                @$this->pageVars[ $params[0] ][ $params[1] ] = $params[2];         
 
        }
        /**
                Gets a variable to an array.
                param 0: variable name
                param 1: array key
         */
        public function mg_varaget( &$parser )
        {
                $params = StubManager::processArgList( func_get_args(), true );
                return @$this->pageVars[ $params[0] ][ $params[1] ];          
        }
        // ===============================================================
        public function mg_cshow( &$parser, &$group, &$text )
        // Conditional Show: if user is part of $group, then allow for '$text'
        // Parser Cache friendly of 'ConditionalShowSection' extension.
        {
                global $wgUser;
                $g = $wgUser->getEffectiveGroups();
                if (in_array( $group, $g ))
                        return $text;
        }
 
        /**
                Magic Word 'noclientcaching'
 
                The actual action of disabling the client caching process is already performed through
                'ParserCache2' extension when processing 'magic words' such as this one (($noclientcaching$)).
                If on the contrary this function is called through the usual {{noclientcaching}} statement, then
                1) If 'parser caching' is used, this statement will have limited effect
                2) If 'parser caching' is not used, then this statement will have an effect everytime the page is visited.
         */
        public function MW_noclientcaching( &$parser, &$varcache, &$ret )
        {
                global $wgOut;
                $wgOut->enableClientCache(false);
        }
 
        public function mg_noext( &$parser, $pagename = null)
        {
                if (empty( $pagename ))  
                        return null;
                return substr( $pagename, 0, strpos( $pagename, '.' ) );     
        }
 
} // end class  
//

Simple Security MediaWiki Extension for controlling each page edit rights

source

#EXTENSIONS



#security
include('extensions/SimpleSecurity.php');
$wgSecurityMagic = "security";
$wgSecurityMagicNoi = "!security";
$wgSecurityMagicIf = "ifusercan";
$wgSecurityMagicGroup = "ifgroup";
$wgSecurityEnableInheritance = false;
$wgSecuritySysops = "sysop";

$wgSecurityDenyTemplate = "Template:Action not permitted";
$wgSecurityInfoTemplate = "Template:Security info";

$wgSecurityEnableForImages = false;
$wgSecurityDenyImage = "local mediawiki logo";
$wgSecurityParseInfo = false;

#BASIC USER RIGHTS  
$wgGroupPermissions['*'    ]['createaccount']   = false;
$wgGroupPermissions['*'    ]['createpage']      = false;
$wgGroupPermissions['*'    ]['edit']            = false;
$wgGroupPermissions['user'    ]['createpage']      = false;
$wgShowIPinHeader = false;


Adding RSS

WikiFeeds

<?php

/*
 Wiki Feed Generator for MediaWiki
 Gregory Szorc <gregory.szorc@gmail.com>

 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.

 This library 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
 Lesser General Public License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA


 Directions:
 This script requires MediaWiki 1.5+ and PHP 5 to run.  It was developed against MediaWiki
 1.8.2 and PHP 5.1.6.  If it doesn't work, upgrade!

 To use this script, copy it to your extensions/ subdirectory inside the MediaWiki install.
 Add the following in LocalSettings.php:

 include_once('SpecialWikiFeeds.php');

 This script also needs my GenericXmlSyndicationFeed class, which can be found at
 http://opensource.case.edu/svn/MediaWikiHacks/classes/GenericXmlSyndicationFeed/GenericXmlSyndicationFeed.php

 You will need to manually include this file before the require/include SpecialWikiFeeds.php
 in LocalSettings.php or else when this file loads, you will get a big, fat error message.

 Example LocalSettings.php entry:

 require("$IP/extensions/GenericXmlSyndicationFeed.php");
 require("$IP/extensions/SpecialWikiFeeds.php");
 $wgWikiFeedsSettings['cacheEnable'] = true;

 Once WikiFeeds is enabled in LocalSettings.php,
 go to Special:WikiFeeds in your wiki.  Everything should be set!

 WikiFeeds can be slightly customized.  Settings which can be changed are located
 in the $wgWikiFeedsSettings array (defined and documentation below).  If you wish
 to change a setting, re-set it in LocalSettings.php, after including this file
 (see above example)

 If you encounter a bug, please file it at http://opensource.case.edu/projects/MediaWikiHacks
 or e-mail me.

 Other:
 The script supports ATOM 1.0 better than RSS 2.0.  ATOM is the future.  I'm not
 wasting my time adding full support for RSS.

 ToDo:
 Use MediaWiki language support through system messages (partially done)
 Better error checking
 Optimize SQL queries

 */

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

$wgExtensionFunctions[] = 'wfWikiFeeds';
$wgExtensionCredits['specialpage'][] = array(
  'name'=>'Wiki Feeds',
  'author'=>'Gregory Szorc <gregory.szorc@gmail.com>',
  'url'=>'http://wiki.case.edu/User:Gregory.Szorc',
  'description'=>'Produces syndicated feeds for MediaWiki.',
  'version'=>'0.5'
);

/**
 * Holds default settings for WikiFeeds
 *
 * Override values in LocalSettings.php after you include this file
 */
$wgWikiFeedsSettings = array(
	'cacheEnable' => false, //whether to enable the cache
	'cacheRoot'		=> '/tmp/', //cache directory, with trailing slash
	'cacheMaxAge'	=> 600, //max age of cached files, in seconds
	'cachePruneFactor' => 100, //prune stale cache entries 1 out of every this many requests
    'watchlistPrivate' => false, //when true, make per-user watchlists require special access token
);

function wfWikiFeeds() {
	global $wgMessageCache, $wgHooks;

	if (!class_exists('GenericXmlSyndicationFeed')) {
		throw new MWException('GenericXmlSyndicationFeed class not loaded.  Please read the install directions!');
	}

	require_once('SpecialPage.php');

	$wgMessageCache->addmessages(
	array(
		'wikifeeds'=>'Wiki Feeds',
		'wikifeeds_unknownformat' => "==Unknown format==\nThe feed format you requested is not available.",
		'wikifeeds_unknownfeed' => "==Unknown feed==\nThe feed you selected is not available.",
		'wikifeeds_undefinedcategory' => "==Undefined category==\nThe feed you requested requires that the ''category'' parameter be defined",
		'wikifeeds_categorynoexist' => "==Unknown category==\nThe category you tried to request does not exist.  Category names are case sensitive.  Be sure the category is listed at [[Special:Categories]]",
		'wikifeeds_undefineduser' => "==Undefined user==\nThe feed you requested requires that the ''user'' parameter be defined",
		'wikifeeds_unknownuser' => "==Unknown user==\nThe user specified does not exist. Be sure the user is listed at [[Special:User]]",
		'wikifeeds_nowatchlisttoken' => "==No Token==\nYou must supply a token to access your user watchlist",
		'wikifeeds_invalidwatchlisttoken' => "==Invalid Token==\nThe token specified to access the watchlist is invalid",
		'wikifeeds_tokeninfo' => "==Watchlist Token==\nYour private watchlist token is $1.  Access your watchlist via $2",
		'wikifeeds_feed_newestarticles_title' => 'Newest Articles',
		'wikifeeds_feed_newestarticles_description' => 'Newest articles in the wiki',
		'wikifeeds_feed_recentarticlechanges_title' => 'Recently Changed Articles',
		'wikifeeds_feed_recentarticlechanges_description' => 'Recently changed articles in the wiki',
		'wikifeeds_feed_newestarticlesbyuser_title' => 'Newest articles created by $1',
		'wikifeeds_feed_newestarticlesbyuser_description' => 'Newest articles created by $1',
		'wikifeeds_feed_recentuserchanges_title' => 'Recent changes by $1',
		'wikifeeds_feed_recentuserchanges_description' => 'Recent changes made by user $1',
		'wikifeeds_feed_userwatchlist_title' => 'Watchlist for $1',
		'wikifeeds_feed_userwatchlist_description' => 'Watchlist for $1',
		'wikifeeds_feed_recentcategorychanges_title' => 'Recently changed articles in $1',
		'wikifeeds_feed_recentcategorychanges_description' => 'Recently changed articles in category $1',
		'wikifeeds_feed_newestarticlesincategory_title' => 'Newest articles in the category $1',
		'wikifeeds_feed_newestarticlesincategory_description' => 'Newly created articles that are part of the category $1',

		'wikifeeds_mainpage' =>
"WikiFeeds generates syndicated feeds for this wiki.

==WikiArticleFeeds Extension==
[http://jimbojw.com/wiki/index.php?title=WikiArticleFeeds_Extension Get it here]
<pre>
<?php

/*
 * WikiArticleFeeds.php - A MediaWiki extension for converting regular pages into feeds.
 * @author Jim R. Wilson
 * @version 0.6.3
 * @copyright Copyright (C) 2007 Jim R. Wilson
 * @license The MIT License - http://www.opensource.org/licenses/mit-license.php 
 * -----------------------------------------------------------------------
 * Description:
 *     This is a MediaWiki (http://www.mediawiki.org/) extension which adds support
 *     for publishing RSS or Atom feeds generated from standard wiki articles.
 * Requirements:
 *     MediaWiki 1.6.x, 1.8.x, 1.9.x or higher
 *     PHP 4.x, 5.x or higher
 * Installation:
 *     1. Drop this script (WikiArticleFeeds.php) in $IP/extensions
 *         Note: $IP is your MediaWiki install dir.
 *     2. Enable the extension by adding this line to your LocalSettings.php:
 *            require_once('extensions/WikiArticleFeeds.php');
 * Usage:
 *     Once installed, you may utilize WikiArticleFeeds by invoking the 'feed' action of an article:
 *         $wgScript?title=Some_Article&action=feed
 *     Note: You may optionally supply a feed type.  Acceptable values inculde 'rss' and 'atom'.
 *     If no feed type is specified, the default is 'atom'.  For example: 
 *         $wgScript?title=Some_Article&action=feed&feed=atom
 * Creating a Feed:
 *     To delimit a section of an article as containing feed items, use the <startFeed /> 
 *     and <endFeed /> tags respectively.  These tags are merely flags, and any attributes
 *     specified, or content inside the tags themselves will be ignored.
 * Tagging a Feed item:
 *     To tag a feed item, insert either the <itemTags> tag, or the a call to the {{#itemTags}} parser 
 *     function somewhere between the opening header of the item (== Item Title ==) and the header of 
 *     the next item.  For example, to mark an item about dogs and cats, you could do any of the following:
 *         <itemTags>dogs, cats</itemTags>
 *         {{#itemTags:dogs, cats}}
 *         {{#itemTags:dogs|cats}}
 * Version Notes:
 *     version 0.6.3:
 *         Wrapped extension points for versions less than 1.7 (old version compatibility)
 *     version 0.6.2:
 *         Added support for alternate signatures (when users are not in the User namespace)
 *         Tied purge of xml feeds to purge of page - helps with consumers of semantic and DPL
 *             (Thanks to Charlie Huggard of charlie.huggardlee.net for these contributions)
 *     version 0.6.1:
 *         Fixed stale feed problem by expiring the feed cache when any of an article's transcluded pages change.
 *     version 0.6:
 *         Added support for "tagging" feed items by way of <itemTags> or {{itemTags}}
 *         Added support for filtering generated feed based on item tags.
 *         Added global ($wgWikiArticleFeedsSkipCache) used for skipping object-cache while debugging.
 *         Fixed namespace restriction - now works for namespaces other than NS_MAIN
 *     version 0.5:
 *         Now supports offloading to FeedBurner (http://feedburner.com/) via <feedBurner> tag.
 *         Capitalized RSS and Atom links in the toolbox.
 *     version 0.4:
 *         Added wgForceArticleFeedSectionLinks to override default link behavior (set in LocalSettings).
 *         Feed generator now follows Article redirects.
 *     version 0.3:
 *         Added Version Notes.
 *         Fixed relative-links bug (all links in item descriptions are now fully qualified).
 *         Fixed date-overwrite bug (previously, items with the exact same timestamp would be ignored).
 *         Improved W3C validation. Feeds validate, but there are still warnings.
 *     version 0.2:
 *         Renamed from WikiFeeds.php to WikiArticleFeeds.php
 *         Corrected credits and copyright info.
 *         Numerous minor fixes and tweaks.
 *         Expanded support for versions 1.6.x, 1.8.x and 1.9.x.
 *         Improved return values from hooking functions (plays better with other extensions).
 *     version 0.1:
 *         Initial release.
 * -----------------------------------------------------------------------
 * Copyright (c) 2007 Jim R. Wilson
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy 
 * of this software and associated documentation files (the "Software"), to deal 
 * in the Software without restriction, including without limitation the rights to 
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 
 * the Software, and to permit persons to whom the Software is furnished to do 
 * so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all 
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 
 * OTHER DEALINGS IN THE SOFTWARE. 
 * -----------------------------------------------------------------------
 */
 
 # Confirm MW environment
if (!defined('MEDIAWIKI')) die();
 
define('WIKIARTICLEFEEDS_VERSION','0.6.3');
 
# Bring in supporting classes
require_once("$IP/includes/Feed.php");
require_once("$IP/includes/Sanitizer.php");
 
# Credits
$wgExtensionCredits['specialpage'][] = array(
    'name'=>'WikiArticleFeeds',
    'author'=>'Jim Wilson (wilson.jim.r<at>gmail.com)',
    'url'=>'http://jimbojw.com/wiki/index.php?title=WikiArticleFeeds',
    'description'=>'Produces feeds generated from MediaWiki articles.',
    'version'=>WIKIARTICLEFEEDS_VERSION
);
 
/**
 * Wrapper class for consolidating all WAF related parser methods
 */
class WikiArticleFeedsParser {
 
    function feedStart( $text, $params = array() ) {
        return '<!-- FEED_START -->';
    }
    
    function feedEnd( $text, $params = array() ) {
        return '<!-- FEED_END -->';
    }
    
    function burnFeed( $text, $params = array() ) {
        return ($params['name']?'<!-- BURN_FEED '.base64_encode(serialize($params['name'])).' -->':'');
    }
    
    function itemTagsTag( $text, $params = array() ) {
        return ($text?'<!-- ITEM_TAGS '.base64_encode(serialize($text)).' -->':'');
    }
    
    function itemTagsFunction( $parser ) {
        $tags = func_get_args();
        array_shift( $tags );
        return (!empty($tags)?'<pre>@ITEMTAGS@'.base64_encode(serialize(implode(',',$tags))).'@ITEMTAGS@
':);
   }
   
   function itemTagsMagic( &$magicWords, $langCode=null ) {
       $magicWords['itemtags'] = array( 0, 'itemtags' );
       return true;
   }
   
   function itemTagsPlaceholderCorrections( $parser, &$text ) {
       $text = preg_replace(
'|
@ITEMTAGS@([0-9a-zA-Z\\+\\/]+=*)@ITEMTAGS@
|',
           ,
           $text
       );
       return true;
   }

}

  1. Create global instance

$wgWikiArticleFeedsParser = new WikiArticleFeedsParser(); if (version_compare($wgVersion, '1.7', '<')) {

   # Hack solution to resolve 1.6 array parameter nullification for hook args
   function wfWAFParserItemTagsMagic( &$magicWords ) {
       global $wgWikiArticleFeedsParser;
       $wgWikiArticleFeedsParser->itemTagsMagic( $magicWords );
       return true;
   }
   function wfWAFParserPlaceholderCorrections( $parser, &$text ) {
       global $wgWikiArticleFeedsParser;
       $wgWikiArticleFeedsParser->itemTagsPlaceholderCorrections( $parser, $text );
       return true;
   }
   $wgHooks['LanguageGetMagic'][] = 'wfWAFParserItemTagsMagic';
   $wgHooks['ParserBeforeTidy'][] = 'wfWAFParserPlaceholderCorrections';

} else {

   $wgHooks['LanguageGetMagic'][] = array($wgWikiArticleFeedsParser, 'itemTagsMagic');
   $wgHooks['ParserBeforeTidy'][] = array($wgWikiArticleFeedsParser, 'itemTagsPlaceholderCorrections');

}

  1. Add Extension Functions

$wgExtensionFunctions[] = 'wfWikiArticleFeedsParserSetup';

  1. Sets up the WikiArticleFeeds Parser hooks

function wfWikiArticleFeedsParserSetup() { global $wgParser, $wgWikiArticleFeedsParser;

$wgParser->setHook( 'startFeed', array($wgWikiArticleFeedsParser, 'feedStart') ); $wgParser->setHook( 'endFeed', array($wgWikiArticleFeedsParser, 'feedEnd') ); $wgParser->setHook( 'feedBurner', array($wgWikiArticleFeedsParser, 'burnFeed') ); $wgParser->setHook( 'itemTags', array($wgWikiArticleFeedsParser, 'itemTagsTag') );

$wgParser->setFunctionHook( 'itemtags', array($wgWikiArticleFeedsParser, 'itemTagsFunction') ); }

  1. Attach Hooks

$wgHooks['OutputPageBeforeHTML'][] = 'wfAddWikiFeedHeaders'; $wgHooks['MonoBookTemplateToolboxEnd'][] = 'wfWikiArticleFeedsToolboxLinks'; $wgHooks['UnknownAction'][] = 'wfWikiArticleFeedsAction'; $wgHooks['ArticlePurge'][] = 'wfPurgeFeedsOnArticlePurge';

/**

* Adds the Wiki feed link headers.
* Usage: $wgHooks['OutputPageBeforeHTML'][] = 'wfAddWikiFeedHeaders';
* @param $out Handle to an OutputPage object (presumably $wgOut).
* @param $text Article/Output text.
*/

function wfAddWikiFeedHeaders($out, $text) {

   # Short-circuit if this article contains no feeds
   if (!preg_match('//m', $text)) return true;
   
   $rssArr = array(
       'rel' => 'alternate',
       'type' => 'application/rss+xml',
       'title' => 'RSS 2.0',
   );
   $atomArr = array(
       'rel' => 'alternate',
       'type' => 'application/atom+xml',
       'title' => 'Atom 0.3',
   );    

   # Test for feedBurner presence
   if (preg_match('//m', $text, $matches)) {
       $name = @unserialize(@base64_decode($matches[1]));
       if ($name) {
           $rssArr['href'] = 'http://feeds.feedburner.com/'.urlencode($name).'?format=xml';
           $atomArr['href'] = 'http://feeds.feedburner.com/'.urlencode($name).'?format=xml';
       }
   }
   
   # If its not being fed by feedBurner, do it ourselves!
   if (!array_key_exists('href', $rssArr) || !$rssArr['href']) {

       global $wgServer, $wgScript, $wgTitle;
   
       $baseUrl = $wgServer.$wgScript.'?title='.$wgTitle->getDBkey().'&action=feed&feed=';
       $rssArr['href'] = $baseUrl.'rss';
       $atomArr['href'] = $baseUrl.'atom';    
   }

   $out->addLink($rssArr);
   $out->addLink($atomArr);

   global $wgWikiFeedPresent;
   $wgWikiFeedPresent = true;
   
   # True to indicate that other action handlers should continue to process this page
   return true;

}

/**

* Adds the Wiki feed links to the bottom of the toolbox in Monobook or like-minded skins.
* Usage: $wgHooks['MonoBookTemplateToolboxEnd'][] = 'wfWikiArticleFeedsToolboxLinks';
* @param QuickTemplate $template Instance of MonoBookTemplate or other QuickTemplate
*/

function wfWikiArticleFeedsToolboxLinks($template) {

   global $wgOut, $wgServer, $wgScript, $wgArticle, $wgWikiFeedPresent;
   
   # Short-circuit if wgArticle has not been set or there are no Feeds present
   if (!$wgArticle || !$wgWikiFeedPresent) return true;
   
$result = '