Extension talk:GraphViz/Archive 2006 to 2008

From mediawiki.org
Latest comment: 13 years ago by Andy753421 in topic Improvement

I've added a link to Extension:GraphVizAndMSCGen, which is has some improvements for Windows and allows the use of MSCGen graphs too. Please move around these links if required or integrate the code from my extension into this one, etc.. Matthewpearson 16:36, 10 December 2008 (UTC)Reply

Size limit and work-arounds

I'm using the GraphViz extension w/ great delight (hoping to get my company's employees to document some of their formal business processes using the GraphViz extension on the company's MediaWiki-based wiki thing). However, I have been hitting an apparent size limit on the size of the graph you can specify using the GraphViz extension (go figure... there's a size limit on GET request lengths, after all).

So, for a simple work-around, I'm advising my users to split up their graphs into several subgraphs (only slightly nasty-looking, and there's probably some slick way to make it look almost like one connected graph).

For a more complicated work-around, I'm considering making a revised version of the tag(s) (e.g. <dot_graph>) that would "optimize" the graph code for reduced length (only on conversion into raw HTML), doing things like stripping out comments and renaming labeled nodes (to give them a super-short name while still allowing verbose node names in the original Wiki markup).

Just a thought. Nothing's really happening yet, and I thought it would be nice to at least warn people about the length limit (above). Mlibby 17:04, 22 December 2006 (UTC)Reply

Maybe I'll include an approach like this, too: m:User talk:Cygon/Graphviz Extension#Shorting the URLs Mlibby 17:14, 22 December 2006 (UTC)Reply

Use with MW1.10

Has anyone been able to make any of the GraphViz extensions work with MediaWiki version 1.10? I have tried both this one and the one at http://www2.hds.utc.fr/~rherault/index.php/Graphviz_Extension, and neither works. Pages show up without content (completely white) as soon as I activate the extension in LocalSettings. Any advice would be gratefully accepted. 160.33.43.231 July 2nd, 2007, 12:00pm PDT

GRAFCET

Can we create GRAFCET diagrams with this extension? (original question reformulated from French!)

  • The only reference I could find in english about this is here
  • A german Grafcet information page is here.

There seems no way to render these kind of diagrams with GraphViz yet.

Improvement

Well, I decided that it might be a good thing to incorporate those issues seen above in a version that works out of the box AND does not require anything but "standard php" compared to those two alternate versions: Alternate Version and Updated alternate Version -- the Links are dead!

This is an update ... for those who do not want to take/require the more complex version or do not have access to its required SPL module.

Known Issues

Well this plugin has a few issues with special characters in combination with "named naming". Just don't use them. This is true because Filesystem restrict other characters as URL's. Anyway that filename will only be used for referencing and is not displayed, so you don't have to worry if it is a workaround.

Security issues

This plugin does not properly sanitize user input when generating the "named" version of the files. This can lead to clobbered files and/or more serious vulnerabilities. --Andy753421 04:54, 27 July 2010 (UTC)Reply
<?php
/*
 * Extension to allow Graphviz to work inside MediaWiki.
 * This Version is based on CoffMan's nice Graphviz Extension.
 *
 * Licence: http://www.gnu.org/copyleft/fdl.html
 *
 * Configuration
 *
 *  These settings can be overwritten in LocalSettings.php.
 *  Configuration must be done AFTER including this extension using
 *  require("extensions/Graphviz.php");
 *
 *  $wgGraphVizSettings->dotCommand
 *    Describes where your actual dot executable remains.
 *
 *    Windows Default: C:/Programme/ATT/Graphviz/bin/dot.exe
 *    Other Platform : /usr/local/bin/dot
 *
 *  $wgGraphVizSettings->named
 *    Describes the way graph-files are named.
 *
 *    named: name of your graph and its type determine its filename
 *    md5  : name of your graph is based on a md5 hash of its source.
 *    sha1 : name of your graph is based on a SHA1 hash of its source.
 *
 *    Default : named
 *
 *  $wgGraphVizSettings->install
 *    Gets you an errormessage if something fails, but maybe ruins your
 *    wiki's look. This message is in English, always.
 *
 *    Default : false
 *
 * Improvements
 * - Selects defaults for Windows or Unix-like automatically.
 * - should runs out of the box
 * - Creates PNG + MAP File
 * - additional storage modes (see discussion below)
 *   - Meaningful filename
 *   - Hash based filename
 *   - Configurable (name/md5/sha1)
 *
 * Storage Modes:
 * MD5:
 * + don't worry about graphnames
 * + pretty fast hash
 * - permanent cleanup necesary (manually or scripted)
 * - md5 is buggy - possibility that 2 graphs have the same hash but
 *   are not the same
 * SHA1:
 * + don't worry about graphnames
 * + no hash-bug as md5
 * - permanent cleanup necessary (manually or scripted)
 * - not so fast as md5
 * Named:
 * + Graphs have a name, now it's used
 * + no permanent cleanup necessary.
 * - Naming Conflicts
 *   a) if you have multiple graphs of the same name in the same
 *      article, you will only get 1 picture - independently if they're
 *		the same or not.
 *   b) possible naming conflicts in obscure cases (that should not happen)
 *      Read code for possibilities / exploits
 * 
 */

