displayblock.class.inc.php 48 KB

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