Extension:VarsInDB

MediaWiki extensions manual
OOjs UI icon advanced.svg
Persistent Variables in Data Base
Release status: unmaintained
Implementation Parser extension , Parser function
Description Enables the creation of persistent variables which are stored in the Database
Author(s) (carallatalk)
Latest version 0.5 (2009-05-07)
MediaWiki 1.14 (probably previous versions too)
License GPL
Download below
Check usage and version matrix.

IntroductionEdit

This extension enables the creation of variables, whose values are stored in the database.

UsageEdit

Use the functions to get (dbvarget) and set (dbvarset) to get or set the values.

{{#dbvarset:variable|the value for the variable}}

{{#dbvarget:variable|default value in case that it is not stored in the database}}

Download instructions and InstallationEdit

Please cut and paste the code found below and place it in $IP/extensions/VarsInDB/VarsInDB.php.

Note: $IP stands for the root directory of your MediaWiki installation, the same directory that holds LocalSettings.php.

CodeEdit

File VarsInDB.php

<?php
/**
Extension which allows the creation of persistent variables which are stored in the wiki database.

Usage:

{{#dbvarset:<varname>|<value>}} sets the value <value> to the variable <varname>
{{#dbvarget:<varname>|<default value>}} retrieves the value of <varname> or returns <default value> in case that it has no previous value
{{#DB_VARS_SETUP:<force>}} wrapper for configuring the database (creates a table in the database)
	** WARNING: it deletes any previous value for any variable.

** TO-DO: 
	- securizing writting the variables in the database
	- internationalizing	
*/

$wgExtensionCredits['varsindb'][] = array(
'name'         => 'Persistent Variables in Data Base Mediawiki Extension',
'version'      => '0.5.0', // May, 5, 2009
'description'  => 'Enables the creation of persistent variables, which are saved in the database.',
'author'       => '[mailto:caralla76@gmail.com Carlos A.]',
'url'          => 'http://www.mediawiki.org/wiki/Extension:VarsInDB',
);
  
$wgExtensionFunctions[] = 'VarsInDB_Setup';
$wgHooks['LanguageGetMagic'][] = 'VarsInDB_Magic';
 
function VarsInDB_Setup() {
    global $wgParser;
	global $wgVarsInDBTable;
	
    $wgParser->setFunctionHook( 'dbvarget', 'dbvarget_exec' );
    $wgParser->setFunctionHook( 'dbvarset', 'dbvarset_exec' );
    $wgParser->setFunctionHook( 'DB_VARS_SETUP', 'dbvarsetup_exec' );
	
	/** default value for table in database */
	if (!isset($wgVarsInDBTable))
		$wgVarsInDBTable = 'dbvars';
}
 
function VarsInDB_Magic( &$magicWords, $langCode ) {
    $magicWords['dbvarget'] = array( 0, 'dbvarget' );
    $magicWords['dbvarset'] = array( 0, 'dbvarset' );
    $magicWords['DB_VARS_SETUP'] = array( 0, 'DB_VARS_SETUP' );
    return true;
}

function dbvarsetup_exec(&$parser, $force="") {
	/** you should delete this function when using in production in order to avoid the deletion of the variables */
	global $wgVarsInDBTable;

	$force = ($force == "YES");
	
        $dbr = wfGetDB( DB_MASTER );
        $dbVarsTable = $dbr->tableName( $wgVarsInDBTable );
	$sql = "DROP TABLE IF EXISTS {$dbVarsTable}; CREATE TABLE {$dbVarsTable} (`varname` VARCHAR(255) NOT NULL ,`value` VARCHAR(255) NULL ,PRIMARY KEY (`varname`))";
	try {
		$res = $dbr->query($sql, 'dbvarget_exec');
	} catch (Exception $e) {
		trigger_error("ha ocurrido un error al crear la tabla",E_USER_ERROR);
	}
	return "";
}

function dbvarget_exec(&$parser, $varname=null, $default=null) {

	global $wgVarsInDBTable;

	/** {{#dbvarget:varname|defaultvalue}} */
	if ($varname == null) {
		return "usage: {{#dbvarget:<varname>|<default-value>}}";
	}

        $dbr = wfGetDB( DB_SLAVE );
	if (!$dbr->tableExists($wgVarsInDBTable)) {
		/** Si la tabla no existe, no continuamos */
		trigger_error("la variable \$wgVarsInDBTable no apunta a una tabla valida", E_USER_WARNING);
		return "".$default;
	}

	/** continuamos */
	$dbVarsTable = $dbr->tableName( $wgVarsInDBTable );
	$sql = "SELECT {$dbVarsTable}.value FROM {$dbVarsTable} where varname = '{$varname}'";
	try {
		$varValue = $dbr->query($sql, 'dbvarget_exec');
		if ($varValue != null and $varValue->numRows()==0) {
			/** no tenemos valor */
			return "".$default;
		}
		$resultado = $varValue->fetchObject();
	}
	catch (Exception $e) {
		/** si no existe, u ocurre un error inesperado, devolvemos el valor por defecto */
		return "".$default;
	}

	return "".$resultado->value;
}

function dbvarset_exec(&$parser, $varname=null, $value=null) {

	global $wgVarsInDBTable;

	$params = func_get_args();
	array_shift( $params );
	if (count($params)!=2) {
		trigger_error("usage of varsindb extension: {{#dbvarget:<varname>|<default-value>}}", E_USER_WARNING);
		return "usage: {{#dbvarget:<varname>|<default-value>}}";
	}

	$dbr = wfGetDB( DB_MASTER );

	if (!$dbr->tableExists($wgVarsInDBTable)) {
		/** Si la tabla no existe, no continuamos */
		trigger_error("la variable \$wgVarsInDBTable ($wgVarsInDBTable) no apunta a una tabla valida", E_USER_WARNING);
		return "ERROR1";
	}

	$dbVarsTable = $dbr->tableName($wgVarsInDBTable);
	try {
		$sql = "SELECT {$dbVarsTable}.value FROM {$dbVarsTable} where `varname` = '{$varname}'";
		$varValue = $dbr->query($sql, 'dbvarset_exec');
		if ($varValue != null and $varValue->numRows()!=0) {
			$sql = "UPDATE {$dbVarsTable} SET `value`='{$value}' WHERE `varname` = '{$varname}'";
			$varValue = $dbr->query($sql, 'dbvarset_exec');
			/** actualizada */
			return "";
		}
	} catch (Exception $e) {
		/** podria no existir el campo... otra cosa, no creo */
		/** TO-DO: test */
		trigger_error("error al acceder a la base de datos", E_USER_WARNING);
		return "error al actualizar el valor de {$varname}";
	}

	$sql = "INSERT INTO {$dbVarsTable} (`varname`,`value`) VALUES('{$varname}','{$value}')";
	try {
		$varValue = $dbr->query($sql, 'dbvarset_exec');
	} catch (Exception $e) {
		trigger_error("error al introducir una variable en la BD", E_USER_WARNING);
		return "error al introducir el valor de {$varname} en la BD";
	}
	return "";
}
?>