Extension:GraphViz/ru

MediaWiki extensions manual
GraphViz
Release status: unmaintained
Implementation Tag
Description Автоматически генерирует графическое изображение по текстовому описанию на языке разметки DOT
Author(s)
Latest version 3.1.0 (2018-03-13)
MediaWiki 1.29.x-1.32.x
PHP 5.4+
Composer mediawiki/graph-viz
License GNU General Public License 2.0 or later
Download
README
RELEASE-NOTES
Example
  • $wgGraphVizDefaultImageType
  • $wgGraphVizExecPath
  • $wgGraphVizMscgenPath
Quarterly downloads 30 (Ranked 146th)
Translate the GraphViz extension if it is available at translatewiki.net
Issues Open tasks · Report a bug

GraphViz это расширение MediaWiki которое позволяет генерировать графические диаграммы связей по их текстовому описанию и встраивать их в страницы вики, использует дополнительное ПО с открытыми исходным кодом GraphViz и MscGen:

  • Graphviz это программа, которая позволяет создавать различные типы графиков, используя язык разметки DOT.
  • Mscgen это небольшая программа, которая анализирует описание Message Sequence Chart. В отличие от Graphviz, эта программа не делает автоматической маршрутизации, так как это не нужно.

Автоматическое рисование графов имеет много важных приложений в разработке программного обеспечения, баз данных и веб-дизайн, создание сетей и визуальных интерфейсов для многих других областей.

Кроме того, это расширение поддерживает несколько графиков на одной странице, вики-ссылки в виде графиков, а также автоматическое удаление старых изображениях.

История измененийEdit

  • 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.

УстановкаEdit

Установка GraphvizEdit

  1. Вначале необходимо установить дополнительное ПО "Graphviz" или "MscGen" которые будут рисовать вашу графику.
    1. Windows: Скачайте дистрибутив осюда: http://www.graphviz.org/Download.php или отсюда http://www.mcternan.me.uk/mscgen/
    2. 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.
    3. Ubuntu/Debian: Устанавливается из репозитария по командам:
