simplegraph.class.inc.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  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/simplegraph.class.inc.php');
  28. *
  29. * $oGraph = new SimpleGraph();
  30. *
  31. * $oNode1 = new GraphNode($oGraph, 'Source1');
  32. * $oNode2 = new GraphNode($oGraph, 'Sink');
  33. * $oEdge1 = new GraphEdge($oGraph, 'flow1', $oNode1, $oNode2);
  34. * $oNode3 = new GraphNode($oGraph, 'Source2');
  35. * $oEdge2 = new GraphEdge($oGraph, 'flow2', $oNode3, $oNode2);
  36. * $oEdge2 = new GraphEdge($oGraph, 'flow3', $oNode2, $oNode3);
  37. * $oEdge2 = new GraphEdge($oGraph, 'flow4', $oNode1, $oNode3);
  38. *
  39. * echo $oGraph->DumpAsHtmlImage(); // requires graphviz
  40. * echo $oGraph->DumpAsHtmlText();
  41. */
  42. /**
  43. * Exceptions generated by the SimpleGraph class
  44. */
  45. class SimpleGraphException extends Exception
  46. {
  47. }
  48. /**
  49. * The parent class of all elements which can be part of a SimpleGraph
  50. */
  51. class GraphElement
  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 = null)
  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 SimpleGraph
  103. */
  104. class GraphNode extends GraphElement
  105. {
  106. protected $aIncomingEdges;
  107. protected $aOutgoingEdges;
  108. /**
  109. * Create a new node inside a graph
  110. * @param SimpleGraph $oGraph
  111. * @param string $sId The unique identifier of this node inside the graph
  112. */
  113. public function __construct(SimpleGraph $oGraph, $sId)
  114. {
  115. parent::__construct($sId);
  116. $this->aIncomingEdges = array();
  117. $this->aOutgoingEdges = array();
  118. $oGraph->_AddNode($this);
  119. }
  120. public function GetDotAttributes()
  121. {
  122. $sLabel = addslashes($this->GetProperty('label', $this->GetId()));
  123. $sDot = 'label="'.$sLabel.'"';
  124. return $sDot;
  125. }
  126. /**
  127. * INTERNAL USE ONLY
  128. * @param GraphEdge $oEdge
  129. */
  130. public function _AddIncomingEdge(GraphEdge $oEdge)
  131. {
  132. $this->aIncomingEdges[$oEdge->GetId()] = $oEdge;
  133. }
  134. /**
  135. * INTERNAL USE ONLY
  136. * @param GraphEdge $oEdge
  137. */
  138. public function _AddOutgoingEdge(GraphEdge $oEdge)
  139. {
  140. $this->aOutgoingEdges[$oEdge->GetId()] = $oEdge;
  141. }
  142. /**
  143. * Get the list of all incoming edges on the current node
  144. * @return Ambigous <multitype:, GraphEdge>
  145. */
  146. public function GetIncomingEdges()
  147. {
  148. return $this->aIncomingEdges;
  149. }
  150. /**
  151. * Get the list of all outgoing edges from the current node
  152. * @return Ambigous <multitype:, GraphEdge>
  153. */
  154. public function GetOutgoingEdges()
  155. {
  156. return $this->aOutgoingEdges;
  157. }
  158. }
  159. /**
  160. * A directed Edge inside a SimpleGraph
  161. */
  162. class GraphEdge extends GraphElement
  163. {
  164. protected $oSourceNode;
  165. protected $oSinkNode;
  166. /**
  167. * Create a new directed edge inside the given graph
  168. * @param SimpleGraph $oGraph
  169. * @param string $sId The unique identifier of this edge in the graph
  170. * @param GraphNode $oSourceNode
  171. * @param GraphNode $oSinkNode
  172. */
  173. public function __construct(SimpleGraph $oGraph, $sId, GraphNode $oSourceNode, GraphNode $oSinkNode)
  174. {
  175. parent::__construct($sId);
  176. $this->oSourceNode = $oSourceNode;
  177. $this->oSinkNode = $oSinkNode;
  178. $oGraph->_AddEdge($this);
  179. }
  180. /**
  181. * Get the "source" node for this edge
  182. * @return GraphNode
  183. */
  184. public function GetSourceNode()
  185. {
  186. return $this->oSourceNode;
  187. }
  188. /**
  189. * Get the "sink" node for this edge
  190. * @return GraphNode
  191. */
  192. public function GetSinkNode()
  193. {
  194. return $this->oSinkNode;
  195. }
  196. public function GetDotAttributes()
  197. {
  198. $sLabel = addslashes($this->GetProperty('label', ''));
  199. $sDot = 'label="'.$sLabel.'"';
  200. return $sDot;
  201. }
  202. }
  203. /**
  204. * The main container for a graph: SimpleGraph
  205. */
  206. class SimpleGraph
  207. {
  208. protected $aNodes;
  209. protected $aEdges;
  210. /**
  211. * Creates a new empty graph
  212. */
  213. public function __construct()
  214. {
  215. $this->aNodes = array();
  216. $this->aEdges = array();
  217. }
  218. /**
  219. * INTERNAL USE ONLY
  220. * @return Ambigous <multitype:, GraphNode>
  221. */
  222. public function _GetNodes()
  223. {
  224. return $this->aNodes;
  225. }
  226. /**
  227. * INTERNAL USE ONLY
  228. * @return Ambigous <multitype:, GraphNode>
  229. */
  230. public function _GetEdges()
  231. {
  232. return $this->aEdges;
  233. }
  234. /**
  235. * INTERNAL USE ONLY
  236. * @return Ambigous <multitype:, GraphNode>
  237. */
  238. public function _AddNode(GraphNode $oNode)
  239. {
  240. if (array_key_exists($oNode->GetId(), $this->aNodes)) throw new SimpleGraphException('Cannot add node (id='.$oNode->GetId().') to the graph. A node with the same id already exists inthe graph.');
  241. $this->aNodes[$oNode->GetId()] = $oNode;
  242. }
  243. /**
  244. * Get the node identified by $sId or null if not found
  245. * @param string $sId
  246. * @return NULL | GraphNode
  247. */
  248. public function GetNode($sId)
  249. {
  250. return array_key_exists($sId, $this->aNodes) ? $this->aNodes[$sId] : null;
  251. }
  252. /**
  253. * Determine if the id already exists in amongst the existing nodes
  254. * @param string $sId
  255. * @return boolean
  256. */
  257. public function HasNode($sId)
  258. {
  259. return array_key_exists($sId, $this->aNodes);
  260. }
  261. /**
  262. * INTERNAL USE ONLY
  263. * @param GraphEdge $oEdge
  264. * @throws SimpleGraphException
  265. */
  266. public function _AddEdge(GraphEdge $oEdge)
  267. {
  268. if (array_key_exists($oEdge->GetId(), $this->aEdges)) throw new SimpleGraphException('Cannot add edge (id='.$oEdge->GetId().') to the graph. An edge with the same id already exists inthe graph.');
  269. $this->aEdges[$oEdge->GetId()] = $oEdge;
  270. $oEdge->GetSourceNode()->_AddOutgoingEdge($oEdge);
  271. $oEdge->GetSinkNode()->_AddIncomingEdge($oEdge);
  272. }
  273. /**
  274. * Get the edge indentified by $sId or null if not found
  275. * @param string $sId
  276. * @return NULL | GraphEdge
  277. */
  278. public function GetEdge($sId)
  279. {
  280. return array_key_exists($sId, $this->aEdges) ? $this->aEdges[$sId] : null;
  281. }
  282. /**
  283. * Determine if the id already exists in amongst the existing edges
  284. * @param string $sId
  285. * @return boolean
  286. */
  287. public function HasEdge($sId)
  288. {
  289. return array_key_exists($sId, $this->aEdges);
  290. }
  291. /**
  292. * Get the description of the graph as a text string in the graphviz 'dot' language
  293. * @return string
  294. */
  295. public function GetDotDescription()
  296. {
  297. $sDot =
  298. <<<EOF
  299. digraph finite_state_machine {
  300. graph [bgcolor = "transparent"];
  301. rankdir=LR;
  302. size="30,30"
  303. node [ fontname=Verdana style=filled fillcolor="#ffffcc" ];
  304. edge [ fontname=Verdana ];
  305. EOF
  306. ;
  307. $oIterator = new RelationTypeIterator($this, 'Node');
  308. foreach($oIterator as $key => $oNode)
  309. {
  310. $sDot .= "\t\"".$oNode->GetId()."\" [ ".$oNode->GetDotAttributes()." ];\n";
  311. if (count($oNode->GetOutgoingEdges()) > 0)
  312. {
  313. foreach($oNode->GetOutgoingEdges() as $oEdge)
  314. {
  315. $sDot .= "\t\"".$oNode->GetId()."\" -> \"".$oEdge->GetSinkNode()->GetId()."\" [ ".$oEdge->GetDotAttributes()." ];\n";
  316. }
  317. }
  318. }
  319. $sDot .= "}\n";
  320. return $sDot;
  321. }
  322. /**
  323. * Get the description of the graph as an embedded PNG image (using a data: url) as
  324. * generated by graphviz (requires graphviz to be installed on the machine and the path to
  325. * dot/dot.exe to be configured in the iTop configuration file)
  326. * Note: the function creates temporary files in APPROOT/data/tmp
  327. * @return string
  328. */
  329. public function DumpAsHtmlImage()
  330. {
  331. $sDotExecutable = MetaModel::GetConfig()->Get('graphviz_path');
  332. if (file_exists($sDotExecutable))
  333. {
  334. // create the file with Graphviz
  335. if (!is_dir(APPROOT."data"))
  336. {
  337. @mkdir(APPROOT."data");
  338. }
  339. if (!is_dir(APPROOT."data/tmp"))
  340. {
  341. @mkdir(APPROOT."data/tmp");
  342. }
  343. $sImageFilePath = tempnam(APPROOT."data/tmp", 'png-');
  344. $sDotDescription = $this->GetDotDescription();
  345. $sDotFilePath = tempnam(APPROOT."data/tmp", 'dot-');
  346. $rFile = @fopen($sDotFilePath, "w");
  347. @fwrite($rFile, $sDotDescription);
  348. @fclose($rFile);
  349. $aOutput = array();
  350. $CommandLine = "\"$sDotExecutable\" -v -Tpng < $sDotFilePath -o$sImageFilePath 2>&1";
  351. exec($CommandLine, $aOutput, $iRetCode);
  352. if ($iRetCode != 0)
  353. {
  354. $sHtml = '';
  355. $sHtml .= "<p><b>Error:</b></p>";
  356. $sHtml .= "<p>The command: <pre>$CommandLine</pre> returned $iRetCode</p>";
  357. $sHtml .= "<p>The output of the command is:<pre>\n".implode("\n", $aOutput)."</pre></p>";
  358. $sHtml .= "<hr>";
  359. $sHtml .= "<p>Content of the '".basename($sDotFilePath)."' file:<pre>\n$sDotDescription</pre>";
  360. }
  361. else
  362. {
  363. $sHtml = '<img src="data:image/png;base64,'.base64_encode(file_get_contents($sImageFilePath)).'">';
  364. @unlink($sImageFilePath);
  365. }
  366. @unlink($sDotFilePath);
  367. }
  368. else
  369. {
  370. throw new Exception('graphviz not found (executable path: '.$sDotExecutable.')');
  371. }
  372. return $sHtml;
  373. }
  374. /**
  375. * Get the description of the graph as some HTML text
  376. * @return string
  377. */
  378. public function DumpAsHTMLText()
  379. {
  380. $sHtml = '';
  381. $oIterator = new RelationTypeIterator($this);
  382. foreach($oIterator as $key => $oElement)
  383. {
  384. $sHtml .= "<p>$key: ".get_class($oElement)."::".$oElement->GetId()."</p>";
  385. switch(get_class($oElement))
  386. {
  387. case 'GraphNode':
  388. if (count($oElement->GetIncomingEdges()) > 0)
  389. {
  390. $sHtml .= "<ul>Incoming edges:\n";
  391. foreach($oElement->GetIncomingEdges() as $oEdge)
  392. {
  393. $sHtml .= "<li>From: ".$oEdge->GetSourceNode()->GetId()."</li>\n";
  394. }
  395. $sHtml .= "</ul>\n";
  396. }
  397. if (count($oElement->GetOutgoingEdges()) > 0)
  398. {
  399. $sHtml .= "<ul>Outgoing edges:\n";
  400. foreach($oElement->GetOutgoingEdges() as $oEdge)
  401. {
  402. $sHtml .= "<li>To: ".$oEdge->GetSinkNode()->GetId()."</li>\n";
  403. }
  404. $sHtml .= "</ul>\n";
  405. }
  406. break;
  407. case 'GraphEdge':
  408. $sHtml .= "<p>From: ".$oElement->GetSourceNode()->GetId().", to:".$oElement->GetSinkNode()->GetId()."</p>\n";
  409. break;
  410. }
  411. }
  412. return $sHtml;
  413. }
  414. }
  415. /**
  416. * A simple iterator to "browse" the whole content of a graph,
  417. * either for only a given type of elements (Node | Edge) or for every type.
  418. */
  419. class RelationTypeIterator implements Iterator
  420. {
  421. protected $iCurrentIdx;
  422. protected $aList;
  423. /**
  424. * Constructor
  425. * @param SimpleGraph $oGraph The graph to browse
  426. * @param string $sType "Node", "Edge" or null
  427. */
  428. public function __construct(SimpleGraph $oGraph, $sType = null)
  429. {
  430. $this->iCurrentIdx = -1;
  431. $this->aList = array();
  432. switch($sType)
  433. {
  434. case 'Node':
  435. foreach($oGraph->_GetNodes() as $oNode) $this->aList[] = $oNode;
  436. break;
  437. case 'Edge':
  438. foreach($oGraph->_GetEdges() as $oEdge) $this->aList[] = $oEdge;
  439. break;
  440. default:
  441. foreach($oGraph->_GetNodes() as $oNode) $this->aList[] = $oNode;
  442. foreach($oGraph->_GetEdges() as $oEdge) $this->aList[] = $oEdge;
  443. }
  444. }
  445. public function rewind()
  446. {
  447. $this->iCurrentIdx = 0;
  448. }
  449. public function valid()
  450. {
  451. return array_key_exists($this->iCurrentIdx, $this->aList);
  452. }
  453. public function next()
  454. {
  455. $this->iCurrentIdx++;
  456. }
  457. public function current()
  458. {
  459. return $this->aList[$this->iCurrentIdx];
  460. }
  461. public function key()
  462. {
  463. return $this->iCurrentIdx;
  464. }
  465. }