Extension:GraphViz/ru

GraphViz это расширение MediaWiki которое позволяет генерировать графические диаграммы связей по их текстовому описанию и встраивать их в страницы вики, using the open-source Graphviz and Mscgen applications:
 * Graphviz is a program that allows the creation of numerous types of graphs, using the DOT language.
 * Mscgen is a small program that parses Message Sequence Chart descriptions. Unlike Graphviz, this program does no clever layout operations or spline routing, as this is not needed.

Automatic graph drawing has many important applications in software engineering, database and web design, networking, and in visual interfaces for many other domains.

Additionally, this extension supports multiple graphs on one page, wiki-links in graphs, and automatic pruning of old images.

Contributions and history

 * In 2004 the user Coffman created an extension to MediaWiki in response to a basic need: rendering graphs online. He found the utility Graphviz in use on another wiki application, and thought about adapting it for MediaWiki (the wiki he actually used). Exploring the Graphviz tool, he discovered an incredible tool for making graphs.
 * Later on, many people improved the extension on their own or provided little bug fixes as snippets on the discussion page. This led to several functional solutions for different use cases, and to a bit of chaos.
 * In 2006 Gregory Szorc independently created his own GraphViz extension, this one called "Graphviz" (small "v"), that included some helpful features like autopruning.
 * Also in 2006, Ruud Schramp created the MscGen extension, adapting the code from the GraphViz extension to work with MscGen.
 * In 2008 Matthew Pearson created the extension GraphVizAndMSCGen, combining the code from the GraphViz with the MscGen extension.
 * In 2010 Thomas Hummel merged these and other versions, along with his own fixes, to try to create a working solution for several OSes in one file.
 * In 2011 Jeroen De Dauw uploaded the resulting code onto MediaWiki SVN.

Установка Graphviz

 * 1) Вначале необходимо установить дополнительное ПО "Graphviz" или "MscGen" которые будут рисовать вашу графику.
 * 2) Windows: Скачайте дистрибутив осюда: http://www.graphviz.org/Download.php или отсюда http://www.mcternan.me.uk/mscgen/
 * 3) Unix: Same links as for windows but normally it should be preinstalled (at least graphviz - search for dot) or can be found in the package manager.
 * 4) Ubuntu/Debian: Устанваливается из репозитария по командам: sudo aptitude install graphviz-dev
 * 5) Then obtain the Graphviz extension code by downloading a snapshot or getting it from SVN, and then put it in your MediaWiki "/extensions/GraphViz" directory.
 * 6) Т.к. Ubuntu 10.10 и ниже содержат в репозитариях очень старую версию GraphViz, рекомендуется использовать deb-пакет.
 * 7) Добавте эту строку в файл LocalSettings.php:
 * для Windows: "C:/Program Files/Graphviz/bin/" (without dot.exe) или "C:\\Program Files\\Graphviz\\bin\\"
 * для Linux  : "/usr/bin/" or "/usr/local/bin/" (путь к каталогу в котором находится иполняемый файл dot)


 * Make sure that write permissions for the "$IP/images" directory are granted.
 * Make sure that internet users get read/execute access on your executables if you use server installations. (Especially under Windows.)

Установка MscGen
The same procedure as with Graphviz - the path to MscGen has to be provided in LocalSettings.php:

Отличия от предидущей версии

 * The variable $dotCommand that points only to the dot executable is replaced (like in Extension:GraphVizAndMSCGen) with $execPath and $mscgenPath that let you choose between several renderers.

Конфигурирование
Здесь указаны допонительные параметры настройки которые изменяют поведение расширения. По умолчанию они уже содержат значения, которые (скорей всего) позволяют работать GraphViz. Для изменения параметров добавьте строку  в файл LocalSettings.php после строки.

You don't need to set these values if everything works fine for you. They are used in the LocalSettings.php only for the default behaviour of all graphs in this wiki. Some parameters can be set for each individual graph (see or ).

Naming of the Images
There are several ways to name the graphs. Each of them has some benefits and some problems. You set the Naming-Scheme by setting $wgGraphVizSettings->named in the LocalSettings.php (See ).

Drawing Graphs
Basically you only need to write your Graph in the dot language (or any other supported language) and put it into  or. See the for some basic graphs - you don't even need the "border" or "frame"-tags.

Mscgen
Keep in mind that mscgen uses a language _similar_ to dot but it isn't really dot. So you have to write your own code for graphviz and mscgen to display the same graph. (Furthermore the goals of graphviz and mscgen are not the same)

Another limitation when using Mscgen is that you can't use multiple graphs on one page (if you don't use hashed storage-names).

Multiple Graphs
This extension supports multiple graphs on one wiki page.

If you name the pictures by the graph names (named='named'), you just have to give the graphs different names. That means that the following two graphs can be put together on on page.

This doesn't work for Mscgen graphs, because custom names aren't supported. But you can put one Mscgen graph and multiple Graphviz graphs on one page.

If your pictures are named with md5- or sha1-hashes then you can have multiple graphs of each type (Graphviz and/or Mscgen) on your page. Keep in mind that you should clean up your image-directory from time to time, because the hash changes when the code has been modified. (See )

Wiki-links
In dot you can define an URL for each node. This is normally done before defining the graph. See for an example with Wiki-links.

In case you need an external URL, write:

And for an internal link in your wiki, write:

That's all.

Wiki styling
In case you want to put some kind of structure into your page you can use some image attributes as for any other image (in the style of regular MediaWiki syntax), like here: Extended_image_syntax).

The attributes are used like HTML attributes (e.g. ).

