relationgraph.class.inc.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. <?php
  2. // Copyright (C) 2015 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Data structures (i.e. PHP classes) to manage "graphs"
  20. *
  21. * @copyright Copyright (C) 2015 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. *
  24. * Example:
  25. * require_once('../approot.inc.php');
  26. * require_once(APPROOT.'application/startup.inc.php');
  27. * require_once(APPROOT.'core/relationgraph.class.inc.php');
  28. *
  29. * $oGraph = new RelationGraph();
  30. *
  31. * $oNode1 = new RelationNode($oGraph, 'Source1');
  32. * $oNode2 = new RelationNode($oGraph, 'Sink');
  33. * $oEdge1 = new RelationEdge($oGraph, 'flow1', $oNode1, $oNode2);
  34. * $oNode3 = new RelationNode($oGraph, 'Source2');
  35. * $oEdge2 = new RelationEdge($oGraph, 'flow2', $oNode3, $oNode2);
  36. * $oEdge2 = new RelationEdge($oGraph, 'flow3', $oNode2, $oNode3);
  37. * $oEdge2 = new RelationEdge($oGraph, 'flow4', $oNode1, $oNode3);
  38. *
  39. * echo $oGraph->DumpAsHtmlImage(); // requires graphviz
  40. * echo $oGraph->DumpAsHtmlText();
  41. */
  42. /**
  43. * Exceptions generated by the RelationGraph class
  44. */
  45. class RelationGraphException extends Exception
  46. {
  47. }
  48. /**
  49. * The parent class of all elements which can be part of a RelationGraph
  50. */
  51. class RelationElement
  52. {
  53. protected $sId;
  54. protected $aProperties;
  55. /**
  56. * Constructor
  57. * @param string $sId The identifier of the object in the graph
  58. */
  59. public function __construct($sId)
  60. {
  61. $this->sId = $sId;
  62. $this->aProperties = array();
  63. }
  64. /**
  65. * Get the identifier of the object in the graph
  66. * @return string
  67. */
  68. public function GetId()
  69. {
  70. return $this->sId;
  71. }
  72. /**
  73. * Get the value of the given named property for the object
  74. * @param string $sPropName The name of the property to get
  75. * @param mixed $defaultValue The default value to return if the property does not exist
  76. * @return mixed
  77. */
  78. public function GetProperty($sPropName, $defaultValue)
  79. {
  80. return array_key_exists($sPropName, $this->aProperties) ? $this->aProperties[$sPropName] : $defaultValue;
  81. }
  82. /**
  83. * Set the value of a named property for the object
  84. * @param string $sPropName The name of the property to set
  85. * @param mixed $value
  86. * @return void
  87. */
  88. public function SetProperty($sPropName, $value)
  89. {
  90. $this->aProperties[$sPropName] = $value;
  91. }
  92. /**
  93. * Get all the known properties of the object
  94. * @return Ambigous <multitype:, mixed>
  95. */
  96. public function GetProperties()
  97. {
  98. return $this->aProperties;
  99. }
  100. }
  101. /**
  102. * A Node inside a RelationGraph
  103. */
  104. class RelationNode extends RelationElement
  105. {
  106. protected $aIncomingEdges;
  107. protected $aOutgoingEdges;
  108. /**
  109. * Create a new node inside a graph
  110. * @param RelationGraph $oGraph
  111. * @param string $sId The unique identifier of this node inside the graph
  112. */
  113. public function __construct(RelationGraph $oGraph, $sId)
  114. {
  115. parent::__construct($sId);
  116. $this->aIncomingEdges = array();
  117. $this->aOutgoingEdges = array();
  118. $oGraph->_AddNode($this);
  119. }
  120. /**
  121. * INTERNAL USE ONLY
  122. * @param RelationEdge $oEdge
  123. */
  124. public function _AddIncomingEdge(RelationEdge $oEdge)
  125. {
  126. $this->aIncomingEdges[$oEdge->GetId()] = $oEdge;
  127. }
  128. /**
  129. * INTERNAL USE ONLY
  130. * @param RelationEdge $oEdge
  131. */
  132. public function _AddOutgoingEdge(RelationEdge $oEdge)
  133. {
  134. $this->aOutgoingEdges[$oEdge->GetId()] = $oEdge;
  135. }
  136. /**
  137. * Get the list of all incoming edges on the current node
  138. * @return Ambigous <multitype:, RelationEdge>
  139. */
  140. public function GetIncomingEdges()
  141. {
  142. return $this->aIncomingEdges;
  143. }
  144. /**
  145. * Get the list of all outgoing edges from the current node
  146. * @return Ambigous <multitype:, RelationEdge>
  147. */
  148. public function GetOutgoingEdges()
  149. {
  150. return $this->aOutgoingEdges;
  151. }
  152. }
  153. /**
  154. * A directed Edge inside a RelationGraph
  155. */
  156. class RelationEdge extends RelationElement
  157. {
  158. protected $oSourceNode;
  159. protected $oSinkNode;
  160. /**
  161. * Create a new directed edge inside the given graph
  162. * @param RelationGraph $oGraph
  163. * @param string $sId The unique identifier of this edge in the graph
  164. * @param RelationNode $oSourceNode
  165. * @param RelationNode $oSinkNode
  166. */
  167. public function __construct(RelationGraph $oGraph, $sId, RelationNode $oSourceNode, RelationNode $oSinkNode)
  168. {
  169. parent::__construct($sId);
  170. $this->oSourceNode = $oSourceNode;
  171. $this->oSinkNode = $oSinkNode;
  172. $oGraph->_AddEdge($this);
  173. }
  174. /**
  175. * Get the "source" node for this edge
  176. * @return RelationNode
  177. */
  178. public function GetSourceNode()
  179. {
  180. return $this->oSourceNode;
  181. }
  182. /**
  183. * Get the "sink" node for this edge
  184. * @return RelationNode
  185. */
  186. public function GetSinkNode()
  187. {
  188. return $this->oSinkNode;
  189. }
  190. }
  191. /**
  192. * The main container for a graph: RelationGraph
  193. */
  194. class RelationGraph
  195. {
  196. protected $aNodes;
  197. protected $aEdges;
  198. /**
  199. * Creates a new empty graph
  200. */
  201. public function __construct()
  202. {
  203. $this->aNodes = array();
  204. $this->aEdges = array();
  205. }
  206. /**
  207. * INTERNAL USE ONLY
  208. * @return Ambigous <multitype:, RelationNode>
  209. */
  210. public function _GetNodes()
  211. {
  212. return $this->aNodes;
  213. }
  214. /**
  215. * INTERNAL USE ONLY
  216. * @return Ambigous <multitype:, RelationNode>
  217. */
  218. public function _GetEdges()
  219. {
  220. return $this->aEdges;
  221. }
  222. /**
  223. * INTERNAL USE ONLY
  224. * @return Ambigous <multitype:, RelationNode>
  225. */
  226. public function _AddNode(RelationNode $oNode)
  227. {
  228. if (array_key_exists($oNode->GetId(), $this->aNodes)) throw new RelationGraphException('Cannot add node (id='.$oNode->GetId().') to the graph. A node with the same id already exists inthe graph.');
  229. $this->aNodes[$oNode->GetId()] = $oNode;
  230. }
  231. /**
  232. * Get the node identified by $sId or null if not found
  233. * @param string $sId
  234. * @return NULL | RelationNode
  235. */
  236. public function GetNode($sId)
  237. {
  238. return array_key_exists($sId, $this->aNodes) ? $this->aNodes[$sId] : null;
  239. }
  240. /**
  241. * INTERNAL USE ONLY
  242. * @param RelationEdge $oEdge
  243. * @throws RelationGraphException
  244. */
  245. public function _AddEdge(RelationEdge $oEdge)
  246. {
  247. if (array_key_exists($oEdge->GetId(), $this->aEdges)) throw new RelationGraphException('Cannot add edge (id='.$oEdge->GetId().') to the graph. An edge with the same id already exists inthe graph.');
  248. $this->aEdges[$oEdge->GetId()] = $oEdge;
  249. $oEdge->GetSourceNode()->_AddOutgoingEdge($oEdge);
  250. $oEdge->GetSinkNode()->_AddIncomingEdge($oEdge);
  251. }
  252. /**
  253. * Get the edge indentified by $sId or null if not found
  254. * @param string $sId
  255. * @return NULL | RelationEdge
  256. */
  257. public function GetEdge($sId)
  258. {
  259. return array_key_exists($sId, $this->aEdges) ? $this->aEdges[$sId] : null;
  260. }
  261. /**
  262. * Get the description of the graph as a text string in the graphviz 'dot' language
  263. * @return string
  264. */
  265. public function GetDotDescription()
  266. {
  267. $sDot =
  268. <<<EOF
  269. digraph finite_state_machine {
  270. graph [bgcolor = "transparent"];
  271. rankdir=LR;
  272. size="12,12"
  273. node [ fontname=Verdana style=filled fillcolor="#ffffff" ];
  274. edge [ fontname=Verdana ];
  275. EOF
  276. ;
  277. $oIterator = new RelationTypeIterator($this, 'Node');
  278. foreach($oIterator as $key => $oNode)
  279. {
  280. if (count($oNode->GetOutgoingEdges()) > 0)
  281. {
  282. foreach($oNode->GetOutgoingEdges() as $oEdge)
  283. {
  284. $sDot .= "\t".$oNode->GetId()." -> ".$oEdge->GetSinkNode()->GetId()." [ label=\"".$oEdge->GetId()."\" ];\n";
  285. }
  286. }
  287. else
  288. {
  289. $sDot .= "\t".$oNode->GetId().";\n";
  290. }
  291. }
  292. $sDot .= "}\n";
  293. return $sDot;
  294. }
  295. /**
  296. * Get the description of the graph as an embedded PNG image (using a data: url) as
  297. * generated by graphviz (requires graphviz to be installed on the machine and the path to
  298. * dot/dot.exe to be configured in the iTop configuration file)
  299. * Note: the function creates temporary files in APPROOT/data/tmp
  300. * @return string
  301. */
  302. public function DumpAsHtmlImage()
  303. {
  304. $sDotExecutable = MetaModel::GetConfig()->Get('graphviz_path');
  305. if (file_exists($sDotExecutable))
  306. {
  307. // create the file with Graphviz
  308. if (!is_dir(APPROOT."data"))
  309. {
  310. @mkdir(APPROOT."data");
  311. }
  312. if (!is_dir(APPROOT."data/tmp"))
  313. {
  314. @mkdir(APPROOT."data/tmp");
  315. }
  316. $sImageFilePath = tempnam(APPROOT."data/tmp", 'png-');
  317. $sDotDescription = $this->GetDotDescription();
  318. $sDotFilePath = tempnam(APPROOT."data/tmp", 'dot-');
  319. $rFile = @fopen($sDotFilePath, "w");
  320. @fwrite($rFile, $sDotDescription);
  321. @fclose($rFile);
  322. $aOutput = array();
  323. $CommandLine = "$sDotExecutable -v -Tpng < $sDotFilePath -o$sImageFilePath 2>&1";
  324. exec($CommandLine, $aOutput, $iRetCode);
  325. if ($iRetCode != 0)
  326. {
  327. $sHtml = '';
  328. $sHtml .= "<p><b>Error:</b></p>";
  329. $sHtml .= "<p>The command: <pre>$CommandLine</pre> returned $iRetCode</p>";
  330. $sHtml .= "<p>The output of the command is:<pre>\n".implode("\n", $aOutput)."</pre></p>";
  331. $sHtml .= "<hr>";
  332. $sHtml .= "<p>Content of the '".basename($sDotFilePath)."' file:<pre>\n$sDotDescription</pre>";
  333. }
  334. else
  335. {
  336. $sHtml = '<img src="data:image/png;base64,'.base64_encode(file_get_contents($sImageFilePath)).'">';
  337. @unlink($sImageFilePath);
  338. }
  339. @unlink($sDotFilePath);
  340. }
  341. return $sHtml;
  342. }
  343. /**
  344. * Get the description of the graph as some HTML text
  345. * @return string
  346. */
  347. public function DumpAsHTMLText()
  348. {
  349. $sHtml = '';
  350. $oIterator = new RelationTypeIterator($this);
  351. foreach($oIterator as $key => $oElement)
  352. {
  353. $sHtml .= "<p>$key: ".get_class($oElement)."::".$oElement->GetId()."</p>";
  354. switch(get_class($oElement))
  355. {
  356. case 'RelationNode':
  357. if (count($oElement->GetIncomingEdges()) > 0)
  358. {
  359. $sHtml .= "<ul>Incoming edges:\n";
  360. foreach($oElement->GetIncomingEdges() as $oEdge)
  361. {
  362. $sHtml .= "<li>From: ".$oEdge->GetSourceNode()->GetId()."</li>\n";
  363. }
  364. $sHtml .= "</ul>\n";
  365. }
  366. if (count($oElement->GetOutgoingEdges()) > 0)
  367. {
  368. $sHtml .= "<ul>Outgoing edges:\n";
  369. foreach($oElement->GetOutgoingEdges() as $oEdge)
  370. {
  371. $sHtml .= "<li>To: ".$oEdge->GetSinkNode()->GetId()."</li>\n";
  372. }
  373. $sHtml .= "</ul>\n";
  374. }
  375. break;
  376. case 'RelationEdge':
  377. $sHtml .= "<p>From: ".$oElement->GetSourceNode()->GetId().", to:".$oElement->GetSinkNode()->GetId()."</p>\n";
  378. break;
  379. }
  380. }
  381. return $sHtml;
  382. }
  383. }
  384. /**
  385. * A simple iterator to "browse" the whole content of a graph,
  386. * either for only a given type of elements (Node | Edge) or for every type.
  387. */
  388. class RelationTypeIterator implements Iterator
  389. {
  390. protected $iCurrentIdx;
  391. protected $aList;
  392. /**
  393. * Constructor
  394. * @param RelationGraph $oGraph The graph to browse
  395. * @param string $sType "Node", "Edge" or null
  396. */
  397. public function __construct(RelationGraph $oGraph, $sType = null)
  398. {
  399. $this->iCurrentIdx = -1;
  400. $this->aList = array();
  401. switch($sType)
  402. {
  403. case 'Node':
  404. foreach($oGraph->_GetNodes() as $oNode) $this->aList[] = $oNode;
  405. break;
  406. case 'Edge':
  407. foreach($oGraph->_GetEdges() as $oEdge) $this->aList[] = $oEdge;
  408. break;
  409. default:
  410. foreach($oGraph->_GetNodes() as $oNode) $this->aList[] = $oNode;
  411. foreach($oGraph->_GetEdges() as $oEdge) $this->aList[] = $oEdge;
  412. }
  413. }
  414. public function rewind()
  415. {
  416. $this->iCurrentIdx = 0;
  417. }
  418. public function valid()
  419. {
  420. return array_key_exists($this->iCurrentIdx, $this->aList);
  421. }
  422. public function next()
  423. {
  424. $this->iCurrentIdx++;
  425. }
  426. public function current()
  427. {
  428. return $this->aList[$this->iCurrentIdx];
  429. }
  430. public function key()
  431. {
  432. return $this->iCurrentIdx;
  433. }
  434. }