displayblock.class.inc.php 48 KB

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