displayblock.class.inc.php 47 KB

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