class GraphVizSettings {
	public $dotCommand, $named, $install;
};

$wgGraphVizSettings = new GraphVizSettings();

// Config
// ------
if ( ! (stristr (PHP_OS, 'WIN' ) === FALSE) ) {
	$wgGraphVizSettings->dotCommand = 'C:/Programme/ATT/Graphviz/bin/dot.exe';
} else {
	$wgGraphVizSettings->dotCommand = '/usr/local/bin/dot';
}
$wgGraphVizSettings->named = 'named';
$wgGraphVizSettings->install = false;

// Media Wiki Plugin Stuff
// -----------------------
$wgExtensionFunctions[] = "wfGraphVizExtension";

$wgExtensionCredits['parserhook'][] = array(
  'name'=>'Graphviz',
  'author'=>'CoffMan <http://wickle.com>, MasterOfDesaster <mailto://arno.venner@gmail.com>',
  'url'=> 'http://www.mediawiki.org/wiki/Extension:GraphViz',
  'description'=>'Graphviz (http://www.graphviz.org) is a program/language that allows the creation of numerous types of graphs.  This extension allows the embedding of graphviz markup in MediaWiki pages and generates inline images to display.',
  'version'=>'0.4'
);

function wfGraphVizExtension() {
	global $wgParser;
	$wgParser->setHook( "graphviz", "renderGraphviz" );
}

function renderGraphviz( $timelinesrc )	// Raw Script data
{
	global
		$wgUploadDirectory,	// Storage of the final png & map
		$wgUploadPath,			// HTML Reference
		$wgGraphVizSettings;	// Plugin Config

	// Prepare Directories
	$dest = $wgUploadDirectory."/graphviz/";
	if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }

	$storagename = urldecode($_GET['title']).'---';
	$storagename = str_replace("&",'_amp_',$storagename);
	$storagename = str_replace("#",'_shrp_',$storagename);
	$storagename = str_replace("/",'_sd_',$storagename);
	$storagename = str_replace("\\",'_sd_',$storagename);
	
	$wgGraphVizSettings->named = strtolower($wgGraphVizSettings->named);

	if($wgGraphVizSettings->named == 'md5') {
		$storagename .= md5($timelinesrc);
	} else if ($wgGraphVizSettings->named == 'sha1') {
		$storagename .= sha1($timelinesrc);
	} else {
		$storagename .= trim(
			str_replace("\n",'',
				str_replace("\\",'/',
					substr($timelinesrc, 0, strpos($timelinesrc,'{') )
				)
			)
		);
	}

	$src = $dest . $storagename;

	$imgn = $dest . $storagename . '.png';
	$mapn = $dest . $storagename . '.map';

	if ( $wgGraphVizSettings->named == 'named' || ! ( file_exists( $src.".png" ) || file_exists( $src.".err" ) ) )
	{
		$handle = fopen($src, "w");
		fwrite($handle, $timelinesrc);
		fclose($handle);

		$cmdline    = wfEscapeShellArg($wgGraphVizSettings->dotCommand).
			' -Tpng   -o '.wfEscapeShellArg($imgn).' '.wfEscapeShellArg($src);
		$cmdlinemap = wfEscapeShellArg($wgGraphVizSettings->dotCommand).
			' -Tcmapx -o '.wfEscapeShellArg($mapn).' '.wfEscapeShellArg($src);

		$ret = shell_exec($cmdline);
		if ($wgGraphVizSettings->install && $ret == "" ) {
			echo '<div id="toc"><code>Timeline error: Executable not found.'.
				"\n".'Command line was: '.$cmdline.'</code></div>';
			exit;
		}

		$ret = shell_exec($cmdlinemap);
		if ($wgGraphVizSettings->install && $ret == "" ) {
			echo '<div id="toc"><code>Timeline error: Executable not found.'.
				"\n".'Command line was: '.$cmdlinemap.'</code></div>';
			exit;
		}

		unlink($src);
	}
	
	@$err=file_get_contents( $src.".err" ); 

	if ( $err != "" ) {
		$txt = '<div id="toc"><code>'.$err.'</code></div>';
	} else {
		@$map = file_get_contents( $mapn );
		$map  = preg_replace('#<ma(.*)>#',' ',$map);
		$map  = str_replace('</map>','',$map);

		$txt  = '<map name="'.$storagename.'">'.$map.'</map>'.
		        '<img src="'.$wgUploadPath.'/graphviz/'.$storagename.'.png"'.
					' usemap="#'.$storagename.'" />';
	}
	return $txt;
}
?>

Fixed Special Char problem

Well here is a manual patch.

Make Named Files Umlaut-safe

Look for:

        function renderGraphviz( $timelinesrc )