Please bear in mind that these features are not fully identical to MediaWiki's image attributes. Differences/inconsistences are:
 * In case of thumbed images the image-map isn't scaled down, so it won't fit anymore
 * In case of thumbed images, they do not link to an image-page with a further description of the license and the picture in a higher resolution - we only add a (+)-sign to the caption with the direct link to the image.
 * a framed and centered image will have a border with a width of 100%

Alternative: You could link to your images directly if you want to. So you could put the graph into  and put the image of the graph anywhere into your page (or in any other page) via the "img" tag.
 * If you use the named='named'-setting the graph names won't change and can be used easily.
 * You have to allow linking to external images (since the images are not in the db) (and you can restrict it to your domain for security)
 * you cannot use imagemaps that easily

Renderer
This extension can handle two applications for graph-drawing: Graphviz and Mscgen. Graphviz comes with several rendering engines and Mscgen has its own. For Graphviz, different renderers are ideal depending on the use case. More information on the renderers for each application can be found on their respective websites.

You can define a renderer as the default (see ), or set it in an individual graph with an attribute (-> ).

Image types
Graphviz and Mscgen can produce a huge amount of different image types (see more on their websites). The GraphViz extension supports only some of them: Note: To display vector-graphics you have to configure your wiki installation properly (-> SVG)
 * Graphviz: bmp, gif, jpg, jpeg, png, svg, svgz
 * Mscgen: png, svg

You can define an image type as default (-> ) or add it to the individual graph with an attribute (-> ).

Примеры
Для начала Вы можете попробовать эти примеры:

Пример 1

Пример 2

Пример 3

Вы можете посмотреть ещё больше примерв изображений созданных с Graphviz на Галерея на Flickr.

Учебники/примеры использования
Примеры использования GraphViz на вики-сайтах:
 * http://www.wikischool.de/wiki/WikiSchool:Graphviz
 * http://wiki.zum.de/Hilfe:Graphviz
 * http://www.wickle.com/wikis/index.php/Graphviz_extension (устаревший)
 * http://www.EcoReality.org/wiki/Test:Graphviz (comments) (maintained very well)
 * http://www.nerux.org/wiki/Graphviz and http://www.nerux.org/wiki/Accueil

Pruning
Each time we create a new graph we're going to check the Image-Path for pruning. There are several options on how to prune. Configure pruning with the adequate parameters in LocalSettings.php (see ).

With the default settings you don't need any pruning, because each graph is saved accoring to its name. If you update the Graph the image-file will be replaced so there will be no unnecessary file. Reasons for pruning can be: limited storage space for images, renamed or removed graphs, graphs named with a hash.

However the best solution for pruning would be to clean up the images manually from time to time, or do it automatically with a cronjob. This saves much CPU load.

Разработка GrapViz
Since I'm not a very experienced developer it would be nice if some "experts" could review the code or improve it on some edges.

I'm also happy if you'd notify me about bugs or problems you have (e.g. on the Discussion page).

Важные моменты

 * Check for Security Leaks
 * especially there has been mentioned: This [former] 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)
 * See Security for developers for specific types of vulnerabilities
 * Sometimes there is an error of preg_replace: "Unknown modifier '\' on line 434" - I can't find the mistake.
 * NOTE: You need to change the string  by   to correct this error

Это должно быть сделанно

 * What to do with graphs that are too large? e.g. for the GET-request? Maybe some attribute in the -Tag that this is partial code and that it waits? Or at least shortening some commands, links, ...?
 * использование popen/proc_open instead of shell_exec для php save-mode если возможно

Хорошо бы иметь возможность ...

 * менять uploadDir
 * On my local installation a graph is rerendered very often (each hour or so) even if nothing has changed on the page. (Is this only my fault?)
 * Can we reduce CPU load by preventing Graphviz from creating a new image if the page hasn't changed?
 * Can I then prune all images that are older than an hour? Or do proper installations use a cache that maybe lasts a week or so?
 * Error when setting $wgGraphVizSettings->install=true on ubuntu.
 * Generate Graphs without extra tools (directly in the browser): Canvas?, Base 64 Encoding see also, Extension:Graph, ...
 * custom shapes for nodes in Graphviz aren't supported yet (http://www.graphviz.org/Documentation/html/shapehowto.html)
 * improve pruning
 * save pruning settings (maybe settings-file in graphviz-folder or images folder, because of write access?)
 * don't prune for each graph but only check date of last pruning
 * remove files older than some date
 * use the image formatting with wiki syntax with the help of MW-Renderer, so that it doesn't stay hardcoded
 * put the generated graphs into the wiki-database, so that they can be handled like normal pictures

Алтернативы GraphViz
Если Вас не устраивает ПкфзрМшя можно попробовать другие расширения для рисования графики (although I tried to put the main functionality of all of them into this extension - so thank them for their ideas also).
 * The Расширение от Gregory Szorc is absolutely well coded and supports auto-pruning.
 * GraphViz-Version by Bytesmiths
 * Extension:Graph позволяет рисовать ASCII-Art, SVG, и Graphviz-Images without(?). Использует Graphviz-Tool
 * Extension:FreeMind используется для отображения в страницы вики карт памяти нарисованных во FreeMind (*.mm-файлы)
 * Extension:Semantic_Graph также использует FreeMind-Tool для рисования (as an alternative to the
 * Extension:GraphVizAndMSCGen built upon the old graphviz-source

Проекты которые используют это расширение

 * The "Semantic Result Formats" extension is used in conjunction with the Semantic MediaWiki extension, that bundles a number of further result formats for SMW's inline queries.
 * Extension:Semantic Result Formats/graph_format (показывает связи между страницами (графически)
 * Extension:Semantic Result Formats/process_format (displays process graphs)
 * Extension:Collaboration_Diagram (Вычисляет и визуализирует 2-х сторонние графы для для любой статьи и тех кто её редактировал)