relationgraph.class.inc.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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 build and use relation graphs
  20. *
  21. * @copyright Copyright (C) 2015 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. *
  24. */
  25. require_once(APPROOT.'core/simplegraph.class.inc.php');
  26. /**
  27. * An object Node inside a RelationGraph
  28. */
  29. class RelationObjectNode extends GraphNode
  30. {
  31. public function __construct($oGraph, $oObject)
  32. {
  33. parent::__construct($oGraph, self::MakeId($oObject));
  34. $this->SetProperty('object', $oObject);
  35. $this->SetProperty('label', get_class($oObject).'::'.$oObject->GetKey().' ('.$oObject->Get('friendlyname').')');
  36. }
  37. /**
  38. * Make a normalized ID to ensure the uniqueness of such a node
  39. */
  40. public static function MakeId($oObject)
  41. {
  42. return get_class($oObject).'::'.$oObject->GetKey();
  43. }
  44. /**
  45. * Formatting for GraphViz
  46. */
  47. public function GetDotAttributes()
  48. {
  49. $sDot = parent::GetDotAttributes();
  50. if ($this->GetProperty('developped', false))
  51. {
  52. $sDot .= ',fontcolor=black';
  53. }
  54. else
  55. {
  56. $sDot .= ',fontcolor=lightgrey';
  57. }
  58. if ($this->GetProperty('source', false) || $this->GetProperty('sink', false))
  59. {
  60. $sDot .= ',shape=rectangle';
  61. }
  62. if ($this->GetProperty('is_reached', false))
  63. {
  64. $sDot .= ',fillcolor="#ffdddd"';
  65. }
  66. else
  67. {
  68. $sDot .= ',fillcolor=white';
  69. }
  70. return $sDot;
  71. }
  72. /**
  73. * Recursively mark the objects nodes as reached, unless we get stopped by a redundancy node or a 'not allowed' node
  74. */
  75. public function ReachDown($sProperty, $value)
  76. {
  77. if (is_null($this->GetProperty($sProperty)) && ($this->GetProperty($sProperty.'_allowed') !== false))
  78. {
  79. $this->SetProperty($sProperty, $value);
  80. foreach ($this->GetOutgoingEdges() as $oOutgoingEdge)
  81. {
  82. // Recurse
  83. $oOutgoingEdge->GetSinkNode()->ReachDown($sProperty, $value);
  84. }
  85. }
  86. }
  87. }
  88. /**
  89. * An redundancy Node inside a RelationGraph
  90. */
  91. class RelationRedundancyNode extends GraphNode
  92. {
  93. public function __construct($oGraph, $sId, $iMinUp, $fThreshold)
  94. {
  95. parent::__construct($oGraph, $sId);
  96. $this->SetProperty('min_up', $iMinUp);
  97. $this->SetProperty('threshold', $fThreshold);
  98. }
  99. /**
  100. * Make a normalized ID to ensure the uniqueness of such a node
  101. */
  102. public static function MakeId($sRelCode, $sNeighbourId, $oSinkObject)
  103. {
  104. return 'redundancy-'.$sRelCode.'-'.$sNeighbourId.'-'.get_class($oSinkObject).'::'.$oSinkObject->GetKey();
  105. }
  106. /**
  107. * Formatting for GraphViz
  108. */
  109. public function GetDotAttributes()
  110. {
  111. $sDisplayThreshold = sprintf('%.1f', $this->GetProperty('threshold'));
  112. $sDot = 'shape=doublecircle,fillcolor=indianred,fontcolor=papayawhip,label="'.$sDisplayThreshold.'"';
  113. return $sDot;
  114. }
  115. /**
  116. * Recursively mark the objects nodes as reached, unless we get stopped by a redundancy node
  117. */
  118. public function ReachDown($sProperty, $value)
  119. {
  120. $this->SetProperty($sProperty.'_count', $this->GetProperty($sProperty.'_count', 0) + 1);
  121. if ($this->GetProperty($sProperty.'_count') > $this->GetProperty('threshold'))
  122. {
  123. // Looping... though there should be only ONE SINGLE outgoing edge
  124. foreach ($this->GetOutgoingEdges() as $oOutgoingEdge)
  125. {
  126. // Recurse
  127. $oOutgoingEdge->GetSinkNode()->ReachDown($sProperty, $value);
  128. }
  129. }
  130. }
  131. }
  132. /**
  133. * Helper to name the edges in a unique way
  134. */
  135. class RelationEdge extends GraphEdge
  136. {
  137. public function __construct(SimpleGraph $oGraph, GraphNode $oSourceNode, GraphNode $oSinkNode)
  138. {
  139. $sId = $oSourceNode->GetId().'-to-'.$oSinkNode->GetId();
  140. parent::__construct($oGraph, $sId, $oSourceNode, $oSinkNode);
  141. }
  142. }
  143. /**
  144. * A graph representing the relations between objects
  145. * The graph is made of two types of nodes. Here is a list of the meaningful node properties
  146. * 1) RelationObjectNode
  147. * source: boolean, that node was added as a source node
  148. * sink: boolean, that node was added as a sink node
  149. * reached: boolean, that node has been marked as reached (impacted by the source nodes)
  150. * developped: boolean, that node has been visited to search for related objects
  151. * 1) RelationRedundancyNode
  152. * reached_count: int, the number of source nodes having reached=true
  153. * threshold: float, if reached_count > threshold, the sink nodes become reachable
  154. */
  155. class RelationGraph extends SimpleGraph
  156. {
  157. protected $aSourceNodes; // Index of source nodes (for a quicker access)
  158. protected $aSinkNodes; // Index of sink nodes (for a quicker access)
  159. protected $aRedundancySettings; // Cache of user settings
  160. public function __construct()
  161. {
  162. parent::__construct();
  163. $this->aSourceNodes = array();
  164. $this->aSinkNodes = array();
  165. $this->aRedundancySettings = array();
  166. }
  167. /**
  168. * Add an object that will be the starting point for building the relations downstream
  169. */
  170. public function AddSourceObject(DBObject $oObject)
  171. {
  172. $oSourceNode = new RelationObjectNode($this, $oObject);
  173. $oSourceNode->SetProperty('source', true);
  174. $this->aSourceNodes[$oSourceNode->GetId()] = $oSourceNode;
  175. }
  176. /**
  177. * Add an object that will be the starting point for building the relations uptream
  178. */
  179. public function AddSinkObject(DBObject$oObject)
  180. {
  181. $oSinkNode = new RelationObjectNode($this, $oObject);
  182. $oSinkNode->SetProperty('sink', true);
  183. $this->aSinkNodes[$oSinkNode->GetId()] = $oSinkNode;
  184. }
  185. /**
  186. * Build the graph downstream, and mark the nodes that can be reached from the source node
  187. */
  188. public function ComputeRelatedObjectsDown($sRelCode, $iMaxDepth, $bEnableRedundancy, $aUnreachableObjects = array())
  189. {
  190. //echo "<h5>Sources only...</h5>\n".$this->DumpAsHtmlImage()."<br/>\n";
  191. // Build the graph out of the sources
  192. foreach ($this->aSourceNodes as $oSourceNode)
  193. {
  194. $this->AddRelatedObjects($sRelCode, true, $oSourceNode, $iMaxDepth, $bEnableRedundancy);
  195. //echo "<h5>After processing of {$oSourceNode->GetId()}</h5>\n".$this->DumpAsHtmlImage()."<br/>\n";
  196. }
  197. // Mark the unreachable nodes
  198. foreach ($aUnreachableObjects as $oObj)
  199. {
  200. $sNodeId = RelationObjectNode::MakeId($oObj);
  201. $oNode = $this->GetNode($sNodeId);
  202. if($oNode)
  203. {
  204. $oNode->SetProperty('is_reached_allowed', false);
  205. }
  206. else
  207. {
  208. }
  209. }
  210. // Determine the reached nodes
  211. foreach ($this->aSourceNodes as $oSourceNode)
  212. {
  213. $oSourceNode->ReachDown('is_reached', true);
  214. //echo "<h5>After reaching from {$oSourceNode->GetId()}</h5>\n".$this->DumpAsHtmlImage()."<br/>\n";
  215. }
  216. }
  217. /**
  218. * Build the graph upstream
  219. */
  220. public function ComputeRelatedObjectsUp($sRelCode, $iMaxDepth, $bEnableRedundancy)
  221. {
  222. //echo "<h5>Sinks only...</h5>\n".$this->DumpAsHtmlImage()."<br/>\n";
  223. // Build the graph out of the sinks
  224. foreach ($this->aSinkNodes as $oSinkNode)
  225. {
  226. $this->AddRelatedObjects($sRelCode, false, $oSinkNode, $iMaxDepth, $bEnableRedundancy);
  227. //echo "<h5>After processing of {$oSinkNode->GetId()}</h5>\n".$this->DumpAsHtmlImage()."<br/>\n";
  228. }
  229. }
  230. /**
  231. * Recursively find related objects, and add them into the graph
  232. *
  233. * @param string $sRelCode The code of the relation to use for the computation
  234. * @param boolean $bDown The direction: downstream or upstream
  235. * @param array $oObjectNode The node from which to compute the neighbours
  236. * @param int $iMaxDepth
  237. * @param boolean $bEnableReduncancy
  238. *
  239. * @return void
  240. */
  241. protected function AddRelatedObjects($sRelCode, $bDown, $oObjectNode, $iMaxDepth, $bEnableRedundancy)
  242. {
  243. if ($iMaxDepth > 0)
  244. {
  245. if ($oObjectNode instanceof RelationRedundancyNode)
  246. {
  247. // Note: this happens when recursing on an existing part of the graph
  248. // Skip that redundancy node
  249. $aRelatedEdges = $bDown ? $oObjectNode->GetOutgoingEdges() : $oObjectNode->GetIncomingEdges();
  250. foreach ($aRelatedEdges as $oRelatedEdge)
  251. {
  252. $oRelatedNode = $bDown ? $oRelatedEdge->GetSinkNode() : $oRelatedEdge->GetSourceNode();
  253. // Recurse (same depth)
  254. $this->AddRelatedObjects($sRelCode, $bDown, $oRelatedNode, $iMaxDepth, $bEnableRedundancy);
  255. }
  256. }
  257. elseif ($oObjectNode->GetProperty('developped', false))
  258. {
  259. // No need to execute the queries again... just dig into the nodes down/up to iMaxDepth
  260. //
  261. $aRelatedEdges = $bDown ? $oObjectNode->GetOutgoingEdges() : $oObjectNode->GetIncomingEdges();
  262. foreach ($aRelatedEdges as $oRelatedEdge)
  263. {
  264. $oRelatedNode = $bDown ? $oRelatedEdge->GetSinkNode() : $oRelatedEdge->GetSourceNode();
  265. // Recurse (decrement the depth)
  266. $this->AddRelatedObjects($sRelCode, $bDown, $oRelatedNode, $iMaxDepth - 1, $bEnableRedundancy);
  267. }
  268. }
  269. else
  270. {
  271. $oObjectNode->SetProperty('developped', true);
  272. $oObject = $oObjectNode->GetProperty('object');
  273. foreach (MetaModel::EnumRelationQueries(get_class($oObject), $sRelCode, $bDown) as $sDummy => $aQueryInfo)
  274. {
  275. $sQuery = $bDown ? $aQueryInfo['sQueryDown'] : $aQueryInfo['sQueryUp'];
  276. try
  277. {
  278. $oFlt = DBObjectSearch::FromOQL($sQuery);
  279. $oObjSet = new DBObjectSet($oFlt, array(), $oObject->ToArgsForQuery());
  280. $oRelatedObj = $oObjSet->Fetch();
  281. }
  282. catch (Exception $e)
  283. {
  284. $sDirection = $bDown ? 'downstream' : 'upstream';
  285. throw new Exception("Wrong query ($sDirection) for the relation $sRelCode/{$aQueryInfo['sDefinedInClass']}/{$aQueryInfo['sNeighbour']}: ".$e->getMessage());
  286. }
  287. if ($oRelatedObj)
  288. {
  289. do
  290. {
  291. $sObjectRef = RelationObjectNode::MakeId($oRelatedObj);
  292. $oRelatedNode = $this->GetNode($sObjectRef);
  293. if (is_null($oRelatedNode))
  294. {
  295. $oRelatedNode = new RelationObjectNode($this, $oRelatedObj);
  296. }
  297. $oSourceNode = $bDown ? $oObjectNode : $oRelatedNode;
  298. $oSinkNode = $bDown ? $oRelatedNode : $oObjectNode;
  299. if ($bEnableRedundancy)
  300. {
  301. $oRedundancyNode = $this->ComputeRedundancy($sRelCode, $aQueryInfo, $oSourceNode, $oSinkNode);
  302. }
  303. else
  304. {
  305. $oRedundancyNode = null;
  306. }
  307. if (!$oRedundancyNode)
  308. {
  309. // Direct link (otherwise handled by ComputeRedundancy)
  310. $oEdge = new RelationEdge($this, $oSourceNode, $oSinkNode);
  311. }
  312. // Recurse
  313. $this->AddRelatedObjects($sRelCode, $bDown, $oRelatedNode, $iMaxDepth - 1, $bEnableRedundancy);
  314. }
  315. while ($oRelatedObj = $oObjSet->Fetch());
  316. }
  317. }
  318. }
  319. }
  320. }
  321. /**
  322. * Determine if there is a redundancy (or use the existing one) and add the corresponding nodes/edges
  323. */
  324. protected function ComputeRedundancy($sRelCode, $aQueryInfo, $oFromNode, $oToNode)
  325. {
  326. $oRedundancyNode = null;
  327. $oObject = $oToNode->GetProperty('object');
  328. if ($this->IsRedundancyEnabled($sRelCode, $aQueryInfo, $oToNode))
  329. {
  330. $sId = RelationRedundancyNode::MakeId($sRelCode, $aQueryInfo['sNeighbour'], $oToNode->GetProperty('object'));
  331. $oRedundancyNode = $this->GetNode($sId);
  332. if (is_null($oRedundancyNode))
  333. {
  334. // Get the upper neighbours
  335. $sQuery = $aQueryInfo['sQueryUp'];
  336. try
  337. {
  338. $oFlt = DBObjectSearch::FromOQL($sQuery);
  339. $oObjSet = new DBObjectSet($oFlt, array(), $oObject->ToArgsForQuery());
  340. $iCount = $oObjSet->Count();
  341. }
  342. catch (Exception $e)
  343. {
  344. throw new Exception("Wrong query (upstream) for the relation $sRelCode/{$aQueryInfo['sDefinedInClass']}/{$aQueryInfo['sNeighbour']}: ".$e->getMessage());
  345. }
  346. $iMinUp = $this->GetRedundancyMinUp($sRelCode, $aQueryInfo, $oToNode, $iCount);
  347. $fThreshold = max(0, $iCount - $iMinUp);
  348. $oRedundancyNode = new RelationRedundancyNode($this, $sId, $iMinUp, $fThreshold);
  349. new RelationEdge($this, $oRedundancyNode, $oToNode);
  350. while ($oUpperObj = $oObjSet->Fetch())
  351. {
  352. $sObjectRef = RelationObjectNode::MakeId($oUpperObj);
  353. $oUpperNode = $this->GetNode($sObjectRef);
  354. if (is_null($oUpperNode))
  355. {
  356. $oUpperNode = new RelationObjectNode($this, $oUpperObj);
  357. }
  358. new RelationEdge($this, $oUpperNode, $oRedundancyNode);
  359. }
  360. }
  361. }
  362. return $oRedundancyNode;
  363. }
  364. /**
  365. * Helper to determine the redundancy setting on a given relation
  366. */
  367. protected function IsRedundancyEnabled($sRelCode, $aQueryInfo, $oToNode)
  368. {
  369. $bRet = false;
  370. $oToObject = $oToNode->GetProperty('object');
  371. $oRedundancyAttDef = $this->FindRedundancyAttribute($sRelCode, $aQueryInfo, get_class($oToObject));
  372. if ($oRedundancyAttDef)
  373. {
  374. $sValue = $oToObject->Get($oRedundancyAttDef->GetCode());
  375. $bRet = $oRedundancyAttDef->IsEnabled($sValue);
  376. }
  377. return $bRet;
  378. }
  379. /**
  380. * Helper to determine the redundancy threshold, given the count of objects upstream
  381. */
  382. protected function GetRedundancyMinUp($sRelCode, $aQueryInfo, $oToNode, $iUpstreamObjects)
  383. {
  384. $iMinUp = 0;
  385. $oToObject = $oToNode->GetProperty('object');
  386. $oRedundancyAttDef = $this->FindRedundancyAttribute($sRelCode, $aQueryInfo, get_class($oToObject));
  387. if ($oRedundancyAttDef)
  388. {
  389. $sValue = $oToObject->Get($oRedundancyAttDef->GetCode());
  390. if ($oRedundancyAttDef->GetMinUpType($sValue) == 'count')
  391. {
  392. $iMinUp = $oRedundancyAttDef->GetMinUpValue($sValue);
  393. }
  394. else
  395. {
  396. $iMinUp = $iUpstreamObjects * $oRedundancyAttDef->GetMinUpValue($sValue) / 100;
  397. }
  398. }
  399. return $iMinUp;
  400. }
  401. /**
  402. * Helper to search for the redundancy attribute
  403. */
  404. protected function FindRedundancyAttribute($sRelCode, $aQueryInfo, $sClass)
  405. {
  406. $oRet = null;
  407. foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  408. {
  409. if ($oAttDef instanceof AttributeRedundancySettings)
  410. {
  411. if ($oAttDef->Get('relation_code') == $sRelCode)
  412. {
  413. if ($oAttDef->Get('neighbour_id') == $aQueryInfo['sNeighbour'])
  414. {
  415. $oRet = $oAttDef;
  416. break;
  417. }
  418. }
  419. }
  420. }
  421. return $oRet;
  422. }
  423. /**
  424. * Get the objects referenced by the graph as a hash array: 'class' => array of objects
  425. * @return Ambigous <multitype:multitype: , unknown>
  426. */
  427. public function GetObjectsByClass()
  428. {
  429. $aResults = array();
  430. $oIterator = new RelationTypeIterator($this, 'Node');
  431. foreach($oIterator as $oNode)
  432. {
  433. $oObj = $oNode->GetProperty('object'); // Some nodes (Redundancy Nodes and Group) do not contain an object
  434. if ($oObj)
  435. {
  436. $sObjClass = get_class($oObj);
  437. if (!array_key_exists($sObjClass, $aResults))
  438. {
  439. $aResults[$sObjClass] = array();
  440. }
  441. $aResults[$sObjClass][] = $oObj;
  442. }
  443. }
  444. return $aResults;
  445. }
  446. }