displayblock.class.inc.php 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214
  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. foreach($oAppContext->GetNames() as $sContextParam)
  319. {
  320. eval("\$sParamCode = $sClass::MapContextParam('$sContextParam');"); //Map context parameter to the value/filter code depending on the class
  321. if (!is_null($sParamCode))
  322. {
  323. $sParamValue = $oAppContext->GetCurrentValue($sContextParam, null);
  324. if (!is_null($sParamValue))
  325. {
  326. $aExtraParams[$sParamCode] = $sParamValue;
  327. }
  328. }
  329. }
  330. foreach($aFilterCodes as $sFilterCode)
  331. {
  332. $sExternalFilterValue = utils::ReadParam($sFilterCode, '');
  333. $condition = null;
  334. if (isset($aExtraParams[$sFilterCode]))
  335. {
  336. $condition = $aExtraParams[$sFilterCode];
  337. }
  338. // else if ($bDoSearch && $sExternalFilterValue != "")
  339. if ($bDoSearch && $sExternalFilterValue != "")
  340. {
  341. // Search takes precedence over context params...
  342. unset($aExtraParams[$sFilterCode]);
  343. $condition = trim($sExternalFilterValue);
  344. }
  345. if (!is_null($condition))
  346. {
  347. $this->m_oFilter->AddCondition($sFilterCode, $condition); // Use the default 'loose' operator
  348. }
  349. }
  350. }
  351. $this->m_oSet = new CMDBObjectSet($this->m_oFilter, array(), $aQueryParams);
  352. }
  353. switch($this->m_sStyle)
  354. {
  355. case 'count':
  356. if (isset($aExtraParams['group_by']))
  357. {
  358. $sGroupByField = $aExtraParams['group_by'];
  359. $aGroupBy = array();
  360. $sLabels = array();
  361. while($oObj = $this->m_oSet->Fetch())
  362. {
  363. if (isset($aExtraParams['group_by_expr']))
  364. {
  365. eval("\$sValue = ".sprintf($aExtraParams['group_by_expr'], $oObj->Get($sGroupByField)).';');
  366. }
  367. else
  368. {
  369. $sValue = $oObj->Get($sGroupByField);
  370. }
  371. $aGroupBy[$sValue] = isset($aGroupBy[$sValue]) ? $aGroupBy[$sValue]+1 : 1;
  372. $sLabels[$sValue] = $oObj->GetAsHtml($sGroupByField);
  373. }
  374. $sFilter = urlencode($this->m_oFilter->serialize());
  375. $aData = array();
  376. $oAppContext = new ApplicationContext();
  377. $sParams = $oAppContext->GetForLink();
  378. foreach($aGroupBy as $sValue => $iCount)
  379. {
  380. $aData[] = array ( 'group' => $sLabels[$sValue],
  381. 'value' => "<a href=\"./UI.php?operation=search&dosearch=1&$sParams&filter=$sFilter&$sGroupByField=".urlencode($sValue)."\">$iCount</a>"); // TO DO: add the context information
  382. }
  383. $aAttribs =array(
  384. 'group' => array('label' => MetaModel::GetLabel($this->m_oFilter->GetClass(), $sGroupByField), 'description' => ''),
  385. 'value' => array('label'=> Dict::S('UI:GroupBy:Count'), 'description' => Dict::S('UI:GroupBy:Count+'))
  386. );
  387. $sHtml .= $oPage->GetTable($aAttribs, $aData);
  388. }
  389. else
  390. {
  391. // Simply count the number of elements in the set
  392. $iCount = $this->m_oSet->Count();
  393. $sFormat = 'UI:CountOfObjects';
  394. if (isset($aExtraParams['format']))
  395. {
  396. $sFormat = $aExtraParams['format'];
  397. }
  398. $sHtml .= $oPage->GetP(Dict::Format($sFormat, $iCount));
  399. }
  400. break;
  401. case 'join':
  402. $aDisplayAliases = isset($aExtraParams['display_aliases']) ? explode(',', $aExtraParams['display_aliases']): array();
  403. if (!isset($aExtraParams['group_by']))
  404. {
  405. $sHtml .= $oPage->GetP(Dict::S('UI:Error:MandatoryTemplateParameter_group_by'));
  406. }
  407. else
  408. {
  409. $aGroupByFields = array();
  410. $aGroupBy = explode(',', $aExtraParams['group_by']);
  411. foreach($aGroupBy as $sGroupBy)
  412. {
  413. $aMatches = array();
  414. if (preg_match('/^(.+)\.(.+)$/', $sGroupBy, $aMatches) > 0)
  415. {
  416. $aGroupByFields[] = array('alias' => $aMatches[1], 'att_code' => $aMatches[2]);
  417. }
  418. }
  419. if (count($aGroupByFields) == 0)
  420. {
  421. $sHtml .= $oPage->GetP(Dict::Format('UI:Error:InvalidGroupByFields', $aExtraParams['group_by']));
  422. }
  423. else
  424. {
  425. $aResults = array();
  426. $aCriteria = array();
  427. while($aObjects = $this->m_oSet->FetchAssoc())
  428. {
  429. $aKeys = array();
  430. foreach($aGroupByFields as $aField)
  431. {
  432. $sAlias = $aField['alias'];
  433. if (is_null($aObjects[$sAlias]))
  434. {
  435. $aKeys[$sAlias.'.'.$aField['att_code']] = '';
  436. }
  437. else
  438. {
  439. $aKeys[$sAlias.'.'.$aField['att_code']] = $aObjects[$sAlias]->Get($aField['att_code']);
  440. }
  441. }
  442. $sCategory = implode($aKeys, ' ');
  443. $aResults[$sCategory][] = $aObjects;
  444. $aCriteria[$sCategory] = $aKeys;
  445. }
  446. $sHtml .= "<table>\n";
  447. // Construct a new (parametric) query that will return the content of this block
  448. $oBlockFilter = clone $this->m_oFilter;
  449. $aExpressions = array();
  450. $index = 0;
  451. foreach($aGroupByFields as $aField)
  452. {
  453. $aExpressions[] = '`'.$aField['alias'].'`.`'.$aField['att_code'].'` = :param'.$index++;
  454. }
  455. $sExpression = implode(' AND ', $aExpressions);
  456. $oExpression = Expression::FromOQL($sExpression);
  457. $oBlockFilter->AddConditionExpression($oExpression);
  458. $aExtraParams['menu'] = false;
  459. foreach($aResults as $sCategory => $aObjects)
  460. {
  461. $sHtml .= "<tr><td><h1>$sCategory</h1></td></tr>\n";
  462. if (count($aDisplayAliases) == 1)
  463. {
  464. $aSimpleArray = array();
  465. foreach($aObjects as $aRow)
  466. {
  467. $oObj = $aRow[$aDisplayAliases[0]];
  468. if (!is_null($oObj))
  469. {
  470. $aSimpleArray[] = $oObj;
  471. }
  472. }
  473. $oSet = CMDBObjectSet::FromArray($this->m_oFilter->GetClass(), $aSimpleArray);
  474. $sHtml .= "<tr><td>".cmdbAbstractObject::GetDisplaySet($oPage, $oSet, $aExtraParams)."</td></tr>\n";
  475. }
  476. else
  477. {
  478. $index = 0;
  479. $aArgs = array();
  480. foreach($aGroupByFields as $aField)
  481. {
  482. $aArgs['param'.$index] = $aCriteria[$sCategory][$aField['alias'].'.'.$aField['att_code']];
  483. $index++;
  484. }
  485. $oSet = new CMDBObjectSet($oBlockFilter, array(), $aArgs);
  486. $sHtml .= "<tr><td>".cmdbAbstractObject::GetDisplayExtendedSet($oPage, $oSet, $aExtraParams)."</td></tr>\n";
  487. }
  488. }
  489. $sHtml .= "</table>\n";
  490. }
  491. }
  492. break;
  493. case 'list':
  494. $aClasses = $this->m_oSet->GetSelectedClasses();
  495. $aAuthorizedClasses = array();
  496. if (count($aClasses) > 1)
  497. {
  498. // Check the classes that can be read (i.e authorized) by this user...
  499. foreach($aClasses as $sAlias => $sClassName)
  500. {
  501. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $this->m_oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  502. {
  503. $aAuthorizedClasses[$sAlias] = $sClassName;
  504. }
  505. }
  506. if (count($aAuthorizedClasses) > 0)
  507. {
  508. if($this->m_oSet->Count() > 0)
  509. {
  510. $sHtml .= cmdbAbstractObject::GetDisplayExtendedSet($oPage, $this->m_oSet, $aExtraParams);
  511. }
  512. else
  513. {
  514. // Empty set
  515. $sHtml .= $oPage->GetP(Dict::S('UI:NoObjectToDisplay'));
  516. }
  517. }
  518. else
  519. {
  520. // Not authorized
  521. $sHtml .= $oPage->GetP(Dict::S('UI:NoObjectToDisplay'));
  522. }
  523. }
  524. else
  525. {
  526. // The list is made of only 1 class of objects, actions on the list are possible
  527. if ( ($this->m_oSet->Count()> 0) && (UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_READ, $this->m_oSet) == UR_ALLOWED_YES) )
  528. {
  529. $sHtml .= cmdbAbstractObject::GetDisplaySet($oPage, $this->m_oSet, $aExtraParams);
  530. }
  531. else
  532. {
  533. $sHtml .= $oPage->GetP(Dict::S('UI:NoObjectToDisplay'));
  534. $sClass = $this->m_oFilter->GetClass();
  535. $bDisplayMenu = isset($aExtraParams['menu']) ? $aExtraParams['menu'] == true : true;
  536. if ($bDisplayMenu)
  537. {
  538. if ((UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES))
  539. {
  540. $oAppContext = new ApplicationContext();
  541. $sParams = $oAppContext->GetForLink();
  542. // 1:n links, populate the target object as a default value when creating a new linked object
  543. if (isset($aExtraParams['target_attr']))
  544. {
  545. $aExtraParams['default'][$aExtraParams['target_attr']] = $aExtraParams['object_id'];
  546. }
  547. $sDefault = '';
  548. if (!empty($aExtraParams['default']))
  549. {
  550. foreach($aExtraParams['default'] as $sKey => $sValue)
  551. {
  552. $sDefault.= "&default[$sKey]=$sValue";
  553. }
  554. }
  555. $sHtml .= $oPage->GetP("<a href=\"./UI.php?operation=new&class=$sClass&$sParams{$sDefault}\">".Dict::Format('UI:ClickToCreateNew', Metamodel::GetName($sClass))."</a>\n");
  556. }
  557. }
  558. }
  559. }
  560. break;
  561. case 'links':
  562. //$bDashboardMode = isset($aExtraParams['dashboard']) ? ($aExtraParams['dashboard'] == 'true') : false;
  563. //$bSelectMode = isset($aExtraParams['select']) ? ($aExtraParams['select'] == 'true') : false;
  564. if ( ($this->m_oSet->Count()> 0) && (UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_READ, $this->m_oSet) == UR_ALLOWED_YES) )
  565. {
  566. //$sLinkage = isset($aExtraParams['linkage']) ? $aExtraParams['linkage'] : '';
  567. $sHtml .= cmdbAbstractObject::GetDisplaySet($oPage, $this->m_oSet, $aExtraParams);
  568. }
  569. else
  570. {
  571. $sClass = $this->m_oFilter->GetClass();
  572. $oAttDef = MetaModel::GetAttributeDef($sClass, $this->m_aParams['target_attr']);
  573. $sTargetClass = $oAttDef->GetTargetClass();
  574. $sHtml .= $oPage->GetP(Dict::Format('UI:NoObject_Class_ToDisplay', MetaModel::GetName($sTargetClass)));
  575. $bDisplayMenu = isset($this->m_aParams['menu']) ? $this->m_aParams['menu'] == true : true;
  576. if ($bDisplayMenu)
  577. {
  578. if ((UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES))
  579. {
  580. $oAppContext = new ApplicationContext();
  581. $sParams = $oAppContext->GetForLink();
  582. $sDefaults = '';
  583. if (isset($this->m_aParams['default']))
  584. {
  585. foreach($this->m_aParams['default'] as $sName => $sValue)
  586. {
  587. $sDefaults .= '&'.urlencode($sName).'='.urlencode($sValue);
  588. }
  589. }
  590. $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");
  591. }
  592. }
  593. }
  594. break;
  595. case 'details':
  596. while($oObj = $this->m_oSet->Fetch())
  597. {
  598. $sHtml .= $oObj->GetDetails($oPage); // Still used ???
  599. }
  600. break;
  601. case 'actions':
  602. $sClass = $this->m_oFilter->GetClass();
  603. $oAppContext = new ApplicationContext();
  604. $bContextFilter = isset($aExtraParams['context_filter']) ? isset($aExtraParams['context_filter']) != 0 : false;
  605. if ($bContextFilter)
  606. {
  607. $aFilterCodes = array_keys(MetaModel::GetClassFilterDefs($this->m_oFilter->GetClass()));
  608. foreach($oAppContext->GetNames() as $sFilterCode)
  609. {
  610. $sContextParamValue = $oAppContext->GetCurrentValue($sFilterCode, null);
  611. if (!is_null($sContextParamValue) && ! empty($sContextParamValue) && MetaModel::IsValidFilterCode($sClass, $sFilterCode))
  612. {
  613. $this->m_oFilter->AddCondition($sFilterCode, $sContextParamValue); // Use the default 'loose' operator
  614. }
  615. }
  616. $aQueryParams = array();
  617. if (isset($aExtraParams['query_params']))
  618. {
  619. $aQueryParams = $aExtraParams['query_params'];
  620. }
  621. $this->m_oSet = new CMDBObjectSet($this->m_oFilter, array(), $aQueryParams);
  622. }
  623. $iCount = $this->m_oSet->Count();
  624. $sHyperlink = '../pages/UI.php?operation=search&'.$oAppContext->GetForLink().'&filter='.$this->m_oFilter->serialize();
  625. $sHtml .= '<p><a class="actions" href="'.$sHyperlink.'">';
  626. $sHtml .= MetaModel::GetClassIcon($sClass, true, 'float;left;margin-right:10px;');
  627. $sHtml .= MetaModel::GetName($sClass).': '.$iCount.'</a></p>';
  628. $sParams = $oAppContext->GetForLink();
  629. $sHtml .= '<p>';
  630. if (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY))
  631. {
  632. $sHtml .= "<a href=\"../pages/UI.php?operation=new&class={$sClass}&$sParams\">".Dict::Format('UI:ClickToCreateNew', MetaModel::GetName($sClass))."</a><br/>\n";
  633. }
  634. $sHtml .= "<a href=\"../pages/UI.php?operation=search_form&class={$sClass}&$sParams\">".Dict::Format('UI:SearchFor_Class', MetaModel::GetName($sClass))."</a>\n";
  635. $sHtml .= '</p>';
  636. break;
  637. case 'summary':
  638. $sClass = $this->m_oFilter->GetClass();
  639. $oAppContext = new ApplicationContext();
  640. $sTitle = isset($aExtraParams['title[block]']) ? $aExtraParams['title[block]'] : '';
  641. $sLabel = isset($aExtraParams['label[block]']) ? $aExtraParams['label[block]'] : '';
  642. $sStateAttrCode = isset($aExtraParams['status[block]']) ? $aExtraParams['status[block]'] : 'status';
  643. $sStatesList = isset($aExtraParams['status_codes[block]']) ? $aExtraParams['status_codes[block]'] : '';
  644. $bContextFilter = isset($aExtraParams['context_filter']) ? isset($aExtraParams['context_filter']) != 0 : false;
  645. if ($bContextFilter)
  646. {
  647. $aFilterCodes = array_keys(MetaModel::GetClassFilterDefs($this->m_oFilter->GetClass()));
  648. foreach($oAppContext->GetNames() as $sFilterCode)
  649. {
  650. $sContextParamValue = $oAppContext->GetCurrentValue($sFilterCode, null);
  651. if (!is_null($sContextParamValue) && ! empty($sContextParamValue) && MetaModel::IsValidFilterCode($sClass, $sFilterCode))
  652. {
  653. $this->m_oFilter->AddCondition($sFilterCode, $sContextParamValue); // Use the default 'loose' operator
  654. }
  655. }
  656. $aQueryParams = array();
  657. if (isset($aExtraParams['query_params']))
  658. {
  659. $aQueryParams = $aExtraParams['query_params'];
  660. }
  661. $this->m_oSet = new CMDBObjectSet($this->m_oFilter, array(), $aQueryParams);
  662. }
  663. // Summary details
  664. $aCounts = array();
  665. $aStateLabels = array();
  666. if (!empty($sStateAttrCode) && !empty($sStatesList))
  667. {
  668. $aStates = explode(',', $sStatesList);
  669. $oAttDef = MetaModel::GetAttributeDef($sClass, $sStateAttrCode);
  670. foreach($aStates as $sStateValue)
  671. {
  672. $oFilter = clone($this->m_oFilter);
  673. $oFilter->AddCondition($sStateAttrCode, $sStateValue, '=');
  674. $oSet = new DBObjectSet($oFilter);
  675. $aCounts[$sStateValue] = $oSet->Count();
  676. $aStateLabels[$sStateValue] = Dict::S("Class:".$oAttDef->GetHostClass()."/Attribute:$sStateAttrCode/Value:$sStateValue");
  677. if ($aCounts[$sStateValue] == 0)
  678. {
  679. $aCounts[$sStateValue] = '-';
  680. }
  681. else
  682. {
  683. $sHyperlink = '../pages/UI.php?operation=search&'.$oAppContext->GetForLink().'&filter='.$oFilter->serialize();
  684. $aCounts[$sStateValue] = "<a href=\"$sHyperlink\">{$aCounts[$sStateValue]}</a>";
  685. }
  686. }
  687. }
  688. $sHtml .= '<div class="summary-details"><table><tr><th>'.implode('</th><th>', $aStateLabels).'</th></tr>';
  689. $sHtml .= '<tr><td>'.implode('</td><td>', $aCounts).'</td></tr></table></div>';
  690. // Title & summary
  691. $iCount = $this->m_oSet->Count();
  692. $sHyperlink = '../pages/UI.php?operation=search&'.$oAppContext->GetForLink().'&filter='.$this->m_oFilter->serialize();
  693. $sHtml .= '<h1>'.Dict::S(str_replace('_', ':', $sTitle)).'</h1>';
  694. $sHtml .= '<a class="summary" href="'.$sHyperlink.'">'.Dict::Format(str_replace('_', ':', $sLabel), $iCount).'</a>';
  695. break;
  696. case 'bare_details':
  697. while($oObj = $this->m_oSet->Fetch())
  698. {
  699. $sHtml .= $oObj->GetBareProperties($oPage);
  700. }
  701. break;
  702. case 'csv':
  703. $sHtml .= "<textarea style=\"width:95%;height:98%\">\n";
  704. $sHtml .= cmdbAbstractObject::GetSetAsCSV($this->m_oSet);
  705. $sHtml .= "</textarea>\n";
  706. break;
  707. case 'modify':
  708. if ((UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_MODIFY, $this->m_oSet) == UR_ALLOWED_YES))
  709. {
  710. while($oObj = $this->m_oSet->Fetch())
  711. {
  712. $sHtml .= $oObj->GetModifyForm($oPage);
  713. }
  714. }
  715. break;
  716. case 'search':
  717. $sStyle = (isset($aExtraParams['open']) && ($aExtraParams['open'] == 'true')) ? 'SearchDrawer' : 'SearchDrawer DrawerClosed';
  718. $sHtml .= "<div id=\"ds_$sId\" class=\"$sStyle\">\n";
  719. $oPage->add_ready_script(
  720. <<<EOF
  721. $("#dh_$sId").click( function() {
  722. $("#ds_$sId").slideToggle('normal', function() { $("#ds_$sId").parent().resize(); } );
  723. $("#dh_$sId").toggleClass('open');
  724. });
  725. EOF
  726. );
  727. $aExtraParams['currentId'] = $sId;
  728. $sHtml .= cmdbAbstractObject::GetSearchForm($oPage, $this->m_oSet, $aExtraParams);
  729. $sHtml .= "</div>\n";
  730. $sHtml .= "<div class=\"HRDrawer\"></div>\n";
  731. $sHtml .= "<div id=\"dh_$sId\" class=\"DrawerHandle\">".Dict::S('UI:SearchToggle')."</div>\n";
  732. break;
  733. case 'open_flash_chart':
  734. static $iChartCounter = 0;
  735. $sChartType = isset($aExtraParams['chart_type']) ? $aExtraParams['chart_type'] : 'pie';
  736. $sTitle = isset($aExtraParams['chart_title']) ? $aExtraParams['chart_title'] : '';
  737. $sGroupBy = isset($aExtraParams['group_by']) ? $aExtraParams['group_by'] : '';
  738. $sGroupByExpr = isset($aExtraParams['group_by_expr']) ? '&params[group_by_expr]='.$aExtraParams['group_by_expr'] : '';
  739. $sFilter = $this->m_oFilter->serialize();
  740. $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";
  741. $oPage->add_script("function ofc_resize(left, width, top, height) { /* do nothing special */ }");
  742. $oPage->add_ready_script("swfobject.embedSWF(\"../images/open-flash-chart.swf\", \"my_chart_{$iChartCounter}\", \"100%\", \"300\",\"9.0.0\", \"expressInstall.swf\",
  743. {\"data-file\":\"".urlencode("../pages/ajax.render.php?operation=open_flash_chart&params[group_by]=$sGroupBy{$sGroupByExpr}&params[chart_type]=$sChartType&params[chart_title]=$sTitle&filter=".$sFilter)."\"}, {wmode: 'transparent'} );\n");
  744. $iChartCounter++;
  745. break;
  746. case 'open_flash_chart_ajax':
  747. require_once(APPROOT.'/pages/php-ofc-library/open-flash-chart.php');
  748. $sChartType = isset($aExtraParams['chart_type']) ? $aExtraParams['chart_type'] : 'pie';
  749. $oChart = new open_flash_chart();
  750. switch($sChartType)
  751. {
  752. case 'bars':
  753. $oChartElement = new bar_glass();
  754. if (isset($aExtraParams['group_by']))
  755. {
  756. $sGroupByField = $aExtraParams['group_by'];
  757. $aGroupBy = array();
  758. while($oObj = $this->m_oSet->Fetch())
  759. {
  760. if (isset($aExtraParams['group_by_expr']))
  761. {
  762. eval("\$sValue = ".sprintf($aExtraParams['group_by_expr'], $oObj->Get($sGroupByField)).';');
  763. }
  764. else
  765. {
  766. $sValue = $oObj->Get($sGroupByField);
  767. }
  768. $aGroupBy[$sValue] = isset($aGroupBy[$sValue]) ? $aGroupBy[$sValue]+1 : 1;
  769. }
  770. $sFilter = urlencode($this->m_oFilter->serialize());
  771. $aData = array();
  772. $aLabels = array();
  773. foreach($aGroupBy as $sValue => $iValue)
  774. {
  775. $aData[] = $iValue;
  776. $aLabels[] = $sValue;
  777. }
  778. $maxValue = max($aData);
  779. $oYAxis = new y_axis();
  780. $aMagicValues = array(1,2,5,10);
  781. $iMultiplier = 1;
  782. $index = 0;
  783. $iTop = $aMagicValues[$index % count($aMagicValues)]*$iMultiplier;
  784. while($maxValue > $iTop)
  785. {
  786. $index++;
  787. $iTop = $aMagicValues[$index % count($aMagicValues)]*$iMultiplier;
  788. if (($index % count($aMagicValues)) == 0)
  789. {
  790. $iMultiplier = $iMultiplier * 10;
  791. }
  792. }
  793. //echo "oYAxis->set_range(0, $iTop, $iMultiplier);\n";
  794. $oYAxis->set_range(0, $iTop, $iMultiplier);
  795. $oChart->set_y_axis( $oYAxis );
  796. $oChartElement->set_values( $aData );
  797. $oXAxis = new x_axis();
  798. $oXLabels = new x_axis_labels();
  799. // set them vertical
  800. $oXLabels->set_vertical();
  801. // set the label text
  802. $oXLabels->set_labels($aLabels);
  803. // Add the X Axis Labels to the X Axis
  804. $oXAxis->set_labels( $oXLabels );
  805. $oChart->set_x_axis( $oXAxis );
  806. }
  807. break;
  808. case 'pie':
  809. default:
  810. $oChartElement = new pie();
  811. $oChartElement->set_start_angle( 35 );
  812. $oChartElement->set_animate( true );
  813. $oChartElement->set_tooltip( '#label# - #val# (#percent#)' );
  814. $oChartElement->set_colours( array('#FF8A00', '#909980', '#2C2B33', '#CCC08D', '#596664') );
  815. if (isset($aExtraParams['group_by']))
  816. {
  817. $sGroupByField = $aExtraParams['group_by'];
  818. $aGroupBy = array();
  819. while($oObj = $this->m_oSet->Fetch())
  820. {
  821. if (isset($aExtraParams['group_by_expr']))
  822. {
  823. eval("\$sValue = ".sprintf($aExtraParams['group_by_expr'], $oObj->Get($sGroupByField)).';');
  824. }
  825. else
  826. {
  827. $sValue = $oObj->Get($sGroupByField);
  828. }
  829. $aGroupBy[$sValue] = isset($aGroupBy[$sValue]) ? $aGroupBy[$sValue]+1 : 1;
  830. }
  831. $sFilter = urlencode($this->m_oFilter->serialize());
  832. $aData = array();
  833. foreach($aGroupBy as $sValue => $iValue)
  834. {
  835. $aData[] = new pie_value($iValue, $sValue); //@@ BUG: not passed via ajax !!!
  836. }
  837. $oChartElement->set_values( $aData );
  838. $oChart->x_axis = null;
  839. }
  840. }
  841. if (isset($aExtraParams['chart_title']))
  842. {
  843. $oTitle = new title( Dict::S($aExtraParams['chart_title']) );
  844. $oChart->set_title( $oTitle );
  845. }
  846. $oChart->set_bg_colour('#FFFFFF');
  847. $oChart->add_element( $oChartElement );
  848. $sHtml = $oChart->toPrettyString();
  849. break;
  850. default:
  851. // Unsupported style, do nothing.
  852. $sHtml .= Dict::format('UI:Error:UnsupportedStyleOfBlock', $this->m_sStyle);
  853. }
  854. return $sHtml;
  855. }
  856. }
  857. /**
  858. * Helper class to manage 'blocks' of HTML pieces that are parts of a page and contain some list of cmdb objects
  859. *
  860. * Each block is actually rendered as a <div></div> tag that can be rendered synchronously
  861. * or as a piece of Javascript/JQuery/Ajax that will get its content from another page (ajax.render.php).
  862. * The list of cmdbObjects to be displayed into the block is defined by a filter
  863. * Right now the type of display is either: list, count or details
  864. * - list produces a table listing the objects
  865. * - count produces a paragraphs with a sentence saying 'cont' objects found
  866. * - details display (as table) the details of each object found (best if only one)
  867. */
  868. class HistoryBlock extends DisplayBlock
  869. {
  870. public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId)
  871. {
  872. $sHtml = '';
  873. $oSet = new CMDBObjectSet($this->m_oFilter, array('date'=>false));
  874. $sHtml .= "<!-- filter: ".($this->m_oFilter->ToOQL())."-->\n";
  875. switch($this->m_sStyle)
  876. {
  877. case 'toggle':
  878. // First the latest change that the user is allowed to see
  879. do
  880. {
  881. $oLatestChangeOp = $oSet->Fetch();
  882. }
  883. while(is_object($oLatestChangeOp) && ($oLatestChangeOp->GetDescription() == ''));
  884. if (is_object($oLatestChangeOp))
  885. {
  886. // There is one change in the list... only when the object has been created !
  887. $sDate = $oLatestChangeOp->GetAsHTML('date');
  888. $oChange = MetaModel::GetObject('CMDBChange', $oLatestChangeOp->Get('change'));
  889. $sUserInfo = $oChange->GetAsHTML('userinfo');
  890. $sHtml .= $oPage->GetStartCollapsibleSection(Dict::Format('UI:History:LastModified_On_By', $sDate, $sUserInfo));
  891. $sHtml .= $this->GetHistoryTable($oPage, $oSet);
  892. $sHtml .= $oPage->GetEndCollapsibleSection();
  893. }
  894. break;
  895. case 'table':
  896. default:
  897. $sHtml .= $this->GetHistoryTable($oPage, $oSet);
  898. }
  899. return $sHtml;
  900. }
  901. protected function GetHistoryTable(WebPage $oPage, DBObjectSet $oSet)
  902. {
  903. $sHtml = '';
  904. // First the latest change that the user is allowed to see
  905. $oSet->Rewind(); // Reset the pointer to the beginning of the set
  906. $aChanges = array();
  907. while($oChangeOp = $oSet->Fetch())
  908. {
  909. $sChangeDescription = $oChangeOp->GetDescription();
  910. if ($sChangeDescription != '')
  911. {
  912. // The change is visible for the current user
  913. $changeId = $oChangeOp->Get('change');
  914. $aChanges[$changeId]['date'] = $oChangeOp->Get('date');
  915. $aChanges[$changeId]['userinfo'] = $oChangeOp->Get('userinfo');
  916. if (!isset($aChanges[$changeId]['log']))
  917. {
  918. $aChanges[$changeId]['log'] = array();
  919. }
  920. $aChanges[$changeId]['log'][] = $sChangeDescription;
  921. }
  922. }
  923. $aAttribs = array('date' => array('label' => Dict::S('UI:History:Date'), 'description' => Dict::S('UI:History:Date+')),
  924. 'userinfo' => array('label' => Dict::S('UI:History:User'), 'description' => Dict::S('UI:History:User+')),
  925. 'log' => array('label' => Dict::S('UI:History:Changes'), 'description' => Dict::S('UI:History:Changes+')),
  926. );
  927. $aValues = array();
  928. foreach($aChanges as $aChange)
  929. {
  930. $aValues[] = array('date' => $aChange['date'], 'userinfo' => $aChange['userinfo'], 'log' => "<ul><li>".implode('</li><li>', $aChange['log'])."</li></ul>");
  931. }
  932. $sHtml .= $oPage->GetTable($aAttribs, $aValues);
  933. return $sHtml;
  934. }
  935. }
  936. class MenuBlock extends DisplayBlock
  937. {
  938. /**
  939. * Renders the "Actions" popup menu for the given set of objects
  940. *
  941. * Note that the menu links containing (or ending) with a hash (#) will have their fragment
  942. * part (whatever is after the hash) dynamically replaced (by javascript) when the menu is
  943. * displayed, to correspond to the current hash/fragment in the page. This allows modifying
  944. * an object in with the same tab active by default as the tab that was active when selecting
  945. * the "Modify..." action.
  946. */
  947. public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId)
  948. {
  949. $sHtml = '';
  950. $oAppContext = new ApplicationContext();
  951. $sContext = $oAppContext->GetForLink();
  952. $sClass = $this->m_oFilter->GetClass();
  953. $oSet = new CMDBObjectSet($this->m_oFilter);
  954. $sFilter = $this->m_oFilter->serialize();
  955. $aActions = array();
  956. $sUIPage = cmdbAbstractObject::ComputeUIPage($sClass);
  957. // 1:n links, populate the target object as a default value when creating a new linked object
  958. if (isset($aExtraParams['target_attr']))
  959. {
  960. $aExtraParams['default'][$aExtraParams['target_attr']] = $aExtraParams['object_id'];
  961. }
  962. $sDefault = '';
  963. if (!empty($aExtraParams['default']))
  964. {
  965. foreach($aExtraParams['default'] as $sKey => $sValue)
  966. {
  967. $sDefault.= "&default[$sKey]=$sValue";
  968. }
  969. }
  970. switch($oSet->Count())
  971. {
  972. case 0:
  973. // No object in the set, the only possible action is "new"
  974. $bIsModifyAllowed = (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES);
  975. if ($bIsModifyAllowed) { $aActions[] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "../page/$sUIPage?operation=new&class=$sClass&$sContext{$sDefault}"); }
  976. break;
  977. case 1:
  978. $oObj = $oSet->Fetch();
  979. $id = $oObj->GetKey();
  980. $bIsModifyAllowed = (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet) == UR_ALLOWED_YES);
  981. $bIsDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, $oSet);
  982. $bIsBulkModifyAllowed = (!MetaModel::IsAbstract($sClass)) && UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_MODIFY, $oSet);
  983. $bIsBulkDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_DELETE, $oSet);
  984. // Just one object in the set, possible actions are "new / clone / modify and delete"
  985. if (!isset($aExtraParams['link_attr']))
  986. {
  987. $sUrl = utils::GetAbsoluteUrl(false);
  988. if ($bIsModifyAllowed) { $aActions[] = array ('label' => Dict::S('UI:Menu:Modify'), 'url' => "../pages/$sUIPage?operation=modify&class=$sClass&id=$id&$sContext#"); }
  989. if ($bIsModifyAllowed) { $aActions[] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "../pages/$sUIPage?operation=new&class=$sClass&$sContext{$sDefault}"); }
  990. if ($bIsDeleteAllowed) { $aActions[] = array ('label' => Dict::S('UI:Menu:Delete'), 'url' => "../pages/$sUIPage?operation=delete&class=$sClass&id=$id&$sContext"); }
  991. // Transitions / Stimuli
  992. $aTransitions = $oObj->EnumTransitions();
  993. if (count($aTransitions))
  994. {
  995. $this->AddMenuSeparator($aActions);
  996. $aStimuli = Metamodel::EnumStimuli($sClass);
  997. foreach($aTransitions as $sStimulusCode => $aTransitionDef)
  998. {
  999. $iActionAllowed = (get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction') ? UserRights::IsStimulusAllowed($sClass, $sStimulusCode, $oSet) : UR_ALLOWED_NO;
  1000. switch($iActionAllowed)
  1001. {
  1002. case UR_ALLOWED_YES:
  1003. $aActions[] = array('label' => $aStimuli[$sStimulusCode]->GetLabel(), 'url' => "../pages/UI.php?operation=stimulus&stimulus=$sStimulusCode&class=$sClass&id=$id&$sContext");
  1004. break;
  1005. default:
  1006. // Do nothing
  1007. }
  1008. }
  1009. }
  1010. // Relations...
  1011. $aRelations = MetaModel::EnumRelations($sClass);
  1012. if (count($aRelations))
  1013. {
  1014. $this->AddMenuSeparator($aActions);
  1015. foreach($aRelations as $sRelationCode)
  1016. {
  1017. $aActions[] = array ('label' => MetaModel::GetRelationVerbUp($sRelationCode), 'url' => "../pages/$sUIPage?operation=swf_navigator&relation=$sRelationCode&class=$sClass&id=$id&$sContext");
  1018. }
  1019. }
  1020. $this->AddMenuSeparator($aActions);
  1021. // Static menus: Email this page & CSV Export
  1022. $aActions[] = array ('label' => Dict::S('UI:Menu:EMail'), 'url' => "mailto:?subject=".$oObj->GetName()."&body=".urlencode("$sUrl?operation=details&class=$sClass&id=$id&$sContext"));
  1023. $aActions[] = array ('label' => Dict::S('UI:Menu:CSVExport'), 'url' => "../pages/$sUIPage?operation=search&filter=$sFilter&format=csv&$sContext");
  1024. }
  1025. else
  1026. {
  1027. // List of links, the only actions are 'Add...' and 'Manage...'
  1028. $id = $aExtraParams['object_id'];
  1029. $sTargetAttr = $aExtraParams['target_attr'];
  1030. $oAttDef = MetaModel::GetAttributeDef($sClass, $sTargetAttr);
  1031. $sTargetClass = $oAttDef->GetTargetClass();
  1032. 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"); }
  1033. if ($bIsModifyAllowed) { $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"); }
  1034. }
  1035. $this->AddMenuSeparator($aActions);
  1036. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  1037. {
  1038. $oSet->Rewind();
  1039. foreach($oExtensionInstance->EnumAllowedActions($oSet) as $sLabel => $sUrl)
  1040. {
  1041. $aActions[] = array ('label' => $sLabel, 'url' => $sUrl);
  1042. }
  1043. }
  1044. break;
  1045. default:
  1046. // Check rights
  1047. // New / Modify
  1048. $bIsModifyAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet);
  1049. $bIsBulkModifyAllowed = (!MetaModel::IsAbstract($sClass)) && UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_MODIFY, $oSet);
  1050. $bIsBulkDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_DELETE, $oSet);
  1051. if (isset($aExtraParams['link_attr']))
  1052. {
  1053. $id = $aExtraParams['object_id'];
  1054. $sTargetAttr = $aExtraParams['target_attr'];
  1055. $oAttDef = MetaModel::GetAttributeDef($sClass, $sTargetAttr);
  1056. $sTargetClass = $oAttDef->GetTargetClass();
  1057. $bIsDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, $oSet);
  1058. 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"); }
  1059. 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"); }
  1060. //if ($bIsBulkDeleteAllowed) { $aActions[] = array ('label' => 'Remove All...', 'url' => "#"); }
  1061. }
  1062. else
  1063. {
  1064. // many objects in the set, possible actions are: new / modify all / delete all
  1065. $sUrl = utils::GetAbsoluteUrl();
  1066. if ($bIsModifyAllowed) { $aActions[] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "../pages/$sUIPage?operation=new&class=$sClass&$sContext{$sDefault}"); }
  1067. if ($bIsBulkModifyAllowed) { $aActions[] = array ('label' => Dict::S('UI:Menu:ModifyAll'), 'url' => "../pages/$sUIPage?operation=select_for_modify_all&class=$sClass&filter=$sFilter&sContext"); }
  1068. if ($bIsBulkDeleteAllowed) { $aActions[] = array ('label' => Dict::S('UI:Menu:BulkDelete'), 'url' => "../pages/$sUIPage?operation=select_for_deletion&filter=$sFilter&$sContext"); }
  1069. // Stimuli
  1070. $aStates = MetaModel::EnumStates($sClass);
  1071. if (count($aStates) > 0)
  1072. {
  1073. // Life cycle actions may be available... if all objects are in the same state
  1074. $oSet->Rewind();
  1075. $aStates = array();
  1076. while($oObj = $oSet->Fetch())
  1077. {
  1078. $aStates[$oObj->GetState()] = $oObj->GetState();
  1079. }
  1080. $oSet->Rewind();
  1081. if (count($aStates) == 1)
  1082. {
  1083. // All objects are in the same state...
  1084. $sState = array_pop($aStates);
  1085. $aTransitions = Metamodel::EnumTransitions($sClass, $sState);
  1086. if (count($aTransitions))
  1087. {
  1088. $this->AddMenuSeparator($aActions);
  1089. $aStimuli = Metamodel::EnumStimuli($sClass);
  1090. foreach($aTransitions as $sStimulusCode => $aTransitionDef)
  1091. {
  1092. $oChecker = new StimulusChecker($this->m_oFilter, $sState, $sStimulusCode);
  1093. $iActionAllowed = (get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction') ? $oChecker->IsAllowed() : UR_ALLOWED_NO;
  1094. switch($iActionAllowed)
  1095. {
  1096. case UR_ALLOWED_YES:
  1097. case UR_ALLOWED_DEPENDS:
  1098. $aActions[] = array('label' => $aStimuli[$sStimulusCode]->GetLabel(), 'url' => "../pages/UI.php?operation=select_bulk_stimulus&stimulus=$sStimulusCode&state=$sState&class=$sClass&filter=$sFilter&$sContext");
  1099. break;
  1100. default:
  1101. // Do nothing
  1102. }
  1103. }
  1104. }
  1105. }
  1106. }
  1107. $this->AddMenuSeparator($aActions);
  1108. $aActions[] = array ('label' => Dict::S('UI:Menu:EMail'), 'url' => "mailto:?subject=".$oSet->GetFilter()->__DescribeHTML()."&body=".urlencode("$sUrl?operation=search&filter=$sFilter&$sContext"));
  1109. $aActions[] = array ('label' => Dict::S('UI:Menu:CSVExport'), 'url' => "../pages/$sUIPage?operation=search&filter=$sFilter&format=csv&$sContext");
  1110. }
  1111. $this->AddMenuSeparator($aActions);
  1112. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  1113. {
  1114. $oSet->Rewind();
  1115. foreach($oExtensionInstance->EnumAllowedActions($oSet) as $sLabel => $sUrl)
  1116. {
  1117. $aActions[] = array ('label' => $sLabel, 'url' => $sUrl);
  1118. }
  1119. }
  1120. }
  1121. $sHtml .= "<div class=\"itop_popup\"><ul>\n<li>".Dict::S('UI:Menu:Actions')."\n<ul>\n";
  1122. foreach ($aActions as $aAction)
  1123. {
  1124. $sClass = isset($aAction['class']) ? " class=\"{$aAction['class']}\"" : "";
  1125. if (empty($aAction['url']))
  1126. {
  1127. $sHtml .= "<li>{$aAction['label']}</li>\n";
  1128. }
  1129. else
  1130. {
  1131. $sHtml .= "<li><a href=\"{$aAction['url']}\"$sClass>{$aAction['label']}</a></li>\n";
  1132. }
  1133. }
  1134. $sHtml .= "</ul>\n</li>\n</ul></div>\n";
  1135. static $bPopupScript = false;
  1136. if (!$bPopupScript)
  1137. {
  1138. // Output this once per page...
  1139. $oPage->add_ready_script("$(\"div.itop_popup>ul\").popupmenu();\n");
  1140. $bPopupScript = true;
  1141. }
  1142. return $sHtml;
  1143. }
  1144. /**
  1145. * Appends a menu separator to the current list of actions
  1146. * @param Hash $aActions The current actions list
  1147. * @return void
  1148. */
  1149. protected function AddMenuSeparator(&$aActions)
  1150. {
  1151. $sSeparator = '<hr class="menu-separator"/>';
  1152. if (count($aActions) > 0) // Make sure that the separator is not the first item in the menu
  1153. {
  1154. if ($aActions[count($aActions)-1]['label'] != $sSeparator) // Make sure there are no 2 consecutive separators
  1155. {
  1156. $aActions[] = array('label' => $sSeparator, 'url' => '');
  1157. }
  1158. }
  1159. }
  1160. }
  1161. ?>