sudo aptitude install graphviz graphviz-dev
  1. Получите код расширения GraphViz загрузка из snapshot или [http://svn.wikimedia.org/viewvc/mediawiki/trunk/extensions/GraphViz/ загрузка из SVN/

или из GIT

cd extensions
git clone https://gerrit.wikimedia.org/r/mediawiki/extensions/GraphViz.git 
  1. загрузите код расширения в каталог MediaWiki "/extensions/GraphViz"
    1. Т.к. Ubuntu 10.10 и ниже содержат в репозитариях очень старую версию GraphViz, рекомендуется использовать deb-пакет.
  2. Добавьте эту строку в файл LocalSettings.php:
require_once("$IP/extensions/GraphViz/GraphViz.php"); //Подключение расширения GraphViz
$wgGraphVizSettings->execPath = "/usr/bin/"; //Путь к исполняемым файлам Graphviz
для Windows: "C:/Program Files/Graphviz/bin/" (without dot.exe) или "C:\\Program Files\\Graphviz\\bin\\"
для Linux  : "/usr/bin/" или "/usr/local/bin/" (путь к каталогу в котором находится исполняемый файл dot)
  • Разрешите запись в каталог "$IP/images" и его подкаталоги.
  • Убедитесь, что пользователи Интернета имеют права на чтение/выполнение для исполняемых файлов, если вы установили MediaWiki на сервер. (Особенно под Windows).

Установка MscGenEdit

Так же как и в GraphViz - путь к MscGen должна быть указан ​​в LocalSettings.php:

$wgGraphVizSettings->mscgenPath = "/usr/bin/";

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

  • Переменная $dotCommand которая указывает только на DOT-экзишник (исполняемый файл DOT) заменяется (как и в расширение: GraphVizAndMSCGen) ​​на $execPath и $mscgenPath, которые позволяют выбрать один из нескольких способов визуализаций.

КонфигурированиеEdit

Здесь указаны допонительные параметры настройки которые изменяют поведение расширения. По умолчанию они уже содержат значения, которые (скорей всего) позволяют работать GraphViz. Для изменения параметров добавьте строку $wgGraphVizSettings->ИмяПараметра=Значение Параметра; в файл LocalSettings.php после строки include("extensions/Graphviz.php");.

Параметр Значение по умолчанию Возможные значения Описание
execPath "C:/Program Files/ATT/Graphviz/bin/" (Windows) Путь к папке с GraphViz (файлам dot.exe, circo.exe, fpdp.exe, neato.exe, twopi.exe)
execPath "/usr/bin/dot" (Unix/linux) Путь к папке с установленным GraphViz (обычно указывает на /usr/bin/ или /usr/local/bin/) или Вы используете $DOT_PATH
mscgenPath -none- Путь к папке с установленным MscGen
outputType png Смотри #Renderer Формат генерируемых файлов (png, gif, jpg, jpeg, bmp, svg, svgz)
imageFormatting true true, false Если выхотите определить положение, размер, границу сгенерированного изображения (не полностью поддерживается здесь)
named named named, md5, sha1 Как именовать файлы изображений (см. #Именование изображений графов)
info false true, false Добавляет информацию о передаваемых параметрах, например, renderers used, для использования на вики-странице. Используется для отладки.
install false true, false Возвращает вам сообщение об ошибке, если что-то не удается, но, возможно, зависание вашей вики. Сообщение на английском языке (работает нестабильно)
pruneEnabled false true, false Вы хотите, автоматически удалять старый файл, после генерации нового графа?
pruneStrategy количество файлов Количество файлов, размер файлов Вы хотите, удалять файлы, если слишком много файлов или если им нужно слишком много места на диске
pruneAmount 10000 положительное число Укажите максимальное чило файлов / размер файла для pruneStrategy
pruneValue 0.5 0< число <=1 Определяет, сколько файлов сейчас удалять (0,5 = 50%)

Вам не нужно устанавливать эти значения, если все работает хорошо. Они используются файле LocalSettings.php как поведение по умолчанию для всех графах в вашей вики. Некоторые параметры могут быть установлены отдельно для каждого графа (см. #Renderer или #Image-Types).

Именование изображений графовEdit

Используется несколько способов именования изображений графов. Каждый из них имеет достоинства и недостатки. Вы можете указать схему именования в $ wgGraphVizSettings->named в LocalSettings.php (см. # Конфигурация).

Схема Именования Описание Достоинства/Недостатки Пример
named Storagename это имя вики и название график + человеко читаемый
+ нет необходимости очистки
- для 2-х графов нужны разные имена
Graphviz_Sample---digraph+NAME.png
md5 имя графа на основе md5-хэша изображения + не беспокойтесь о имени графов
+ довольно быстро хэширует
- необходима постоянная очистка (вручную или скриптом)
md5 глючит - есть возможность, что 2 графа будут иметь одинаковые хеш
Graphviz_Sample---0a1e0c6bb9c6d3af6486d8f3de657f0f.png
sha1 имя графа на основе SHA1-хэша изображения + не беспокойтесь о имени графов
+ нет бага хэша как в md5
- необходима постоянная очистка (вручную или скриптом)
- не такой быстрый как md5
Graphviz_Sample---a3862ef7e7f889778f0259657b07ba985197ef88.png

Drawing GraphsEdit

Basically you only need to write your Graph in the dot language (or any other supported language) and put it into <graphviz>dot-commands</graphviz> or <mscgen>mscgen-commands</mscgen>.
See the #Examples for some basic graphs - you don't even need the "border" or "frame"-tags.

MscgenEdit

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 GraphsEdit

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.

First Graph Second Graph
<graphviz>
graph NAME {...
}
</graphviz>
<graphviz>
graph ANOTHERNAME {...
}
</graphviz>

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 #Naming of the images)

Wiki-linksEdit

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

In case you need an external URL, write:

Mollusca [URL="http://www.mollusca.animal"];

And for an internal link in your wiki, write:

Mollusca [URL="Mollusca"];

That's all.

Wiki stylingEdit

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: w:Extended_image_syntax).

The attributes are used like HTML attributes (e.g. <graphviz caption="Hello World">...dot...</graphviz>).

Attribute Description Value
caption Adds a caption to the graph (if bordered or thumbed) some string
alt Alternative text for graph (if not set caption is used and at least a default string) some string
border Adds a border around the graph frame, border
location Defines the position of the graph left, middle, center, right, none
alignment Vertical alignment to the text baseline, middle, sub, super, text-top, text-bottom, top, bottom
type Several changes in design frame, framed, thumb, thumbmail, frameless

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 <div style="visibility:none;"><graphviz>...</graphviz></div> 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

RendererEdit

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.

Renderer Description
dot typical hierachical layout with a "start" and an "end"
neato "spring model" layout
fdp like neato but better for larger graphs
sfdp fdp multiscale version
circo circular layout like for telecommunication networks
twopi radial layout with "start" in the middle
mscgen message sequence charts

You can define a renderer as the default (see #Configuration), or set it in an individual graph with an attribute (-> <graphviz renderer='neato'>...dot...</graphviz>).

Типы изображенийEdit

Graphviz и Mscgen может производить большое количество различных типов изображений (подробнее см. на веб-сайте). Расширение GraphViz поддерживает только некоторые из них:

  • Graphviz: PNG, SVG, BMP, GIF, JPG, JPEG, SVGZ
  • MscGen: PNG, SVG

Примечание: Для отображения векторной графики вы должны настроить вики правильно (-> SVG)

Вы можете определить тип изображения по умолчанию (-> #Конфигурация ) или выбрать его при генерации отдельного графа указав атрибут (-> <graphviz outputType='jpg'>...dot...</graphviz>).

ПримерыEdit

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

Пример 1

 
"Hello World" graph for example no. 1
 <graphviz border='frame' format='png'>
  digraph example1 {Hello->World!}
 </graphviz>

Пример 2

 
Example No. 2 rendered with neato
 <graphviz renderer='neato' caption='Hello Neato'>
 graph EXAMPLE2 {
    run -- intr;
    intr -- runbl;
    runbl -- run;
    run -- kernel;
    kernel -- zombie;
    kernel -- sleep;
    kernel -- runmem;
    sleep -- swap;
    swap -- runswap;
    runswap -- new;
    runswap -- runmem;
    new -- runmem;
    sleep -- runmem;
 }
 </graphviz>

Пример 3

 
A more complex graph as defined by Example No. 3 (original imagemap contains (Wiki-)Links)
 <graphviz caption='Hello SVG and PNG' alt='phylogenetic tree' format='png'>
 digraph G {
 		node [shape=plaintext];
 		Mollusca [URL="Mollusca"];
 		Neomeniomorpha [URL="Neomeniomorpha"];
 		X1 [shape=point,label=""];
 		Caudofoveata [URL="Caudofoveata"];
 		Testaria [URL="Testaria"];
 		Polyplacophora [URL="Polyplacophora"];
 		Conchifera [URL="Conchifera"];
 		Tryblidiida [URL="Tryblidiida"];
 		Ganglioneura [URL="Ganglioneura"];
 		Bivalvia [URL="Bivalvia"];
 		X2 [shape=point,label=""];
 		X3 [shape=point,label=""];
 		Scaphopoda [URL="Scaphopoda"];
 		Cephalopoda [URL="Cephalopoda"];
 		Gastropoda [URL="Gastropoda"];
 		Mollusca->X1->Testaria->Conchifera->Ganglioneura->X2->Gastropoda
 		Mollusca->Neomeniomorpha
 		X1->Caudofoveata
 		Testaria->Polyplacophora
 		Conchifera->Tryblidiida
 		Ganglioneura ->Bivalvia
 		X2->X3->Cephalopoda
 		X3->Scaphopoda
 }
 </graphviz>


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

Учебники/примеры использованияEdit

Примеры использования GraphViz на вики-сайтах:

Удаление (периодическое удаление старых сгенерированных изображений графов)Edit

Каждый раз, когда мы создаем новый график расширение проверяет папку с изображениями для удаления предидущего варианта картинки. Есть несколько способов это сделать. Настройка осуществляется в файле LocalSettings.php (см. #Конфигурация).

При настройках по умолчанию вам не нужны никакие сокращения, потому что каждый граф сохраняется в соответствии с его именем. Если вы обновляете график файл-образ будет заменен так что не будет никаких лишних файлов. Причины для удаления могут быть: ограниченное пространство для хранения изображений, переименовывание или удаление графов, графы с именем содержащим MD5- или MSH1-хэш.

Однако лучшим решением будет убирать изображения графов время от времени вручную или делать это автоматически скриптом с помощью cron. Это значительно экономит загрузку процессора.

Разработка GrapVizEdit

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).

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

  • 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 '/(\w+)\s([_:%#/\w]+)\s(\d+,\d+)\s(\d+,\d+)/' by '/(\w+)\s([_:%#\/\w]+)\s(\d+,\d+)\s(\d+,\d+)/' to correct this error

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

  • What to do with graphs that are too large? e.g. for the GET-request? Maybe some attribute in the <graphviz>-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 если возможно

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

  • менять 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

Альтернативы GraphVizEdit

Если Вас не устраивает GraphViz можно попробовать другие расширения для рисования графики (although I tried to put the main functionality of all of them into this extension - so thank them for their ideas also).

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