displayablegraph.class.inc.php 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  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. * Special kind of Graph for producing some nice output
  20. *
  21. * @copyright Copyright (C) 2015 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. class DisplayableNode extends GraphNode
  25. {
  26. public $x;
  27. public $y;
  28. /**
  29. * Create a new node inside a graph
  30. * @param SimpleGraph $oGraph
  31. * @param string $sId The unique identifier of this node inside the graph
  32. * @param number $x Horizontal position
  33. * @param number $y Vertical position
  34. */
  35. public function __construct(SimpleGraph $oGraph, $sId, $x = 0, $y = 0)
  36. {
  37. parent::__construct($oGraph, $sId);
  38. $this->x = $x;
  39. $this->y = $y;
  40. $this->bFiltered = false;
  41. }
  42. public function GetIconURL()
  43. {
  44. return $this->GetProperty('icon_url', '');
  45. }
  46. public function GetLabel()
  47. {
  48. return $this->GetProperty('label', $this->sId);
  49. }
  50. public function GetWidth()
  51. {
  52. return max(32, 5*strlen($this->GetProperty('label'))); // approximation of the text's bounding box
  53. }
  54. public function GetHeight()
  55. {
  56. return 32;
  57. }
  58. public function Distance2(DisplayableNode $oNode)
  59. {
  60. $dx = $this->x - $oNode->x;
  61. $dy = $this->y - $oNode->y;
  62. $d2 = $dx*$dx + $dy*$dy - $this->GetHeight()*$this->GetHeight();
  63. if ($d2 < 40)
  64. {
  65. $d2 = 40;
  66. }
  67. return $d2;
  68. }
  69. public function Distance(DisplayableNode $oNode)
  70. {
  71. return sqrt($this->Distance2($oNode));
  72. }
  73. public function GetForRaphael()
  74. {
  75. $aNode = array();
  76. $aNode['shape'] = 'icon';
  77. $aNode['icon_url'] = $this->GetIconURL();
  78. $aNode['width'] = 32;
  79. $aNode['source'] = ($this->GetProperty('source') == true);
  80. $aNode['obj_class'] = get_class($this->GetProperty('object'));
  81. $aNode['obj_key'] = $this->GetProperty('object')->GetKey();
  82. $aNode['sink'] = ($this->GetProperty('sink') == true);
  83. $aNode['x'] = $this->x;
  84. $aNode['y']= $this->y;
  85. $aNode['label'] = $this->GetLabel();
  86. $aNode['id'] = $this->GetId();
  87. $fOpacity = ($this->GetProperty('is_reached') ? 1 : 0.4);
  88. $aNode['icon_attr'] = array('opacity' => $fOpacity);
  89. $aNode['text_attr'] = array('opacity' => $fOpacity);
  90. return $aNode;
  91. }
  92. public function RenderAsPDF(TCPDF $oPdf, DisplayableGraph $oGraph, $fScale)
  93. {
  94. $Alpha = 1.0;
  95. $oPdf->SetFillColor(200, 200, 200);
  96. $oPdf->setAlpha(1);
  97. $sIconUrl = $this->GetProperty('icon_url');
  98. $sIconPath = str_replace(utils::GetAbsoluteUrlModulesRoot(), APPROOT.'env-production/', $sIconUrl);
  99. if ($this->GetProperty('source'))
  100. {
  101. $oPdf->SetLineStyle(array('width' => 2*$fScale, 'cap' => 'round', 'join' => 'miter', 'dash' => 0, 'color' => array(204, 51, 51)));
  102. $oPdf->Circle($this->x * $fScale, $this->y * $fScale, 16 * 1.25 * $fScale, 0, 360, 'D');
  103. }
  104. else if ($this->GetProperty('sink'))
  105. {
  106. $oPdf->SetLineStyle(array('width' => 2*$fScale, 'cap' => 'round', 'join' => 'miter', 'dash' => 0, 'color' => array(51, 51, 204)));
  107. $oPdf->Circle($this->x * $fScale, $this->y * $fScale, 16 * 1.25 * $fScale, 0, 360, 'D');
  108. }
  109. if (!$this->GetProperty('is_reached'))
  110. {
  111. $sTempImageName = $this->CreateWhiteIcon($oGraph, $sIconPath);
  112. if ($sTempImageName != null)
  113. {
  114. $oPdf->Image($sTempImageName, ($this->x - 16)*$fScale, ($this->y - 16)*$fScale, 32*$fScale, 32*$fScale, 'PNG');
  115. }
  116. $Alpha = 0.4;
  117. $oPdf->setAlpha($Alpha);
  118. }
  119. $oPdf->Image($sIconPath, ($this->x - 16)*$fScale, ($this->y - 16)*$fScale, 32*$fScale, 32*$fScale);
  120. $oPdf->SetFont('dejavusans', '', 24 * $fScale, '', true);
  121. $width = $oPdf->GetStringWidth($this->GetProperty('label'));
  122. $height = $oPdf->GetStringHeight(1000, $this->GetProperty('label'));
  123. $oPdf->setAlpha(0.6 * $Alpha);
  124. $oPdf->SetFillColor(255, 255, 255);
  125. $oPdf->SetDrawColor(255, 255, 255);
  126. $oPdf->Rect($this->x*$fScale - $width/2, ($this->y + 18)*$fScale, $width, $height, 'DF');
  127. $oPdf->setAlpha($Alpha);
  128. $oPdf->SetTextColor(0, 0, 0);
  129. $oPdf->Text($this->x*$fScale - $width/2, ($this->y + 18)*$fScale, $this->GetProperty('label'));
  130. }
  131. /**
  132. * Create a "whitened" version of the icon (retaining the transparency) to be used a background for masking the underlying lines
  133. * @param string $sIconFile The path to the file containing the icon
  134. * @return NULL|string The path to a temporary file containing the white version of the icon
  135. */
  136. protected function CreateWhiteIcon(DisplayableGraph $oGraph, $sIconFile)
  137. {
  138. $aInfo = getimagesize($sIconFile);
  139. $im = null;
  140. switch($aInfo['mime'])
  141. {
  142. case 'image/png':
  143. if (function_exists('imagecreatefrompng'))
  144. {
  145. $im = imagecreatefrompng($sIconFile);
  146. }
  147. break;
  148. case 'image/gif':
  149. if (function_exists('imagecreatefromgif'))
  150. {
  151. $im = imagecreatefromgif($sIconFile);
  152. }
  153. break;
  154. case 'image/jpeg':
  155. case 'image/jpg':
  156. if (function_exists('imagecreatefromjpeg'))
  157. {
  158. $im = imagecreatefromjpeg($sIconFile);
  159. }
  160. break;
  161. default:
  162. return null;
  163. }
  164. if($im && imagefilter($im, IMG_FILTER_COLORIZE, 255, 255, 255))
  165. {
  166. $sTempImageName = $oGraph->GetTempImageName();
  167. imagesavealpha($im, true);
  168. imagepng($im, $sTempImageName);
  169. imagedestroy($im);
  170. return $sTempImageName;
  171. }
  172. else
  173. {
  174. return null;
  175. }
  176. }
  177. /**
  178. * Group together (as a special kind of nodes) all the similar neighbours of the current node
  179. * @param DisplayableGraph $oGraph
  180. * @param int $iThresholdCount
  181. * @param boolean $bDirectionUp
  182. * @param boolean $bDirectionDown
  183. */
  184. public function GroupSimilarNeighbours(DisplayableGraph $oGraph, $iThresholdCount, $bDirectionUp = false, $bDirectionDown = true)
  185. {
  186. //echo "<p>".$this->GetProperty('label').":</p>";
  187. if ($this->GetProperty('grouped') === true) return;
  188. $this->SetProperty('grouped', true);
  189. if ($bDirectionDown)
  190. {
  191. $aNodesPerClass = array();
  192. foreach($this->GetOutgoingEdges() as $oEdge)
  193. {
  194. $oNode = $oEdge->GetSinkNode();
  195. if ($oNode->GetProperty('class') !== null)
  196. {
  197. $sClass = $oNode->GetProperty('class');
  198. if (($sClass!== null) && (!array_key_exists($sClass, $aNodesPerClass)))
  199. {
  200. $aNodesPerClass[$sClass] = array(
  201. 'reached' => array(
  202. 'count' => 0,
  203. 'nodes' => array(),
  204. 'icon_url' => $oNode->GetProperty('icon_url'),
  205. ),
  206. 'not_reached' => array(
  207. 'count' => 0,
  208. 'nodes' => array(),
  209. 'icon_url' => $oNode->GetProperty('icon_url'),
  210. )
  211. );
  212. }
  213. $sKey = $oNode->GetProperty('is_reached') ? 'reached' : 'not_reached';
  214. if (!array_key_exists($oNode->GetId(), $aNodesPerClass[$sClass][$sKey]['nodes']))
  215. {
  216. $aNodesPerClass[$sClass][$sKey]['nodes'][$oNode->GetId()] = $oNode;
  217. $aNodesPerClass[$sClass][$sKey]['count'] += (int)$oNode->GetProperty('count', 1);
  218. //echo "<p>New count: ".$aNodesPerClass[$sClass][$sKey]['count']."</p>";
  219. }
  220. }
  221. else
  222. {
  223. $oNode->GroupSimilarNeighbours($oGraph, $iThresholdCount, $bDirectionUp, $bDirectionDown);
  224. }
  225. }
  226. foreach($aNodesPerClass as $sClass => $aDefs)
  227. {
  228. foreach($aDefs as $sStatus => $aGroupProps)
  229. {
  230. //echo "<p>$sClass/$sStatus: {$aGroupProps['count']} object(s), actually: ".count($aGroupProps['nodes'])."</p>";
  231. if (count($aGroupProps['nodes']) >= $iThresholdCount)
  232. {
  233. $oNewNode = new DisplayableGroupNode($oGraph, $this->GetId().'::'.$sClass);
  234. $oNewNode->SetProperty('label', 'x'.$aGroupProps['count']);
  235. $oNewNode->SetProperty('icon_url', $aGroupProps['icon_url']);
  236. $oNewNode->SetProperty('class', $sClass);
  237. $oNewNode->SetProperty('is_reached', ($sStatus == 'reached'));
  238. $oNewNode->SetProperty('count', $aGroupProps['count']);
  239. //$oNewNode->SetProperty('grouped', true);
  240. $oIncomingEdge = new DisplayableEdge($oGraph, $this->GetId().'-'.$oNewNode->GetId(), $this, $oNewNode);
  241. foreach($aGroupProps['nodes'] as $oNode)
  242. {
  243. foreach($oNode->GetIncomingEdges() as $oEdge)
  244. {
  245. if ($oEdge->GetSourceNode()->GetId() !== $this->GetId())
  246. {
  247. $oNewEdge = new DisplayableEdge($oGraph, $oEdge->GetId().'::'.$sClass, $oEdge->GetSourceNode(), $oNewNode);
  248. }
  249. }
  250. foreach($oNode->GetOutgoingEdges() as $oEdge)
  251. {
  252. $aOutgoing[] = $oEdge->GetSinkNode();
  253. try
  254. {
  255. $oNewEdge = new DisplayableEdge($oGraph, $oEdge->GetId().'::'.$sClass, $oNewNode, $oEdge->GetSinkNode());
  256. }
  257. catch(Exception $e)
  258. {
  259. // ignore this edge
  260. }
  261. }
  262. if ($oGraph->GetNode($oNode->GetId()))
  263. {
  264. $oGraph->_RemoveNode($oNode);
  265. $oNewNode->AddObject($oNode->GetProperty('object'));
  266. }
  267. }
  268. $oNewNode->GroupSimilarNeighbours($oGraph, $iThresholdCount, $bDirectionUp, $bDirectionDown);
  269. }
  270. else
  271. {
  272. foreach($aGroupProps['nodes'] as $oNode)
  273. {
  274. $oNode->GroupSimilarNeighbours($oGraph, $iThresholdCount, $bDirectionUp, $bDirectionDown);
  275. }
  276. }
  277. }
  278. }
  279. }
  280. }
  281. }
  282. class DisplayableRedundancyNode extends DisplayableNode
  283. {
  284. public function GetWidth()
  285. {
  286. return 24;
  287. }
  288. public function GetForRaphael()
  289. {
  290. $aNode = array();
  291. $aNode['shape'] = 'disc';
  292. $aNode['icon_url'] = $this->GetIconURL();
  293. $aNode['source'] = ($this->GetProperty('source') == true);
  294. $aNode['width'] = $this->GetWidth();
  295. $aNode['x'] = $this->x;
  296. $aNode['y']= $this->y;
  297. $aNode['label'] = $this->GetLabel();
  298. $aNode['id'] = $this->GetId();
  299. $fDiscOpacity = ($this->GetProperty('is_reached') ? 1 : 0.2);
  300. $aNode['disc_attr'] = array('stroke-width' => 3, 'stroke' => '#000', 'fill' => '#c33', 'opacity' => $fDiscOpacity);
  301. $fTextOpacity = ($this->GetProperty('is_reached') ? 1 : 0.4);
  302. $aNode['text_attr'] = array('fill' => '#fff', 'opacity' => $fTextOpacity);
  303. return $aNode;
  304. }
  305. public function RenderAsPDF(TCPDF $oPdf, DisplayableGraph $oGraph, $fScale)
  306. {
  307. $oPdf->SetAlpha(1);
  308. $oPdf->SetFillColor(200, 0, 0);
  309. $oPdf->SetDrawColor(0, 0, 0);
  310. $oPdf->Circle($this->x*$fScale, $this->y*$fScale, 16*$fScale, 0, 360, 'DF');
  311. $oPdf->SetTextColor(255, 255, 255);
  312. $oPdf->SetFont('dejavusans', '', 28 * $fScale, '', true);
  313. $sLabel = (string)$this->GetProperty('label');
  314. $width = $oPdf->GetStringWidth($sLabel, 'dejavusans', 'B', 24*$fScale);
  315. $height = $oPdf->GetStringHeight(1000, $sLabel);
  316. $xPos = (float)$this->x*$fScale - $width/2;
  317. $yPos = (float)$this->y*$fScale - $height/2;
  318. $oPdf->SetXY(($this->x - 16)*$fScale, ($this->y - 16)*$fScale);
  319. $oPdf->Cell(32*$fScale, 32*$fScale, $sLabel, 0, 0, 'C', 0, '', 0, false, 'T', 'C');
  320. }
  321. /**
  322. * @see DisplayableNode::GroupSimilarNeighbours()
  323. */
  324. public function GroupSimilarNeighbours(DisplayableGraph $oGraph, $iThresholdCount, $bDirectionUp = false, $bDirectionDown = true)
  325. {
  326. parent::GroupSimilarNeighbours($oGraph, $iThresholdCount, $bDirectionUp, $bDirectionDown);
  327. if ($bDirectionUp)
  328. {
  329. $aNodesPerClass = array();
  330. foreach($this->GetIncomingEdges() as $oEdge)
  331. {
  332. $oNode = $oEdge->GetSourceNode();
  333. if (($oNode->GetProperty('class') !== null) && (!$oNode->GetProperty('is_reached')))
  334. {
  335. $sClass = $oNode->GetProperty('class');
  336. if (!array_key_exists($sClass, $aNodesPerClass))
  337. {
  338. $aNodesPerClass[$sClass] = array('reached' => array(), 'not_reached' => array());
  339. }
  340. $aNodesPerClass[$sClass][$oNode->GetProperty('is_reached') ? 'reached' : 'not_reached'][] = $oNode;
  341. }
  342. else
  343. {
  344. //$oNode->GroupSimilarNeighbours($oGraph, $iThresholdCount, $bDirectionUp, $bDirectionDown);
  345. }
  346. }
  347. foreach($aNodesPerClass as $sClass => $aDefs)
  348. {
  349. foreach($aDefs as $sStatus => $aNodes)
  350. {
  351. //echo "<p>".$this->GetId().' has '.count($aNodes)." neighbours of class $sClass in status $sStatus\n";
  352. if (count($aNodes) >= $iThresholdCount)
  353. {
  354. $oNewNode = new DisplayableGroupNode($oGraph, '-'.$this->GetId().'::'.$sClass.'/'.$sStatus);
  355. $oNewNode->SetProperty('label', 'x'.count($aNodes));
  356. $oNewNode->SetProperty('icon_url', $aNodes[0]->GetProperty('icon_url'));
  357. $oNewNode->SetProperty('is_reached', $aNodes[0]->GetProperty('is_reached'));
  358. $oOutgoingEdge = new DisplayableEdge($oGraph, '-'.$this->GetId().'-'.$oNewNode->GetId().'/'.$sStatus, $oNewNode, $this);
  359. foreach($aNodes as $oNode)
  360. {
  361. foreach($oNode->GetIncomingEdges() as $oEdge)
  362. {
  363. $oNewEdge = new DisplayableEdge($oGraph, '-'.$oEdge->GetId().'::'.$sClass, $oEdge->GetSourceNode(), $oNewNode);
  364. }
  365. foreach($oNode->GetOutgoingEdges() as $oEdge)
  366. {
  367. if ($oEdge->GetSinkNode()->GetId() !== $this->GetId())
  368. {
  369. $aOutgoing[] = $oEdge->GetSinkNode();
  370. $oNewEdge = new DisplayableEdge($oGraph, '-'.$oEdge->GetId().'::'.$sClass.'/'.$sStatus, $oNewNode, $oEdge->GetSinkNode());
  371. }
  372. }
  373. //echo "<p>Replacing ".$oNode->GetId().' by '.$oNewNode->GetId()."\n";
  374. $oGraph->_RemoveNode($oNode);
  375. $oNewNode->AddObject($oNode->GetProperty('object'));
  376. }
  377. //$oNewNode->GroupSimilarNeighbours($oGraph, $iThresholdCount, $bDirectionUp, $bDirectionDown);
  378. }
  379. else
  380. {
  381. foreach($aNodes as $oNode)
  382. {
  383. //$oNode->GroupSimilarNeighbours($oGraph, $iThresholdCount, $bDirectionUp, $bDirectionDown);
  384. }
  385. }
  386. }
  387. }
  388. }
  389. }
  390. }
  391. class DisplayableEdge extends GraphEdge
  392. {
  393. public function RenderAsPDF(TCPDF $oPdf, DisplayableGraph $oGraph, $fScale)
  394. {
  395. $xStart = $this->GetSourceNode()->x * $fScale;
  396. $yStart = $this->GetSourceNode()->y * $fScale;
  397. $xEnd = $this->GetSinkNode()->x * $fScale;
  398. $yEnd = $this->GetSinkNode()->y * $fScale;
  399. $bReached = ($this->GetSourceNode()->GetProperty('is_reached') && $this->GetSinkNode()->GetProperty('is_reached'));
  400. $oPdf->setAlpha(1);
  401. if ($bReached)
  402. {
  403. $aColor = array(100, 100, 100);
  404. }
  405. else
  406. {
  407. $aColor = array(200, 200, 200);
  408. }
  409. $oPdf->SetLineStyle(array('width' => 2*$fScale, 'cap' => 'round', 'join' => 'miter', 'dash' => 0, 'color' => $aColor));
  410. $oPdf->Line($xStart, $yStart, $xEnd, $yEnd);
  411. $vx = $xEnd - $xStart;
  412. $vy = $yEnd - $yStart;
  413. $l = sqrt($vx*$vx + $vy*$vy);
  414. $vx = $vx / $l;
  415. $vy = $vy / $l;
  416. $ux = -$vy;
  417. $uy = $vx;
  418. $lPos = max($l/2, $l - 40*$fScale);
  419. $iArrowSize = 5*$fScale;
  420. $x = $xStart + $lPos * $vx;
  421. $y = $yStart + $lPos * $vy;
  422. $oPdf->Line($x, $y, $x + $iArrowSize * ($ux-$vx), $y + $iArrowSize * ($uy-$vy));
  423. $oPdf->Line($x, $y, $x - $iArrowSize * ($ux+$vx), $y - $iArrowSize * ($uy+$vy));
  424. }
  425. }
  426. class DisplayableGroupNode extends DisplayableNode
  427. {
  428. protected $aObjects;
  429. public function __construct(SimpleGraph $oGraph, $sId, $x = 0, $y = 0)
  430. {
  431. parent::__construct($oGraph, $sId, $x, $y);
  432. $this->aObjects = array();
  433. }
  434. public function AddObject(DBObject $oObj)
  435. {
  436. $this->aObjects[$oObj->GetKey()] = $oObj;
  437. }
  438. public function GetObjects()
  439. {
  440. return $this->aObjects;
  441. }
  442. public function GetWidth()
  443. {
  444. return 50;
  445. }
  446. public function GetForRaphael()
  447. {
  448. $aNode = array();
  449. $aNode['shape'] = 'group';
  450. $aNode['icon_url'] = $this->GetIconURL();
  451. $aNode['source'] = ($this->GetProperty('source') == true);
  452. $aNode['width'] = $this->GetWidth();
  453. $aNode['x'] = $this->x;
  454. $aNode['y']= $this->y;
  455. $aNode['label'] = $this->GetLabel();
  456. $aNode['id'] = $this->GetId();
  457. $aNode['group_index'] = $this->GetProperty('group_index'); // if supplied
  458. $fDiscOpacity = ($this->GetProperty('is_reached') ? 1 : 0.2);
  459. $fTextOpacity = ($this->GetProperty('is_reached') ? 1 : 0.4);
  460. $aNode['icon_attr'] = array('opacity' => $fTextOpacity);
  461. $aNode['disc_attr'] = array('stroke-width' => 3, 'stroke' => '#000', 'fill' => '#fff', 'opacity' => $fDiscOpacity);
  462. $aNode['text_attr'] = array('fill' => '#000', 'opacity' => $fTextOpacity);
  463. return $aNode;
  464. }
  465. public function RenderAsPDF(TCPDF $oPdf, DisplayableGraph $oGraph, $fScale)
  466. {
  467. $bReached = $this->GetProperty('is_reached');
  468. $oPdf->SetFillColor(255, 255, 255);
  469. if ($bReached)
  470. {
  471. $aBorderColor = array(100, 100, 100);
  472. }
  473. else
  474. {
  475. $aBorderColor = array(200, 200, 200);
  476. }
  477. $oPdf->SetLineStyle(array('width' => 2*$fScale, 'cap' => 'round', 'join' => 'miter', 'dash' => 0, 'color' => $aBorderColor));
  478. $sIconUrl = $this->GetProperty('icon_url');
  479. $sIconPath = str_replace(utils::GetAbsoluteUrlModulesRoot(), APPROOT.'env-production/', $sIconUrl);
  480. $oPdf->SetAlpha(1);
  481. $oPdf->Circle($this->x*$fScale, $this->y*$fScale, $this->GetWidth() / 2 * $fScale, 0, 360, 'DF');
  482. if ($bReached)
  483. {
  484. $oPdf->SetAlpha(1);
  485. }
  486. else
  487. {
  488. $oPdf->SetAlpha(0.4);
  489. }
  490. $oPdf->Image($sIconPath, ($this->x - 17)*$fScale, ($this->y - 17)*$fScale, 16*$fScale, 16*$fScale);
  491. $oPdf->Image($sIconPath, ($this->x + 1)*$fScale, ($this->y - 17)*$fScale, 16*$fScale, 16*$fScale);
  492. $oPdf->Image($sIconPath, ($this->x -8)*$fScale, ($this->y +1)*$fScale, 16*$fScale, 16*$fScale);
  493. $oPdf->SetFont('dejavusans', '', 24 * $fScale, '', true);
  494. $width = $oPdf->GetStringWidth($this->GetProperty('label'));
  495. $oPdf->SetTextColor(0, 0, 0);
  496. $oPdf->Text($this->x*$fScale - $width/2, ($this->y + 25)*$fScale, $this->GetProperty('label'));
  497. }
  498. }
  499. /**
  500. * A Graph that can be displayed interactively using Raphael JS or saved as a PDF document
  501. */
  502. class DisplayableGraph extends SimpleGraph
  503. {
  504. protected $sDirection;
  505. protected $aTempImages;
  506. public function __construct()
  507. {
  508. parent::__construct();
  509. $this->aTempImages = array();
  510. }
  511. public function GetTempImageName()
  512. {
  513. $sNewTempName = tempnam(APPROOT.'data', 'img-');
  514. $this->aTempImages[] = $sNewTempName;
  515. return $sNewTempName;
  516. }
  517. public function __destruct()
  518. {
  519. foreach($this->aTempImages as $sTempFile)
  520. {
  521. @unlink($sTempFile);
  522. }
  523. }
  524. /**
  525. * Build a DisplayableGraph from a RelationGraph
  526. * @param RelationGraph $oGraph
  527. * @param number $iGroupingThreshold
  528. * @param string $bDirectionDown
  529. * @return DisplayableGraph
  530. */
  531. public static function FromRelationGraph(RelationGraph $oGraph, $iGroupingThreshold = 20, $bDirectionDown = true)
  532. {
  533. $oNewGraph = new DisplayableGraph();
  534. $oNodesIter = new RelationTypeIterator($oGraph, 'Node');
  535. foreach($oNodesIter as $oNode)
  536. {
  537. switch(get_class($oNode))
  538. {
  539. case 'RelationObjectNode':
  540. $oNewNode = new DisplayableNode($oNewGraph, $oNode->GetId(), 0, 0);
  541. if ($oNode->GetProperty('source'))
  542. {
  543. $oNewNode->SetProperty('source', true);
  544. }
  545. if ($oNode->GetProperty('sink'))
  546. {
  547. $oNewNode->SetProperty('sink', true);
  548. }
  549. $oObj = $oNode->GetProperty('object');
  550. $oNewNode->SetProperty('class', get_class($oObj));
  551. $oNewNode->SetProperty('object', $oObj);
  552. $oNewNode->SetProperty('icon_url', $oObj->GetIcon(false));
  553. $oNewNode->SetProperty('label', $oObj->GetRawName());
  554. $oNewNode->SetProperty('is_reached', $bDirectionDown ? $oNode->GetProperty('is_reached') : true); // When going "up" is_reached does not matter
  555. $oNewNode->SetProperty('developped', $oNode->GetProperty('developped'));
  556. break;
  557. default:
  558. $oNewNode = new DisplayableRedundancyNode($oNewGraph, $oNode->GetId(), 0, 0);
  559. $oNewNode->SetProperty('label', $oNode->GetProperty('min_up'));
  560. $oNewNode->SetProperty('is_reached', true);
  561. }
  562. }
  563. $oEdgesIter = new RelationTypeIterator($oGraph, 'Edge');
  564. foreach($oEdgesIter as $oEdge)
  565. {
  566. $oSourceNode = $oNewGraph->GetNode($oEdge->GetSourceNode()->GetId());
  567. $oSinkNode = $oNewGraph->GetNode($oEdge->GetSinkNode()->GetId());
  568. $oNewEdge = new DisplayableEdge($oNewGraph, $oEdge->GetId(), $oSourceNode, $oSinkNode);
  569. }
  570. // Remove duplicate edges between two nodes
  571. $oEdgesIter = new RelationTypeIterator($oNewGraph, 'Edge');
  572. $aEdgeKeys = array();
  573. foreach($oEdgesIter as $oEdge)
  574. {
  575. $sSourceId = $oEdge->GetSourceNode()->GetId();
  576. $sSinkId = $oEdge->GetSinkNode()->GetId();
  577. if ($sSourceId == $sSinkId)
  578. {
  579. // Remove self referring edges
  580. $oNewGraph->_RemoveEdge($oEdge);
  581. }
  582. else
  583. {
  584. $sKey = $sSourceId.'//'.$sSinkId;
  585. if (array_key_exists($sKey, $aEdgeKeys))
  586. {
  587. // Remove duplicate edges
  588. $oNewGraph->_RemoveEdge($oEdge);
  589. }
  590. else
  591. {
  592. $aEdgeKeys[$sKey] = true;
  593. }
  594. }
  595. }
  596. $iNbGrouping = 1;
  597. //for($iter=0; $iter<$iNbGrouping; $iter++)
  598. {
  599. $oNodesIter = new RelationTypeIterator($oNewGraph, 'Node');
  600. foreach($oNodesIter as $oNode)
  601. {
  602. if ($oNode->GetProperty('source'))
  603. {
  604. $oNode->GroupSimilarNeighbours($oNewGraph, $iGroupingThreshold, true, true);
  605. }
  606. }
  607. }
  608. // Remove duplicate edges between two nodes
  609. $oEdgesIter = new RelationTypeIterator($oNewGraph, 'Edge');
  610. $aEdgeKeys = array();
  611. foreach($oEdgesIter as $oEdge)
  612. {
  613. $sSourceId = $oEdge->GetSourceNode()->GetId();
  614. $sSinkId = $oEdge->GetSinkNode()->GetId();
  615. if ($sSourceId == $sSinkId)
  616. {
  617. // Remove self referring edges
  618. $oNewGraph->_RemoveEdge($oEdge);
  619. }
  620. else
  621. {
  622. $sKey = $sSourceId.'//'.$sSinkId;
  623. if (array_key_exists($sKey, $aEdgeKeys))
  624. {
  625. // Remove duplicate edges
  626. $oNewGraph->_RemoveEdge($oEdge);
  627. }
  628. else
  629. {
  630. $aEdgeKeys[$sKey] = true;
  631. }
  632. }
  633. }
  634. return $oNewGraph;
  635. }
  636. /**
  637. * Initializes the positions by rendering using Graphviz in xdot format
  638. * and parsing the output.
  639. * @throws Exception
  640. */
  641. public function InitFromGraphviz()
  642. {
  643. $sDot = $this->DumpAsXDot();
  644. if (strpos($sDot, 'digraph') === false)
  645. {
  646. throw new Exception($sDot);
  647. }
  648. $sDot = preg_replace('/.*label=.*,/', '', $sDot); // Get rid of label lines since they may contain weird characters than can break the split and pattern matching below
  649. $aChunks = explode(";", $sDot);
  650. foreach($aChunks as $sChunk)
  651. {
  652. //echo "<p>$sChunk</p>";
  653. if(preg_match('/"([^"]+)".+pos="([0-9\\.]+),([0-9\\.]+)"/ms', $sChunk, $aMatches))
  654. {
  655. $sId = $aMatches[1];
  656. $xPos = $aMatches[2];
  657. $yPos = $aMatches[3];
  658. $oNode = $this->GetNode($sId);
  659. $oNode->x = (float)$xPos;
  660. $oNode->y = (float)$yPos;
  661. //echo "<p>$sId at $xPos,$yPos</p>";
  662. }
  663. else
  664. {
  665. //echo "<p>No match</p>";
  666. }
  667. }
  668. }
  669. public function GetBoundingBox()
  670. {
  671. $xMin = null;
  672. $xMax = null;
  673. $yMin = null;
  674. $yMax = null;
  675. $oIterator = new RelationTypeIterator($this, 'Node');
  676. foreach($oIterator as $sId => $oNode)
  677. {
  678. if ($xMin === null) // First element in the loop
  679. {
  680. $xMin = $oNode->x - $oNode->GetWidth();
  681. $xMax = $oNode->x + $oNode->GetWidth();
  682. $yMin = $oNode->y - $oNode->GetHeight();
  683. $yMax = $oNode->y + $oNode->GetHeight();
  684. }
  685. else
  686. {
  687. $xMin = min($xMin, $oNode->x - $oNode->GetWidth() / 2);
  688. $xMax = max($xMax, $oNode->x + $oNode->GetWidth() / 2);
  689. $yMin = min($yMin, $oNode->y - $oNode->GetHeight() / 2);
  690. $yMax = max($yMax, $oNode->y + $oNode->GetHeight() / 2);
  691. }
  692. }
  693. return array('xmin' => $xMin, 'xmax' => $xMax, 'ymin' => $yMin, 'ymax' => $yMax);
  694. }
  695. function Translate($dx, $dy)
  696. {
  697. $oIterator = new RelationTypeIterator($this, 'Node');
  698. foreach($oIterator as $sId => $oNode)
  699. {
  700. $oNode->x += $dx;
  701. $oNode->y += $dy;
  702. }
  703. }
  704. public function UpdatePositions($aPositions)
  705. {
  706. foreach($aPositions as $sNodeId => $aPos)
  707. {
  708. $oNode = $this->GetNode($sNodeId);
  709. if ($oNode != null)
  710. {
  711. $oNode->x = $aPos['x'];
  712. $oNode->y = $aPos['y'];
  713. }
  714. }
  715. }
  716. /**
  717. * Renders as a suite of Javascript instructions to display the graph using the simple_graph widget
  718. * @param WebPage $oP
  719. * @param string $sId
  720. * @param string $sExportAsPdfURL
  721. * @param string $sExportAsDocumentURL
  722. * @param string $sDrillDownURL
  723. */
  724. function RenderAsRaphael(WebPage $oP, $sId = null, $sExportAsPdfURL, $sExportAsDocumentURL, $sDrillDownURL)
  725. {
  726. if ($sId == null)
  727. {
  728. $sId = 'graph';
  729. }
  730. $oP->add('<div id="'.$sId.'" class="simple-graph"></div>');
  731. $aParams = array(
  732. 'export_as_pdf' => array('url' => $sExportAsPdfURL, 'label' => Dict::S('UI:Relation:ExportAsPDF')),
  733. 'export_as_document' => array('url' => $sExportAsDocumentURL, 'label' => Dict::S('UI:Relation:ExportAsDocument')),
  734. 'drill_down' => array('url' => $sDrillDownURL, 'label' => Dict::S('UI:Relation:DrillDown')),
  735. 'labels' => array(
  736. 'export_pdf_title' => Dict::S('UI:Relation:PDFExportOptions'),
  737. 'export' => Dict::S('UI:Relation:PDFExportOptions'),
  738. 'cancel' => Dict::S('UI:Button:Cancel'),
  739. ),
  740. 'page_format' => array(
  741. 'label' => Dict::S('UI:Relation:PDFExportPageFormat'),
  742. 'values' => array(
  743. 'A3' => Dict::S('UI:PageFormat_A3'),
  744. 'A4' => Dict::S('UI:PageFormat_A4'),
  745. 'Letter' => Dict::S('UI:PageFormat_Letter'),
  746. ),
  747. ),
  748. 'page_orientation' => array(
  749. 'label' => Dict::S('UI:Relation:PDFExportPageOrientation'),
  750. 'values' => array(
  751. 'P' => Dict::S('UI:PageOrientation_Portrait'),
  752. 'L' => Dict::S('UI:PageOrientation_Landscape'),
  753. ),
  754. ),
  755. );
  756. $oP->add_ready_script("var oGraph = $('#$sId').simple_graph(".json_encode($aParams).");");
  757. $oIterator = new RelationTypeIterator($this, 'Node');
  758. foreach($oIterator as $sId => $oNode)
  759. {
  760. $aNode = $oNode->GetForRaphael();
  761. $sJSNode = json_encode($aNode);
  762. $oP->add_ready_script("oGraph.simple_graph('add_node', $sJSNode);");
  763. }
  764. $oIterator = new RelationTypeIterator($this, 'Edge');
  765. foreach($oIterator as $sId => $oEdge)
  766. {
  767. $aEdge = array();
  768. $aEdge['id'] = $oEdge->GetId();
  769. $aEdge['source_node_id'] = $oEdge->GetSourceNode()->GetId();
  770. $aEdge['sink_node_id'] = $oEdge->GetSinkNode()->GetId();
  771. $fOpacity = ($oEdge->GetSinkNode()->GetProperty('is_reached') && $oEdge->GetSourceNode()->GetProperty('is_reached') ? 1 : 0.2);
  772. $aEdge['attr'] = array('opacity' => $fOpacity, 'stroke' => '#000');
  773. $sJSEdge = json_encode($aEdge);
  774. $oP->add_ready_script("oGraph.simple_graph('add_edge', $sJSEdge);");
  775. }
  776. $oP->add_ready_script("oGraph.simple_graph('draw');");
  777. }
  778. /**
  779. * Renders as JSON string suitable for loading into the simple_graph widget
  780. */
  781. function GetAsJSON()
  782. {
  783. $aData = array('nodes' => array(), 'edges' => array());
  784. $iGroupIdx = 0;
  785. $oIterator = new RelationTypeIterator($this, 'Node');
  786. foreach($oIterator as $sId => $oNode)
  787. {
  788. if ($oNode instanceof DisplayableGroupNode)
  789. {
  790. $aGroups[] = $oNode->GetObjects();
  791. $oNode->SetProperty('group_index', $iGroupIdx);
  792. $iGroupIdx++;
  793. }
  794. $aData['nodes'][] = $oNode->GetForRaphael();
  795. }
  796. $oIterator = new RelationTypeIterator($this, 'Edge');
  797. foreach($oIterator as $sId => $oEdge)
  798. {
  799. $aEdge = array();
  800. $aEdge['id'] = $oEdge->GetId();
  801. $aEdge['source_node_id'] = $oEdge->GetSourceNode()->GetId();
  802. $aEdge['sink_node_id'] = $oEdge->GetSinkNode()->GetId();
  803. $fOpacity = ($oEdge->GetSinkNode()->GetProperty('is_reached') && $oEdge->GetSourceNode()->GetProperty('is_reached') ? 1 : 0.2);
  804. $aEdge['attr'] = array('opacity' => $fOpacity, 'stroke' => '#000');
  805. $aData['edges'][] = $aEdge;
  806. }
  807. return json_encode($aData);
  808. }
  809. /**
  810. * Renders the graph in a PDF document: centered in the current page
  811. * @param PDFPage $oPage The PDFPage representing the PDF document to draw into
  812. * @param string $sComments An optional comment to display next to the graph (HTML entities will be escaped, \n replaced by <br/>)
  813. * @param float $xMin Left coordinate of the bounding box to display the graph
  814. * @param float $xMax Right coordinate of the bounding box to display the graph
  815. * @param float $yMin Top coordinate of the bounding box to display the graph
  816. * @param float $yMax Bottom coordinate of the bounding box to display the graph
  817. */
  818. function RenderAsPDF(PDFPage $oPage, $sComments = '', $xMin = -1, $xMax = -1, $yMin = -1, $yMax = -1)
  819. {
  820. $oPdf = $oPage->get_tcpdf();
  821. $aBB = $this->GetBoundingBox();
  822. $this->Translate(-$aBB['xmin'], -$aBB['ymin']);
  823. $aMargins = $oPdf->getMargins();
  824. if ($xMin == -1)
  825. {
  826. $xMin = $aMargins['left'];
  827. }
  828. if ($xMax == -1)
  829. {
  830. $xMax = $oPdf->getPageWidth() - $aMargins['right'];
  831. }
  832. if ($yMin == -1)
  833. {
  834. $yMin = $aMargins['top'];
  835. }
  836. if ($yMax == -1)
  837. {
  838. $yMax = $oPdf->getPageHeight() - $aMargins['bottom'];
  839. }
  840. $fBreakMargin = $oPdf->getBreakMargin();
  841. $oPdf->SetAutoPageBreak(false);
  842. $fKeyWidth = $this->RenderKey($oPdf, $sComments, $xMin, $yMin, $xMax, $yMax);
  843. $xMin += + $fKeyWidth;
  844. //$oPdf->Rect($xMin, $yMin, $xMax - $xMin, $yMax - $yMin, 'D', array(), array(225, 225, 225));
  845. $fPageW = $xMax - $xMin;
  846. $fPageH = $yMax - $yMin;
  847. $w = $aBB['xmax'] - $aBB['xmin'];
  848. $h = $aBB['ymax'] - $aBB['ymin'] + 10; // Extra space for the labels which may appear "below" the icons
  849. $fScale = min($fPageW / $w, $fPageH / $h);
  850. $dx = ($fPageW - $fScale * $w) / 2;
  851. $dy = ($fPageH - $fScale * $h) / 2;
  852. $this->Translate(($xMin + $dx)/$fScale, ($yMin + $dy)/$fScale);
  853. $oIterator = new RelationTypeIterator($this, 'Edge');
  854. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  855. foreach($oIterator as $sId => $oEdge)
  856. {
  857. set_time_limit($iLoopTimeLimit);
  858. $oEdge->RenderAsPDF($oPdf, $this, $fScale);
  859. }
  860. $oIterator = new RelationTypeIterator($this, 'Node');
  861. foreach($oIterator as $sId => $oNode)
  862. {
  863. set_time_limit($iLoopTimeLimit);
  864. $oNode->RenderAsPDF($oPdf, $this, $fScale);
  865. }
  866. $oIterator = new RelationTypeIterator($this, 'Node');
  867. $oPdf->SetAutoPageBreak(true, $fBreakMargin);
  868. $oPdf->SetAlpha(1);
  869. }
  870. protected function RenderKey(TCPDF $oPdf, $sComments, $xMin, $yMin, $xMax, $yMax)
  871. {
  872. $oIterator = new RelationTypeIterator($this, 'Node');
  873. $fMaxWidth = max($oPdf->GetStringWidth(Dict::S('UI:Relation:Key')) - 6, $oPdf->GetStringWidth(Dict::S('UI:Relation:Comments')) - 6);
  874. $aClasses = array();
  875. $aIcons = array();
  876. $oPdf->SetFont('dejavusans', '', 8, '', true);
  877. foreach($oIterator as $sId => $oNode)
  878. {
  879. if ($sClass = $oNode->GetProperty('class'))
  880. {
  881. if (!array_key_exists($sClass, $aClasses))
  882. {
  883. $sClassLabel = MetaModel::GetName($sClass);
  884. $width = $oPdf->GetStringWidth($sClassLabel);
  885. $fMaxWidth = max($width, $fMaxWidth);
  886. $aClasses[$sClass] = $sClassLabel;
  887. $sIconUrl = $oNode->GetProperty('icon_url');
  888. $sIconPath = str_replace(utils::GetAbsoluteUrlModulesRoot(), APPROOT.'env-production/', $sIconUrl);
  889. $aIcons[$sClass] = $sIconPath;
  890. }
  891. }
  892. }
  893. $oPdf->SetXY($xMin + 1, $yMin +1);
  894. $yPos = $yMin + 1;
  895. $oPdf->SetFillColor(225, 225, 225);
  896. $oPdf->Cell(7 + $fMaxWidth, 7, Dict::S('UI:Relation:Key'), 0 /* border */, 1 /* ln */, 'C', true /* fill */);
  897. $yPos += 8;
  898. foreach($aClasses as $sClass => $sLabel)
  899. {
  900. $oPdf->SetX($xMin + 7);
  901. $oPdf->Cell(0, 8, $sLabel, 0 /* border */, 1 /* ln */);
  902. $oPdf->Image($aIcons[$sClass], $xMin+1, $yPos, 6, 6);
  903. $yPos += 8;
  904. }
  905. $oPdf->Rect($xMin, $yMin, $fMaxWidth+9, $yPos - $yMin, 'D');
  906. $oPdf->Rect($xMin, $yPos, $fMaxWidth+9, $yMax - $yPos, 'D');
  907. $yPos +=1;
  908. $oPdf->SetXY($xMin + 1, $yPos);
  909. $oPdf->Cell(7 + $fMaxWidth, 7, Dict::S('UI:Relation:Comments'), 0 /* border */, 1 /* ln */, 'C', true /* fill */);
  910. $yPos += 8;
  911. $oPdf->SetX($xMin);
  912. $oPdf->writeHTMLCell(8 + $fMaxWidth, $yMax - $yPos, $xMin, $yPos, '<p>'.str_replace("\n", '<br/>', htmlentities($sComments, ENT_QUOTES, 'UTF-8')).'</p>', 0 /* border */, 1 /* ln */);
  913. return $fMaxWidth + 10;
  914. }
  915. }