displayblock.class.inc.php 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712
  1. <?php
  2. // Copyright (C) 2010-2017 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * DisplayBlock and derived class
  20. *
  21. * @copyright Copyright (C) 2010-2017 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  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_aConditions; // Conditions added to the filter -> avoid duplicate conditions
  46. protected $m_sStyle;
  47. protected $m_bAsynchronous;
  48. protected $m_aParams;
  49. protected $m_oSet;
  50. public function __construct(DBSearch $oFilter, $sStyle = 'list', $bAsynchronous = false, $aParams = array(), $oSet = null)
  51. {
  52. $this->m_oFilter = $oFilter->DeepClone();
  53. $this->m_aConditions = array();
  54. $this->m_sStyle = $sStyle;
  55. $this->m_bAsynchronous = $bAsynchronous;
  56. $this->m_aParams = $aParams;
  57. $this->m_oSet = $oSet;
  58. }
  59. public function GetFilter()
  60. {
  61. return $this->m_oFilter;
  62. }
  63. /**
  64. * Constructs a DisplayBlock object from a DBObjectSet already in memory
  65. * @param $oSet DBObjectSet
  66. * @return DisplayBlock The DisplayBlock object, or null if the creation failed
  67. */
  68. public static function FromObjectSet(DBObjectSet $oSet, $sStyle, $aParams = array())
  69. {
  70. $oDummyFilter = new DBObjectSearch($oSet->GetClass());
  71. $aKeys = array();
  72. $oSet->OptimizeColumnLoad(array('id')); // No need to load all the columns just to get the id
  73. while($oObject = $oSet->Fetch())
  74. {
  75. $aKeys[] = $oObject->GetKey();
  76. }
  77. $oSet->Rewind();
  78. if (count($aKeys) > 0)
  79. {
  80. $oDummyFilter->AddCondition('id', $aKeys, 'IN');
  81. }
  82. else
  83. {
  84. $oDummyFilter->AddCondition('id', 0, '=');
  85. }
  86. $oBlock = new DisplayBlock($oDummyFilter, $sStyle, false, $aParams); // DisplayBlocks built this way are synchronous
  87. return $oBlock;
  88. }
  89. /**
  90. * Constructs a DisplayBlock object from an XML template
  91. * @param $sTemplate string The XML template
  92. * @return DisplayBlock The DisplayBlock object, or null if the template is invalid
  93. */
  94. public static function FromTemplate($sTemplate)
  95. {
  96. $iStartPos = stripos($sTemplate, '<'.self::TAG_BLOCK.' ',0);
  97. $iEndPos = stripos($sTemplate, '</'.self::TAG_BLOCK.'>', $iStartPos);
  98. $iEndTag = stripos($sTemplate, '>', $iStartPos);
  99. $aParams = array();
  100. if (($iStartPos === false) || ($iEndPos === false)) return null; // invalid template
  101. $sITopBlock = substr($sTemplate,$iStartPos, $iEndPos-$iStartPos+strlen('</'.self::TAG_BLOCK.'>'));
  102. $sITopData = substr($sTemplate, 1+$iEndTag, $iEndPos - $iEndTag - 1);
  103. $sITopTag = substr($sTemplate, $iStartPos + strlen('<'.self::TAG_BLOCK), $iEndTag - $iStartPos - strlen('<'.self::TAG_BLOCK));
  104. $aMatches = array();
  105. $sBlockClass = "DisplayBlock";
  106. $bAsynchronous = false;
  107. $sBlockType = 'list';
  108. $sEncoding = 'text/serialize';
  109. if (preg_match('/ type="(.*)"/U',$sITopTag, $aMatches))
  110. {
  111. $sBlockType = strtolower($aMatches[1]);
  112. }
  113. if (preg_match('/ asynchronous="(.*)"/U',$sITopTag, $aMatches))
  114. {
  115. $bAsynchronous = (strtolower($aMatches[1]) == 'true');
  116. }
  117. if (preg_match('/ blockclass="(.*)"/U',$sITopTag, $aMatches))
  118. {
  119. $sBlockClass = $aMatches[1];
  120. }
  121. if (preg_match('/ objectclass="(.*)"/U',$sITopTag, $aMatches))
  122. {
  123. $sObjectClass = $aMatches[1];
  124. }
  125. if (preg_match('/ encoding="(.*)"/U',$sITopTag, $aMatches))
  126. {
  127. $sEncoding = strtolower($aMatches[1]);
  128. }
  129. if (preg_match('/ link_attr="(.*)"/U',$sITopTag, $aMatches))
  130. {
  131. // The list to display is a list of links to the specified object
  132. $aParams['link_attr'] = $aMatches[1]; // Name of the Ext. Key that makes this linkage
  133. }
  134. if (preg_match('/ target_attr="(.*)"/U',$sITopTag, $aMatches))
  135. {
  136. // The list to display is a list of links to the specified object
  137. $aParams['target_attr'] = $aMatches[1]; // Name of the Ext. Key that make this linkage
  138. }
  139. if (preg_match('/ object_id="(.*)"/U',$sITopTag, $aMatches))
  140. {
  141. // The list to display is a list of links to the specified object
  142. $aParams['object_id'] = $aMatches[1]; // Id of the object to be linked to
  143. }
  144. // Parameters contains a list of extra parameters for the block
  145. // the syntax is param_name1:value1;param_name2:value2;...
  146. if (preg_match('/ parameters="(.*)"/U',$sITopTag, $aMatches))
  147. {
  148. $sParameters = $aMatches[1];
  149. $aPairs = explode(';', $sParameters);
  150. foreach($aPairs as $sPair)
  151. {
  152. if (preg_match('/(.*)\:(.*)/',$sPair, $aMatches))
  153. {
  154. $aParams[trim($aMatches[1])] = trim($aMatches[2]);
  155. }
  156. }
  157. }
  158. if (!empty($aParams['link_attr']))
  159. {
  160. // Check that all mandatory parameters are present:
  161. if(empty($aParams['object_id']))
  162. {
  163. // if 'links' mode is requested the d of the object to link to must be specified
  164. throw new ApplicationException(Dict::S('UI:Error:MandatoryTemplateParameter_object_id'));
  165. }
  166. if(empty($aParams['target_attr']))
  167. {
  168. // if 'links' mode is requested the id of the object to link to must be specified
  169. throw new ApplicationException(Dict::S('UI:Error:MandatoryTemplateParameter_target_attr'));
  170. }
  171. }
  172. switch($sEncoding)
  173. {
  174. case 'text/serialize':
  175. $oFilter = DBSearch::unserialize($sITopData);
  176. break;
  177. case 'text/oql':
  178. $oFilter = DBSearch::FromOQL($sITopData);
  179. break;
  180. }
  181. return new $sBlockClass($oFilter, $sBlockType, $bAsynchronous, $aParams);
  182. }
  183. public function Display(WebPage $oPage, $sId, $aExtraParams = array())
  184. {
  185. $oPage->add($this->GetDisplay($oPage, $sId, $aExtraParams));
  186. }
  187. public function GetDisplay(WebPage $oPage, $sId, $aExtraParams = array())
  188. {
  189. $sHtml = '';
  190. $aExtraParams = array_merge($aExtraParams, $this->m_aParams);
  191. $aExtraParams['currentId'] = $sId;
  192. $sExtraParams = addslashes(str_replace('"', "'", json_encode($aExtraParams))); // JSON encode, change the style of the quotes and escape them
  193. $bAutoReload = false;
  194. if (isset($aExtraParams['auto_reload']))
  195. {
  196. if ($aExtraParams['auto_reload'] === true)
  197. {
  198. // Note: does not work in the switch (case true) because a positive number evaluates to true!!!
  199. $aExtraParams['auto_reload'] = 'standard';
  200. }
  201. switch($aExtraParams['auto_reload'])
  202. {
  203. case 'fast':
  204. $bAutoReload = true;
  205. $iReloadInterval = MetaModel::GetConfig()->GetFastReloadInterval()*1000;
  206. break;
  207. case 'standard':
  208. case 'true':
  209. $bAutoReload = true;
  210. $iReloadInterval = MetaModel::GetConfig()->GetStandardReloadInterval()*1000;
  211. break;
  212. default:
  213. if (is_numeric($aExtraParams['auto_reload']) && ($aExtraParams['auto_reload'] > 0))
  214. {
  215. $bAutoReload = true;
  216. $iReloadInterval = max(MetaModel::GetConfig()->Get('min_reload_interval'), $aExtraParams['auto_reload'])*1000;
  217. }
  218. else
  219. {
  220. // incorrect config, ignore it
  221. $bAutoReload = false;
  222. }
  223. }
  224. }
  225. $sFilter = $this->m_oFilter->serialize(); // Used either for asynchronous or auto_reload
  226. if (!$this->m_bAsynchronous)
  227. {
  228. // render now
  229. $sHtml .= "<div id=\"$sId\" class=\"display_block\">\n";
  230. $sHtml .= $this->GetRenderContent($oPage, $aExtraParams, $sId);
  231. $sHtml .= "</div>\n";
  232. }
  233. else
  234. {
  235. // render it as an Ajax (asynchronous) call
  236. $sHtml .= "<div id=\"$sId\" class=\"display_block loading\">\n";
  237. $sHtml .= $oPage->GetP("<img src=\"../images/indicator_arrows.gif\"> ".Dict::S('UI:Loading'));
  238. $sHtml .= "</div>\n";
  239. $oPage->add_script('
  240. $.post("ajax.render.php?style='.$this->m_sStyle.'",
  241. { operation: "ajax", filter: "'.$sFilter.'", extra_params: "'.$sExtraParams.'" },
  242. function(data){
  243. $("#'.$sId.'").empty();
  244. $("#'.$sId.'").append(data);
  245. $("#'.$sId.'").removeClass("loading");
  246. }
  247. );
  248. ');
  249. }
  250. if (($bAutoReload) && ($this->m_sStyle != 'search')) // Search form do NOT auto-reload
  251. {
  252. $oPage->add_script('setInterval("ReloadBlock(\''.$sId.'\', \''.$this->m_sStyle.'\', \''.$sFilter.'\', \"'.$sExtraParams.'\")", '.$iReloadInterval.');');
  253. }
  254. return $sHtml;
  255. }
  256. public function RenderContent(WebPage $oPage, $aExtraParams = array())
  257. {
  258. if (!isset($aExtraParams['currentId']))
  259. {
  260. $sId = $oPage->GetUniqueId(); // Works only if the page is not an Ajax one !
  261. }
  262. else
  263. {
  264. $sId = $aExtraParams['currentId'];
  265. }
  266. $oPage->add($this->GetRenderContent($oPage, $aExtraParams, $sId));
  267. }
  268. public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId)
  269. {
  270. $sHtml = '';
  271. // Add the extra params into the filter if they make sense for such a filter
  272. $bDoSearch = utils::ReadParam('dosearch', false);
  273. if ($this->m_oSet == null)
  274. {
  275. $aQueryParams = array();
  276. if (isset($aExtraParams['query_params']))
  277. {
  278. $aQueryParams = $aExtraParams['query_params'];
  279. }
  280. if ($this->m_sStyle != 'links')
  281. {
  282. $oAppContext = new ApplicationContext();
  283. $sClass = $this->m_oFilter->GetClass();
  284. $aFilterCodes = array_keys(MetaModel::GetClassFilterDefs($sClass));
  285. $aCallSpec = array($sClass, 'MapContextParam');
  286. if (is_callable($aCallSpec))
  287. {
  288. foreach($oAppContext->GetNames() as $sContextParam)
  289. {
  290. $sParamCode = call_user_func($aCallSpec, $sContextParam); //Map context parameter to the value/filter code depending on the class
  291. if (!is_null($sParamCode))
  292. {
  293. $sParamValue = $oAppContext->GetCurrentValue($sContextParam, null);
  294. if (!is_null($sParamValue))
  295. {
  296. $aExtraParams[$sParamCode] = $sParamValue;
  297. }
  298. }
  299. }
  300. }
  301. foreach($aFilterCodes as $sFilterCode)
  302. {
  303. $externalFilterValue = utils::ReadParam($sFilterCode, '', false, 'raw_data');
  304. $condition = null;
  305. $bParseSearchString = true;
  306. if (isset($aExtraParams[$sFilterCode]))
  307. {
  308. $bParseSearchString = false;
  309. $condition = $aExtraParams[$sFilterCode];
  310. }
  311. if ($bDoSearch && $externalFilterValue != "")
  312. {
  313. // Search takes precedence over context params...
  314. $bParseSearchString = true;
  315. unset($aExtraParams[$sFilterCode]);
  316. if (!is_array($externalFilterValue))
  317. {
  318. $condition = trim($externalFilterValue);
  319. }
  320. else if (count($externalFilterValue) == 1)
  321. {
  322. $condition = trim($externalFilterValue[0]);
  323. }
  324. else
  325. {
  326. $condition = $externalFilterValue;
  327. }
  328. }
  329. if (!is_null($condition))
  330. {
  331. $sOpCode = null; // default operator
  332. if (is_array($condition))
  333. {
  334. // Multiple values, add them as AND X IN (v1, v2, v3...)
  335. $sOpCode = 'IN';
  336. }
  337. $this->AddCondition($sFilterCode, $condition, $sOpCode, $bParseSearchString);
  338. }
  339. }
  340. if ($bDoSearch)
  341. {
  342. // Keep the table_id identifying this table if we're performing a search
  343. $sTableId = utils::ReadParam('_table_id_', null, false, 'raw_data');
  344. if ($sTableId != null)
  345. {
  346. $aExtraParams['table_id'] = $sTableId;
  347. }
  348. }
  349. }
  350. $aOrderBy = array();
  351. if (isset($aExtraParams['order_by']))
  352. {
  353. // Convert the string describing the order_by parameter into an array
  354. // The syntax is +attCode1,-attCode2
  355. // attCode1 => ascending, attCode2 => descending
  356. $aTemp = explode(',', $aExtraParams['order_by']);
  357. foreach($aTemp as $sTemp)
  358. {
  359. $aMatches = array();
  360. if (preg_match('/^([+-])?(.+)$/', $sTemp, $aMatches))
  361. {
  362. $bAscending = true;
  363. if ($aMatches[1] == '-')
  364. {
  365. $bAscending = false;
  366. }
  367. $aOrderBy[$aMatches[2]] = $bAscending;
  368. }
  369. }
  370. }
  371. $this->m_oSet = new CMDBObjectSet($this->m_oFilter, $aOrderBy, $aQueryParams);
  372. }
  373. $this->m_oSet->SetShowObsoleteData(utils::ShowObsoleteData());
  374. switch($this->m_sStyle)
  375. {
  376. case 'count':
  377. if (isset($aExtraParams['group_by']))
  378. {
  379. if (isset($aExtraParams['group_by_label']))
  380. {
  381. $oGroupByExp = Expression::FromOQL($aExtraParams['group_by']);
  382. $sGroupByLabel = $aExtraParams['group_by_label'];
  383. }
  384. else
  385. {
  386. // Backward compatibility: group_by is simply a field id
  387. $sAlias = $this->m_oFilter->GetClassAlias();
  388. $oGroupByExp = new FieldExpression($aExtraParams['group_by'], $sAlias);
  389. $sGroupByLabel = MetaModel::GetLabel($this->m_oFilter->GetClass(), $aExtraParams['group_by']);
  390. }
  391. // Security filtering
  392. $aFields = $oGroupByExp->ListRequiredFields();
  393. foreach($aFields as $sFieldAlias)
  394. {
  395. if (preg_match('/^([^.]+)\\.([^.]+)$/', $sFieldAlias, $aMatches))
  396. {
  397. $sFieldClass = $this->m_oFilter->GetClassName($aMatches[1]);
  398. $oAttDef = MetaModel::GetAttributeDef($sFieldClass, $aMatches[2]);
  399. if ($oAttDef instanceof AttributeOneWayPassword)
  400. {
  401. throw new Exception('Grouping on password fields is not supported.');
  402. }
  403. }
  404. }
  405. $aGroupBy = array();
  406. $aGroupBy['grouped_by_1'] = $oGroupByExp;
  407. $sSql = $this->m_oFilter->MakeGroupByQuery($aQueryParams, $aGroupBy, true);
  408. $aRes = CMDBSource::QueryToArray($sSql);
  409. $aGroupBy = array();
  410. $aLabels = array();
  411. $aValues = array();
  412. $iTotalCount = 0;
  413. foreach ($aRes as $iRow => $aRow)
  414. {
  415. $sValue = $aRow['grouped_by_1'];
  416. $aValues[$iRow] = $sValue;
  417. $sHtmlValue = $oGroupByExp->MakeValueLabel($this->m_oFilter, $sValue, $sValue);
  418. $aLabels[$iRow] = $sHtmlValue;
  419. $aGroupBy[$iRow] = (int) $aRow['_itop_count_'];
  420. $iTotalCount += $aRow['_itop_count_'];
  421. }
  422. $aData = array();
  423. $oAppContext = new ApplicationContext();
  424. $sParams = $oAppContext->GetForLink();
  425. foreach($aGroupBy as $iRow => $iCount)
  426. {
  427. // Build the search for this subset
  428. $oSubsetSearch = $this->m_oFilter->DeepClone();
  429. $oCondition = new BinaryExpression($oGroupByExp, '=', new ScalarExpression($aValues[$iRow]));
  430. $oSubsetSearch->AddConditionExpression($oCondition);
  431. $sFilter = urlencode($oSubsetSearch->serialize());
  432. $aData[] = array ( 'group' => $aLabels[$iRow],
  433. 'value' => "<a href=\"".utils::GetAbsoluteUrlAppRoot()."pages/UI.php?operation=search&dosearch=1&$sParams&filter=$sFilter\">$iCount</a>"); // TO DO: add the context information
  434. }
  435. $aAttribs =array(
  436. 'group' => array('label' => $sGroupByLabel, 'description' => ''),
  437. 'value' => array('label'=> Dict::S('UI:GroupBy:Count'), 'description' => Dict::S('UI:GroupBy:Count+'))
  438. );
  439. $sFormat = isset($aExtraParams['format']) ? $aExtraParams['format'] : 'UI:Pagination:HeaderNoSelection';
  440. $sHtml .= $oPage->GetP(Dict::Format($sFormat, $iTotalCount));
  441. $sHtml .= $oPage->GetTable($aAttribs, $aData);
  442. $oPage->add_ready_script("LoadGroupBySortOrder('$sId');\n$('#{$sId} table.listResults').unbind('sortEnd.group_by').bind('sortEnd.group_by', function() { SaveGroupBySortOrder('$sId', $(this)[0].config.sortList); })");
  443. }
  444. else
  445. {
  446. // Simply count the number of elements in the set
  447. $iCount = $this->m_oSet->Count();
  448. $sFormat = 'UI:CountOfObjects';
  449. if (isset($aExtraParams['format']))
  450. {
  451. $sFormat = $aExtraParams['format'];
  452. }
  453. $sHtml .= $oPage->GetP(Dict::Format($sFormat, $iCount));
  454. }
  455. break;
  456. case 'join':
  457. $aDisplayAliases = isset($aExtraParams['display_aliases']) ? explode(',', $aExtraParams['display_aliases']): array();
  458. if (!isset($aExtraParams['group_by']))
  459. {
  460. $sHtml .= $oPage->GetP(Dict::S('UI:Error:MandatoryTemplateParameter_group_by'));
  461. }
  462. else
  463. {
  464. $aGroupByFields = array();
  465. $aGroupBy = explode(',', $aExtraParams['group_by']);
  466. foreach($aGroupBy as $sGroupBy)
  467. {
  468. $aMatches = array();
  469. if (preg_match('/^(.+)\.(.+)$/', $sGroupBy, $aMatches) > 0)
  470. {
  471. $aGroupByFields[] = array('alias' => $aMatches[1], 'att_code' => $aMatches[2]);
  472. }
  473. }
  474. if (count($aGroupByFields) == 0)
  475. {
  476. $sHtml .= $oPage->GetP(Dict::Format('UI:Error:InvalidGroupByFields', $aExtraParams['group_by']));
  477. }
  478. else
  479. {
  480. $aResults = array();
  481. $aCriteria = array();
  482. while($aObjects = $this->m_oSet->FetchAssoc())
  483. {
  484. $aKeys = array();
  485. foreach($aGroupByFields as $aField)
  486. {
  487. $sAlias = $aField['alias'];
  488. if (is_null($aObjects[$sAlias]))
  489. {
  490. $aKeys[$sAlias.'.'.$aField['att_code']] = '';
  491. }
  492. else
  493. {
  494. $aKeys[$sAlias.'.'.$aField['att_code']] = $aObjects[$sAlias]->Get($aField['att_code']);
  495. }
  496. }
  497. $sCategory = implode($aKeys, ' ');
  498. $aResults[$sCategory][] = $aObjects;
  499. $aCriteria[$sCategory] = $aKeys;
  500. }
  501. $sHtml .= "<table>\n";
  502. // Construct a new (parametric) query that will return the content of this block
  503. $oBlockFilter = $this->m_oFilter->DeepClone();
  504. $aExpressions = array();
  505. $index = 0;
  506. foreach($aGroupByFields as $aField)
  507. {
  508. $aExpressions[] = '`'.$aField['alias'].'`.`'.$aField['att_code'].'` = :param'.$index++;
  509. }
  510. $sExpression = implode(' AND ', $aExpressions);
  511. $oExpression = Expression::FromOQL($sExpression);
  512. $oBlockFilter->AddConditionExpression($oExpression);
  513. $aExtraParams['menu'] = false;
  514. foreach($aResults as $sCategory => $aObjects)
  515. {
  516. $sHtml .= "<tr><td><h1>$sCategory</h1></td></tr>\n";
  517. if (count($aDisplayAliases) == 1)
  518. {
  519. $aSimpleArray = array();
  520. foreach($aObjects as $aRow)
  521. {
  522. $oObj = $aRow[$aDisplayAliases[0]];
  523. if (!is_null($oObj))
  524. {
  525. $aSimpleArray[] = $oObj;
  526. }
  527. }
  528. $oSet = CMDBObjectSet::FromArray($this->m_oFilter->GetClass(), $aSimpleArray);
  529. $sHtml .= "<tr><td>".cmdbAbstractObject::GetDisplaySet($oPage, $oSet, $aExtraParams)."</td></tr>\n";
  530. }
  531. else
  532. {
  533. $index = 0;
  534. $aArgs = array();
  535. foreach($aGroupByFields as $aField)
  536. {
  537. $aArgs['param'.$index] = $aCriteria[$sCategory][$aField['alias'].'.'.$aField['att_code']];
  538. $index++;
  539. }
  540. $oSet = new CMDBObjectSet($oBlockFilter, array(), $aArgs);
  541. $sHtml .= "<tr><td>".cmdbAbstractObject::GetDisplayExtendedSet($oPage, $oSet, $aExtraParams)."</td></tr>\n";
  542. }
  543. }
  544. $sHtml .= "</table>\n";
  545. }
  546. }
  547. break;
  548. case 'list':
  549. $aClasses = $this->m_oSet->GetSelectedClasses();
  550. $aAuthorizedClasses = array();
  551. if (count($aClasses) > 1)
  552. {
  553. // Check the classes that can be read (i.e authorized) by this user...
  554. foreach($aClasses as $sAlias => $sClassName)
  555. {
  556. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $this->m_oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  557. {
  558. $aAuthorizedClasses[$sAlias] = $sClassName;
  559. }
  560. }
  561. if (count($aAuthorizedClasses) > 0)
  562. {
  563. if($this->m_oSet->Count() > 0)
  564. {
  565. $sHtml .= cmdbAbstractObject::GetDisplayExtendedSet($oPage, $this->m_oSet, $aExtraParams);
  566. }
  567. else
  568. {
  569. // Empty set
  570. $sHtml .= $oPage->GetP(Dict::S('UI:NoObjectToDisplay'));
  571. }
  572. }
  573. else
  574. {
  575. // Not authorized
  576. $sHtml .= $oPage->GetP(Dict::S('UI:NoObjectToDisplay'));
  577. }
  578. }
  579. else
  580. {
  581. // The list is made of only 1 class of objects, actions on the list are possible
  582. if ( ($this->m_oSet->Count()> 0) && (UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_READ, $this->m_oSet) == UR_ALLOWED_YES) )
  583. {
  584. $sHtml .= cmdbAbstractObject::GetDisplaySet($oPage, $this->m_oSet, $aExtraParams);
  585. }
  586. else
  587. {
  588. $sHtml .= $oPage->GetP(Dict::S('UI:NoObjectToDisplay'));
  589. $sClass = $this->m_oFilter->GetClass();
  590. $bDisplayMenu = isset($aExtraParams['menu']) ? $aExtraParams['menu'] == true : true;
  591. if ($bDisplayMenu)
  592. {
  593. if ((UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES))
  594. {
  595. $sLinkTarget = '';
  596. $oAppContext = new ApplicationContext();
  597. $sParams = $oAppContext->GetForLink();
  598. // 1:n links, populate the target object as a default value when creating a new linked object
  599. if (isset($aExtraParams['target_attr']))
  600. {
  601. $sLinkTarget = ' target="_blank" ';
  602. $aExtraParams['default'][$aExtraParams['target_attr']] = $aExtraParams['object_id'];
  603. }
  604. $sDefault = '';
  605. if (!empty($aExtraParams['default']))
  606. {
  607. foreach($aExtraParams['default'] as $sKey => $sValue)
  608. {
  609. $sDefault.= "&default[$sKey]=$sValue";
  610. }
  611. }
  612. $sHtml .= $oPage->GetP("<a{$sLinkTarget} href=\"".utils::GetAbsoluteUrlAppRoot()."pages/UI.php?operation=new&class=$sClass&$sParams{$sDefault}\">".Dict::Format('UI:ClickToCreateNew', Metamodel::GetName($sClass))."</a>\n");
  613. }
  614. }
  615. }
  616. }
  617. break;
  618. case 'links':
  619. //$bDashboardMode = isset($aExtraParams['dashboard']) ? ($aExtraParams['dashboard'] == 'true') : false;
  620. //$bSelectMode = isset($aExtraParams['select']) ? ($aExtraParams['select'] == 'true') : false;
  621. if ( ($this->m_oSet->Count()> 0) && (UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_READ, $this->m_oSet) == UR_ALLOWED_YES) )
  622. {
  623. //$sLinkage = isset($aExtraParams['linkage']) ? $aExtraParams['linkage'] : '';
  624. $sHtml .= cmdbAbstractObject::GetDisplaySet($oPage, $this->m_oSet, $aExtraParams);
  625. }
  626. else
  627. {
  628. $sClass = $this->m_oFilter->GetClass();
  629. $oAttDef = MetaModel::GetAttributeDef($sClass, $this->m_aParams['target_attr']);
  630. $sTargetClass = $oAttDef->GetTargetClass();
  631. $sHtml .= $oPage->GetP(Dict::Format('UI:NoObject_Class_ToDisplay', MetaModel::GetName($sTargetClass)));
  632. $bDisplayMenu = isset($this->m_aParams['menu']) ? $this->m_aParams['menu'] == true : true;
  633. if ($bDisplayMenu)
  634. {
  635. if ((UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES))
  636. {
  637. $oAppContext = new ApplicationContext();
  638. $sParams = $oAppContext->GetForLink();
  639. $sDefaults = '';
  640. if (isset($this->m_aParams['default']))
  641. {
  642. foreach($this->m_aParams['default'] as $sName => $sValue)
  643. {
  644. $sDefaults .= '&'.urlencode($sName).'='.urlencode($sValue);
  645. }
  646. }
  647. $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");
  648. }
  649. }
  650. }
  651. break;
  652. case 'details':
  653. while($oObj = $this->m_oSet->Fetch())
  654. {
  655. $sHtml .= $oObj->GetDetails($oPage); // Still used ???
  656. }
  657. break;
  658. case 'actions':
  659. $sClass = $this->m_oFilter->GetClass();
  660. $oAppContext = new ApplicationContext();
  661. $bContextFilter = isset($aExtraParams['context_filter']) ? isset($aExtraParams['context_filter']) != 0 : false;
  662. if ($bContextFilter)
  663. {
  664. $aFilterCodes = array_keys(MetaModel::GetClassFilterDefs($this->m_oFilter->GetClass()));
  665. foreach($oAppContext->GetNames() as $sFilterCode)
  666. {
  667. $sContextParamValue = $oAppContext->GetCurrentValue($sFilterCode, null);
  668. if (!is_null($sContextParamValue) && ! empty($sContextParamValue) && MetaModel::IsValidFilterCode($sClass, $sFilterCode))
  669. {
  670. $this->AddCondition($sFilterCode, $sContextParamValue);
  671. }
  672. }
  673. $aQueryParams = array();
  674. if (isset($aExtraParams['query_params']))
  675. {
  676. $aQueryParams = $aExtraParams['query_params'];
  677. }
  678. $this->m_oSet = new CMDBObjectSet($this->m_oFilter, array(), $aQueryParams);
  679. $this->m_oSet->SetShowObsoleteData(utils::ShowObsoleteData());
  680. }
  681. $iCount = $this->m_oSet->Count();
  682. $sHyperlink = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=search&'.$oAppContext->GetForLink().'&filter='.urlencode($this->m_oFilter->serialize());
  683. $sHtml .= '<p><a class="actions" href="'.$sHyperlink.'">';
  684. // Note: border set to 0 due to various browser interpretations (IE9 adding a 2px border)
  685. $sHtml .= MetaModel::GetClassIcon($sClass, true, 'float;left;margin-right:10px;border:0;');
  686. $sHtml .= MetaModel::GetName($sClass).': '.$iCount.'</a></p>';
  687. $sParams = $oAppContext->GetForLink();
  688. $sHtml .= '<p>';
  689. if (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY))
  690. {
  691. $sHtml .= "<a href=\"".utils::GetAbsoluteUrlAppRoot()."pages/UI.php?operation=new&class={$sClass}&$sParams\">".Dict::Format('UI:ClickToCreateNew', MetaModel::GetName($sClass))."</a><br/>\n";
  692. }
  693. $sHtml .= "<a href=\"".utils::GetAbsoluteUrlAppRoot()."pages/UI.php?operation=search_form&do_search=0&class={$sClass}&$sParams\">".Dict::Format('UI:SearchFor_Class', MetaModel::GetName($sClass))."</a>\n";
  694. $sHtml .= '</p>';
  695. break;
  696. case 'summary':
  697. $sClass = $this->m_oFilter->GetClass();
  698. $oAppContext = new ApplicationContext();
  699. $sTitle = isset($aExtraParams['title[block]']) ? $aExtraParams['title[block]'] : '';
  700. $sLabel = isset($aExtraParams['label[block]']) ? $aExtraParams['label[block]'] : '';
  701. $sStateAttrCode = isset($aExtraParams['status[block]']) ? $aExtraParams['status[block]'] : 'status';
  702. $sStatesList = isset($aExtraParams['status_codes[block]']) ? $aExtraParams['status_codes[block]'] : '';
  703. $bContextFilter = isset($aExtraParams['context_filter']) ? isset($aExtraParams['context_filter']) != 0 : false;
  704. if ($bContextFilter)
  705. {
  706. $aFilterCodes = array_keys(MetaModel::GetClassFilterDefs($this->m_oFilter->GetClass()));
  707. foreach($oAppContext->GetNames() as $sFilterCode)
  708. {
  709. $sContextParamValue = $oAppContext->GetCurrentValue($sFilterCode, null);
  710. if (!is_null($sContextParamValue) && ! empty($sContextParamValue) && MetaModel::IsValidFilterCode($sClass, $sFilterCode))
  711. {
  712. $this->AddCondition($sFilterCode, $sContextParamValue);
  713. }
  714. }
  715. $aQueryParams = array();
  716. if (isset($aExtraParams['query_params']))
  717. {
  718. $aQueryParams = $aExtraParams['query_params'];
  719. }
  720. $this->m_oSet = new CMDBObjectSet($this->m_oFilter, array(), $aQueryParams);
  721. $this->m_oSet->SetShowObsoleteData(utils::ShowObsoleteData());
  722. }
  723. // Summary details
  724. $aCounts = array();
  725. $aStateLabels = array();
  726. if (!empty($sStateAttrCode) && !empty($sStatesList))
  727. {
  728. $aStates = explode(',', $sStatesList);
  729. $oAttDef = MetaModel::GetAttributeDef($sClass, $sStateAttrCode);
  730. foreach($aStates as $sStateValue)
  731. {
  732. $oFilter = $this->m_oFilter->DeepClone();
  733. $oFilter->AddCondition($sStateAttrCode, $sStateValue, '=');
  734. $oSet = new DBObjectSet($oFilter);
  735. $oSet->SetShowObsoleteData(utils::ShowObsoleteData());
  736. $aCounts[$sStateValue] = $oSet->Count();
  737. $aStateLabels[$sStateValue] = htmlentities($oAttDef->GetValueLabel($sStateValue), ENT_QUOTES, 'UTF-8');
  738. if ($aCounts[$sStateValue] == 0)
  739. {
  740. $aCounts[$sStateValue] = '-';
  741. }
  742. else
  743. {
  744. $sHyperlink = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=search&'.$oAppContext->GetForLink().'&filter='.urlencode($oFilter->serialize());
  745. $aCounts[$sStateValue] = "<a href=\"$sHyperlink\">{$aCounts[$sStateValue]}</a>";
  746. }
  747. }
  748. }
  749. $sHtml .= '<div class="summary-details"><table><tr><th>'.implode('</th><th>', $aStateLabels).'</th></tr>';
  750. $sHtml .= '<tr><td>'.implode('</td><td>', $aCounts).'</td></tr></table></div>';
  751. // Title & summary
  752. $iCount = $this->m_oSet->Count();
  753. $sHyperlink = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=search&'.$oAppContext->GetForLink().'&filter='.urlencode($this->m_oFilter->serialize());
  754. $sHtml .= '<h1>'.Dict::S(str_replace('_', ':', $sTitle)).'</h1>';
  755. $sHtml .= '<a class="summary" href="'.$sHyperlink.'">'.Dict::Format(str_replace('_', ':', $sLabel), $iCount).'</a>';
  756. $sHtml .= '<div style="clear:both;"></div>';
  757. break;
  758. case 'csv':
  759. $bAdvancedMode = utils::ReadParam('advanced', false);
  760. $sCsvFile = strtolower($this->m_oFilter->GetClass()).'.csv';
  761. $sDownloadLink = utils::GetAbsoluteUrlAppRoot().'webservices/export.php?expression='.urlencode($this->m_oFilter->ToOQL(true)).'&format=csv&filename='.urlencode($sCsvFile);
  762. $sLinkToToggle = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=search&'.$oAppContext->GetForLink().'&filter='.urlencode($this->m_oFilter->serialize()).'&format=csv';
  763. // Pass the parameters via POST, since expression may be very long
  764. $aParamsToPost = array(
  765. 'expression' => $this->m_oFilter->ToOQL(true),
  766. 'format' => 'csv',
  767. 'filename' => $sCsvFile,
  768. 'charset' => 'UTF-8',
  769. );
  770. if ($bAdvancedMode)
  771. {
  772. $sDownloadLink .= '&fields_advanced=1';
  773. $aParamsToPost['fields_advance'] = 1;
  774. $sChecked = 'CHECKED';
  775. }
  776. else
  777. {
  778. $sLinkToToggle = $sLinkToToggle.'&advanced=1';
  779. $sChecked = '';
  780. }
  781. $sAjaxLink = utils::GetAbsoluteUrlAppRoot().'webservices/export.php';
  782. /*
  783. $sCSVData = cmdbAbstractObject::GetSetAsCSV($this->m_oSet, array('fields_advanced' => $bAdvancedMode));
  784. $sCharset = MetaModel::GetConfig()->Get('csv_file_default_charset');
  785. if ($sCharset == 'UTF-8')
  786. {
  787. $bLostChars = false;
  788. }
  789. else
  790. {
  791. $sConverted = @iconv('UTF-8', $sCharset, $sCSVData);
  792. $sRestored = @iconv($sCharset, 'UTF-8', $sConverted);
  793. $bLostChars = ($sRestored != $sCSVData);
  794. }
  795. if ($bLostChars)
  796. {
  797. $sCharsetNotice = "&nbsp;&nbsp;<span id=\"csv_charset_issue\">";
  798. $sCharsetNotice .= '<img src="../images/error.png" style="vertical-align:middle"/>';
  799. $sCharsetNotice .= "</span>";
  800. $sTip = "<p>".htmlentities(Dict::S('UI:CSVExport:LostChars'), ENT_QUOTES, 'UTF-8')."</p>";
  801. $sTip .= "<p>".htmlentities(Dict::Format('UI:CSVExport:LostChars+', $sCharset), ENT_QUOTES, 'UTF-8')."</p>";
  802. $oPage->add_ready_script("$('#csv_charset_issue').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );");
  803. }
  804. else
  805. {
  806. $sCharsetNotice = '';
  807. }
  808. */
  809. $sCharsetNotice = false;
  810. $sHtml .= "<div>";
  811. $sHtml .= '<table style="width:100%" class="transparent">';
  812. $sHtml .= '<tr>';
  813. $sHtml .= '<td><a href="'.$sDownloadLink.'">'.Dict::Format('UI:Download-CSV', $sCsvFile).'</a>'.$sCharsetNotice.'</td>';
  814. $sHtml .= '<td style="text-align:right"><input type="checkbox" '.$sChecked.' onClick="window.location.href=\''.$sLinkToToggle.'\'">&nbsp;'.Dict::S('UI:CSVExport:AdvancedMode').'</td>';
  815. $sHtml .= '</tr>';
  816. $sHtml .= '</table>';
  817. if ($bAdvancedMode)
  818. {
  819. $sHtml .= "<p>";
  820. $sHtml .= htmlentities(Dict::S('UI:CSVExport:AdvancedMode+'), ENT_QUOTES, 'UTF-8');
  821. $sHtml .= "</p>";
  822. }
  823. $sHtml .= "</div>";
  824. $sHtml .= "<div id=\"csv_content_loading\"><div style=\"width: 250px; height: 20px; background: url(../setup/orange-progress.gif); border: 1px #999 solid; margin-left:auto; margin-right: auto; text-align: center;\">".Dict::S('UI:Loading')."</div></div><textarea id=\"csv_content\" style=\"display:none;\">\n";
  825. //$sHtml .= htmlentities($sCSVData, ENT_QUOTES, 'UTF-8');
  826. $sHtml .= "</textarea>\n";
  827. $sJsonParams = json_encode($aParamsToPost);
  828. $oPage->add_ready_script("$.post('$sAjaxLink', $sJsonParams, function(data) { $('#csv_content').html(data); $('#csv_content_loading').hide(); $('#csv_content').show();} );");
  829. break;
  830. case 'modify':
  831. if ((UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_MODIFY, $this->m_oSet) == UR_ALLOWED_YES))
  832. {
  833. while($oObj = $this->m_oSet->Fetch())
  834. {
  835. $sHtml .= $oObj->GetModifyForm($oPage);
  836. }
  837. }
  838. break;
  839. case 'search':
  840. if (!$oPage->IsPrintableVersion())
  841. {
  842. $sStyle = (isset($aExtraParams['open']) && ($aExtraParams['open'] == 'true')) ? 'SearchDrawer' : 'SearchDrawer DrawerClosed';
  843. $sHtml .= "<div id=\"ds_$sId\" class=\"$sStyle\">\n";
  844. $oPage->add_ready_script(
  845. <<<EOF
  846. $("#dh_$sId").click( function() {
  847. $("#ds_$sId").slideToggle('normal', function() { $("#ds_$sId").parent().resize(); FixSearchFormsDisposition(); $("#dh_$sId").trigger('toggle_complete'); } );
  848. $("#dh_$sId").toggleClass('open');
  849. });
  850. EOF
  851. );
  852. $aExtraParams['currentId'] = $sId;
  853. $sHtml .= cmdbAbstractObject::GetSearchForm($oPage, $this->m_oSet, $aExtraParams);
  854. $sHtml .= "</div>\n";
  855. $sHtml .= "<div class=\"HRDrawer\"></div>\n";
  856. $sHtml .= "<div id=\"dh_$sId\" class=\"DrawerHandle\">".Dict::S('UI:SearchToggle')."</div>\n";
  857. }
  858. break;
  859. case 'chart':
  860. static $iChartCounter = 0;
  861. $iChartCounter++;
  862. $sChartType = isset($aExtraParams['chart_type']) ? $aExtraParams['chart_type'] : 'pie';
  863. $sTitle = isset($aExtraParams['chart_title']) ? '<h1 style="text-align:center">'.htmlentities(Dict::S($aExtraParams['chart_title']), ENT_QUOTES, 'UTF-8').'</h1>' : '';
  864. $sHtml = "$sTitle<div style=\"height:200px;width:100%\" id=\"my_chart_$sId{$iChartCounter}\"><div style=\"height:200px;line-height:200px;vertical-align:center;text-align:center;width:100%\"><img src=\"../images/indicator.gif\"></div></div>\n";
  865. $sGroupBy = isset($aExtraParams['group_by']) ? $aExtraParams['group_by'] : '';
  866. $sGroupByExpr = isset($aExtraParams['group_by_expr']) ? '&params[group_by_expr]='.$aExtraParams['group_by_expr'] : '';
  867. $sFilter = $this->m_oFilter->serialize();
  868. $oContext = new ApplicationContext();
  869. $sContextParam = $oContext->GetForLink();
  870. if (isset($aExtraParams['group_by_label']))
  871. {
  872. $sUrl = json_encode(utils::GetAbsoluteUrlAppRoot()."pages/ajax.render.php?operation=chart&params[group_by]=$sGroupBy{$sGroupByExpr}&params[group_by_label]={$aExtraParams['group_by_label']}&params[chart_type]=$sChartType&params[currentId]=$sId{$iChartCounter}&id=$sId{$iChartCounter}&filter=".urlencode($sFilter).'&'.$sContextParam);
  873. }
  874. else
  875. {
  876. $sUrl = json_encode(utils::GetAbsoluteUrlAppRoot()."pages/ajax.render.php?operation=chart&params[group_by]=$sGroupBy{$sGroupByExpr}&params[chart_type]=$sChartType&params[currentId]=$sId{$iChartCounter}&id=$sId{$iChartCounter}&filter=".urlencode($sFilter).'&'.$sContextParam);
  877. }
  878. $sType = ($sChartType == 'pie') ? 'pie' : 'bar';
  879. $oPage->add_ready_script(
  880. <<<EOF
  881. $.post($sUrl, {}, function(data) {
  882. $('body').append(data);
  883. });
  884. EOF
  885. );
  886. break;
  887. case 'chart_ajax':
  888. $sHtml = '';
  889. $sChartType = isset($aExtraParams['chart_type']) ? $aExtraParams['chart_type'] : 'pie';
  890. $sId = utils::ReadParam('id', '');
  891. if (isset($aExtraParams['group_by']))
  892. {
  893. if (isset($aExtraParams['group_by_label']))
  894. {
  895. $oGroupByExp = Expression::FromOQL($aExtraParams['group_by']);
  896. $sGroupByLabel = $aExtraParams['group_by_label'];
  897. }
  898. else
  899. {
  900. // Backward compatibility: group_by is simply a field id
  901. $sAlias = $this->m_oFilter->GetClassAlias();
  902. $oGroupByExp = new FieldExpression($aExtraParams['group_by'], $sAlias);
  903. $sGroupByLabel = MetaModel::GetLabel($this->m_oFilter->GetClass(), $aExtraParams['group_by']);
  904. }
  905. $aGroupBy = array();
  906. $aGroupBy['grouped_by_1'] = $oGroupByExp;
  907. $sSql = $this->m_oFilter->MakeGroupByQuery($aQueryParams, $aGroupBy, true);
  908. $aRes = CMDBSource::QueryToArray($sSql);
  909. $oContext = new ApplicationContext();
  910. $sContextParam = $oContext->GetForLink();
  911. $aGroupBy = array();
  912. $iTotalCount = 0;
  913. $aValues = array();
  914. $aURLs = array();
  915. foreach ($aRes as $iRow => $aRow)
  916. {
  917. $sValue = $aRow['grouped_by_1'];
  918. $sHtmlValue = $oGroupByExp->MakeValueLabel($this->m_oFilter, $sValue, $sValue);
  919. $aGroupBy[(int)$iRow] = (int) $aRow['_itop_count_'];
  920. $iTotalCount += $aRow['_itop_count_'];
  921. $aValues[] = array('label' => html_entity_decode(strip_tags($sHtmlValue), ENT_QUOTES, 'UTF-8'), 'label_html' => $sHtmlValue, 'value' => (int) $aRow['_itop_count_']);
  922. // Build the search for this subset
  923. $oSubsetSearch = $this->m_oFilter->DeepClone();
  924. $oCondition = new BinaryExpression($oGroupByExp, '=', new ScalarExpression($sValue));
  925. $oSubsetSearch->AddConditionExpression($oCondition);
  926. $aURLs[] = utils::GetAbsoluteUrlAppRoot()."pages/UI.php?operation=search&format=html&filter=".urlencode($oSubsetSearch->serialize()).'&'.$sContextParam;
  927. }
  928. $sJSURLs = json_encode($aURLs);
  929. }
  930. switch($sChartType)
  931. {
  932. case 'bars':
  933. $aNames = array();
  934. foreach($aValues as $idx => $aValue)
  935. {
  936. $aNames[$idx] = $aValue['label'];
  937. }
  938. $sJSNames = json_encode($aNames);
  939. $sJson = json_encode($aValues);
  940. $sJSCount = json_encode(Dict::S('UI:GroupBy:Count'));
  941. $oPage->add_ready_script(
  942. <<<EOF
  943. var chart = c3.generate({
  944. bindto: d3.select('#my_chart_$sId'),
  945. data: {
  946. json: $sJson,
  947. keys: {
  948. x: 'label',
  949. value: ["value"]
  950. },
  951. onclick: function (d, element) {
  952. var aURLs = $sJSURLs;
  953. window.location.href = aURLs[d.index];
  954. },
  955. selection: {
  956. enabled: true
  957. },
  958. type: 'bar'
  959. },
  960. axis: {
  961. x: {
  962. tick: {
  963. culling: {max: 25}, // Maximum 24 labels on x axis (2 years).
  964. centered: true,
  965. rotate: 90,
  966. multiline: false
  967. },
  968. type: 'category' // this needed to load string x value
  969. }
  970. },
  971. grid: {
  972. y: {
  973. show: true
  974. }
  975. },
  976. legend: {
  977. show: false,
  978. },
  979. tooltip: {
  980. grouped: false,
  981. format: {
  982. title: function() { return '' },
  983. name: function (name, ratio, id, index) {
  984. var aNames = $sJSNames;
  985. return aNames[index];
  986. }
  987. }
  988. }
  989. });
  990. EOF
  991. );
  992. break;
  993. case 'pie':
  994. $aColumns = array();
  995. $aNames = array();
  996. foreach($aValues as $idx => $aValue)
  997. {
  998. $aColumns[] = array('series_'.$idx, (int)$aValue['value']);
  999. $aNames['series_'.$idx] = $aValue['label'];
  1000. }
  1001. $sJSColumns = json_encode($aColumns);
  1002. $sJSNames = json_encode($aNames);
  1003. $oPage->add_ready_script(
  1004. <<<EOF
  1005. var chart = c3.generate({
  1006. bindto: d3.select('#my_chart_$sId'),
  1007. data: {
  1008. columns: $sJSColumns,
  1009. type: 'pie',
  1010. names: $sJSNames,
  1011. onclick: function (d, element) {
  1012. var aURLs = $sJSURLs;
  1013. window.location.href= aURLs[d.index];
  1014. },
  1015. },
  1016. legend: {
  1017. show: true,
  1018. position: 'right',
  1019. },
  1020. tooltip: {
  1021. format: {
  1022. value: function (value, ratio, id) { return value; }
  1023. }
  1024. }
  1025. });
  1026. EOF
  1027. );
  1028. break;
  1029. }
  1030. break;
  1031. default:
  1032. // Unsupported style, do nothing.
  1033. $sHtml .= Dict::format('UI:Error:UnsupportedStyleOfBlock', $this->m_sStyle);
  1034. }
  1035. return $sHtml;
  1036. }
  1037. /**
  1038. * Add a condition (restriction) to the current DBSearch on which the display block is based
  1039. * taking into account the hierarchical keys for which the condition is based on the 'below' operator
  1040. */
  1041. protected function AddCondition($sFilterCode, $condition, $sOpCode = null, $bParseSearchString = false)
  1042. {
  1043. // Workaround to an issue revealed whenever a condition on org_id is applied twice (with a hierarchy of organizations)
  1044. // Moreover, it keeps the query as simple as possible
  1045. if (isset($this->m_aConditions[$sFilterCode]) && $condition == $this->m_aConditions[$sFilterCode])
  1046. {
  1047. // Skip
  1048. return;
  1049. }
  1050. $this->m_aConditions[$sFilterCode] = $condition;
  1051. $sClass = $this->m_oFilter->GetClass();
  1052. $bConditionAdded = false;
  1053. // If the condition is an external key with a class having a hierarchy, use a "below" criteria
  1054. if (MetaModel::IsValidAttCode($sClass, $sFilterCode))
  1055. {
  1056. $oAttDef = MetaModel::GetAttributeDef($sClass, $sFilterCode);
  1057. if ($oAttDef->IsExternalKey())
  1058. {
  1059. $sHierarchicalKeyCode = MetaModel::IsHierarchicalClass($oAttDef->GetTargetClass());
  1060. if ($sHierarchicalKeyCode !== false)
  1061. {
  1062. $oFilter = new DBObjectSearch($oAttDef->GetTargetClass());
  1063. if (($sOpCode == 'IN') && is_array($condition))
  1064. {
  1065. $oFilter->AddConditionExpression(self::GetConditionIN($oFilter, 'id', $condition));
  1066. }
  1067. else
  1068. {
  1069. $oFilter->AddCondition('id', $condition);
  1070. }
  1071. $oHKFilter = new DBObjectSearch($oAttDef->GetTargetClass());
  1072. $oHKFilter->AddCondition_PointingTo($oFilter, $sHierarchicalKeyCode, TREE_OPERATOR_BELOW); // Use the 'below' operator by default
  1073. $this->m_oFilter->AddCondition_PointingTo($oHKFilter, $sFilterCode);
  1074. $bConditionAdded = true;
  1075. }
  1076. else if (($sOpCode == 'IN') && is_array($condition))
  1077. {
  1078. $this->m_oFilter->AddConditionExpression(self::GetConditionIN($this->m_oFilter, $sFilterCode, $condition));
  1079. $bConditionAdded = true;
  1080. }
  1081. }
  1082. else if (($sOpCode == 'IN') && is_array($condition))
  1083. {
  1084. $this->m_oFilter->AddConditionExpression(self::GetConditionIN($this->m_oFilter, $sFilterCode, $condition));
  1085. $bConditionAdded = true;
  1086. }
  1087. }
  1088. // In all other cases, just add the condition directly
  1089. if (!$bConditionAdded)
  1090. {
  1091. $this->m_oFilter->AddCondition($sFilterCode, $condition, null, $bParseSearchString); // Use the default 'loose' operator
  1092. }
  1093. }
  1094. static protected function GetConditionIN($oFilter, $sFilterCode, $condition)
  1095. {
  1096. $oField = new FieldExpression($sFilterCode, $oFilter->GetClassAlias());
  1097. $sListExpr = '('.implode(', ', CMDBSource::Quote($condition)).')';
  1098. $sOQLCondition = $oField->Render()." IN $sListExpr";
  1099. $oNewCondition = Expression::FromOQL($sOQLCondition);
  1100. return $oNewCondition;
  1101. }
  1102. /**
  1103. * For the result to be meaningful, this function must be called AFTER GetRenderContent() (or Display())
  1104. * @return int
  1105. */
  1106. public function GetDisplayedCount()
  1107. {
  1108. return $this->m_oSet->Count();
  1109. }
  1110. }
  1111. /**
  1112. * Helper class to manage 'blocks' of HTML pieces that are parts of a page and contain some list of cmdb objects
  1113. *
  1114. * Each block is actually rendered as a <div></div> tag that can be rendered synchronously
  1115. * or as a piece of Javascript/JQuery/Ajax that will get its content from another page (ajax.render.php).
  1116. * The list of cmdbObjects to be displayed into the block is defined by a filter
  1117. * Right now the type of display is either: list, count or details
  1118. * - list produces a table listing the objects
  1119. * - count produces a paragraphs with a sentence saying 'cont' objects found
  1120. * - details display (as table) the details of each object found (best if only one)
  1121. */
  1122. class HistoryBlock extends DisplayBlock
  1123. {
  1124. protected $iLimitCount;
  1125. protected $iLimitStart;
  1126. public function __construct(DBSearch $oFilter, $sStyle = 'list', $bAsynchronous = false, $aParams = array(), $oSet = null)
  1127. {
  1128. parent::__construct($oFilter, $sStyle, $bAsynchronous, $aParams, $oSet);
  1129. $this->iLimitStart = 0;
  1130. $this->iLimitCount = 0;
  1131. }
  1132. public function SetLimit($iCount, $iStart = 0)
  1133. {
  1134. $this->iLimitStart = $iStart;
  1135. $this->iLimitCount = $iCount;
  1136. }
  1137. public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId)
  1138. {
  1139. $sHtml = '';
  1140. $bTruncated = false;
  1141. $oSet = new CMDBObjectSet($this->m_oFilter, array('date'=>false));
  1142. if (!$oPage->IsPrintableVersion())
  1143. {
  1144. if (($this->iLimitStart > 0) || ($this->iLimitCount > 0))
  1145. {
  1146. $oSet->SetLimit($this->iLimitCount, $this->iLimitStart);
  1147. if (($this->iLimitCount - $this->iLimitStart) < $oSet->Count())
  1148. {
  1149. $bTruncated = true;
  1150. }
  1151. }
  1152. }
  1153. $sHtml .= "<!-- filter: ".($this->m_oFilter->ToOQL())."-->\n";
  1154. switch($this->m_sStyle)
  1155. {
  1156. case 'toggle':
  1157. // First the latest change that the user is allowed to see
  1158. do
  1159. {
  1160. $oLatestChangeOp = $oSet->Fetch();
  1161. }
  1162. while(is_object($oLatestChangeOp) && ($oLatestChangeOp->GetDescription() == ''));
  1163. if (is_object($oLatestChangeOp))
  1164. {
  1165. // There is one change in the list... only when the object has been created !
  1166. $sDate = $oLatestChangeOp->GetAsHTML('date');
  1167. $oChange = MetaModel::GetObject('CMDBChange', $oLatestChangeOp->Get('change'));
  1168. $sUserInfo = $oChange->GetAsHTML('userinfo');
  1169. $sHtml .= $oPage->GetStartCollapsibleSection(Dict::Format('UI:History:LastModified_On_By', $sDate, $sUserInfo));
  1170. $sHtml .= $this->GetHistoryTable($oPage, $oSet);
  1171. $sHtml .= $oPage->GetEndCollapsibleSection();
  1172. }
  1173. break;
  1174. case 'table':
  1175. default:
  1176. if ($bTruncated)
  1177. {
  1178. $sFilter = $this->m_oFilter->serialize();
  1179. $sHtml .= '<div id="history_container"><p>';
  1180. $sHtml .= Dict::Format('UI:TruncatedResults', $this->iLimitCount, $oSet->Count());
  1181. $sHtml .= ' ';
  1182. $sHtml .= '<a href="#" onclick="DisplayHistory(\'#history_container\', \''.$sFilter.'\', 0, 0); return false;">'.Dict::S('UI:DisplayAll').'</a>';
  1183. $sHtml .= $this->GetHistoryTable($oPage, $oSet);
  1184. $sHtml .= '</p></div>';
  1185. $oPage->add_ready_script("$('#{$sId} table.listResults tr:last td').addClass('truncated');");
  1186. }
  1187. else
  1188. {
  1189. $sHtml .= $this->GetHistoryTable($oPage, $oSet);
  1190. }
  1191. $oPage->add_ready_script(InlineImage::FixImagesWidth());
  1192. $oPage->add_ready_script("$('.case-log-history-entry-toggle').on('click', function () { $(this).closest('.case-log-history-entry').toggleClass('expanded');});");
  1193. $oPage->add_ready_script(
  1194. <<<EOF
  1195. $('.history_entry').each(function() {
  1196. var jMe = $(this);
  1197. var oContent = $(this).find('.history_html_content');
  1198. if (jMe.height() < oContent.height())
  1199. {
  1200. jMe.prepend('<span class="history_truncated_toggler"></span>');
  1201. jMe.find('.history_truncated_toggler').on('click', function() {
  1202. jMe.toggleClass('history_entry_truncated');
  1203. });
  1204. }
  1205. });
  1206. EOF
  1207. );
  1208. }
  1209. return $sHtml;
  1210. }
  1211. protected function GetHistoryTable(WebPage $oPage, DBObjectSet $oSet)
  1212. {
  1213. $sHtml = '';
  1214. // First the latest change that the user is allowed to see
  1215. $oSet->Rewind(); // Reset the pointer to the beginning of the set
  1216. $aChanges = array();
  1217. while($oChangeOp = $oSet->Fetch())
  1218. {
  1219. $sChangeDescription = $oChangeOp->GetDescription();
  1220. if ($sChangeDescription != '')
  1221. {
  1222. // The change is visible for the current user
  1223. $changeId = $oChangeOp->Get('change');
  1224. $aChanges[$changeId]['date'] = $oChangeOp->Get('date');
  1225. $aChanges[$changeId]['userinfo'] = $oChangeOp->Get('userinfo');
  1226. if (!isset($aChanges[$changeId]['log']))
  1227. {
  1228. $aChanges[$changeId]['log'] = array();
  1229. }
  1230. $aChanges[$changeId]['log'][] = $sChangeDescription;
  1231. }
  1232. }
  1233. $aAttribs = array('date' => array('label' => Dict::S('UI:History:Date'), 'description' => Dict::S('UI:History:Date+')),
  1234. 'userinfo' => array('label' => Dict::S('UI:History:User'), 'description' => Dict::S('UI:History:User+')),
  1235. 'log' => array('label' => Dict::S('UI:History:Changes') , 'description' => Dict::S('UI:History:Changes+')),
  1236. );
  1237. $aValues = array();
  1238. foreach($aChanges as $aChange)
  1239. {
  1240. $aValues[] = array('date' => AttributeDateTime::GetFormat()->Format($aChange['date']), 'userinfo' => htmlentities($aChange['userinfo'], ENT_QUOTES, 'UTF-8'), 'log' => "<ul><li>".implode('</li><li>', $aChange['log'])."</li></ul>");
  1241. }
  1242. $sHtml .= $oPage->GetTable($aAttribs, $aValues);
  1243. return $sHtml;
  1244. }
  1245. }
  1246. /**
  1247. * Displays the 'Actions' menu for a given (list of) object(s)
  1248. * The 'style' of the list (see constructor of DisplayBlock) can be either 'list' or 'details'
  1249. * For backward compatibility 'popup' is equivalent to 'list'...
  1250. */
  1251. class MenuBlock extends DisplayBlock
  1252. {
  1253. /**
  1254. * Renders the "Actions" popup menu for the given set of objects
  1255. *
  1256. * Note that the menu links containing (or ending) with a hash (#) will have their fragment
  1257. * part (whatever is after the hash) dynamically replaced (by javascript) when the menu is
  1258. * displayed, to correspond to the current hash/fragment in the page. This allows modifying
  1259. * an object in with the same tab active by default as the tab that was active when selecting
  1260. * the "Modify..." action.
  1261. */
  1262. public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId)
  1263. {
  1264. if ($this->m_sStyle == 'popup') // popup is a synonym of 'list' for backward compatibility
  1265. {
  1266. $this->m_sStyle = 'list';
  1267. }
  1268. $sHtml = '';
  1269. $oAppContext = new ApplicationContext();
  1270. $sContext = $oAppContext->GetForLink();
  1271. if (!empty($sContext))
  1272. {
  1273. $sContext = '&'.$sContext;
  1274. }
  1275. $sClass = $this->m_oFilter->GetClass();
  1276. $oReflectionClass = new ReflectionClass($sClass);
  1277. $oSet = new CMDBObjectSet($this->m_oFilter);
  1278. $sFilter = $this->m_oFilter->serialize();
  1279. $sFilterDesc = $this->m_oFilter->ToOql(true);
  1280. $aActions = array();
  1281. $sUIPage = cmdbAbstractObject::ComputeStandardUIPage($sClass);
  1282. $sRootUrl = utils::GetAbsoluteUrlAppRoot();
  1283. // 1:n links, populate the target object as a default value when creating a new linked object
  1284. if (isset($aExtraParams['target_attr']))
  1285. {
  1286. $aExtraParams['default'][$aExtraParams['target_attr']] = $aExtraParams['object_id'];
  1287. }
  1288. $sDefault = '';
  1289. if (!empty($aExtraParams['default']))
  1290. {
  1291. foreach($aExtraParams['default'] as $sKey => $sValue)
  1292. {
  1293. $sDefault.= "&default[$sKey]=$sValue";
  1294. }
  1295. }
  1296. $bIsCreationAllowed = (UserRights::IsActionAllowed($sClass, UR_ACTION_CREATE) == UR_ALLOWED_YES) && ($oReflectionClass->IsSubclassOf('cmdbAbstractObject'));
  1297. $sRefreshAction = '';
  1298. switch($oSet->Count())
  1299. {
  1300. case 0:
  1301. // No object in the set, the only possible action is "new"
  1302. if ($bIsCreationAllowed) { $aActions['UI:Menu:New'] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=new&class=$sClass{$sContext}{$sDefault}"); }
  1303. break;
  1304. case 1:
  1305. $oObj = $oSet->Fetch();
  1306. if (is_null($oObj))
  1307. {
  1308. if (!isset($aExtraParams['link_attr']))
  1309. {
  1310. if ($bIsCreationAllowed) { $aActions['UI:Menu:New'] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=new&class=$sClass{$sContext}{$sDefault}"); }
  1311. }
  1312. }
  1313. else
  1314. {
  1315. $id = $oObj->GetKey();
  1316. if (utils::ReadParam('operation') == 'details')
  1317. {
  1318. if ($_SERVER['REQUEST_METHOD'] == 'GET')
  1319. {
  1320. $sRefreshAction = "window.location.reload();";
  1321. }
  1322. else
  1323. {
  1324. $sRefreshAction = "window.location.href='".ApplicationContext::MakeObjectUrl(get_class($oObj), $id)."';";
  1325. }
  1326. }
  1327. $bLocked = false;
  1328. if (MetaModel::GetConfig()->Get('concurrent_lock_enabled'))
  1329. {
  1330. $aLockInfo = iTopOwnershipLock::IsLocked(get_class($oObj), $id);
  1331. if ($aLockInfo['locked'])
  1332. {
  1333. $bLocked = true;
  1334. //$this->AddMenuSeparator($aActions);
  1335. //$aActions['concurrent_lock_unlock'] = array ('label' => Dict::S('UI:Menu:ReleaseConcurrentLock'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=kill_lock&class=$sClass&id=$id{$sContext}");
  1336. }
  1337. }
  1338. $bRawModifiedAllowed = (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet) == UR_ALLOWED_YES) && ($oReflectionClass->IsSubclassOf('cmdbAbstractObject'));
  1339. $bIsModifyAllowed = !$bLocked && $bRawModifiedAllowed;
  1340. $bIsDeleteAllowed = !$bLocked && UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, $oSet);
  1341. // Just one object in the set, possible actions are "new / clone / modify and delete"
  1342. if (!isset($aExtraParams['link_attr']))
  1343. {
  1344. if ($bIsModifyAllowed) { $aActions['UI:Menu:Modify'] = array ('label' => Dict::S('UI:Menu:Modify'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=modify&class=$sClass&id=$id{$sContext}#"); }
  1345. if ($bIsCreationAllowed) { $aActions['UI:Menu:New'] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=new&class=$sClass{$sContext}{$sDefault}"); }
  1346. if ($bIsDeleteAllowed) { $aActions['UI:Menu:Delete'] = array ('label' => Dict::S('UI:Menu:Delete'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=delete&class=$sClass&id=$id{$sContext}"); }
  1347. // Transitions / Stimuli
  1348. if (!$bLocked)
  1349. {
  1350. $aTransitions = $oObj->EnumTransitions();
  1351. if (count($aTransitions))
  1352. {
  1353. $this->AddMenuSeparator($aActions);
  1354. $aStimuli = Metamodel::EnumStimuli(get_class($oObj));
  1355. foreach($aTransitions as $sStimulusCode => $aTransitionDef)
  1356. {
  1357. $iActionAllowed = (get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction') ? UserRights::IsStimulusAllowed($sClass, $sStimulusCode, $oSet) : UR_ALLOWED_NO;
  1358. switch($iActionAllowed)
  1359. {
  1360. case UR_ALLOWED_YES:
  1361. $aActions[$sStimulusCode] = array('label' => $aStimuli[$sStimulusCode]->GetLabel(), 'url' => "{$sRootUrl}pages/UI.php?operation=stimulus&stimulus=$sStimulusCode&class=$sClass&id=$id{$sContext}");
  1362. break;
  1363. default:
  1364. // Do nothing
  1365. }
  1366. }
  1367. }
  1368. }
  1369. // Relations...
  1370. $aRelations = MetaModel::EnumRelationsEx($sClass);
  1371. if (count($aRelations))
  1372. {
  1373. $this->AddMenuSeparator($aActions);
  1374. foreach($aRelations as $sRelationCode => $aRelationInfo)
  1375. {
  1376. if (array_key_exists('down', $aRelationInfo))
  1377. {
  1378. $aActions[$sRelationCode.'_down'] = array ('label' => $aRelationInfo['down'], 'url' => "{$sRootUrl}pages/$sUIPage?operation=swf_navigator&relation=$sRelationCode&direction=down&class=$sClass&id=$id{$sContext}");
  1379. }
  1380. if (array_key_exists('up', $aRelationInfo))
  1381. {
  1382. $aActions[$sRelationCode.'_up'] = array ('label' => $aRelationInfo['up'], 'url' => "{$sRootUrl}pages/$sUIPage?operation=swf_navigator&relation=$sRelationCode&direction=up&class=$sClass&id=$id{$sContext}");
  1383. }
  1384. }
  1385. }
  1386. if ($bLocked && $bRawModifiedAllowed)
  1387. {
  1388. // Add a special menu to kill the lock, but only to allowed users who can also modify this object
  1389. $aAllowedProfiles = MetaModel::GetConfig()->Get('concurrent_lock_override_profiles');
  1390. $bCanKill = false;
  1391. $oUser = UserRights::GetUserObject();
  1392. $aUserProfiles = array();
  1393. if (!is_null($oUser))
  1394. {
  1395. $oProfileSet = $oUser->Get('profile_list');
  1396. while ($oProfile = $oProfileSet->Fetch())
  1397. {
  1398. $aUserProfiles[$oProfile->Get('profile')] = true;
  1399. }
  1400. }
  1401. foreach($aAllowedProfiles as $sProfile)
  1402. {
  1403. if (array_key_exists($sProfile, $aUserProfiles))
  1404. {
  1405. $bCanKill = true;
  1406. break;
  1407. }
  1408. }
  1409. if ($bCanKill)
  1410. {
  1411. $this->AddMenuSeparator($aActions);
  1412. $aActions['concurrent_lock_unlock'] = array ('label' => Dict::S('UI:Menu:KillConcurrentLock'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=kill_lock&class=$sClass&id=$id{$sContext}");
  1413. }
  1414. }
  1415. /*
  1416. $this->AddMenuSeparator($aActions);
  1417. // Static menus: Email this page & CSV Export
  1418. $sUrl = ApplicationContext::MakeObjectUrl($sClass, $id);
  1419. $aActions['UI:Menu:EMail'] = array ('label' => Dict::S('UI:Menu:EMail'), 'url' => "mailto:?subject=".urlencode($oObj->GetRawName())."&body=".urlencode($sUrl));
  1420. $aActions['UI:Menu:CSVExport'] = array ('label' => Dict::S('UI:Menu:CSVExport'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=search&filter=".urlencode($sFilter)."&format=csv{$sContext}");
  1421. // The style tells us whether the menu is displayed on a list of one object, or on the details of the given object
  1422. if ($this->m_sStyle == 'list')
  1423. {
  1424. // Actions specific to the list
  1425. $sOQL = addslashes($sFilterDesc);
  1426. $aActions['UI:Menu:AddToDashboard'] = array ('label' => Dict::S('UI:Menu:AddToDashboard'), 'url' => "#", 'onclick' => "return DashletCreationDlg('$sOQL')");
  1427. }
  1428. */
  1429. }
  1430. $this->AddMenuSeparator($aActions);
  1431. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  1432. {
  1433. $oSet->Rewind();
  1434. foreach($oExtensionInstance->EnumAllowedActions($oSet) as $sLabel => $sUrl)
  1435. {
  1436. $aActions[$sLabel] = array ('label' => $sLabel, 'url' => $sUrl);
  1437. }
  1438. }
  1439. }
  1440. break;
  1441. default:
  1442. // Check rights
  1443. // New / Modify
  1444. $bIsModifyAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet) && ($oReflectionClass->IsSubclassOf('cmdbAbstractObject'));
  1445. $bIsBulkModifyAllowed = (!MetaModel::IsAbstract($sClass)) && UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_MODIFY, $oSet) && ($oReflectionClass->IsSubclassOf('cmdbAbstractObject'));
  1446. $bIsBulkDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_DELETE, $oSet);
  1447. if (isset($aExtraParams['link_attr']))
  1448. {
  1449. $id = $aExtraParams['object_id'];
  1450. $sTargetAttr = $aExtraParams['target_attr'];
  1451. $oAttDef = MetaModel::GetAttributeDef($sClass, $sTargetAttr);
  1452. $sTargetClass = $oAttDef->GetTargetClass();
  1453. $bIsDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, $oSet);
  1454. 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}"); }
  1455. 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}"); }
  1456. //if ($bIsBulkDeleteAllowed) { $aActions[] = array ('label' => 'Remove All...', 'url' => "#"); }
  1457. }
  1458. else
  1459. {
  1460. // many objects in the set, possible actions are: new / modify all / delete all
  1461. if ($bIsCreationAllowed) { $aActions['UI:Menu:New'] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=new&class=$sClass{$sContext}{$sDefault}"); }
  1462. 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=".urlencode($sFilter)."{$sContext}"); }
  1463. if ($bIsBulkDeleteAllowed) { $aActions['UI:Menu:BulkDelete'] = array ('label' => Dict::S('UI:Menu:BulkDelete'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=select_for_deletion&filter=".urlencode($sFilter)."{$sContext}"); }
  1464. // Stimuli
  1465. $aStates = MetaModel::EnumStates($sClass);
  1466. // Do not perform time consuming computations if there are too may objects in the list
  1467. $iLimit = MetaModel::GetConfig()->Get('complex_actions_limit');
  1468. if ((count($aStates) > 0) && (($iLimit == 0) || ($oSet->Count() < $iLimit)))
  1469. {
  1470. // Life cycle actions may be available... if all objects are in the same state
  1471. //
  1472. // Group by <state>
  1473. $oGroupByExp = new FieldExpression(MetaModel::GetStateAttributeCode($sClass), $this->m_oFilter->GetClassAlias());
  1474. $aGroupBy = array('__state__' => $oGroupByExp);
  1475. $aQueryParams = array();
  1476. if (isset($aExtraParams['query_params']))
  1477. {
  1478. $aQueryParams = $aExtraParams['query_params'];
  1479. }
  1480. $sSql = $this->m_oFilter->MakeGroupByQuery($aQueryParams, $aGroupBy);
  1481. $aRes = CMDBSource::QueryToArray($sSql);
  1482. if (count($aRes) == 1)
  1483. {
  1484. // All objects are in the same state...
  1485. $sState = $aRes[0]['__state__'];
  1486. $aTransitions = Metamodel::EnumTransitions($sClass, $sState);
  1487. if (count($aTransitions))
  1488. {
  1489. $this->AddMenuSeparator($aActions);
  1490. $aStimuli = Metamodel::EnumStimuli($sClass);
  1491. foreach($aTransitions as $sStimulusCode => $aTransitionDef)
  1492. {
  1493. $oSet->Rewind();
  1494. // As soon as the user rights implementation will browse the object set,
  1495. // then we might consider using OptimizeColumnLoad() here
  1496. $iActionAllowed = UserRights::IsStimulusAllowed($sClass, $sStimulusCode, $oSet);
  1497. $iActionAllowed = (get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction') ? $iActionAllowed : UR_ALLOWED_NO;
  1498. switch($iActionAllowed)
  1499. {
  1500. case UR_ALLOWED_YES:
  1501. case UR_ALLOWED_DEPENDS:
  1502. $aActions[$sStimulusCode] = array('label' => $aStimuli[$sStimulusCode]->GetLabel(), 'url' => "{$sRootUrl}pages/UI.php?operation=select_bulk_stimulus&stimulus=$sStimulusCode&state=$sState&class=$sClass&filter=".urlencode($sFilter)."{$sContext}");
  1503. break;
  1504. default:
  1505. // Do nothing
  1506. }
  1507. }
  1508. }
  1509. }
  1510. }
  1511. /*
  1512. $this->AddMenuSeparator($aActions);
  1513. $sUrl = utils::GetAbsoluteUrlAppRoot();
  1514. $aActions['UI:Menu:EMail'] = array ('label' => Dict::S('UI:Menu:EMail'), 'url' => "mailto:?subject=$sFilterDesc&body=".urlencode("{$sUrl}pages/$sUIPage?operation=search&filter=".urlencode($sFilter)."{$sContext}"));
  1515. $aActions['UI:Menu:CSVExport'] = array ('label' => Dict::S('UI:Menu:CSVExport'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=search&filter=".urlencode($sFilter)."&format=csv{$sContext}");
  1516. $sOQL = addslashes($sFilterDesc);
  1517. $aActions['UI:Menu:AddToDashboard'] = array ('label' => Dict::S('UI:Menu:AddToDashboard'), 'url' => "#", 'onclick' => "return DashletCreationDlg('$sOQL')");
  1518. */
  1519. }
  1520. }
  1521. $this->AddMenuSeparator($aActions);
  1522. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  1523. {
  1524. $oSet->Rewind();
  1525. foreach($oExtensionInstance->EnumAllowedActions($oSet) as $sLabel => $data)
  1526. {
  1527. if (is_array($data))
  1528. {
  1529. // New plugins can provide javascript handlers via the 'onclick' property
  1530. //TODO: enable extension of different menus by checking the 'target' property ??
  1531. $aActions[$sLabel] = array ('label' => $sLabel, 'url' => isset($data['url']) ? $data['url'] : '#', 'onclick' => isset($data['onclick']) ? $data['onclick'] : '');
  1532. }
  1533. else
  1534. {
  1535. // Backward compatibility with old plugins
  1536. $aActions[$sLabel] = array ('label' => $sLabel, 'url' => $data);
  1537. }
  1538. }
  1539. }
  1540. // New extensions based on iPopupMenuItem interface
  1541. switch($this->m_sStyle)
  1542. {
  1543. case 'list':
  1544. $oSet->Rewind();
  1545. $param = $oSet;
  1546. $iMenuId = iPopupMenuExtension::MENU_OBJLIST_ACTIONS;
  1547. break;
  1548. case 'details':
  1549. $oSet->Rewind();
  1550. $param = $oSet->Fetch();
  1551. $iMenuId = iPopupMenuExtension::MENU_OBJDETAILS_ACTIONS;
  1552. break;
  1553. }
  1554. utils::GetPopupMenuItems($oPage, $iMenuId, $param, $aActions);
  1555. $aFavoriteActions = array();
  1556. $aCallSpec = array($sClass, 'GetShortcutActions');
  1557. if (is_callable($aCallSpec))
  1558. {
  1559. $aShortcutActions = call_user_func($aCallSpec, $sClass);
  1560. foreach ($aActions as $key => $aAction)
  1561. {
  1562. if (in_array($key, $aShortcutActions))
  1563. {
  1564. $aFavoriteActions[] = $aAction;
  1565. unset($aActions[$key]);
  1566. }
  1567. }
  1568. }
  1569. else
  1570. {
  1571. $aShortcutActions = array();
  1572. }
  1573. if (!$oPage->IsPrintableVersion())
  1574. {
  1575. if (count($aFavoriteActions) > 0)
  1576. {
  1577. $sHtml .= "<div class=\"itop_popup actions_menu\"><ul>\n<li>".Dict::S('UI:Menu:OtherActions')."\n<ul>\n";
  1578. }
  1579. else
  1580. {
  1581. $sHtml .= "<div class=\"itop_popup actions_menu\"><ul>\n<li>".Dict::S('UI:Menu:Actions')."\n<ul>\n";
  1582. }
  1583. $sHtml .= $oPage->RenderPopupMenuItems($aActions, $aFavoriteActions);
  1584. if (!$oPage->IsPrintableVersion() && ($sRefreshAction!=''))
  1585. {
  1586. $sHtml .= "<div class=\"actions_button\" title=\"".htmlentities(Dict::S('UI:Button:Refresh'), ENT_QUOTES, 'UTF-8')."\"><span class=\"refresh-button\" onclick=\"$sRefreshAction\"></span></div>";
  1587. }
  1588. }
  1589. static $bPopupScript = false;
  1590. if (!$bPopupScript)
  1591. {
  1592. // Output this once per page...
  1593. $oPage->add_ready_script("$(\"div.itop_popup>ul\").popupmenu();\n");
  1594. $bPopupScript = true;
  1595. }
  1596. return $sHtml;
  1597. }
  1598. /**
  1599. * Appends a menu separator to the current list of actions
  1600. * @param Hash $aActions The current actions list
  1601. * @return void
  1602. */
  1603. protected function AddMenuSeparator(&$aActions)
  1604. {
  1605. $sSeparator = '<hr class="menu-separator"/>';
  1606. if (count($aActions) > 0) // Make sure that the separator is not the first item in the menu
  1607. {
  1608. $aKeys = array_keys($aActions);
  1609. $sLastKey = array_pop($aKeys);
  1610. if ($aActions[$sLastKey]['label'] != $sSeparator) // Make sure there are no 2 consecutive separators
  1611. {
  1612. $aActions['sep_'.(count($aActions)-1)] = array('label' => $sSeparator, 'url' => '');
  1613. }
  1614. }
  1615. }
  1616. }