Replace these lines:

        $storagename = urldecode($_GET['title']).'---';
        $storagename = str_replace("&",'_amp_',$storagename);
        $storagename = str_replace("#",'_shrp_',$storagename);
        $storagename = str_replace("/",'_sd_',$storagename);
        $storagename = str_replace("\\",'_sd_',$storagename);

With that line

        $storagename = str_replace("%",'_perc_',urlencode($_GET['title'])).'---';

Then replace this block:

        } else {
                $storagename .= trim(
                        str_replace("\n",'',
                                str_replace("\\",'/',
                                        substr($timelinesrc, 0, strpos($timelinesrc,'{') )
                                )
                        )
                );
        }

With that one

	} else { // 'named'
		$storagename .=  str_replace("%",'_perc_',
			urlencode(
				trim(
					str_replace("\n",'',
						str_replace("\\",'/',
							substr($timelinesrc, 0, strpos($timelinesrc,'{'))
						)
					)
				)
			)
		);
	}

A typo

There is also a type in the above listed file:

if ( $wgGraphVizSettings->named == 'named' | ! ( file_exists( $src.".png" ) || file_exists( $src.".err" ) ) )

Should be that:

if ( $wgGraphVizSettings->named == 'named' || ! ( file_exists( $src.".png" ) || file_exists( $src.".err" ) ) )
Fixed. (This appears to be not related to #Fixed Special Char problem) --Alvin-cs 12:19, 17 November 2007 (UTC)Reply

On Updating

The update will work without noticing. Old (and unchanged) pages will stay the same and reference old images, a graph that is updated will automatically create a file in the new naming shema. If you worry about diskspace ... you can easily detect old files and new files.

Old files contain
_amp_, _shrp_, _sd_ instead of &, \ and /
New files
Replacing "_perc_" -> with "%" makes them valid urls.
Independent files
Usually don't have any of those things.
Had problem with ':' (COLON) in file names under windows. This happens when the article is not

in the default namespace. What about adding the following line:

        $storagename = str_replace(":",'_colon_',$storagename);

around line 113? --195.206.74.130 13:08, 7 February 2008 (UTC)Reply

I had the same problem with colons on a debian, $storagename = str_replace(":",'_colon_',$storagename); works perfectly :) --Church of emacs talk ¡ contrib 15:51, 26 March 2010 (UTC)Reply

local wiki URLs

A rather crude hack to allow local wiki url tags (--Dannyh 23:18, 26 March 2008 (UTC)). Suppose you want your graph to contain local links like the following:Reply

 <graphviz>
 digraph G {
 Boss [URL = "[[User:Boss]]"]
 John [URL="[[User:John]]" ]
 
 Boss->John 
 }
 </graphviz>
 

Then add the following function to GraphViz.php

function rewriteWikiUrls( &$source)
{
    $line = preg_replace(
        '|\[\[([^]]+)\]\]|e',
        'Title::newFromText("$1")->getFullURL()',
        $source
    );
    return $line;
}

And then, right before this block:

 $handle = fopen($fname, "w");
 fwrite($handle, $timelinesrc);
 fclose($handle);

Add the following line:

$timelinesrc = rewriteWikiUrls( $timelinesrc);

Wikilinks from within graph

A neat feature would be to be able to use wikilinks inside the graphviz code. Is this by any means feasible? --Berland 13:23, 3 October 2008 (UTC)Reply

Broken with MW 1.12?

Is this broken again with MW 1.12? I'm getting no images. I tried both the main page version and the one added above on this page. --Cymen 15:31, 3 October 2008 (UTC)Reply

Update: The RedHat version of graphviz requires the graphviz-gd package for PNG (and more) suport. I modified the script to replace spaces (' ') with underscore ('_') too.

        $storagename = str_replace(' ','_',$storagename); #new
        $src = $dest . $storagename; # not modifed

And to print an error if it can't write to disk:

                $handle = fopen($src, 'w');
                if (! $handle) return 'Error writing graphviz file to disk.';
                fwrite($handle, $timelinesrc);

--Cymen 16:07, 3 October 2008 (UTC)Reply

Suse 11 + MW 1.13.2

I think this plug in will be great, once it works which is what I can't do.

I installed a Fresh Suse 11 distro and put MW 1.13.2 on it, configured correctly as far as I can tell, the graphviz plugin picks up the tags, and generates the images, which are correct, but they will not display in the wiki page.

The error I keep getting is:

Timeline error: Executable not found. Command line was: '/usr/local/bin/dot' -Tpng -o '/srv/www/htdocs/wiki/images/graphviz/Test---graph+G.png' '/srv/www/htdocs/wiki/images/graphviz/Test---graph+G'

I'm no expert in php since I think if I were I'd be able to figure this out, but if someone could lend a hand I'd be very grateful.

The original documentationf or the plugin states to use /usr/bin for the dot command, however since mine is generating the files from /usr/local/bin, I don't see why I would need to change it.

Thanks


You have to change the path in Graphviz.php and use this one /usr/bin because dot in suse is there.


xp190 38.113.160.194 20:57, 3 October 2008 (UTC)Reply