displayblock.class.inc.php 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * DisplayBlock and derived class
  18. *
  19. * @author Erwan Taloc <erwan.taloc@combodo.com>
  20. * @author Romain Quetiez <romain.quetiez@combodo.com>
  21. * @author Denis Flaven <denis.flaven@combodo.com>
  22. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  23. */
  24. require_once(APPROOT.'/application/webpage.class.inc.php');
  25. require_once(APPROOT.'/application/utils.inc.php');
  26. /**
  27. * Helper class to manage 'blocks' of HTML pieces that are parts of a page and contain some list of cmdb objects
  28. *
  29. * Each block is actually rendered as a <div></div> tag that can be rendered synchronously
  30. * or as a piece of Javascript/JQuery/Ajax that will get its content from another page (ajax.render.php).
  31. * The list of cmdbObjects to be displayed into the block is defined by a filter
  32. * Right now the type of display is either: list, count, bare_details, details, csv, modify or search
  33. * - list produces a table listing the objects
  34. * - count produces a paragraphs with a sentence saying 'cont' objects found
  35. * - bare_details displays just the details of the attributes of the object (best if only one)
  36. * - details display the full details of each object found using its template (best if only one)
  37. * - csv displays a textarea with the CSV export of the list of objects
  38. * - modify displays the form to modify an object (best if only one)
  39. * - search displays a search form with the criteria of the filter set
  40. */
  41. class DisplayBlock
  42. {
  43. const TAG_BLOCK = 'itopblock';
  44. protected $m_oFilter;
  45. protected $m_sStyle;
  46. protected $m_bAsynchronous;
  47. protected $m_aParams;
  48. protected $m_oSet;
  49. public function __construct(DBObjectSearch $oFilter, $sStyle = 'list', $bAsynchronous = false, $aParams = array(), $oSet = null)
  50. {
  51. $this->m_oFilter = $oFilter;
  52. $this->m_sStyle = $sStyle;
  53. $this->m_bAsynchronous = $bAsynchronous;
  54. $this->m_aParams = $aParams;
  55. $this->m_oSet = $oSet;
  56. }
  57. /**
  58. * Constructs a DisplayBlock object from a DBObjectSet already in memory
  59. * @param $oSet DBObjectSet
  60. * @return DisplayBlock The DisplayBlock object, or null if the creation failed
  61. */
  62. public static function FromObjectSet(DBObjectSet $oSet, $sStyle, $aParams = array())
  63. {
  64. $oDummyFilter = new DBObjectSearch($oSet->GetClass());
  65. $aKeys = array();
  66. while($oObject = $oSet->Fetch())
  67. {
  68. $aKeys[] = $oObject->GetKey();
  69. }
  70. $oSet->Rewind();
  71. $oDummyFilter->AddCondition('id', $aKeys, 'IN');
  72. $oBlock = new DisplayBlock($oDummyFilter, $sStyle, false, $aParams); // DisplayBlocks built this way are synchronous
  73. return $oBlock;
  74. }
  75. /**
  76. * Constructs a DisplayBlock object from an XML template
  77. * @param $sTemplate string The XML template
  78. * @return DisplayBlock The DisplayBlock object, or null if the template is invalid
  79. */
  80. public static function FromTemplate($sTemplate)
  81. {
  82. $iStartPos = stripos($sTemplate, '<'.self::TAG_BLOCK.' ',0);
  83. $iEndPos = stripos($sTemplate, '</'.self::TAG_BLOCK.'>', $iStartPos);
  84. $iEndTag = stripos($sTemplate, '>', $iStartPos);
  85. $aParams = array();
  86. if (($iStartPos === false) || ($iEndPos === false)) return null; // invalid template
  87. $sITopBlock = substr($sTemplate,$iStartPos, $iEndPos-$iStartPos+strlen('</'.self::TAG_BLOCK.'>'));
  88. $sITopData = substr($sTemplate, 1+$iEndTag, $iEndPos - $iEndTag - 1);
  89. $sITopTag = substr($sTemplate, $iStartPos + strlen('<'.self::TAG_BLOCK), $iEndTag - $iStartPos - strlen('<'.self::TAG_BLOCK));
  90. $aMatches = array();
  91. $sBlockClass = "DisplayBlock";
  92. $bAsynchronous = false;
  93. $sBlockType = 'list';
  94. $sEncoding = 'text/serialize';
  95. if (preg_match('/ type="(.*)"/U',$sITopTag, $aMatches))
  96. {
  97. $sBlockType = strtolower($aMatches[1]);
  98. }
  99. if (preg_match('/ asynchronous="(.*)"/U',$sITopTag, $aMatches))
  100. {
  101. $bAsynchronous = (strtolower($aMatches[1]) == 'true');
  102. }
  103. if (preg_match('/ blockclass="(.*)"/U',$sITopTag, $aMatches))
  104. {
  105. $sBlockClass = $aMatches[1];
  106. }
  107. if (preg_match('/ objectclass="(.*)"/U',$sITopTag, $aMatches))
  108. {
  109. $sObjectClass = $aMatches[1];
  110. }
  111. if (preg_match('/ encoding="(.*)"/U',$sITopTag, $aMatches))
  112. {
  113. $sEncoding = strtolower($aMatches[1]);
  114. }
  115. if (preg_match('/ link_attr="(.*)"/U',$sITopTag, $aMatches))
  116. {
  117. // The list to display is a list of links to the specified object
  118. $aParams['link_attr'] = $aMatches[1]; // Name of the Ext. Key that makes this linkage
  119. }
  120. if (preg_match('/ target_attr="(.*)"/U',$sITopTag, $aMatches))
  121. {
  122. // The list to display is a list of links to the specified object
  123. $aParams['target_attr'] = $aMatches[1]; // Name of the Ext. Key that make this linkage
  124. }
  125. if (preg_match('/ object_id="(.*)"/U',$sITopTag, $aMatches))
  126. {
  127. // The list to display is a list of links to the specified object
  128. $aParams['object_id'] = $aMatches[1]; // Id of the object to be linked to
  129. }
  130. // Parameters contains a list of extra parameters for the block
  131. // the syntax is param_name1:value1;param_name2:value2;...
  132. if (preg_match('/ parameters="(.*)"/U',$sITopTag, $aMatches))
  133. {
  134. $sParameters = $aMatches[1];
  135. $aPairs = explode(';', $sParameters);
  136. foreach($aPairs as $sPair)
  137. {
  138. if (preg_match('/(.*)\:(.*)/',$sPair, $aMatches))
  139. {
  140. $aParams[trim($aMatches[1])] = trim($aMatches[2]);
  141. }
  142. }
  143. }
  144. if (!empty($aParams['link_attr']))
  145. {
  146. // Check that all mandatory parameters are present:
  147. if(empty($aParams['object_id']))
  148. {
  149. // if 'links' mode is requested the d of the object to link to must be specified
  150. throw new ApplicationException(Dict::S('UI:Error:MandatoryTemplateParameter_object_id'));
  151. }
  152. if(empty($aParams['target_attr']))
  153. {
  154. // if 'links' mode is requested the id of the object to link to must be specified
  155. throw new ApplicationException(Dict::S('UI:Error:MandatoryTemplateParameter_target_attr'));
  156. }
  157. }
  158. switch($sEncoding)
  159. {
  160. case 'text/serialize':
  161. $oFilter = CMDBSearchFilter::unserialize($sITopData);
  162. break;
  163. case 'text/oql':
  164. $oFilter = CMDBSearchFilter::FromOQL($sITopData);
  165. break;
  166. }
  167. return new $sBlockClass($oFilter, $sBlockType, $bAsynchronous, $aParams);
  168. }
  169. public function Display(WebPage $oPage, $sId, $aExtraParams = array())
  170. {
  171. $oPage->add($this->GetDisplay($oPage, $sId, $aExtraParams));
  172. /*
  173. $aExtraParams = array_merge($aExtraParams, $this->m_aParams);
  174. $aExtraParams['block_id'] = $sId;
  175. if (!$this->m_bAsynchronous)
  176. {
  177. // render now
  178. $oPage->add("<div id=\"$sId\" class=\"display_block\">\n");
  179. $this->RenderContent($oPage, $aExtraParams);
  180. $oPage->add("</div>\n");
  181. }
  182. else
  183. {
  184. // render it as an Ajax (asynchronous) call
  185. $sFilter = $this->m_oFilter->serialize();
  186. $oPage->add("<div id=\"$sId\" class=\"display_block loading\">\n");
  187. $oPage->p("<img src=\"../images/indicator_arrows.gif\"> Loading...");
  188. $oPage->add("</div>\n");
  189. $oPage->add('
  190. <script language="javascript">
  191. $.post("ajax.render.php?style='.$this->m_sStyle.'",
  192. { operation: "ajax", filter: "$sFilter" },
  193. function(data){
  194. $("#'.$sId.'").empty();
  195. $("#'.$sId.'").append(data);
  196. $("#'.$sId.'").removeClass("loading");
  197. }
  198. );
  199. </script>'); // TO DO: add support for $aExtraParams in asynchronous/Ajax mode
  200. }
  201. */
  202. }
  203. public function GetDisplay(WebPage $oPage, $sId, $aExtraParams = array())
  204. {
  205. $sHtml = '';
  206. $aExtraParams = array_merge($aExtraParams, $this->m_aParams);
  207. $aExtraParams['currentId'] = $sId;
  208. $sExtraParams = addslashes(str_replace('"', "'", json_encode($aExtraParams))); // JSON encode, change the style of the quotes and escape them
  209. $bAutoReload = false;
  210. if (isset($aExtraParams['auto_reload']))
  211. {
  212. switch($aExtraParams['auto_reload'])
  213. {
  214. case 'fast':
  215. $bAutoReload = true;
  216. $iReloadInterval = MetaModel::GetConfig()->GetFastReloadInterval()*1000;
  217. break;
  218. case 'standard':
  219. case 'true':
  220. case true:
  221. $bAutoReload = true;
  222. $iReloadInterval = MetaModel::GetConfig()->GetStandardReloadInterval()*1000;
  223. break;
  224. default:
  225. if (is_numeric($aExtraParams['auto_reload']))
  226. {
  227. $bAutoReload = true;
  228. $iReloadInterval = $aExtraParams['auto_reload']*1000;
  229. }
  230. else
  231. {
  232. // incorrect config, ignore it
  233. $bAutoReload = false;
  234. }
  235. }
  236. }
  237. $sFilter = $this->m_oFilter->serialize(); // Used either for asynchronous or auto_reload
  238. if (!$this->m_bAsynchronous)
  239. {
  240. // render now
  241. $sHtml .= "<div id=\"$sId\" class=\"display_block\">\n";
  242. $sHtml .= $this->GetRenderContent($oPage, $aExtraParams, $sId);
  243. $sHtml .= "</div>\n";
  244. }
  245. else
  246. {
  247. // render it as an Ajax (asynchronous) call
  248. $sHtml .= "<div id=\"$sId\" class=\"display_block loading\">\n";
  249. $sHtml .= $oPage->GetP("<img src=\"../images/indicator_arrows.gif\"> ".Dict::S('UI:Loading'));
  250. $sHtml .= "</div>\n";
  251. $sHtml .= '
  252. <script language="javascript">
  253. $.post("ajax.render.php?style='.$this->m_sStyle.'",
  254. { operation: "ajax", filter: "'.$sFilter.'", extra_params: "'.$sExtraParams.'" },
  255. function(data){
  256. $("#'.$sId.'").empty();
  257. $("#'.$sId.'").append(data);
  258. $("#'.$sId.'").removeClass("loading");
  259. // Check each "listResults" table for a checkbox in the first column and make the first column sortable only if it does not contain a checkbox in the header
  260. $("#'.$sId.'.listResults").each( function()
  261. {
  262. var table = $(this);
  263. var id = $(this).parent();
  264. var checkbox = (table.find(\'th:first :checkbox\').length > 0);
  265. if (checkbox)
  266. {
  267. // There is a checkbox in the first column, do not make it sortable
  268. table.tablesorter( { headers: { 0: {sorter: false}}, widgets: [\'myZebra\', \'truncatedList\']} ); // sortable and zebra tables
  269. }
  270. else
  271. {
  272. // There is NO checkbox in the first column, all columns are considered sortable
  273. table.tablesorter( { widgets: [\'myZebra\', \'truncatedList\']} ); // sortable and zebra tables
  274. }
  275. });
  276. }
  277. );
  278. </script>';
  279. }
  280. if ($bAutoReload)
  281. {
  282. $sHtml .= '
  283. <script language="javascript">
  284. setInterval("ReloadBlock(\''.$sId.'\', \''.$this->m_sStyle.'\', \''.$sFilter.'\', \"'.$sExtraParams.'\")", '.$iReloadInterval.');
  285. </script>';
  286. }
  287. return $sHtml;
  288. }
  289. public function RenderContent(WebPage $oPage, $aExtraParams = array())
  290. {
  291. if (empty($aExtraParams['currentId']))
  292. {
  293. $sId = $oPage->GetUniqueId(); // Works only if the page is not an Ajax one !
  294. }
  295. else
  296. {
  297. $sId = $aExtraParams['currentId'];
  298. }
  299. $oPage->add($this->GetRenderContent($oPage, $aExtraParams, $sId));
  300. }
  301. public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId)
  302. {
  303. $sHtml = '';
  304. // Add the extra params into the filter if they make sense for such a filter
  305. $bDoSearch = utils::ReadParam('dosearch', false);
  306. if ($this->m_oSet == null)
  307. {
  308. $aQueryParams = array();
  309. if (isset($aExtraParams['query_params']))
  310. {
  311. $aQueryParams = $aExtraParams['query_params'];
  312. }
  313. if ($this->m_sStyle != 'links')
  314. {
  315. $oAppContext = new ApplicationContext();
  316. $sClass = $this->m_oFilter->GetClass();
  317. $aFilterCodes = array_keys(MetaModel::GetClassFilterDefs($sClass));
  318. $aCallSpec = array($sClass, 'MapContextParam');
  319. foreach($oAppContext->GetNames() as $sContextParam)
  320. {
  321. $sParamCode = call_user_func($aCallSpec, $sContextParam); //Map context parameter to the value/filter code depending on the class
  322. if (!is_null($sParamCode))
  323. {
  324. $sParamValue = $oAppContext->GetCurrentValue($sContextParam, null);
  325. if (!is_null($sParamValue))
  326. {
  327. $aExtraParams[$sParamCode] = $sParamValue;
  328. }
  329. }
  330. }
  331. foreach($aFilterCodes as $sFilterCode)
  332. {
  333. $sExternalFilterValue = utils::ReadParam($sFilterCode, '');
  334. $condition = null;
  335. if (isset($aExtraParams[$sFilterCode]))
  336. {
  337. $condition = $aExtraParams[$sFilterCode];
  338. }
  339. // else if ($bDoSearch && $sExternalFilterValue != "")
  340. if ($bDoSearch && $sExternalFilterValue != "")
  341. {
  342. // Search takes precedence over context params...
  343. unset($aExtraParams[$sFilterCode]);
  344. $condition = trim($sExternalFilterValue);
  345. }
  346. if (!is_null($condition))
  347. {
  348. $this->AddCondition($sFilterCode, $condition);
  349. }
  350. }
  351. }
  352. $this->m_oSet = new CMDBObjectSet($this->m_oFilter, array(), $aQueryParams);
  353. }
  354. switch($this->m_sStyle)
  355. {
  356. case 'count':
  357. if (isset($aExtraParams['group_by']))
  358. {
  359. $sGroupByField = $aExtraParams['group_by'];
  360. $aGroupBy = array();
  361. $sLabels = array();
  362. while($oObj = $this->m_oSet->Fetch())
  363. {
  364. if (isset($aExtraParams['group_by_expr']))
  365. {
  366. eval("\$sValue = ".sprintf($aExtraParams['group_by_expr'], $oObj->Get($sGroupByField)).';');
  367. }
  368. else
  369. {
  370. $sValue = $oObj->Get($sGroupByField);
  371. }
  372. $aGroupBy[$sValue] = isset($aGroupBy[$sValue]) ? $aGroupBy[$sValue]+1 : 1;
  373. $sLabels[$sValue] = $oObj->GetAsHtml($sGroupByField);
  374. }
  375. $sFilter = urlencode($this->m_oFilter->serialize());
  376. $aData = array();
  377. $oAppContext = new ApplicationContext();
  378. $sParams = $oAppContext->GetForLink();
  379. foreach($aGroupBy as $sValue => $iCount)
  380. {
  381. $aData[] = array ( 'group' => $sLabels[$sValue],
  382. 'value' => "<a href=\"./UI.php?operation=search&dosearch=1&$sParams&filter=$sFilter&$sGroupByField=".urlencode($sValue)."\">$iCount</a>"); // TO DO: add the context information
  383. }
  384. $aAttribs =array(
  385. 'group' => array('label' => MetaModel::GetLabel($this->m_oFilter->GetClass(), $sGroupByField), 'description' => ''),
  386. 'value' => array('label'=> Dict::S('UI:GroupBy:Count'), 'description' => Dict::S('UI:GroupBy:Count+'))
  387. );
  388. $sHtml .= $oPage->GetTable($aAttribs, $aData);
  389. }
  390. else
  391. {
  392. // Simply count the number of elements in the set
  393. $iCount = $this->m_oSet->Count();
  394. $sFormat = 'UI:CountOfObjects';
  395. if (isset($aExtraParams['format']))
  396. {
  397. $sFormat = $aExtraParams['format'];
  398. }
  399. $sHtml .= $oPage->GetP(Dict::Format($sFormat, $iCount));
  400. }
  401. break;
  402. case 'join':
  403. $aDisplayAliases = isset($aExtraParams['display_aliases']) ? explode(',', $aExtraParams['display_aliases']): array();
  404. if (!isset($aExtraParams['group_by']))
  405. {
  406. $sHtml .= $oPage->GetP(Dict::S('UI:Error:MandatoryTemplateParameter_group_by'));
  407. }
  408. else
  409. {
  410. $aGroupByFields = array();
  411. $aGroupBy = explode(',', $aExtraParams['group_by']);
  412. foreach($aGroupBy as $sGroupBy)
  413. {
  414. $aMatches = array();
  415. if (preg_match('/^(.+)\.(.+)$/', $sGroupBy, $aMatches) > 0)
  416. {
  417. $aGroupByFields[] = array('alias' => $aMatches[1], 'att_code' => $aMatches[2]);
  418. }
  419. }
  420. if (count($aGroupByFields) == 0)
  421. {
  422. $sHtml .= $oPage->GetP(Dict::Format('UI:Error:InvalidGroupByFields', $aExtraParams['group_by']));
  423. }
  424. else
  425. {
  426. $aResults = array();
  427. $aCriteria = array();
  428. while($aObjects = $this->m_oSet->FetchAssoc())
  429. {
  430. $aKeys = array();
  431. foreach($aGroupByFields as $aField)
  432. {
  433. $sAlias = $aField['alias'];
  434. if (is_null($aObjects[$sAlias]))
  435. {
  436. $aKeys[$sAlias.'.'.$aField['att_code']] = '';
  437. }
  438. else
  439. {
  440. $aKeys[$sAlias.'.'.$aField['att_code']] = $aObjects[$sAlias]->Get($aField['att_code']);
  441. }
  442. }
  443. $sCategory = implode($aKeys, ' ');
  444. $aResults[$sCategory][] = $aObjects;
  445. $aCriteria[$sCategory] = $aKeys;
  446. }
  447. $sHtml .= "<table>\n";
  448. // Construct a new (parametric) query that will return the content of this block
  449. $oBlockFilter = clone $this->m_oFilter;
  450. $aExpressions = array();
  451. $index = 0;
  452. foreach($aGroupByFields as $aField)
  453. {
  454. $aExpressions[] = '`'.$aField['alias'].'`.`'.$aField['att_code'].'` = :param'.$index++;
  455. }
  456. $sExpression = implode(' AND ', $aExpressions);
  457. $oExpression = Expression::FromOQL($sExpression);
  458. $oBlockFilter->AddConditionExpression($oExpression);
  459. $aExtraParams['menu'] = false;
  460. foreach($aResults as $sCategory => $aObjects)
  461. {
  462. $sHtml .= "<tr><td><h1>$sCategory</h1></td></tr>\n";
  463. if (count($aDisplayAliases) == 1)
  464. {
  465. $aSimpleArray = array();
  466. foreach($aObjects as $aRow)
  467. {
  468. $oObj = $aRow[$aDisplayAliases[0]];
  469. if (!is_null($oObj))
  470. {
  471. $aSimpleArray[] = $oObj;
  472. }
  473. }
  474. $oSet = CMDBObjectSet::FromArray($this->m_oFilter->GetClass(), $aSimpleArray);
  475. $sHtml .= "<tr><td>".cmdbAbstractObject::GetDisplaySet($oPage, $oSet, $aExtraParams)."</td></tr>\n";
  476. }
  477. else
  478. {
  479. $index = 0;
  480. $aArgs = array();
  481. foreach($aGroupByFields as $aField)
  482. {
  483. $aArgs['param'.$index] = $aCriteria[$sCategory][$aField['alias'].'.'.$aField['att_code']];
  484. $index++;
  485. }
  486. $oSet = new CMDBObjectSet($oBlockFilter, array(), $aArgs);
  487. $sHtml .= "<tr><td>".cmdbAbstractObject::GetDisplayExtendedSet($oPage, $oSet, $aExtraParams)."</td></tr>\n";
  488. }
  489. }
  490. $sHtml .= "</table>\n";
  491. }
  492. }
  493. break;
  494. case 'list':
  495. $aClasses = $this->m_oSet->GetSelectedClasses();
  496. $aAuthorizedClasses = array();
  497. if (count($aClasses) > 1)
  498. {
  499. // Check the classes that can be read (i.e authorized) by this user...
  500. foreach($aClasses as $sAlias => $sClassName)
  501. {
  502. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $this->m_oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  503. {
  504. $aAuthorizedClasses[$sAlias] = $sClassName;
  505. }
  506. }
  507. if (count($aAuthorizedClasses) > 0)
  508. {
  509. if($this->m_oSet->Count() > 0)
  510. {
  511. $sHtml .= cmdbAbstractObject::GetDisplayExtendedSet($oPage, $this->m_oSet, $aExtraParams);
  512. }
  513. else
  514. {
  515. // Empty set
  516. $sHtml .= $oPage->GetP(Dict::S('UI:NoObjectToDisplay'));
  517. }
  518. }
  519. else
  520. {
  521. // Not authorized
  522. $sHtml .= $oPage->GetP(Dict::S('UI:NoObjectToDisplay'));
  523. }
  524. }
  525. else
  526. {
  527. // The list is made of only 1 class of objects, actions on the list are possible
  528. if ( ($this->m_oSet->Count()> 0) && (UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_READ, $this->m_oSet) == UR_ALLOWED_YES) )
  529. {
  530. $sHtml .= cmdbAbstractObject::GetDisplaySet($oPage, $this->m_oSet, $aExtraParams);
  531. }
  532. else
  533. {
  534. $sHtml .= $oPage->GetP(Dict::S('UI:NoObjectToDisplay'));
  535. $sClass = $this->m_oFilter->GetClass();
  536. $bDisplayMenu = isset($aExtraParams['menu']) ? $aExtraParams['menu'] == true : true;
  537. if ($bDisplayMenu)
  538. {
  539. if ((UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES))
  540. {
  541. $oAppContext = new ApplicationContext();
  542. $sParams = $oAppContext->GetForLink();
  543. // 1:n links, populate the target object as a default value when creating a new linked object
  544. if (isset($aExtraParams['target_attr']))
  545. {
  546. $aExtraParams['default'][$aExtraParams['target_attr']] = $aExtraParams['object_id'];
  547. }
  548. $sDefault = '';
  549. if (!empty($aExtraParams['default']))
  550. {
  551. foreach($aExtraParams['default'] as $sKey => $sValue)
  552. {
  553. $sDefault.= "&default[$sKey]=$sValue";
  554. }
  555. }
  556. $sHtml .= $oPage->GetP("<a href=\"./UI.php?operation=new&class=$sClass&$sParams{$sDefault}\">".Dict::Format('UI:ClickToCreateNew', Metamodel::GetName($sClass))."</a>\n");
  557. }
  558. }
  559. }
  560. }
  561. break;
  562. case 'links':
  563. //$bDashboardMode = isset($aExtraParams['dashboard']) ? ($aExtraParams['dashboard'] == 'true') : false;
  564. //$bSelectMode = isset($aExtraParams['select']) ? ($aExtraParams['select'] == 'true') : false;
  565. if ( ($this->m_oSet->Count()> 0) && (UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_READ, $this->m_oSet) == UR_ALLOWED_YES) )
  566. {
  567. //$sLinkage = isset($aExtraParams['linkage']) ? $aExtraParams['linkage'] : '';
  568. $sHtml .= cmdbAbstractObject::GetDisplaySet($oPage, $this->m_oSet, $aExtraParams);
  569. }
  570. else
  571. {
  572. $sClass = $this->m_oFilter->GetClass();
  573. $oAttDef = MetaModel::GetAttributeDef($sClass, $this->m_aParams['target_attr']);
  574. $sTargetClass = $oAttDef->GetTargetClass();
  575. $sHtml .= $oPage->GetP(Dict::Format('UI:NoObject_Class_ToDisplay', MetaModel::GetName($sTargetClass)));
  576. $bDisplayMenu = isset($this->m_aParams['menu']) ? $this->m_aParams['menu'] == true : true;
  577. if ($bDisplayMenu)
  578. {
  579. if ((UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES))
  580. {
  581. $oAppContext = new ApplicationContext();
  582. $sParams = $oAppContext->GetForLink();
  583. $sDefaults = '';
  584. if (isset($this->m_aParams['default']))
  585. {
  586. foreach($this->m_aParams['default'] as $sName => $sValue)
  587. {
  588. $sDefaults .= '&'.urlencode($sName).'='.urlencode($sValue);
  589. }
  590. }
  591. $sHtml .= $oPage->GetP("<a href=\"../pages/UI.php?operation=modify_links&class=$sClass&sParams&link_attr=".$aExtraParams['link_attr']."&id=".$aExtraParams['object_id']."&target_class=$sTargetClass&addObjects=true$sDefaults\">".Dict::Format('UI:ClickToCreateNew', Metamodel::GetName($sClass))."</a>\n");
  592. }
  593. }
  594. }
  595. break;
  596. case 'details':
  597. while($oObj = $this->m_oSet->Fetch())
  598. {
  599. $sHtml .= $oObj->GetDetails($oPage); // Still used ???
  600. }
  601. break;
  602. case 'actions':
  603. $sClass = $this->m_oFilter->GetClass();
  604. $oAppContext = new ApplicationContext();
  605. $bContextFilter = isset($aExtraParams['context_filter']) ? isset($aExtraParams['context_filter']) != 0 : false;
  606. if ($bContextFilter)
  607. {
  608. $aFilterCodes = array_keys(MetaModel::GetClassFilterDefs($this->m_oFilter->GetClass()));
  609. foreach($oAppContext->GetNames() as $sFilterCode)
  610. {
  611. $sContextParamValue = $oAppContext->GetCurrentValue($sFilterCode, null);
  612. if (!is_null($sContextParamValue) && ! empty($sContextParamValue) && MetaModel::IsValidFilterCode($sClass, $sFilterCode))
  613. {
  614. $this->AddCondition($sFilterCode, $sContextParamValue);
  615. }
  616. }
  617. $aQueryParams = array();
  618. if (isset($aExtraParams['query_params']))
  619. {
  620. $aQueryParams = $aExtraParams['query_params'];
  621. }
  622. $this->m_oSet = new CMDBObjectSet($this->m_oFilter, array(), $aQueryParams);
  623. }
  624. $iCount = $this->m_oSet->Count();
  625. $sHyperlink = '../pages/UI.php?operation=search&'.$oAppContext->GetForLink().'&filter='.$this->m_oFilter->serialize();
  626. $sHtml .= '<p><a class="actions" href="'.$sHyperlink.'">';
  627. $sHtml .= MetaModel::GetClassIcon($sClass, true, 'float;left;margin-right:10px;');
  628. $sHtml .= MetaModel::GetName($sClass).': '.$iCount.'</a></p>';
  629. $sParams = $oAppContext->GetForLink();
  630. $sHtml .= '<p>';
  631. if (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY))
  632. {
  633. $sHtml .= "<a href=\"../pages/UI.php?operation=new&class={$sClass}&$sParams\">".Dict::Format('UI:ClickToCreateNew', MetaModel::GetName($sClass))."</a><br/>\n";
  634. }
  635. $sHtml .= "<a href=\"../pages/UI.php?operation=search_form&class={$sClass}&$sParams\">".Dict::Format('UI:SearchFor_Class', MetaModel::GetName($sClass))."</a>\n";
  636. $sHtml .= '</p>';
  637. break;
  638. case 'summary':
  639. $sClass = $this->m_oFilter->GetClass();
  640. $oAppContext = new ApplicationContext();
  641. $sTitle = isset($aExtraParams['title[block]']) ? $aExtraParams['title[block]'] : '';
  642. $sLabel = isset($aExtraParams['label[block]']) ? $aExtraParams['label[block]'] : '';
  643. $sStateAttrCode = isset($aExtraParams['status[block]']) ? $aExtraParams['status[block]'] : 'status';
  644. $sStatesList = isset($aExtraParams['status_codes[block]']) ? $aExtraParams['status_codes[block]'] : '';
  645. $bContextFilter = isset($aExtraParams['context_filter']) ? isset($aExtraParams['context_filter']) != 0 : false;
  646. if ($bContextFilter)
  647. {
  648. $aFilterCodes = array_keys(MetaModel::GetClassFilterDefs($this->m_oFilter->GetClass()));
  649. foreach($oAppContext->GetNames() as $sFilterCode)
  650. {
  651. $sContextParamValue = $oAppContext->GetCurrentValue($sFilterCode, null);
  652. if (!is_null($sContextParamValue) && ! empty($sContextParamValue) && MetaModel::IsValidFilterCode($sClass, $sFilterCode))
  653. {
  654. $this->AddCondition($sFilterCode, $sContextParamValue);
  655. }
  656. }
  657. $aQueryParams = array();
  658. if (isset($aExtraParams['query_params']))
  659. {
  660. $aQueryParams = $aExtraParams['query_params'];
  661. }
  662. $this->m_oSet = new CMDBObjectSet($this->m_oFilter, array(), $aQueryParams);
  663. }
  664. // Summary details
  665. $aCounts = array();
  666. $aStateLabels = array();
  667. if (!empty($sStateAttrCode) && !empty($sStatesList))
  668. {
  669. $aStates = explode(',', $sStatesList);
  670. $oAttDef = MetaModel::GetAttributeDef($sClass, $sStateAttrCode);
  671. foreach($aStates as $sStateValue)
  672. {
  673. $oFilter = clone($this->m_oFilter);
  674. $oFilter->AddCondition($sStateAttrCode, $sStateValue, '=');
  675. $oSet = new DBObjectSet($oFilter);
  676. $aCounts[$sStateValue] = $oSet->Count();
  677. $aStateLabels[$sStateValue] = Dict::S("Class:".$oAttDef->GetHostClass()."/Attribute:$sStateAttrCode/Value:$sStateValue");
  678. if ($aCounts[$sStateValue] == 0)
  679. {
  680. $aCounts[$sStateValue] = '-';
  681. }
  682. else
  683. {
  684. $sHyperlink = '../pages/UI.php?operation=search&'.$oAppContext->GetForLink().'&filter='.$oFilter->serialize();
  685. $aCounts[$sStateValue] = "<a href=\"$sHyperlink\">{$aCounts[$sStateValue]}</a>";
  686. }
  687. }
  688. }
  689. $sHtml .= '<div class="summary-details"><table><tr><th>'.implode('</th><th>', $aStateLabels).'</th></tr>';
  690. $sHtml .= '<tr><td>'.implode('</td><td>', $aCounts).'</td></tr></table></div>';
  691. // Title & summary
  692. $iCount = $this->m_oSet->Count();
  693. $sHyperlink = '../pages/UI.php?operation=search&'.$oAppContext->GetForLink().'&filter='.$this->m_oFilter->serialize();
  694. $sHtml .= '<h1>'.Dict::S(str_replace('_', ':', $sTitle)).'</h1>';
  695. $sHtml .= '<a class="summary" href="'.$sHyperlink.'">'.Dict::Format(str_replace('_', ':', $sLabel), $iCount).'</a>';
  696. break;
  697. case 'bare_details':
  698. while($oObj = $this->m_oSet->Fetch())
  699. {
  700. $sHtml .= $oObj->GetBareProperties($oPage);
  701. }
  702. break;
  703. case 'csv':
  704. $sHtml .= "<textarea style=\"width:95%;height:98%\">\n";
  705. $sHtml .= cmdbAbstractObject::GetSetAsCSV($this->m_oSet);
  706. $sHtml .= "</textarea>\n";
  707. break;
  708. case 'modify':
  709. if ((UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_MODIFY, $this->m_oSet) == UR_ALLOWED_YES))
  710. {
  711. while($oObj = $this->m_oSet->Fetch())
  712. {
  713. $sHtml .= $oObj->GetModifyForm($oPage);
  714. }
  715. }
  716. break;
  717. case 'search':
  718. $sStyle = (isset($aExtraParams['open']) && ($aExtraParams['open'] == 'true')) ? 'SearchDrawer' : 'SearchDrawer DrawerClosed';
  719. $sHtml .= "<div id=\"ds_$sId\" class=\"$sStyle\">\n";
  720. $oPage->add_ready_script(
  721. <<<EOF
  722. $("#dh_$sId").click( function() {
  723. $("#ds_$sId").slideToggle('normal', function() { $("#ds_$sId").parent().resize(); } );
  724. $("#dh_$sId").toggleClass('open');
  725. });
  726. EOF
  727. );
  728. $aExtraParams['currentId'] = $sId;
  729. $sHtml .= cmdbAbstractObject::GetSearchForm($oPage, $this->m_oSet, $aExtraParams);
  730. $sHtml .= "</div>\n";
  731. $sHtml .= "<div class=\"HRDrawer\"></div>\n";
  732. $sHtml .= "<div id=\"dh_$sId\" class=\"DrawerHandle\">".Dict::S('UI:SearchToggle')."</div>\n";
  733. break;
  734. case 'open_flash_chart':
  735. static $iChartCounter = 0;
  736. $sChartType = isset($aExtraParams['chart_type']) ? $aExtraParams['chart_type'] : 'pie';
  737. $sTitle = isset($aExtraParams['chart_title']) ? $aExtraParams['chart_title'] : '';
  738. $sGroupBy = isset($aExtraParams['group_by']) ? $aExtraParams['group_by'] : '';
  739. $sGroupByExpr = isset($aExtraParams['group_by_expr']) ? '&params[group_by_expr]='.$aExtraParams['group_by_expr'] : '';
  740. $sFilter = $this->m_oFilter->serialize();
  741. $sHtml .= "<div id=\"my_chart_{$iChartCounter}\">If the chart does not display, <a href=\"http://get.adobe.com/flash/\" target=\"_blank\">install Flash</a></div>\n";
  742. $oPage->add_script("function ofc_resize(left, width, top, height) { /* do nothing special */ }");
  743. $oPage->add_ready_script("swfobject.embedSWF(\"../images/open-flash-chart.swf\", \"my_chart_{$iChartCounter}\", \"100%\", \"300\",\"9.0.0\", \"expressInstall.swf\",
  744. {\"data-file\":\"".urlencode("../pages/ajax.render.php?operation=open_flash_chart&params[group_by]=$sGroupBy{$sGroupByExpr}&params[chart_type]=$sChartType&params[chart_title]=$sTitle&id=$sId&filter=".$sFilter)."\"}, {wmode: 'transparent'} );\n");
  745. $iChartCounter++;
  746. if (isset($aExtraParams['group_by']))
  747. {
  748. $sGroupByField = $aExtraParams['group_by'];
  749. $aGroupBy = array();
  750. while($oObj = $this->m_oSet->Fetch())
  751. {
  752. if (isset($aExtraParams['group_by_expr']))
  753. {
  754. eval("\$sValue = ".sprintf($aExtraParams['group_by_expr'], $oObj->Get($sGroupByField)).';');
  755. }
  756. else
  757. {
  758. $sValue = $oObj->Get($sGroupByField);
  759. }
  760. $aGroupBy[$sValue] = isset($aGroupBy[$sValue]) ? $aGroupBy[$sValue]+1 : 1;
  761. }
  762. $sFilter = urlencode($this->m_oFilter->serialize());
  763. $aData = array();
  764. $aLabels = array();
  765. $idx = 0;
  766. foreach($aGroupBy as $sValue => $iValue)
  767. {
  768. $oDrillDownFilter = clone $this->m_oFilter;
  769. $oDrillDownFilter->AddCondition($sGroupByField, $sValue, '=');
  770. $aURLs[$idx] = $oDrillDownFilter->serialize();
  771. $idx++;
  772. }
  773. $sURLList = '';
  774. foreach($aURLs as $index => $sURL)
  775. {
  776. $sURLList .= "\taURLs[$index] = '".utils::GetAbsoluteUrlAppRoot()."pages/UI.php?operation=search&format=html&filter=".addslashes($sURL)."';\n";
  777. }
  778. $oPage->add_script(
  779. <<<EOF
  780. function ofc_drill_down_{$sId}(index)
  781. {
  782. var aURLs = new Array();
  783. {$sURLList}
  784. window.location.href=aURLs[index];
  785. }
  786. EOF
  787. );
  788. }
  789. break;
  790. case 'open_flash_chart_ajax':
  791. require_once(APPROOT.'/pages/php-ofc-library/open-flash-chart.php');
  792. $sChartType = isset($aExtraParams['chart_type']) ? $aExtraParams['chart_type'] : 'pie';
  793. $sId = utils::ReadParam('id', '');
  794. $oChart = new open_flash_chart();
  795. switch($sChartType)
  796. {
  797. case 'bars':
  798. $oChartElement = new bar_glass();
  799. if (isset($aExtraParams['group_by']))
  800. {
  801. $sGroupByField = $aExtraParams['group_by'];
  802. $aGroupBy = array();
  803. while($oObj = $this->m_oSet->Fetch())
  804. {
  805. if (isset($aExtraParams['group_by_expr']))
  806. {
  807. eval("\$sValue = ".sprintf($aExtraParams['group_by_expr'], $oObj->Get($sGroupByField)).';');
  808. }
  809. else
  810. {
  811. $sValue = $oObj->Get($sGroupByField);
  812. }
  813. $aGroupBy[$sValue] = isset($aGroupBy[$sValue]) ? $aGroupBy[$sValue]+1 : 1;
  814. }
  815. $sFilter = urlencode($this->m_oFilter->serialize());
  816. $aData = array();
  817. $aLabels = array();
  818. $maxValue = 0;
  819. foreach($aGroupBy as $sValue => $iValue)
  820. {
  821. $oBarValue = new bar_value($iValue);
  822. $oBarValue->on_click("ofc_drill_down_$sId");
  823. $aData[] = $oBarValue;
  824. if ($iValue > $maxValue) $maxValue = $iValue;
  825. $aLabels[] = $sValue;
  826. }
  827. $oYAxis = new y_axis();
  828. $aMagicValues = array(1,2,5,10);
  829. $iMultiplier = 1;
  830. $index = 0;
  831. $iTop = $aMagicValues[$index % count($aMagicValues)]*$iMultiplier;
  832. while($maxValue > $iTop)
  833. {
  834. $index++;
  835. $iTop = $aMagicValues[$index % count($aMagicValues)]*$iMultiplier;
  836. if (($index % count($aMagicValues)) == 0)
  837. {
  838. $iMultiplier = $iMultiplier * 10;
  839. }
  840. }
  841. //echo "oYAxis->set_range(0, $iTop, $iMultiplier);\n";
  842. $oYAxis->set_range(0, $iTop, $iMultiplier);
  843. $oChart->set_y_axis( $oYAxis );
  844. $oChartElement->set_values( $aData );
  845. $oXAxis = new x_axis();
  846. $oXLabels = new x_axis_labels();
  847. // set them vertical
  848. $oXLabels->set_vertical();
  849. // set the label text
  850. $oXLabels->set_labels($aLabels);
  851. // Add the X Axis Labels to the X Axis
  852. $oXAxis->set_labels( $oXLabels );
  853. $oChart->set_x_axis( $oXAxis );
  854. }
  855. break;
  856. case 'pie':
  857. default:
  858. $oChartElement = new pie();
  859. $oChartElement->set_start_angle( 35 );
  860. $oChartElement->set_animate( true );
  861. $oChartElement->set_tooltip( '#label# - #val# (#percent#)' );
  862. $oChartElement->set_colours( array('#FF8A00', '#909980', '#2C2B33', '#CCC08D', '#596664') );
  863. if (isset($aExtraParams['group_by']))
  864. {
  865. $sGroupByField = $aExtraParams['group_by'];
  866. $aGroupBy = array();
  867. while($oObj = $this->m_oSet->Fetch())
  868. {
  869. if (isset($aExtraParams['group_by_expr']))
  870. {
  871. eval("\$sValue = ".sprintf($aExtraParams['group_by_expr'], $oObj->Get($sGroupByField)).';');
  872. }
  873. else
  874. {
  875. $sValue = $oObj->Get($sGroupByField);
  876. }
  877. $aGroupBy[$sValue] = isset($aGroupBy[$sValue]) ? $aGroupBy[$sValue]+1 : 1;
  878. }
  879. $sFilter = urlencode($this->m_oFilter->serialize());
  880. $aData = array();
  881. foreach($aGroupBy as $sValue => $iValue)
  882. {
  883. $PieValue = new pie_value($iValue, $sValue); //@@ BUG: not passed via ajax !!!
  884. $PieValue->on_click("ofc_drill_down_$sId");
  885. $aData[] = $PieValue;
  886. }
  887. $oChartElement->set_values( $aData );
  888. $oChart->x_axis = null;
  889. }
  890. }
  891. if (isset($aExtraParams['chart_title']))
  892. {
  893. $oTitle = new title( Dict::S($aExtraParams['chart_title']) );
  894. $oChart->set_title( $oTitle );
  895. }
  896. $oChart->set_bg_colour('#FFFFFF');
  897. $oChart->add_element( $oChartElement );
  898. $sHtml = $oChart->toPrettyString();
  899. break;
  900. default:
  901. // Unsupported style, do nothing.
  902. $sHtml .= Dict::format('UI:Error:UnsupportedStyleOfBlock', $this->m_sStyle);
  903. }
  904. return $sHtml;
  905. }
  906. /**
  907. * Add a condition (restriction) to the current DBObjectSearch on which the display block is based
  908. * taking into account the hierarchical keys for which the condition is based on the 'below' operator
  909. */
  910. protected function AddCondition($sFilterCode, $condition)
  911. {
  912. $sClass = $this->m_oFilter->GetClass();
  913. $bConditionAdded = false;
  914. // If the condition is an external key with a class having a hierarchy, use a "below" criteria
  915. if (MetaModel::IsValidAttCode($sClass, $sFilterCode))
  916. {
  917. $oAttDef = MetaModel::GetAttributeDef($sClass, $sFilterCode);
  918. if ($oAttDef->IsExternalKey())
  919. {
  920. $sHierarchicalKeyCode = MetaModel::IsHierarchicalClass($oAttDef->GetTargetClass());
  921. if ($sHierarchicalKeyCode !== false)
  922. {
  923. $oFilter = new DBObjectSearch($oAttDef->GetTargetClass());
  924. $oFilter->AddCondition('id', $condition);
  925. $oHKFilter = new DBObjectSearch($oAttDef->GetTargetClass());
  926. $oHKFilter->AddCondition_PointingTo($oFilter, $sHierarchicalKeyCode, TREE_OPERATOR_BELOW); // Use the 'below' operator by default
  927. $this->m_oFilter->AddCondition_PointingTo($oHKFilter, $sFilterCode);
  928. $bConditionAdded = true;
  929. }
  930. }
  931. }
  932. // In all other cases, just add the condition directly
  933. if (!$bConditionAdded)
  934. {
  935. $this->m_oFilter->AddCondition($sFilterCode, $condition); // Use the default 'loose' operator
  936. }
  937. }
  938. }
  939. /**
  940. * Helper class to manage 'blocks' of HTML pieces that are parts of a page and contain some list of cmdb objects
  941. *
  942. * Each block is actually rendered as a <div></div> tag that can be rendered synchronously
  943. * or as a piece of Javascript/JQuery/Ajax that will get its content from another page (ajax.render.php).
  944. * The list of cmdbObjects to be displayed into the block is defined by a filter
  945. * Right now the type of display is either: list, count or details
  946. * - list produces a table listing the objects
  947. * - count produces a paragraphs with a sentence saying 'cont' objects found
  948. * - details display (as table) the details of each object found (best if only one)
  949. */
  950. class HistoryBlock extends DisplayBlock
  951. {
  952. public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId)
  953. {
  954. $sHtml = '';
  955. $oSet = new CMDBObjectSet($this->m_oFilter, array('date'=>false));
  956. $sHtml .= "<!-- filter: ".($this->m_oFilter->ToOQL())."-->\n";
  957. switch($this->m_sStyle)
  958. {
  959. case 'toggle':
  960. // First the latest change that the user is allowed to see
  961. do
  962. {
  963. $oLatestChangeOp = $oSet->Fetch();
  964. }
  965. while(is_object($oLatestChangeOp) && ($oLatestChangeOp->GetDescription() == ''));
  966. if (is_object($oLatestChangeOp))
  967. {
  968. // There is one change in the list... only when the object has been created !
  969. $sDate = $oLatestChangeOp->GetAsHTML('date');
  970. $oChange = MetaModel::GetObject('CMDBChange', $oLatestChangeOp->Get('change'));
  971. $sUserInfo = $oChange->GetAsHTML('userinfo');
  972. $sHtml .= $oPage->GetStartCollapsibleSection(Dict::Format('UI:History:LastModified_On_By', $sDate, $sUserInfo));
  973. $sHtml .= $this->GetHistoryTable($oPage, $oSet);
  974. $sHtml .= $oPage->GetEndCollapsibleSection();
  975. }
  976. break;
  977. case 'table':
  978. default:
  979. $sHtml .= $this->GetHistoryTable($oPage, $oSet);
  980. }
  981. return $sHtml;
  982. }
  983. protected function GetHistoryTable(WebPage $oPage, DBObjectSet $oSet)
  984. {
  985. $sHtml = '';
  986. // First the latest change that the user is allowed to see
  987. $oSet->Rewind(); // Reset the pointer to the beginning of the set
  988. $aChanges = array();
  989. while($oChangeOp = $oSet->Fetch())
  990. {
  991. $sChangeDescription = $oChangeOp->GetDescription();
  992. if ($sChangeDescription != '')
  993. {
  994. // The change is visible for the current user
  995. $changeId = $oChangeOp->Get('change');
  996. $aChanges[$changeId]['date'] = $oChangeOp->Get('date');
  997. $aChanges[$changeId]['userinfo'] = $oChangeOp->Get('userinfo');
  998. if (!isset($aChanges[$changeId]['log']))
  999. {
  1000. $aChanges[$changeId]['log'] = array();
  1001. }
  1002. $aChanges[$changeId]['log'][] = $sChangeDescription;
  1003. }
  1004. }
  1005. $aAttribs = array('date' => array('label' => Dict::S('UI:History:Date'), 'description' => Dict::S('UI:History:Date+')),
  1006. 'userinfo' => array('label' => Dict::S('UI:History:User'), 'description' => Dict::S('UI:History:User+')),
  1007. 'log' => array('label' => Dict::S('UI:History:Changes'), 'description' => Dict::S('UI:History:Changes+')),
  1008. );
  1009. $aValues = array();
  1010. foreach($aChanges as $aChange)
  1011. {
  1012. $aValues[] = array('date' => $aChange['date'], 'userinfo' => $aChange['userinfo'], 'log' => "<ul><li>".implode('</li><li>', $aChange['log'])."</li></ul>");
  1013. }
  1014. $sHtml .= $oPage->GetTable($aAttribs, $aValues);
  1015. return $sHtml;
  1016. }
  1017. }
  1018. class MenuBlock extends DisplayBlock
  1019. {
  1020. /**
  1021. * Renders the "Actions" popup menu for the given set of objects
  1022. *
  1023. * Note that the menu links containing (or ending) with a hash (#) will have their fragment
  1024. * part (whatever is after the hash) dynamically replaced (by javascript) when the menu is
  1025. * displayed, to correspond to the current hash/fragment in the page. This allows modifying
  1026. * an object in with the same tab active by default as the tab that was active when selecting
  1027. * the "Modify..." action.
  1028. */
  1029. public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId)
  1030. {
  1031. $sHtml = '';
  1032. $oAppContext = new ApplicationContext();
  1033. $sContext = $oAppContext->GetForLink();
  1034. $sClass = $this->m_oFilter->GetClass();
  1035. $oSet = new CMDBObjectSet($this->m_oFilter);
  1036. $sFilter = $this->m_oFilter->serialize();
  1037. $sFilterDesc = $this->m_oFilter->ToOql();
  1038. $aActions = array();
  1039. $sUIPage = cmdbAbstractObject::ComputeStandardUIPage($sClass);
  1040. // 1:n links, populate the target object as a default value when creating a new linked object
  1041. if (isset($aExtraParams['target_attr']))
  1042. {
  1043. $aExtraParams['default'][$aExtraParams['target_attr']] = $aExtraParams['object_id'];
  1044. }
  1045. $sDefault = '';
  1046. if (!empty($aExtraParams['default']))
  1047. {
  1048. foreach($aExtraParams['default'] as $sKey => $sValue)
  1049. {
  1050. $sDefault.= "&default[$sKey]=$sValue";
  1051. }
  1052. }
  1053. switch($oSet->Count())
  1054. {
  1055. case 0:
  1056. // No object in the set, the only possible action is "new"
  1057. $bIsModifyAllowed = (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES);
  1058. if ($bIsModifyAllowed) { $aActions[] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "../page/$sUIPage?operation=new&class=$sClass&$sContext{$sDefault}"); }
  1059. break;
  1060. case 1:
  1061. $oObj = $oSet->Fetch();
  1062. $id = $oObj->GetKey();
  1063. $bIsModifyAllowed = (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet) == UR_ALLOWED_YES);
  1064. $bIsDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, $oSet);
  1065. $bIsBulkModifyAllowed = (!MetaModel::IsAbstract($sClass)) && UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_MODIFY, $oSet);
  1066. $bIsBulkDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_DELETE, $oSet);
  1067. // Just one object in the set, possible actions are "new / clone / modify and delete"
  1068. if (!isset($aExtraParams['link_attr']))
  1069. {
  1070. if ($bIsModifyAllowed) { $aActions[] = array ('label' => Dict::S('UI:Menu:Modify'), 'url' => "../pages/$sUIPage?operation=modify&class=$sClass&id=$id&$sContext#"); }
  1071. if ($bIsModifyAllowed) { $aActions[] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "../pages/$sUIPage?operation=new&class=$sClass&$sContext{$sDefault}"); }
  1072. if ($bIsDeleteAllowed) { $aActions[] = array ('label' => Dict::S('UI:Menu:Delete'), 'url' => "../pages/$sUIPage?operation=delete&class=$sClass&id=$id&$sContext"); }
  1073. // Transitions / Stimuli
  1074. $aTransitions = $oObj->EnumTransitions();
  1075. if (count($aTransitions))
  1076. {
  1077. $this->AddMenuSeparator($aActions);
  1078. $aStimuli = Metamodel::EnumStimuli($sClass);
  1079. foreach($aTransitions as $sStimulusCode => $aTransitionDef)
  1080. {
  1081. $iActionAllowed = (get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction') ? UserRights::IsStimulusAllowed($sClass, $sStimulusCode, $oSet) : UR_ALLOWED_NO;
  1082. switch($iActionAllowed)
  1083. {
  1084. case UR_ALLOWED_YES:
  1085. $aActions[] = array('label' => $aStimuli[$sStimulusCode]->GetLabel(), 'url' => "../pages/UI.php?operation=stimulus&stimulus=$sStimulusCode&class=$sClass&id=$id&$sContext");
  1086. break;
  1087. default:
  1088. // Do nothing
  1089. }
  1090. }
  1091. }
  1092. // Relations...
  1093. $aRelations = MetaModel::EnumRelations($sClass);
  1094. if (count($aRelations))
  1095. {
  1096. $this->AddMenuSeparator($aActions);
  1097. foreach($aRelations as $sRelationCode)
  1098. {
  1099. $aActions[] = array ('label' => MetaModel::GetRelationVerbUp($sRelationCode), 'url' => "../pages/$sUIPage?operation=swf_navigator&relation=$sRelationCode&class=$sClass&id=$id&$sContext");
  1100. }
  1101. }
  1102. $this->AddMenuSeparator($aActions);
  1103. // Static menus: Email this page & CSV Export
  1104. $sUrl = ApplicationContext::MakeObjectUrl($sClass, $id);
  1105. $aActions[] = array ('label' => Dict::S('UI:Menu:EMail'), 'url' => "mailto:?subject=".$oObj->GetName()."&body=".urlencode($sUrl));
  1106. $aActions[] = array ('label' => Dict::S('UI:Menu:CSVExport'), 'url' => "../pages/$sUIPage?operation=search&filter=$sFilter&format=csv&$sContext");
  1107. }
  1108. $this->AddMenuSeparator($aActions);
  1109. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  1110. {
  1111. $oSet->Rewind();
  1112. foreach($oExtensionInstance->EnumAllowedActions($oSet) as $sLabel => $sUrl)
  1113. {
  1114. $aActions[] = array ('label' => $sLabel, 'url' => $sUrl);
  1115. }
  1116. }
  1117. break;
  1118. default:
  1119. // Check rights
  1120. // New / Modify
  1121. $bIsModifyAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet);
  1122. $bIsBulkModifyAllowed = (!MetaModel::IsAbstract($sClass)) && UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_MODIFY, $oSet);
  1123. $bIsBulkDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_DELETE, $oSet);
  1124. if (isset($aExtraParams['link_attr']))
  1125. {
  1126. $id = $aExtraParams['object_id'];
  1127. $sTargetAttr = $aExtraParams['target_attr'];
  1128. $oAttDef = MetaModel::GetAttributeDef($sClass, $sTargetAttr);
  1129. $sTargetClass = $oAttDef->GetTargetClass();
  1130. $bIsDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, $oSet);
  1131. if ($bIsModifyAllowed) { $aActions[] = array ('label' => Dict::S('UI:Menu:Add'), 'url' => "../pages/$sUIPage?operation=modify_links&class=$sClass&link_attr=".$aExtraParams['link_attr']."&target_class=$sTargetClass&id=$id&addObjects=true&$sContext"); }
  1132. if ($bIsBulkModifyAllowed) { $aActions[] = array ('label' => Dict::S('UI:Menu:Manage'), 'url' => "../pages/$sUIPage?operation=modify_links&class=$sClass&link_attr=".$aExtraParams['link_attr']."&target_class=$sTargetClass&id=$id&sContext"); }
  1133. //if ($bIsBulkDeleteAllowed) { $aActions[] = array ('label' => 'Remove All...', 'url' => "#"); }
  1134. }
  1135. else
  1136. {
  1137. // many objects in the set, possible actions are: new / modify all / delete all
  1138. if ($bIsModifyAllowed) { $aActions[] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "../pages/$sUIPage?operation=new&class=$sClass&$sContext{$sDefault}"); }
  1139. if ($bIsBulkModifyAllowed) { $aActions[] = array ('label' => Dict::S('UI:Menu:ModifyAll'), 'url' => "../pages/$sUIPage?operation=select_for_modify_all&class=$sClass&filter=$sFilter&sContext"); }
  1140. if ($bIsBulkDeleteAllowed) { $aActions[] = array ('label' => Dict::S('UI:Menu:BulkDelete'), 'url' => "../pages/$sUIPage?operation=select_for_deletion&filter=$sFilter&$sContext"); }
  1141. // Stimuli
  1142. $aStates = MetaModel::EnumStates($sClass);
  1143. if (count($aStates) > 0)
  1144. {
  1145. // Life cycle actions may be available... if all objects are in the same state
  1146. $oSet->Rewind();
  1147. $aStates = array();
  1148. while($oObj = $oSet->Fetch())
  1149. {
  1150. $aStates[$oObj->GetState()] = $oObj->GetState();
  1151. }
  1152. $oSet->Rewind();
  1153. if (count($aStates) == 1)
  1154. {
  1155. // All objects are in the same state...
  1156. $sState = array_pop($aStates);
  1157. $aTransitions = Metamodel::EnumTransitions($sClass, $sState);
  1158. if (count($aTransitions))
  1159. {
  1160. $this->AddMenuSeparator($aActions);
  1161. $aStimuli = Metamodel::EnumStimuli($sClass);
  1162. foreach($aTransitions as $sStimulusCode => $aTransitionDef)
  1163. {
  1164. $oChecker = new StimulusChecker($this->m_oFilter, $sState, $sStimulusCode);
  1165. $iActionAllowed = (get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction') ? $oChecker->IsAllowed() : UR_ALLOWED_NO;
  1166. switch($iActionAllowed)
  1167. {
  1168. case UR_ALLOWED_YES:
  1169. case UR_ALLOWED_DEPENDS:
  1170. $aActions[] = array('label' => $aStimuli[$sStimulusCode]->GetLabel(), 'url' => "../pages/UI.php?operation=select_bulk_stimulus&stimulus=$sStimulusCode&state=$sState&class=$sClass&filter=$sFilter&$sContext");
  1171. break;
  1172. default:
  1173. // Do nothing
  1174. }
  1175. }
  1176. }
  1177. }
  1178. }
  1179. $this->AddMenuSeparator($aActions);
  1180. $sUrl = utils::GetAbsoluteUrlAppRoot();
  1181. $aActions[] = array ('label' => Dict::S('UI:Menu:EMail'), 'url' => "mailto:?subject=$sFilterDesc&body=".urlencode("{$sUrl}pages/$sUIPage?operation=search&filter=$sFilter&$sContext"));
  1182. $aActions[] = array ('label' => Dict::S('UI:Menu:CSVExport'), 'url' => "../pages/$sUIPage?operation=search&filter=$sFilter&format=csv&$sContext");
  1183. }
  1184. $this->AddMenuSeparator($aActions);
  1185. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  1186. {
  1187. $oSet->Rewind();
  1188. foreach($oExtensionInstance->EnumAllowedActions($oSet) as $sLabel => $sUrl)
  1189. {
  1190. $aActions[] = array ('label' => $sLabel, 'url' => $sUrl);
  1191. }
  1192. }
  1193. }
  1194. $sHtml .= "<div class=\"itop_popup\"><ul>\n<li>".Dict::S('UI:Menu:Actions')."\n<ul>\n";
  1195. foreach ($aActions as $aAction)
  1196. {
  1197. $sClass = isset($aAction['class']) ? " class=\"{$aAction['class']}\"" : "";
  1198. if (empty($aAction['url']))
  1199. {
  1200. $sHtml .= "<li>{$aAction['label']}</li>\n";
  1201. }
  1202. else
  1203. {
  1204. $sHtml .= "<li><a href=\"{$aAction['url']}\"$sClass>{$aAction['label']}</a></li>\n";
  1205. }
  1206. }
  1207. $sHtml .= "</ul>\n</li>\n</ul></div>\n";
  1208. static $bPopupScript = false;
  1209. if (!$bPopupScript)
  1210. {
  1211. // Output this once per page...
  1212. $oPage->add_ready_script("$(\"div.itop_popup>ul\").popupmenu();\n");
  1213. $bPopupScript = true;
  1214. }
  1215. return $sHtml;
  1216. }
  1217. /**
  1218. * Appends a menu separator to the current list of actions
  1219. * @param Hash $aActions The current actions list
  1220. * @return void
  1221. */
  1222. protected function AddMenuSeparator(&$aActions)
  1223. {
  1224. $sSeparator = '<hr class="menu-separator"/>';
  1225. if (count($aActions) > 0) // Make sure that the separator is not the first item in the menu
  1226. {
  1227. if ($aActions[count($aActions)-1]['label'] != $sSeparator) // Make sure there are no 2 consecutive separators
  1228. {
  1229. $aActions[] = array('label' => $sSeparator, 'url' => '');
  1230. }
  1231. }
  1232. }
  1233. }
  1234. ?>