simplegraph.class.inc.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  1. <?php
  2. // Copyright (C) 2015-2017 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-2017 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($bNoLabel = false)
  121. {
  122. $sDot = '';
  123. if (!$bNoLabel)
  124. {
  125. $sLabel = addslashes($this->GetProperty('label', $this->GetId()));
  126. $sDot = 'label="'.$sLabel.'"';
  127. }
  128. return $sDot;
  129. }
  130. /**
  131. * INTERNAL USE ONLY
  132. * @param GraphEdge $oEdge
  133. */
  134. public function _AddIncomingEdge(GraphEdge $oEdge)
  135. {
  136. $this->aIncomingEdges[$oEdge->GetId()] = $oEdge;
  137. }
  138. /**
  139. * INTERNAL USE ONLY
  140. * @param GraphEdge $oEdge
  141. */
  142. public function _AddOutgoingEdge(GraphEdge $oEdge)
  143. {
  144. $this->aOutgoingEdges[$oEdge->GetId()] = $oEdge;
  145. }
  146. /**
  147. * INTERNAL USE ONLY
  148. * @param GraphEdge $oEdge
  149. */
  150. public function _RemoveIncomingEdge(GraphEdge $oEdge)
  151. {
  152. unset($this->aIncomingEdges[$oEdge->GetId()]);
  153. }
  154. /**
  155. * INTERNAL USE ONLY
  156. * @param GraphEdge $oEdge
  157. */
  158. public function _RemoveOutgoingEdge(GraphEdge $oEdge)
  159. {
  160. unset($this->aOutgoingEdges[$oEdge->GetId()]);
  161. }
  162. /**
  163. * Get the list of all incoming edges on the current node
  164. * @return Ambigous <multitype:, GraphEdge>
  165. */
  166. public function GetIncomingEdges()
  167. {
  168. return $this->aIncomingEdges;
  169. }
  170. /**
  171. * Get the list of all outgoing edges from the current node
  172. * @return Ambigous <multitype:, GraphEdge>
  173. */
  174. public function GetOutgoingEdges()
  175. {
  176. return $this->aOutgoingEdges;
  177. }
  178. /**
  179. * Flood fill the chart with the given value for the specified property
  180. * @param string $sPropName The name of the property to set
  181. * @param mixed $value Teh value to set in the property
  182. * @param bool $bFloodDown Whether or not to fill in the downstream direction
  183. * @param bool $bFloodUp Whether or not to fill in the upstream direction
  184. */
  185. public function FloodProperty($sPropName, $value, $bFloodDown, $bFloodUp)
  186. {
  187. if ($this->GetProperty($sPropName, null) == null)
  188. {
  189. // Property not already set, let's do it
  190. $this->SetProperty($sPropName, $value);
  191. if ($bFloodDown)
  192. {
  193. foreach($this->GetOutgoingEdges() as $oEdge)
  194. {
  195. $oEdge->SetProperty($sPropName, $value);
  196. $oEdge->GetSinkNode()->FloodProperty($sPropName, $value, $bFloodDown, $bFloodUp);
  197. }
  198. }
  199. if ($bFloodUp)
  200. {
  201. foreach($this->GetIncomingEdges() as $oEdge)
  202. {
  203. $oEdge->SetProperty($sPropName, $value);
  204. $oEdge->GetSourceNode()->FloodProperty($sPropName, $value, $bFloodDown, $bFloodUp);
  205. }
  206. }
  207. }
  208. }
  209. }
  210. /**
  211. * A directed Edge inside a SimpleGraph
  212. */
  213. class GraphEdge extends GraphElement
  214. {
  215. protected $oSourceNode;
  216. protected $oSinkNode;
  217. /**
  218. * Create a new directed edge inside the given graph
  219. * @param SimpleGraph $oGraph
  220. * @param string $sId The unique identifier of this edge in the graph
  221. * @param GraphNode $oSourceNode
  222. * @param GraphNode $oSinkNode
  223. * @param bool $bMustBeUnique
  224. * @throws SimpleGraphException
  225. */
  226. public function __construct(SimpleGraph $oGraph, $sId, GraphNode $oSourceNode, GraphNode $oSinkNode, $bMustBeUnique = false)
  227. {
  228. parent::__construct($sId);
  229. $this->oSourceNode = $oSourceNode;
  230. $this->oSinkNode = $oSinkNode;
  231. $oGraph->_AddEdge($this, $bMustBeUnique);
  232. }
  233. /**
  234. * Get the "source" node for this edge
  235. * @return GraphNode
  236. */
  237. public function GetSourceNode()
  238. {
  239. return $this->oSourceNode;
  240. }
  241. /**
  242. * Get the "sink" node for this edge
  243. * @return GraphNode
  244. */
  245. public function GetSinkNode()
  246. {
  247. return $this->oSinkNode;
  248. }
  249. public function GetDotAttributes($bNoLabel = false)
  250. {
  251. $sDot = '';
  252. if (!$bNoLabel)
  253. {
  254. $sLabel = addslashes($this->GetProperty('label', ''));
  255. $sDot = 'label="'.$sLabel.'"';
  256. }
  257. return $sDot;
  258. }
  259. }
  260. /**
  261. * The main container for a graph: SimpleGraph
  262. */
  263. class SimpleGraph
  264. {
  265. protected $aNodes;
  266. protected $aEdges;
  267. /**
  268. * Creates a new empty graph
  269. */
  270. public function __construct()
  271. {
  272. $this->aNodes = array();
  273. $this->aEdges = array();
  274. }
  275. /**
  276. * INTERNAL USE ONLY
  277. * @return Ambigous <multitype:, GraphNode>
  278. */
  279. public function _GetNodes()
  280. {
  281. return $this->aNodes;
  282. }
  283. /**
  284. * INTERNAL USE ONLY
  285. * @return Ambigous <multitype:, GraphNode>
  286. */
  287. public function _GetEdges()
  288. {
  289. return $this->aEdges;
  290. }
  291. /**
  292. * INTERNAL USE ONLY
  293. * @return Ambigous <multitype:, GraphNode>
  294. */
  295. public function _AddNode(GraphNode $oNode)
  296. {
  297. 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 in the graph.');
  298. $this->aNodes[$oNode->GetId()] = $oNode;
  299. }
  300. /**
  301. * INTERNAL USE ONLY
  302. * @return Ambigous <multitype:, GraphNode>
  303. */
  304. public function _RemoveNode(GraphNode $oNode)
  305. {
  306. if (!array_key_exists($oNode->GetId(), $this->aNodes)) throw new SimpleGraphException('Cannot remove the node (id='.$oNode->GetId().') from the graph. The node was not found in the graph.');
  307. foreach($oNode->GetOutgoingEdges() as $oEdge)
  308. {
  309. $this->_RemoveEdge($oEdge);
  310. }
  311. foreach($oNode->GetIncomingEdges() as $oEdge)
  312. {
  313. $this->_RemoveEdge($oEdge);
  314. }
  315. unset($this->aNodes[$oNode->GetId()]);
  316. }
  317. /**
  318. * Removes the given node but preserves the connectivity of the graph
  319. * all "source" nodes are connected to all "sink" nodes
  320. * @param GraphNode $oNode
  321. * @param bool $bAllowLoopingEdge
  322. * @throws SimpleGraphException
  323. */
  324. public function FilterNode(GraphNode $oNode, $bAllowLoopingEdge = false)
  325. {
  326. if (!array_key_exists($oNode->GetId(), $this->aNodes)) throw new SimpleGraphException('Cannot filter the node (id='.$oNode->GetId().') from the graph. The node was not found in the graph.');
  327. $aSourceNodes = array();
  328. $aSinkNodes = array();
  329. foreach($oNode->GetOutgoingEdges() as $oEdge)
  330. {
  331. $sSinkId = $oEdge->GetSinkNode()->GetId();
  332. if ($sSinkId != $oNode->GetId())
  333. {
  334. $aSinkNodes[$sSinkId] = $oEdge->GetSinkNode();
  335. }
  336. $this->_RemoveEdge($oEdge);
  337. }
  338. foreach($oNode->GetIncomingEdges() as $oEdge)
  339. {
  340. $sSourceId = $oEdge->GetSourceNode()->GetId();
  341. if ($sSourceId != $oNode->GetId())
  342. {
  343. $aSourceNodes[$sSourceId] = $oEdge->GetSourceNode();
  344. }
  345. $this->_RemoveEdge($oEdge);
  346. }
  347. unset($this->aNodes[$oNode->GetId()]);
  348. foreach($aSourceNodes as $sSourceId => $oSourceNode)
  349. {
  350. foreach($aSinkNodes as $sSinkId => $oSinkNode)
  351. {
  352. if ($bAllowLoopingEdge || ($oSourceNode->GetId() != $oSinkNode->GetId()))
  353. {
  354. $oEdge = new RelationEdge($this, $oSourceNode, $oSinkNode);
  355. }
  356. }
  357. }
  358. }
  359. /**
  360. * Get the node identified by $sId or null if not found
  361. * @param string $sId
  362. * @return NULL | GraphNode
  363. */
  364. public function GetNode($sId)
  365. {
  366. return array_key_exists($sId, $this->aNodes) ? $this->aNodes[$sId] : null;
  367. }
  368. /**
  369. * Determine if the id already exists in amongst the existing nodes
  370. * @param string $sId
  371. * @return boolean
  372. */
  373. public function HasNode($sId)
  374. {
  375. return array_key_exists($sId, $this->aNodes);
  376. }
  377. /**
  378. * INTERNAL USE ONLY
  379. * @param GraphEdge $oEdge
  380. * @param bool $bMustBeUnique
  381. * @throws SimpleGraphException
  382. */
  383. public function _AddEdge(GraphEdge $oEdge, $bMustBeUnique = false)
  384. {
  385. if (array_key_exists($oEdge->GetId(), $this->aEdges))
  386. {
  387. if ($bMustBeUnique)
  388. {
  389. throw new SimpleGraphException('Cannot add edge (id=' . $oEdge->GetId() . ') to the graph. An edge with the same id already exists in the graph.');
  390. }
  391. else
  392. {
  393. return;
  394. }
  395. }
  396. $this->aEdges[$oEdge->GetId()] = $oEdge;
  397. $oEdge->GetSourceNode()->_AddOutgoingEdge($oEdge);
  398. $oEdge->GetSinkNode()->_AddIncomingEdge($oEdge);
  399. }
  400. /**
  401. * INTERNAL USE ONLY
  402. * @param GraphEdge $oEdge
  403. * @throws SimpleGraphException
  404. */
  405. public function _RemoveEdge(GraphEdge $oEdge)
  406. {
  407. if (!array_key_exists($oEdge->GetId(), $this->aEdges)) throw new SimpleGraphException('Cannot remove edge (id='.$oEdge->GetId().') from the graph. The edge was not found.');
  408. $oEdge->GetSourceNode()->_RemoveOutgoingEdge($oEdge);
  409. $oEdge->GetSinkNode()->_RemoveIncomingEdge($oEdge);
  410. unset($this->aEdges[$oEdge->GetId()]);
  411. }
  412. /**
  413. * Get the edge indentified by $sId or null if not found
  414. * @param string $sId
  415. * @return NULL | GraphEdge
  416. */
  417. public function GetEdge($sId)
  418. {
  419. return array_key_exists($sId, $this->aEdges) ? $this->aEdges[$sId] : null;
  420. }
  421. /**
  422. * Determine if the id already exists in amongst the existing edges
  423. * @param string $sId
  424. * @return boolean
  425. */
  426. public function HasEdge($sId)
  427. {
  428. return array_key_exists($sId, $this->aEdges);
  429. }
  430. /**
  431. * Get the description of the graph as a text string in the graphviz 'dot' language
  432. * @param $bNoLabel bool Whether or not to include the labels in the dot file
  433. * @return string
  434. */
  435. public function GetDotDescription($bNoLabel = false)
  436. {
  437. $sDot =
  438. <<<EOF
  439. digraph finite_state_machine {
  440. graph [bgcolor = "transparent"];
  441. rankdir=LR;
  442. size="30,30";
  443. fontsize=8.0;
  444. node [ fontname=Verdana style=filled fillcolor="#ffffcc" fontsize=8.0 ];
  445. edge [ fontname=Verdana ];
  446. EOF
  447. ;
  448. $oIterator = new RelationTypeIterator($this, 'Node');
  449. foreach($oIterator as $key => $oNode)
  450. {
  451. $sDot .= "\t\"".$oNode->GetId()."\" [ ".$oNode->GetDotAttributes($bNoLabel)." ];\n";
  452. if (count($oNode->GetOutgoingEdges()) > 0)
  453. {
  454. foreach($oNode->GetOutgoingEdges() as $oEdge)
  455. {
  456. $sDot .= "\t\"".$oNode->GetId()."\" -> \"".$oEdge->GetSinkNode()->GetId()."\" [ ".$oEdge->GetDotAttributes($bNoLabel)." ];\n";
  457. }
  458. }
  459. }
  460. $sDot .= "}\n";
  461. return $sDot;
  462. }
  463. /**
  464. * Get the description of the graph as an embedded PNG image (using a data: url) as
  465. * generated by graphviz (requires graphviz to be installed on the machine and the path to
  466. * dot/dot.exe to be configured in the iTop configuration file)
  467. * Note: the function creates temporary files in APPROOT/data/tmp
  468. * @return string
  469. */
  470. public function DumpAsHtmlImage()
  471. {
  472. $sDotExecutable = MetaModel::GetConfig()->Get('graphviz_path');
  473. if (file_exists($sDotExecutable))
  474. {
  475. // create the file with Graphviz
  476. if (!is_dir(APPROOT."data"))
  477. {
  478. @mkdir(APPROOT."data");
  479. }
  480. if (!is_dir(APPROOT."data/tmp"))
  481. {
  482. @mkdir(APPROOT."data/tmp");
  483. }
  484. $sImageFilePath = tempnam(APPROOT."data/tmp", 'png-');
  485. $sDotDescription = $this->GetDotDescription();
  486. $sDotFilePath = tempnam(APPROOT."data/tmp", 'dot-');
  487. $rFile = @fopen($sDotFilePath, "w");
  488. @fwrite($rFile, $sDotDescription);
  489. @fclose($rFile);
  490. $aOutput = array();
  491. $CommandLine = "\"$sDotExecutable\" -v -Tpng < \"$sDotFilePath\" -o\"$sImageFilePath\" 2>&1";
  492. exec($CommandLine, $aOutput, $iRetCode);
  493. if ($iRetCode != 0)
  494. {
  495. $sHtml = '';
  496. $sHtml .= "<p><b>Error:</b></p>";
  497. $sHtml .= "<p>The command: <pre>$CommandLine</pre> returned $iRetCode</p>";
  498. $sHtml .= "<p>The output of the command is:<pre>\n".implode("\n", $aOutput)."</pre></p>";
  499. $sHtml .= "<hr>";
  500. $sHtml .= "<p>Content of the '".basename($sDotFilePath)."' file:<pre>\n$sDotDescription</pre>";
  501. }
  502. else
  503. {
  504. $sHtml = '<img src="data:image/png;base64,'.base64_encode(file_get_contents($sImageFilePath)).'">';
  505. @unlink($sImageFilePath);
  506. }
  507. @unlink($sDotFilePath);
  508. }
  509. else
  510. {
  511. throw new Exception('graphviz not found (executable path: '.$sDotExecutable.')');
  512. }
  513. return $sHtml;
  514. }
  515. /**
  516. * Get the description of the graph as text string in the XDot format
  517. * including the positions of the nodes and egdes (requires graphviz
  518. * to be installed on the machine and the path to dot/dot.exe to be
  519. * configured in the iTop configuration file)
  520. * Note: the function creates temporary files in APPROOT/data/tmp
  521. * @return string
  522. */
  523. public function DumpAsXDot()
  524. {
  525. $sDotExecutable = MetaModel::GetConfig()->Get('graphviz_path');
  526. if (file_exists($sDotExecutable))
  527. {
  528. // create the file with Graphviz
  529. if (!is_dir(APPROOT."data"))
  530. {
  531. @mkdir(APPROOT."data");
  532. }
  533. if (!is_dir(APPROOT."data/tmp"))
  534. {
  535. @mkdir(APPROOT."data/tmp");
  536. }
  537. $sXdotFilePath = tempnam(APPROOT."data/tmp", 'xdot-');
  538. $sDotDescription = $this->GetDotDescription(true); // true => don't put (localized) labels in the file, since it makes it harder to parse
  539. $sDotFilePath = tempnam(APPROOT."data/tmp", 'dot-');
  540. $rFile = @fopen($sDotFilePath, "w");
  541. @fwrite($rFile, $sDotDescription);
  542. @fclose($rFile);
  543. $aOutput = array();
  544. $CommandLine = "\"$sDotExecutable\" -v -Tdot < \"$sDotFilePath\" -o\"$sXdotFilePath\" 2>&1";
  545. exec($CommandLine, $aOutput, $iRetCode);
  546. if ($iRetCode != 0)
  547. {
  548. $sHtml = '';
  549. $sHtml .= "<p><b>Error:</b></p>";
  550. $sHtml .= "<p>The command: <pre>$CommandLine</pre> returned $iRetCode</p>";
  551. $sHtml .= "<p>The output of the command is:<pre>\n".implode("\n", $aOutput)."</pre></p>";
  552. IssueLog::Error($sHtml);
  553. }
  554. else
  555. {
  556. $sHtml = '<pre>'.file_get_contents($sXdotFilePath).'</pre>';
  557. @unlink($sXdotFilePath);
  558. }
  559. @unlink($sDotFilePath);
  560. }
  561. else
  562. {
  563. throw new Exception('graphviz not found (executable path: '.$sDotExecutable.')');
  564. }
  565. return $sHtml;
  566. }
  567. /**
  568. * Get the description of the graph as some HTML text
  569. * @return string
  570. */
  571. public function DumpAsHTMLText()
  572. {
  573. $sHtml = '';
  574. $oIterator = new RelationTypeIterator($this);
  575. foreach($oIterator as $key => $oElement)
  576. {
  577. $sHtml .= "<p>$key: ".get_class($oElement)."::".$oElement->GetId()."</p>";
  578. switch(get_class($oElement))
  579. {
  580. case 'GraphNode':
  581. if (count($oElement->GetIncomingEdges()) > 0)
  582. {
  583. $sHtml .= "<ul>Incoming edges:\n";
  584. foreach($oElement->GetIncomingEdges() as $oEdge)
  585. {
  586. $sHtml .= "<li>From: ".$oEdge->GetSourceNode()->GetId()."</li>\n";
  587. }
  588. $sHtml .= "</ul>\n";
  589. }
  590. if (count($oElement->GetOutgoingEdges()) > 0)
  591. {
  592. $sHtml .= "<ul>Outgoing edges:\n";
  593. foreach($oElement->GetOutgoingEdges() as $oEdge)
  594. {
  595. $sHtml .= "<li>To: ".$oEdge->GetSinkNode()->GetId()."</li>\n";
  596. }
  597. $sHtml .= "</ul>\n";
  598. }
  599. break;
  600. case 'GraphEdge':
  601. $sHtml .= "<p>From: ".$oElement->GetSourceNode()->GetId().", to:".$oElement->GetSinkNode()->GetId()."</p>\n";
  602. break;
  603. }
  604. }
  605. return $sHtml;
  606. }
  607. /**
  608. * Split the graph in a array of non connected subgraphs
  609. * @return multitype:SimpleGraph unknown
  610. */
  611. public function GetSubgraphs()
  612. {
  613. $iNbColors = 0;
  614. $aResult = array();
  615. $oIterator = new RelationTypeIterator($this, 'Node');
  616. foreach($oIterator as $oNode)
  617. {
  618. $iPrevColor = $oNode->GetProperty('color', null);
  619. if ($iPrevColor == null)
  620. {
  621. $iNbColors++; // Start a new color
  622. $oNode->FloodProperty('color', $iNbColors, true, true);
  623. }
  624. }
  625. if ($iNbColors == 1)
  626. {
  627. // Everything is connected together, only one subgraph
  628. $aResult[] = $this;
  629. }
  630. else
  631. {
  632. // Let's reconstruct each separate graph
  633. $sClass = get_class($this);
  634. for($i = 1; $i <= $iNbColors; $i++)
  635. {
  636. $aResult[$i] = new $sClass();
  637. }
  638. foreach($oIterator as $oNode)
  639. {
  640. $iNodeColor = $oNode->GetProperty('color');
  641. $aResult[$iNodeColor]->_AddNode($oNode);
  642. }
  643. $oIter2 = new RelationTypeIterator($this, 'Edge');
  644. foreach($oIter2 as $oEdge)
  645. {
  646. $iEdgeColor = $oEdge->GetProperty('color');
  647. $aResult[$iEdgeColor]->_AddEdge($oEdge);
  648. }
  649. }
  650. return $aResult;
  651. }
  652. /**
  653. * Merge back two subgraphs into one
  654. * @param SimpleGraph $oGraph
  655. */
  656. public function Merge(SimpleGraph $oGraph)
  657. {
  658. $oIter1 = new RelationTypeIterator($oGraph, 'Node');
  659. foreach($oIter1 as $oNode)
  660. {
  661. $this->_AddNode($oNode);
  662. }
  663. $oIter2 = new RelationTypeIterator($oGraph, 'Edge');
  664. foreach($oIter2 as $oEdge)
  665. {
  666. $this->_AddEdge($oEdge);
  667. }
  668. }
  669. }
  670. /**
  671. * A simple iterator to "browse" the whole content of a graph,
  672. * either for only a given type of elements (Node | Edge) or for every type.
  673. */
  674. class RelationTypeIterator implements Iterator
  675. {
  676. protected $iCurrentIdx;
  677. protected $aList;
  678. /**
  679. * Constructor
  680. * @param SimpleGraph $oGraph The graph to browse
  681. * @param string $sType "Node", "Edge" or null
  682. */
  683. public function __construct(SimpleGraph $oGraph, $sType = null)
  684. {
  685. $this->iCurrentIdx = -1;
  686. $this->aList = array();
  687. switch($sType)
  688. {
  689. case 'Node':
  690. foreach($oGraph->_GetNodes() as $oNode) $this->aList[] = $oNode;
  691. break;
  692. case 'Edge':
  693. foreach($oGraph->_GetEdges() as $oEdge) $this->aList[] = $oEdge;
  694. break;
  695. default:
  696. foreach($oGraph->_GetNodes() as $oNode) $this->aList[] = $oNode;
  697. foreach($oGraph->_GetEdges() as $oEdge) $this->aList[] = $oEdge;
  698. }
  699. }
  700. public function rewind()
  701. {
  702. $this->iCurrentIdx = 0;
  703. }
  704. public function valid()
  705. {
  706. return array_key_exists($this->iCurrentIdx, $this->aList);
  707. }
  708. public function next()
  709. {
  710. $this->iCurrentIdx++;
  711. }
  712. public function current()
  713. {
  714. return $this->aList[$this->iCurrentIdx];
  715. }
  716. public function key()
  717. {
  718. return $this->iCurrentIdx;
  719. }
  720. }