displayblock.class.inc.php 52 KB

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