Open main menu

Extension:Managetemplates

MediaWiki extensions manual
OOjs UI icon advanced.svg
ManageTemplates
Release status: stable
Implementation Page action
Description User-friendly way to add Templates into an article.
Author(s) Robert von Heeren (Pianorobtalk)
Latest version 1.3
MediaWiki 1.5+
License No license specified
Download No link
none
1.17.0 (tested) should work since version 1.5 (untested)
Translate the Managetemplates extension if it is available at translatewiki.net
Check usage and version matrix.

Contents

What can this extension do?Edit

ManageTemplates version 1.3 is a derivation of the similar Extension:ManageCategories by Florian Mayrhuber. (That's an extension that allows user-friendly add of categories to an article). ManageTemplates does the same for templates instead of categories: it allows to add existing templates to new articles and also to create new empty templates, which can be modified later. Both extensions can be used together. All inputs or changes to these fields are then transformed to wiki markup and put into the textarea of the editpage.

Like ManageCategories, ManageTemplates is located beneath the main edit textarea and consists of:

  • a select box with all current templates of the wiki, but only the ones which are used at least once
  • a text field to create a new template-name
  • shows currently active templates represented with their names and check boxes

ManageTemplates has successfully been used and tested also in combination with ManageCategories under MW 1.17.0, php 5.3.3 and php 5.2.6 It only works along with the managetemplates.js which is included by the php-script itself. If you use rewrite-rules on your server and MW-installation make sure that MW can directly access the /extension/managetemplates/managetemplates.js - file.

InstallationEdit

  • Create the folder /managetemplates within the extension directory of your MW.
  • Create an empty managetemplates.php file and empty managetemplates.js - file
  • Copy the php-code below into the managetemplates.php and the js-code into the managetemplates.js -file
  • Copy both files into your managetemplates -folder on the server.
  • Include the managetemplates.php -script into your LocalSettings.php -file:
require_once("$IP/extensions/managetemplates/managetemplates.php");

Note: $IP stands for the root directory of your MediaWiki installation.

UsageEdit

  • To add an existing template to the article pick it from the selectbox and click add.
  • To add a new empty template enter the template name into the text field and click create.
  • To remove a template uncheck the corresponding checkbox.
  • Update: managetemplates.js now determines the cursor's position within the textarea of the editform, so it will put the template-code there. Just click into the editform at the position in which the template shall be placed. The JS works fine in IE9 and Firefox 5. Older browsers have not been tested yet.

CodeEdit

Code for managetemplates.php

<?php
/**
	 ManageTemplates version 1.2ß is a derivation of the similar ManageCategories-Extension by Florian Mayrhuber:   http://www.mediawiki.org/wiki/Extension:ManageCategories. 
	 It's an extension for mediawiki that allows user-friendly 
	 adding of categories to an article. ManageTemplates does the same for templates: 
	 it allows to add existing templates to new articles and also to create new empty templates, 
	 which can be modified later. Both extensions can be used together.
	  
	 Like ManageCategories, ManageTemplates is located beneath the main edit textarea and consists of:
	 - a select box with all current templates of the wiki
	 - a text field to create a new template
	 - shows currently active templates represented with their names and check boxes

	 ManageTemplates is still in beta but has successfully been used and tested also in combination with ManageCategories under MW 1.17.0 and php 5.3.3
	 It only works along with the managetemplates.js which is included by the php-script itself.
	 If you use serversided rewrite-rules make sure that MW can directly access the /extension/managetemplates/managetemplates.js - file.
*/

$wgExtensionCredits['other'][] = array(
	'name'		=> 'managetemplates',
	'author'	=> 'Robert von Heeren',
	'url'		=> 'http://www.mediawiki.org/w/index.php?title=Extension:Managetemplates',
	'description'	=> 'Allows to use templates within articles in a user-friendly way. It is a derivation of the extension ManageCategories by Florian Mayrhuber.'
);

if ( !defined('MEDIAWIKI') )
{
    die();
}
/**
	 * hook function
	 * asserts the main function to the hook
*/
$wgExtensionFunctions[] = 'wfEditTemplate';

function wfEditTemplate()
{
    // set up hooks
    global $wgHooks;
    $wgHooks['EditPage::showEditForm:initial'][] = 'fnShowTemplateBox';
}
/**
	* param: editpage
*/
function fnShowTemplateBox( $editPage )
{
	// output
	global $wgOut;
	// get articleid
    global $wgTitle;
    $id = $wgTitle->getArticleID();
	$wgOut->addScript("<script type=\"text/javascript\" src=\"extensions/managetemplates/managetemplates.js\"></script>\n");
 	// get article data
    $dbr = &wfGetDB( DB_SLAVE );
    $templateList = fnGetAllTemplates( $dbr );
    $articleTemplates = fnGetArticleTemplates( $dbr, $id );
    // determine if articles has already templates
   if ($reg=strpbrk($editPage->textbox1, '{{')) $templates = true;
    // open tags and description
    $editPage->editFormTextAfterWarn .= "<table width=\"750\" border=\"0\">";
    //$editPage->editFormTextAfterWarn .= "<caption>Templates</caption>";	
    $editPage->editFormTextAfterWarn .= "<tr><th height=\"30\" width=\"350\" align=\"left\" colspan=\"2\" scope=\"col\">Vorlagen hinzufuegen</th>";   
      // if article has templates show caption
    if ($templates) {
 	$editPage->editFormTextAfterWarn .= "<th height=\"30\" align=\"left\" scope=\"col\">
 	<blockquote>Vorlagen aktualisieren</blockquote></th></tr>";
	 }     
     // if article has no templates show nothing
    if (!$templates) {
 		$editPage->editFormTextAfterWarn .= "<th height=\"20\" align=\"left\" scope=\"col\"> </th></tr>";
	 }     
    $editPage->editFormTextAfterWarn .= "<tr>";
	// show all existing templates as drop down box
    $editPage->editFormTextAfterWarn .= "<td width=\"350\" height=\"20\">
	<select name=\"templates\" style=\"width:300px;border: 1px solid\">";
    while ( $row = $dbr->fetchObject($templateList) )
    {
	$editPage->editFormTextAfterWarn .= "<option style=\"color:#000000;\">$row->tl_title</option>";
    }
    $editPage->editFormTextAfterWarn .= "</select></td>";    
	$editPage->editFormTextAfterWarn .= "<td width=\"100\"><input type=\"button\" style=\"width:75px\" value=\"Hinzufuegen\" 
	onClick=\"insertTemplatesTags1()\"/></td>";
	// show current templates as check boxes 
	$editPage->editFormTextAfterWarn .= "<td width=\"350\" valign=\"top\" rowspan=\"3\" height=\"20\"><blockquote>";
        $templateList = fnGetAllTemplates( $dbr );
  	while ( $current = $dbr->fetchObject($templateList) )
    {
		if ( in_array($current->tl_title, $articleTemplates) ) {
			$editPage->editFormTextAfterWarn .= "<p><input type=\"checkbox\" checked=\"checked\" value=$current->tl_title 
		    name=\"currentTemplates[]\" onClick=\"insertTemplatesTags2(this)\"/> $current->tl_title </p>";
		}	
	}
	$editPage->editFormTextAfterWarn .= "</blockquote></td></tr>";
	// input field for new template
	$editPage->editFormTextAfterWarn .= "<tr><td width=\"100\">
	<input name=\"newTemplate\" type=\"text\" style=\"width:296px\" maxlength=\"30\" value=\"Neuen Vorlagen-Namen eingeben\"/></td>";	
	$editPage->editFormTextAfterWarn .= "<td width=\"100\"><input type=\"button\" style=\"width:75px\" value=\"Erstellen\" 
	onClick=\"insertTemplatesTags3()\"/></td></tr>";
	$editPage->editFormTextAfterWarn .= "<tr><td>&nbsp;</td><td>&nbsp;</td>";	
	//closing tags
    $editPage->editFormTextAfterWarn .= "</tr></table><br>";
    return true;
}
/**
	* retrieve all templates from the db using the mediawiki select wrapper
	* param: wiki db object
	* return: resultset with all templates 
*/ 
function fnGetAllTemplates( $dbr )
{
     $res = $dbr->select('templatelinks', // FROM
        array('tl_title', 'tl_from'), // SELECT
        array(), $fname, array('GROUP BY' => 'tl_title'));// GROUP BY
    return $res;
}
/**
	* determine to which templates the current article
	* is asigned and return array with results  
	* param: wiki db object, article id
	* return: resultset with templates 
*/
function fnGetArticleTemplates( $dbr, $id )
{
    $rs = array();
    $res = $dbr->select( 'templatelinks', // FROM
        array('tl_title', 'tl_from'), // SELECT
        array('tl_from' => $id) );// WHERE
    while ( $row = $dbr->fetchObject($res) )
    {
        $rs[] = $row->tl_title;
    }
    return $rs;
}

Code for managetemplates.js

/**
	determines the cursor's position within the editfield
*/

function insertAtCursorPos(Feld, Wert) {
  //IE support
  if (document.selection) {
    Feld.focus();
    sel = document.selection.createRange();
    sel.text = Wert;
  }
  //Firefox support
  else if (Feld.selectionStart || Feld.selectionStart == '0') {
    var startPos = Feld.selectionStart;
    var endPos = Feld.selectionEnd;
    Feld.value = Feld.value.substring(0, startPos)
                  + Wert
                  + Feld.value.substring(endPos, Feld.Wert.length);
  } else {
    Feld.value += Wert;
  }
}

/**
	evaluates select box
	create markup and put it into article if a value from selectbox is chosen
*/
function insertTemplatesTags1() {

	for (var i=0; i<document.editform.templates.length; i++) {
		if (document.editform.templates.options[i].selected)
			//document.editform.wpTextbox1.value += "{{"+document.editform.templates.options[i].text+"}}";
		   // calling the function
			insertAtCursorPos(document.editform.wpTextbox1, "{{"+document.editform.templates.options[i].text+"}}");
	}
	document.editform.wpTextbox1.focus();
}

/**
	evaluates check boxes 
	remove markup if a current article template is beeing deselected
	create markup and put it into article if a current article template is beeing selected
*/

function insertTemplatesTags2(obj) {
   if (obj.checked) // radio box checked 
		// document.editform.wpTextbox1.value += 
    	 // calling the function
		insertAtCursorPos(document.editform.wpTextbox1, "{{"+obj.value+"}}");

	else { 
		// radio box not checked
		// search and remove markups
		var pattern = "\{\{" + obj.value + "\}\}";
		var myregex = new RegExp("\{\{"+obj.value+"\}\}","g");
		var res = document.editform.wpTextbox1.value.match(myregex);

		for (var i=0;i<res.length;i++) {
			document.editform.wpTextbox1.value = document.editform.wpTextbox1.value.replace(pattern,"");
		}
	}			
	document.editform.wpTextbox1.focus();	
}
/**
	evaluates textfield
	create markup for a new template put it into article
*/
function insertTemplatesTags3() {
	if(document.editform.newTemplate.value != "Neuen Vorlagen-Namen eingeben")
	//	document.editform.wpTextbox1.value += "{{"+document.editform.newTemplate.value+"}}";
	 insertAtCursorPos(document.editform.wpTextbox1, "{{"+document.editform.newTemplate.value+"}}");
	document.editform.wpTextbox1.focus();
}

Known issuesEdit

  • Fixed: The template-tag is not inserted at the cursor's position within the editform, but normally at the bottom/end of MW-markup
  • This extension does not work with FCKEditor, tested with new FCKEditor. Reason: FCKEditor loads the textarea into a new DOM-level, which is invisible for this extension.
  • Like Extension:ManageCategories it also may not work with the new usability initiative (Vector) editor: Extension:UsabilityInitiative Update: Managetemplates is compatible with the new WikiEditor-extension, which is the successor of the UsabilityInitiative and is used as standard toolbar in MW 1.17.0. and with the new vector-skin.
  • No translation for other languages than German and English are available at the moment. Although you can easily translate the inline texts within the code.

NoteEdit

  • In case you use hundreds of templates in your MW this extension may slow down the load of the editpage dialog a bit because it has to query all template-names first. Currently there is no limit to the query!
  • The extension's dropdown box shows only templates which are already in use. If you create templates, which are not used anywhere they will not be displayed in the selectbox. The first time you use a template in an article the selectbox will offer it.

ToDosEdit

  • Fixed: Fix the cursor problem mentioned above
  • Add config-params e.g. to enable setting a limit for the queries
  • More translations of the dialog's texts, create variables for them and put them into a new managetemplates.i18n.php

Bugreports and suggestionsEdit

  • Bug reports and suggestions for code optimization are welcome and should please be posted onto the Extension_talk:Managetemplates - page here. I will consider and test code enhancements and changes, and will post an update here if it's stable.
  • Fixed: Unchecking or re-checking an checkbox does not update the editfield