displayblock.class.inc.php 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679
  1. <?php
  2. // Copyright (C) 2010-2016 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-2016 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. switch($this->m_sStyle)
  374. {
  375. case 'count':
  376. if (isset($aExtraParams['group_by']))
  377. {
  378. if (isset($aExtraParams['group_by_label']))
  379. {
  380. $oGroupByExp = Expression::FromOQL($aExtraParams['group_by']);
  381. $sGroupByLabel = $aExtraParams['group_by_label'];
  382. }
  383. else
  384. {
  385. // Backward compatibility: group_by is simply a field id
  386. $sAlias = $this->m_oFilter->GetClassAlias();
  387. $oGroupByExp = new FieldExpression($aExtraParams['group_by'], $sAlias);
  388. $sGroupByLabel = MetaModel::GetLabel($this->m_oFilter->GetClass(), $aExtraParams['group_by']);
  389. }
  390. $aGroupBy = array();
  391. $aGroupBy['grouped_by_1'] = $oGroupByExp;
  392. $sSql = $this->m_oFilter->MakeGroupByQuery($aQueryParams, $aGroupBy, true);
  393. $aRes = CMDBSource::QueryToArray($sSql);
  394. $aGroupBy = array();
  395. $aLabels = array();
  396. $aValues = array();
  397. $iTotalCount = 0;
  398. foreach ($aRes as $iRow => $aRow)
  399. {
  400. $sValue = $aRow['grouped_by_1'];
  401. $aValues[$iRow] = $sValue;
  402. $sHtmlValue = $oGroupByExp->MakeValueLabel($this->m_oFilter, $sValue, $sValue);
  403. $aLabels[$iRow] = $sHtmlValue;
  404. $aGroupBy[$iRow] = (int) $aRow['_itop_count_'];
  405. $iTotalCount += $aRow['_itop_count_'];
  406. }
  407. $aData = array();
  408. $oAppContext = new ApplicationContext();
  409. $sParams = $oAppContext->GetForLink();
  410. foreach($aGroupBy as $iRow => $iCount)
  411. {
  412. // Build the search for this subset
  413. $oSubsetSearch = $this->m_oFilter->DeepClone();
  414. $oCondition = new BinaryExpression($oGroupByExp, '=', new ScalarExpression($aValues[$iRow]));
  415. $oSubsetSearch->AddConditionExpression($oCondition);
  416. $sFilter = urlencode($oSubsetSearch->serialize());
  417. $aData[] = array ( 'group' => $aLabels[$iRow],
  418. 'value' => "<a href=\"".utils::GetAbsoluteUrlAppRoot()."pages/UI.php?operation=search&dosearch=1&$sParams&filter=$sFilter\">$iCount</a>"); // TO DO: add the context information
  419. }
  420. $aAttribs =array(
  421. 'group' => array('label' => $sGroupByLabel, 'description' => ''),
  422. 'value' => array('label'=> Dict::S('UI:GroupBy:Count'), 'description' => Dict::S('UI:GroupBy:Count+'))
  423. );
  424. $sFormat = isset($aExtraParams['format']) ? $aExtraParams['format'] : 'UI:Pagination:HeaderNoSelection';
  425. $sHtml .= $oPage->GetP(Dict::Format($sFormat, $iTotalCount));
  426. $sHtml .= $oPage->GetTable($aAttribs, $aData);
  427. $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); })");
  428. }
  429. else
  430. {
  431. // Simply count the number of elements in the set
  432. $iCount = $this->m_oSet->Count();
  433. $sFormat = 'UI:CountOfObjects';
  434. if (isset($aExtraParams['format']))
  435. {
  436. $sFormat = $aExtraParams['format'];
  437. }
  438. $sHtml .= $oPage->GetP(Dict::Format($sFormat, $iCount));
  439. }
  440. break;
  441. case 'join':
  442. $aDisplayAliases = isset($aExtraParams['display_aliases']) ? explode(',', $aExtraParams['display_aliases']): array();
  443. if (!isset($aExtraParams['group_by']))
  444. {
  445. $sHtml .= $oPage->GetP(Dict::S('UI:Error:MandatoryTemplateParameter_group_by'));
  446. }
  447. else
  448. {
  449. $aGroupByFields = array();
  450. $aGroupBy = explode(',', $aExtraParams['group_by']);
  451. foreach($aGroupBy as $sGroupBy)
  452. {
  453. $aMatches = array();
  454. if (preg_match('/^(.+)\.(.+)$/', $sGroupBy, $aMatches) > 0)
  455. {
  456. $aGroupByFields[] = array('alias' => $aMatches[1], 'att_code' => $aMatches[2]);
  457. }
  458. }
  459. if (count($aGroupByFields) == 0)
  460. {
  461. $sHtml .= $oPage->GetP(Dict::Format('UI:Error:InvalidGroupByFields', $aExtraParams['group_by']));
  462. }
  463. else
  464. {
  465. $aResults = array();
  466. $aCriteria = array();
  467. while($aObjects = $this->m_oSet->FetchAssoc())
  468. {
  469. $aKeys = array();
  470. foreach($aGroupByFields as $aField)
  471. {
  472. $sAlias = $aField['alias'];
  473. if (is_null($aObjects[$sAlias]))
  474. {
  475. $aKeys[$sAlias.'.'.$aField['att_code']] = '';
  476. }
  477. else
  478. {
  479. $aKeys[$sAlias.'.'.$aField['att_code']] = $aObjects[$sAlias]->Get($aField['att_code']);
  480. }
  481. }
  482. $sCategory = implode($aKeys, ' ');
  483. $aResults[$sCategory][] = $aObjects;
  484. $aCriteria[$sCategory] = $aKeys;
  485. }
  486. $sHtml .= "<table>\n";
  487. // Construct a new (parametric) query that will return the content of this block
  488. $oBlockFilter = $this->m_oFilter->DeepClone();
  489. $aExpressions = array();
  490. $index = 0;
  491. foreach($aGroupByFields as $aField)
  492. {
  493. $aExpressions[] = '`'.$aField['alias'].'`.`'.$aField['att_code'].'` = :param'.$index++;
  494. }
  495. $sExpression = implode(' AND ', $aExpressions);
  496. $oExpression = Expression::FromOQL($sExpression);
  497. $oBlockFilter->AddConditionExpression($oExpression);
  498. $aExtraParams['menu'] = false;
  499. foreach($aResults as $sCategory => $aObjects)
  500. {
  501. $sHtml .= "<tr><td><h1>$sCategory</h1></td></tr>\n";
  502. if (count($aDisplayAliases) == 1)
  503. {
  504. $aSimpleArray = array();
  505. foreach($aObjects as $aRow)
  506. {
  507. $oObj = $aRow[$aDisplayAliases[0]];
  508. if (!is_null($oObj))
  509. {
  510. $aSimpleArray[] = $oObj;
  511. }
  512. }
  513. $oSet = CMDBObjectSet::FromArray($this->m_oFilter->GetClass(), $aSimpleArray);
  514. $sHtml .= "<tr><td>".cmdbAbstractObject::GetDisplaySet($oPage, $oSet, $aExtraParams)."</td></tr>\n";
  515. }
  516. else
  517. {
  518. $index = 0;
  519. $aArgs = array();
  520. foreach($aGroupByFields as $aField)
  521. {
  522. $aArgs['param'.$index] = $aCriteria[$sCategory][$aField['alias'].'.'.$aField['att_code']];
  523. $index++;
  524. }
  525. $oSet = new CMDBObjectSet($oBlockFilter, array(), $aArgs);
  526. $sHtml .= "<tr><td>".cmdbAbstractObject::GetDisplayExtendedSet($oPage, $oSet, $aExtraParams)."</td></tr>\n";
  527. }
  528. }
  529. $sHtml .= "</table>\n";
  530. }
  531. }
  532. break;
  533. case 'list':
  534. $aClasses = $this->m_oSet->GetSelectedClasses();
  535. $aAuthorizedClasses = array();
  536. if (count($aClasses) > 1)
  537. {
  538. // Check the classes that can be read (i.e authorized) by this user...
  539. foreach($aClasses as $sAlias => $sClassName)
  540. {
  541. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $this->m_oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  542. {
  543. $aAuthorizedClasses[$sAlias] = $sClassName;
  544. }
  545. }
  546. if (count($aAuthorizedClasses) > 0)
  547. {
  548. if($this->m_oSet->Count() > 0)
  549. {
  550. $sHtml .= cmdbAbstractObject::GetDisplayExtendedSet($oPage, $this->m_oSet, $aExtraParams);
  551. }
  552. else
  553. {
  554. // Empty set
  555. $sHtml .= $oPage->GetP(Dict::S('UI:NoObjectToDisplay'));
  556. }
  557. }
  558. else
  559. {
  560. // Not authorized
  561. $sHtml .= $oPage->GetP(Dict::S('UI:NoObjectToDisplay'));
  562. }
  563. }
  564. else
  565. {
  566. // The list is made of only 1 class of objects, actions on the list are possible
  567. if ( ($this->m_oSet->Count()> 0) && (UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_READ, $this->m_oSet) == UR_ALLOWED_YES) )
  568. {
  569. $sHtml .= cmdbAbstractObject::GetDisplaySet($oPage, $this->m_oSet, $aExtraParams);
  570. }
  571. else
  572. {
  573. $sHtml .= $oPage->GetP(Dict::S('UI:NoObjectToDisplay'));
  574. $sClass = $this->m_oFilter->GetClass();
  575. $bDisplayMenu = isset($aExtraParams['menu']) ? $aExtraParams['menu'] == true : true;
  576. if ($bDisplayMenu)
  577. {
  578. if ((UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES))
  579. {
  580. $sLinkTarget = '';
  581. $oAppContext = new ApplicationContext();
  582. $sParams = $oAppContext->GetForLink();
  583. // 1:n links, populate the target object as a default value when creating a new linked object
  584. if (isset($aExtraParams['target_attr']))
  585. {
  586. $sLinkTarget = ' target="_blank" ';
  587. $aExtraParams['default'][$aExtraParams['target_attr']] = $aExtraParams['object_id'];
  588. }
  589. $sDefault = '';
  590. if (!empty($aExtraParams['default']))
  591. {
  592. foreach($aExtraParams['default'] as $sKey => $sValue)
  593. {
  594. $sDefault.= "&default[$sKey]=$sValue";
  595. }
  596. }
  597. $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");
  598. }
  599. }
  600. }
  601. }
  602. break;
  603. case 'links':
  604. //$bDashboardMode = isset($aExtraParams['dashboard']) ? ($aExtraParams['dashboard'] == 'true') : false;
  605. //$bSelectMode = isset($aExtraParams['select']) ? ($aExtraParams['select'] == 'true') : false;
  606. if ( ($this->m_oSet->Count()> 0) && (UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_READ, $this->m_oSet) == UR_ALLOWED_YES) )
  607. {
  608. //$sLinkage = isset($aExtraParams['linkage']) ? $aExtraParams['linkage'] : '';
  609. $sHtml .= cmdbAbstractObject::GetDisplaySet($oPage, $this->m_oSet, $aExtraParams);
  610. }
  611. else
  612. {
  613. $sClass = $this->m_oFilter->GetClass();
  614. $oAttDef = MetaModel::GetAttributeDef($sClass, $this->m_aParams['target_attr']);
  615. $sTargetClass = $oAttDef->GetTargetClass();
  616. $sHtml .= $oPage->GetP(Dict::Format('UI:NoObject_Class_ToDisplay', MetaModel::GetName($sTargetClass)));
  617. $bDisplayMenu = isset($this->m_aParams['menu']) ? $this->m_aParams['menu'] == true : true;
  618. if ($bDisplayMenu)
  619. {
  620. if ((UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES))
  621. {
  622. $oAppContext = new ApplicationContext();
  623. $sParams = $oAppContext->GetForLink();
  624. $sDefaults = '';
  625. if (isset($this->m_aParams['default']))
  626. {
  627. foreach($this->m_aParams['default'] as $sName => $sValue)
  628. {
  629. $sDefaults .= '&'.urlencode($sName).'='.urlencode($sValue);
  630. }
  631. }
  632. $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");
  633. }
  634. }
  635. }
  636. break;
  637. case 'details':
  638. while($oObj = $this->m_oSet->Fetch())
  639. {
  640. $sHtml .= $oObj->GetDetails($oPage); // Still used ???
  641. }
  642. break;
  643. case 'actions':
  644. $sClass = $this->m_oFilter->GetClass();
  645. $oAppContext = new ApplicationContext();
  646. $bContextFilter = isset($aExtraParams['context_filter']) ? isset($aExtraParams['context_filter']) != 0 : false;
  647. if ($bContextFilter)
  648. {
  649. $aFilterCodes = array_keys(MetaModel::GetClassFilterDefs($this->m_oFilter->GetClass()));
  650. foreach($oAppContext->GetNames() as $sFilterCode)
  651. {
  652. $sContextParamValue = $oAppContext->GetCurrentValue($sFilterCode, null);
  653. if (!is_null($sContextParamValue) && ! empty($sContextParamValue) && MetaModel::IsValidFilterCode($sClass, $sFilterCode))
  654. {
  655. $this->AddCondition($sFilterCode, $sContextParamValue);
  656. }
  657. }
  658. $aQueryParams = array();
  659. if (isset($aExtraParams['query_params']))
  660. {
  661. $aQueryParams = $aExtraParams['query_params'];
  662. }
  663. $this->m_oSet = new CMDBObjectSet($this->m_oFilter, array(), $aQueryParams);
  664. }
  665. $iCount = $this->m_oSet->Count();
  666. $sHyperlink = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=search&'.$oAppContext->GetForLink().'&filter='.urlencode($this->m_oFilter->serialize());
  667. $sHtml .= '<p><a class="actions" href="'.$sHyperlink.'">';
  668. // Note: border set to 0 due to various browser interpretations (IE9 adding a 2px border)
  669. $sHtml .= MetaModel::GetClassIcon($sClass, true, 'float;left;margin-right:10px;border:0;');
  670. $sHtml .= MetaModel::GetName($sClass).': '.$iCount.'</a></p>';
  671. $sParams = $oAppContext->GetForLink();
  672. $sHtml .= '<p>';
  673. if (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY))
  674. {
  675. $sHtml .= "<a href=\"".utils::GetAbsoluteUrlAppRoot()."pages/UI.php?operation=new&class={$sClass}&$sParams\">".Dict::Format('UI:ClickToCreateNew', MetaModel::GetName($sClass))."</a><br/>\n";
  676. }
  677. $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";
  678. $sHtml .= '</p>';
  679. break;
  680. case 'summary':
  681. $sClass = $this->m_oFilter->GetClass();
  682. $oAppContext = new ApplicationContext();
  683. $sTitle = isset($aExtraParams['title[block]']) ? $aExtraParams['title[block]'] : '';
  684. $sLabel = isset($aExtraParams['label[block]']) ? $aExtraParams['label[block]'] : '';
  685. $sStateAttrCode = isset($aExtraParams['status[block]']) ? $aExtraParams['status[block]'] : 'status';
  686. $sStatesList = isset($aExtraParams['status_codes[block]']) ? $aExtraParams['status_codes[block]'] : '';
  687. $bContextFilter = isset($aExtraParams['context_filter']) ? isset($aExtraParams['context_filter']) != 0 : false;
  688. if ($bContextFilter)
  689. {
  690. $aFilterCodes = array_keys(MetaModel::GetClassFilterDefs($this->m_oFilter->GetClass()));
  691. foreach($oAppContext->GetNames() as $sFilterCode)
  692. {
  693. $sContextParamValue = $oAppContext->GetCurrentValue($sFilterCode, null);
  694. if (!is_null($sContextParamValue) && ! empty($sContextParamValue) && MetaModel::IsValidFilterCode($sClass, $sFilterCode))
  695. {
  696. $this->AddCondition($sFilterCode, $sContextParamValue);
  697. }
  698. }
  699. $aQueryParams = array();
  700. if (isset($aExtraParams['query_params']))
  701. {
  702. $aQueryParams = $aExtraParams['query_params'];
  703. }
  704. $this->m_oSet = new CMDBObjectSet($this->m_oFilter, array(), $aQueryParams);
  705. }
  706. // Summary details
  707. $aCounts = array();
  708. $aStateLabels = array();
  709. if (!empty($sStateAttrCode) && !empty($sStatesList))
  710. {
  711. $aStates = explode(',', $sStatesList);
  712. $oAttDef = MetaModel::GetAttributeDef($sClass, $sStateAttrCode);
  713. foreach($aStates as $sStateValue)
  714. {
  715. $oFilter = $this->m_oFilter->DeepClone();
  716. $oFilter->AddCondition($sStateAttrCode, $sStateValue, '=');
  717. $oSet = new DBObjectSet($oFilter);
  718. $aCounts[$sStateValue] = $oSet->Count();
  719. $aStateLabels[$sStateValue] = htmlentities($oAttDef->GetValueLabel($sStateValue), ENT_QUOTES, 'UTF-8');
  720. if ($aCounts[$sStateValue] == 0)
  721. {
  722. $aCounts[$sStateValue] = '-';
  723. }
  724. else
  725. {
  726. $sHyperlink = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=search&'.$oAppContext->GetForLink().'&filter='.urlencode($oFilter->serialize());
  727. $aCounts[$sStateValue] = "<a href=\"$sHyperlink\">{$aCounts[$sStateValue]}</a>";
  728. }
  729. }
  730. }
  731. $sHtml .= '<div class="summary-details"><table><tr><th>'.implode('</th><th>', $aStateLabels).'</th></tr>';
  732. $sHtml .= '<tr><td>'.implode('</td><td>', $aCounts).'</td></tr></table></div>';
  733. // Title & summary
  734. $iCount = $this->m_oSet->Count();
  735. $sHyperlink = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=search&'.$oAppContext->GetForLink().'&filter='.urlencode($this->m_oFilter->serialize());
  736. $sHtml .= '<h1>'.Dict::S(str_replace('_', ':', $sTitle)).'</h1>';
  737. $sHtml .= '<a class="summary" href="'.$sHyperlink.'">'.Dict::Format(str_replace('_', ':', $sLabel), $iCount).'</a>';
  738. $sHtml .= '<div style="clear:both;"></div>';
  739. break;
  740. case 'csv':
  741. $bAdvancedMode = utils::ReadParam('advanced', false);
  742. $sCsvFile = strtolower($this->m_oFilter->GetClass()).'.csv';
  743. $sDownloadLink = utils::GetAbsoluteUrlAppRoot().'webservices/export.php?expression='.urlencode($this->m_oFilter->ToOQL(true)).'&format=csv&filename='.urlencode($sCsvFile);
  744. $sLinkToToggle = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=search&'.$oAppContext->GetForLink().'&filter='.urlencode($this->m_oFilter->serialize()).'&format=csv';
  745. if ($bAdvancedMode)
  746. {
  747. $sDownloadLink .= '&fields_advanced=1';
  748. $sChecked = 'CHECKED';
  749. }
  750. else
  751. {
  752. $sLinkToToggle = $sLinkToToggle.'&advanced=1';
  753. $sChecked = '';
  754. }
  755. $sAjaxLink = $sDownloadLink.'&charset=UTF-8'; // Includes &fields_advanced=1 if in advanced mode
  756. /*
  757. $sCSVData = cmdbAbstractObject::GetSetAsCSV($this->m_oSet, array('fields_advanced' => $bAdvancedMode));
  758. $sCharset = MetaModel::GetConfig()->Get('csv_file_default_charset');
  759. if ($sCharset == 'UTF-8')
  760. {
  761. $bLostChars = false;
  762. }
  763. else
  764. {
  765. $sConverted = @iconv('UTF-8', $sCharset, $sCSVData);
  766. $sRestored = @iconv($sCharset, 'UTF-8', $sConverted);
  767. $bLostChars = ($sRestored != $sCSVData);
  768. }
  769. if ($bLostChars)
  770. {
  771. $sCharsetNotice = "&nbsp;&nbsp;<span id=\"csv_charset_issue\">";
  772. $sCharsetNotice .= '<img src="../images/error.png" style="vertical-align:middle"/>';
  773. $sCharsetNotice .= "</span>";
  774. $sTip = "<p>".htmlentities(Dict::S('UI:CSVExport:LostChars'), ENT_QUOTES, 'UTF-8')."</p>";
  775. $sTip .= "<p>".htmlentities(Dict::Format('UI:CSVExport:LostChars+', $sCharset), ENT_QUOTES, 'UTF-8')."</p>";
  776. $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' }} } );");
  777. }
  778. else
  779. {
  780. $sCharsetNotice = '';
  781. }
  782. */
  783. $sCharsetNotice = false;
  784. $sHtml .= "<div>";
  785. $sHtml .= '<table style="width:100%" class="transparent">';
  786. $sHtml .= '<tr>';
  787. $sHtml .= '<td><a href="'.$sDownloadLink.'">'.Dict::Format('UI:Download-CSV', $sCsvFile).'</a>'.$sCharsetNotice.'</td>';
  788. $sHtml .= '<td style="text-align:right"><input type="checkbox" '.$sChecked.' onClick="window.location.href=\''.$sLinkToToggle.'\'">&nbsp;'.Dict::S('UI:CSVExport:AdvancedMode').'</td>';
  789. $sHtml .= '</tr>';
  790. $sHtml .= '</table>';
  791. if ($bAdvancedMode)
  792. {
  793. $sHtml .= "<p>";
  794. $sHtml .= htmlentities(Dict::S('UI:CSVExport:AdvancedMode+'), ENT_QUOTES, 'UTF-8');
  795. $sHtml .= "</p>";
  796. }
  797. $sHtml .= "</div>";
  798. $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";
  799. //$sHtml .= htmlentities($sCSVData, ENT_QUOTES, 'UTF-8');
  800. $sHtml .= "</textarea>\n";
  801. $oPage->add_ready_script("$.post('$sAjaxLink', {}, function(data) { $('#csv_content').html(data); $('#csv_content_loading').hide(); $('#csv_content').show();} );");
  802. break;
  803. case 'modify':
  804. if ((UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_MODIFY, $this->m_oSet) == UR_ALLOWED_YES))
  805. {
  806. while($oObj = $this->m_oSet->Fetch())
  807. {
  808. $sHtml .= $oObj->GetModifyForm($oPage);
  809. }
  810. }
  811. break;
  812. case 'search':
  813. if (!$oPage->IsPrintableVersion())
  814. {
  815. $sStyle = (isset($aExtraParams['open']) && ($aExtraParams['open'] == 'true')) ? 'SearchDrawer' : 'SearchDrawer DrawerClosed';
  816. $sHtml .= "<div id=\"ds_$sId\" class=\"$sStyle\">\n";
  817. $oPage->add_ready_script(
  818. <<<EOF
  819. $("#dh_$sId").click( function() {
  820. $("#ds_$sId").slideToggle('normal', function() { $("#ds_$sId").parent().resize(); FixSearchFormsDisposition(); $("#dh_$sId").trigger('toggle_complete'); } );
  821. $("#dh_$sId").toggleClass('open');
  822. });
  823. EOF
  824. );
  825. $aExtraParams['currentId'] = $sId;
  826. $sHtml .= cmdbAbstractObject::GetSearchForm($oPage, $this->m_oSet, $aExtraParams);
  827. $sHtml .= "</div>\n";
  828. $sHtml .= "<div class=\"HRDrawer\"></div>\n";
  829. $sHtml .= "<div id=\"dh_$sId\" class=\"DrawerHandle\">".Dict::S('UI:SearchToggle')."</div>\n";
  830. }
  831. break;
  832. case 'chart':
  833. static $iChartCounter = 0;
  834. $iChartCounter++;
  835. $sChartType = isset($aExtraParams['chart_type']) ? $aExtraParams['chart_type'] : 'pie';
  836. $sTitle = isset($aExtraParams['chart_title']) ? '<h1 style="text-align:center">'.htmlentities(Dict::S($aExtraParams['chart_title']), ENT_QUOTES, 'UTF-8').'</h1>' : '';
  837. $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";
  838. $sGroupBy = isset($aExtraParams['group_by']) ? $aExtraParams['group_by'] : '';
  839. $sGroupByExpr = isset($aExtraParams['group_by_expr']) ? '&params[group_by_expr]='.$aExtraParams['group_by_expr'] : '';
  840. $sFilter = $this->m_oFilter->serialize();
  841. $oContext = new ApplicationContext();
  842. $sContextParam = $oContext->GetForLink();
  843. if (isset($aExtraParams['group_by_label']))
  844. {
  845. $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);
  846. }
  847. else
  848. {
  849. $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);
  850. }
  851. $sType = ($sChartType == 'pie') ? 'pie' : 'bar';
  852. $oPage->add_ready_script(
  853. <<<EOF
  854. $.post($sUrl, {}, function(data) {
  855. $('body').append(data);
  856. });
  857. EOF
  858. );
  859. break;
  860. case 'chart_ajax':
  861. $sHtml = '';
  862. $sChartType = isset($aExtraParams['chart_type']) ? $aExtraParams['chart_type'] : 'pie';
  863. $sId = utils::ReadParam('id', '');
  864. if (isset($aExtraParams['group_by']))
  865. {
  866. if (isset($aExtraParams['group_by_label']))
  867. {
  868. $oGroupByExp = Expression::FromOQL($aExtraParams['group_by']);
  869. $sGroupByLabel = $aExtraParams['group_by_label'];
  870. }
  871. else
  872. {
  873. // Backward compatibility: group_by is simply a field id
  874. $sAlias = $this->m_oFilter->GetClassAlias();
  875. $oGroupByExp = new FieldExpression($aExtraParams['group_by'], $sAlias);
  876. $sGroupByLabel = MetaModel::GetLabel($this->m_oFilter->GetClass(), $aExtraParams['group_by']);
  877. }
  878. $aGroupBy = array();
  879. $aGroupBy['grouped_by_1'] = $oGroupByExp;
  880. $sSql = $this->m_oFilter->MakeGroupByQuery($aQueryParams, $aGroupBy, true);
  881. $aRes = CMDBSource::QueryToArray($sSql);
  882. $oContext = new ApplicationContext();
  883. $sContextParam = $oContext->GetForLink();
  884. $aGroupBy = array();
  885. $aLabels = array();
  886. $iTotalCount = 0;
  887. $aValues = array();
  888. $aURLs = array();
  889. foreach ($aRes as $iRow => $aRow)
  890. {
  891. $sValue = $aRow['grouped_by_1'];
  892. $sHtmlValue = $oGroupByExp->MakeValueLabel($this->m_oFilter, $sValue, $sValue);
  893. $aLabels[$iRow] = strip_tags($sHtmlValue);
  894. $aGroupBy[(int)$iRow] = (int) $aRow['_itop_count_'];
  895. $iTotalCount += $aRow['_itop_count_'];
  896. $aValues[] = array('label' => html_entity_decode(strip_tags($sHtmlValue), ENT_QUOTES, 'UTF-8'), 'label_html' => $sHtmlValue, 'value' => (int) $aRow['_itop_count_']);
  897. // Build the search for this subset
  898. $oSubsetSearch = $this->m_oFilter->DeepClone();
  899. $oCondition = new BinaryExpression($oGroupByExp, '=', new ScalarExpression($sValue));
  900. $oSubsetSearch->AddConditionExpression($oCondition);
  901. $aURLs[] = utils::GetAbsoluteUrlAppRoot()."pages/UI.php?operation=search&format=html&filter=".urlencode($oSubsetSearch->serialize()).'&'.$sContextParam;
  902. }
  903. $sJSURLs = json_encode($aURLs);
  904. }
  905. switch($sChartType)
  906. {
  907. case 'bars':
  908. $aNames = array();
  909. foreach($aValues as $idx => $aValue)
  910. {
  911. $aNames[$idx] = $aValue['label_html'];
  912. }
  913. $sJSNames = json_encode($aNames);
  914. $sJson = json_encode($aValues);
  915. $sJSCount = json_encode(Dict::S('UI:GroupBy:Count'));
  916. $oPage->add_ready_script(
  917. <<<EOF
  918. var chart = c3.generate({
  919. bindto: d3.select('#my_chart_$sId'),
  920. data: {
  921. json: $sJson,
  922. keys: {
  923. x: 'label',
  924. value: ["value"]
  925. },
  926. onclick: function (d, element) {
  927. var aURLs = $sJSURLs;
  928. window.location.href = aURLs[d.index];
  929. },
  930. selection: {
  931. enabled: true
  932. },
  933. type: 'bar'
  934. },
  935. axis: {
  936. x: {
  937. type: 'category' // this needed to load string x value
  938. }
  939. },
  940. grid: {
  941. y: {
  942. show: true
  943. }
  944. },
  945. legend: {
  946. show: false,
  947. },
  948. tooltip: {
  949. grouped: false,
  950. format: {
  951. title: function() { return '' },
  952. name: function (name, ratio, id, index) {
  953. var aNames = $sJSNames;
  954. return aNames[index];
  955. }
  956. }
  957. }
  958. });
  959. EOF
  960. );
  961. break;
  962. case 'pie':
  963. $aColumns = array();
  964. $aNames = array();
  965. foreach($aValues as $idx => $aValue)
  966. {
  967. $aColumns[] = array('series_'.$idx, (int)$aValue['value']);
  968. $aNames['series_'.$idx] = $aValue['label'];
  969. }
  970. $sJSColumns = json_encode($aColumns);
  971. $sJSNames = json_encode($aNames);
  972. $oPage->add_ready_script(
  973. <<<EOF
  974. var chart = c3.generate({
  975. bindto: d3.select('#my_chart_$sId'),
  976. data: {
  977. columns: $sJSColumns,
  978. type: 'pie',
  979. names: $sJSNames,
  980. onclick: function (d, element) {
  981. var aURLs = $sJSURLs;
  982. window.location.href= aURLs[d.index];
  983. },
  984. },
  985. legend: {
  986. show: true,
  987. },
  988. tooltip: {
  989. format: {
  990. value: function (value, ratio, id) { return value; }
  991. }
  992. }
  993. });
  994. EOF
  995. );
  996. break;
  997. }
  998. break;
  999. default:
  1000. // Unsupported style, do nothing.
  1001. $sHtml .= Dict::format('UI:Error:UnsupportedStyleOfBlock', $this->m_sStyle);
  1002. }
  1003. return $sHtml;
  1004. }
  1005. /**
  1006. * Add a condition (restriction) to the current DBSearch on which the display block is based
  1007. * taking into account the hierarchical keys for which the condition is based on the 'below' operator
  1008. */
  1009. protected function AddCondition($sFilterCode, $condition, $sOpCode = null, $bParseSearchString = false)
  1010. {
  1011. // Workaround to an issue revealed whenever a condition on org_id is applied twice (with a hierarchy of organizations)
  1012. // Moreover, it keeps the query as simple as possible
  1013. if (isset($this->m_aConditions[$sFilterCode]) && $condition == $this->m_aConditions[$sFilterCode])
  1014. {
  1015. // Skip
  1016. return;
  1017. }
  1018. $this->m_aConditions[$sFilterCode] = $condition;
  1019. $sClass = $this->m_oFilter->GetClass();
  1020. $bConditionAdded = false;
  1021. // If the condition is an external key with a class having a hierarchy, use a "below" criteria
  1022. if (MetaModel::IsValidAttCode($sClass, $sFilterCode))
  1023. {
  1024. $oAttDef = MetaModel::GetAttributeDef($sClass, $sFilterCode);
  1025. if ($oAttDef->IsExternalKey())
  1026. {
  1027. $sHierarchicalKeyCode = MetaModel::IsHierarchicalClass($oAttDef->GetTargetClass());
  1028. if ($sHierarchicalKeyCode !== false)
  1029. {
  1030. $oFilter = new DBObjectSearch($oAttDef->GetTargetClass());
  1031. if (($sOpCode == 'IN') && is_array($condition))
  1032. {
  1033. $oFilter->AddConditionExpression(self::GetConditionIN($oFilter, 'id', $condition));
  1034. }
  1035. else
  1036. {
  1037. $oFilter->AddCondition('id', $condition);
  1038. }
  1039. $oHKFilter = new DBObjectSearch($oAttDef->GetTargetClass());
  1040. $oHKFilter->AddCondition_PointingTo($oFilter, $sHierarchicalKeyCode, TREE_OPERATOR_BELOW); // Use the 'below' operator by default
  1041. $this->m_oFilter->AddCondition_PointingTo($oHKFilter, $sFilterCode);
  1042. $bConditionAdded = true;
  1043. }
  1044. else if (($sOpCode == 'IN') && is_array($condition))
  1045. {
  1046. $this->m_oFilter->AddConditionExpression(self::GetConditionIN($this->m_oFilter, $sFilterCode, $condition));
  1047. $bConditionAdded = true;
  1048. }
  1049. }
  1050. else if (($sOpCode == 'IN') && is_array($condition))
  1051. {
  1052. $this->m_oFilter->AddConditionExpression(self::GetConditionIN($this->m_oFilter, $sFilterCode, $condition));
  1053. $bConditionAdded = true;
  1054. }
  1055. }
  1056. // In all other cases, just add the condition directly
  1057. if (!$bConditionAdded)
  1058. {
  1059. $this->m_oFilter->AddCondition($sFilterCode, $condition, null, $bParseSearchString); // Use the default 'loose' operator
  1060. }
  1061. }
  1062. static protected function GetConditionIN($oFilter, $sFilterCode, $condition)
  1063. {
  1064. $oField = new FieldExpression($sFilterCode, $oFilter->GetClassAlias());
  1065. $sListExpr = '('.implode(', ', CMDBSource::Quote($condition)).')';
  1066. $sOQLCondition = $oField->Render()." IN $sListExpr";
  1067. $oNewCondition = Expression::FromOQL($sOQLCondition);
  1068. return $oNewCondition;
  1069. }
  1070. /**
  1071. * For the result to be meaningful, this function must be called AFTER GetRenderContent() (or Display())
  1072. * @return int
  1073. */
  1074. public function GetDisplayedCount()
  1075. {
  1076. return $this->m_oSet->Count();
  1077. }
  1078. }
  1079. /**
  1080. * Helper class to manage 'blocks' of HTML pieces that are parts of a page and contain some list of cmdb objects
  1081. *
  1082. * Each block is actually rendered as a <div></div> tag that can be rendered synchronously
  1083. * or as a piece of Javascript/JQuery/Ajax that will get its content from another page (ajax.render.php).
  1084. * The list of cmdbObjects to be displayed into the block is defined by a filter
  1085. * Right now the type of display is either: list, count or details
  1086. * - list produces a table listing the objects
  1087. * - count produces a paragraphs with a sentence saying 'cont' objects found
  1088. * - details display (as table) the details of each object found (best if only one)
  1089. */
  1090. class HistoryBlock extends DisplayBlock
  1091. {
  1092. protected $iLimitCount;
  1093. protected $iLimitStart;
  1094. public function __construct(DBSearch $oFilter, $sStyle = 'list', $bAsynchronous = false, $aParams = array(), $oSet = null)
  1095. {
  1096. parent::__construct($oFilter, $sStyle, $bAsynchronous, $aParams, $oSet);
  1097. $this->iLimitStart = 0;
  1098. $this->iLimitCount = 0;
  1099. }
  1100. public function SetLimit($iCount, $iStart = 0)
  1101. {
  1102. $this->iLimitStart = $iStart;
  1103. $this->iLimitCount = $iCount;
  1104. }
  1105. public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId)
  1106. {
  1107. $sHtml = '';
  1108. $bTruncated = false;
  1109. $oSet = new CMDBObjectSet($this->m_oFilter, array('date'=>false));
  1110. if (!$oPage->IsPrintableVersion())
  1111. {
  1112. if (($this->iLimitStart > 0) || ($this->iLimitCount > 0))
  1113. {
  1114. $oSet->SetLimit($this->iLimitCount, $this->iLimitStart);
  1115. if (($this->iLimitCount - $this->iLimitStart) < $oSet->Count())
  1116. {
  1117. $bTruncated = true;
  1118. }
  1119. }
  1120. }
  1121. $sHtml .= "<!-- filter: ".($this->m_oFilter->ToOQL())."-->\n";
  1122. switch($this->m_sStyle)
  1123. {
  1124. case 'toggle':
  1125. // First the latest change that the user is allowed to see
  1126. do
  1127. {
  1128. $oLatestChangeOp = $oSet->Fetch();
  1129. }
  1130. while(is_object($oLatestChangeOp) && ($oLatestChangeOp->GetDescription() == ''));
  1131. if (is_object($oLatestChangeOp))
  1132. {
  1133. // There is one change in the list... only when the object has been created !
  1134. $sDate = $oLatestChangeOp->GetAsHTML('date');
  1135. $oChange = MetaModel::GetObject('CMDBChange', $oLatestChangeOp->Get('change'));
  1136. $sUserInfo = $oChange->GetAsHTML('userinfo');
  1137. $sHtml .= $oPage->GetStartCollapsibleSection(Dict::Format('UI:History:LastModified_On_By', $sDate, $sUserInfo));
  1138. $sHtml .= $this->GetHistoryTable($oPage, $oSet);
  1139. $sHtml .= $oPage->GetEndCollapsibleSection();
  1140. }
  1141. break;
  1142. case 'table':
  1143. default:
  1144. if ($bTruncated)
  1145. {
  1146. $sFilter = $this->m_oFilter->serialize();
  1147. $sHtml .= '<div id="history_container"><p>';
  1148. $sHtml .= Dict::Format('UI:TruncatedResults', $this->iLimitCount, $oSet->Count());
  1149. $sHtml .= ' ';
  1150. $sHtml .= '<a href="#" onclick="DisplayHistory(\'#history_container\', \''.$sFilter.'\', 0, 0); return false;">'.Dict::S('UI:DisplayAll').'</a>';
  1151. $sHtml .= $this->GetHistoryTable($oPage, $oSet);
  1152. $sHtml .= '</p></div>';
  1153. $oPage->add_ready_script("$('#{$sId} table.listResults tr:last td').addClass('truncated');");
  1154. }
  1155. else
  1156. {
  1157. $sHtml .= $this->GetHistoryTable($oPage, $oSet);
  1158. }
  1159. $oPage->add_ready_script(InlineImage::FixImagesWidth());
  1160. $oPage->add_ready_script("$('.case-log-history-entry-toggle').on('click', function () { $(this).closest('.case-log-history-entry').toggleClass('expanded');});");
  1161. $oPage->add_ready_script(
  1162. <<<EOF
  1163. $('.history_entry').each(function() {
  1164. var jMe = $(this);
  1165. var oContent = $(this).find('.history_html_content');
  1166. if (jMe.height() < oContent.height())
  1167. {
  1168. jMe.prepend('<span class="history_truncated_toggler"></span>');
  1169. jMe.find('.history_truncated_toggler').on('click', function() {
  1170. jMe.toggleClass('history_entry_truncated');
  1171. });
  1172. }
  1173. });
  1174. EOF
  1175. );
  1176. }
  1177. return $sHtml;
  1178. }
  1179. protected function GetHistoryTable(WebPage $oPage, DBObjectSet $oSet)
  1180. {
  1181. $sHtml = '';
  1182. // First the latest change that the user is allowed to see
  1183. $oSet->Rewind(); // Reset the pointer to the beginning of the set
  1184. $aChanges = array();
  1185. while($oChangeOp = $oSet->Fetch())
  1186. {
  1187. $sChangeDescription = $oChangeOp->GetDescription();
  1188. if ($sChangeDescription != '')
  1189. {
  1190. // The change is visible for the current user
  1191. $changeId = $oChangeOp->Get('change');
  1192. $aChanges[$changeId]['date'] = $oChangeOp->Get('date');
  1193. $aChanges[$changeId]['userinfo'] = $oChangeOp->Get('userinfo');
  1194. if (!isset($aChanges[$changeId]['log']))
  1195. {
  1196. $aChanges[$changeId]['log'] = array();
  1197. }
  1198. $aChanges[$changeId]['log'][] = $sChangeDescription;
  1199. }
  1200. }
  1201. $aAttribs = array('date' => array('label' => Dict::S('UI:History:Date'), 'description' => Dict::S('UI:History:Date+')),
  1202. 'userinfo' => array('label' => Dict::S('UI:History:User'), 'description' => Dict::S('UI:History:User+')),
  1203. 'log' => array('label' => Dict::S('UI:History:Changes') , 'description' => Dict::S('UI:History:Changes+')),
  1204. );
  1205. $aValues = array();
  1206. foreach($aChanges as $aChange)
  1207. {
  1208. $aValues[] = array('date' => $aChange['date'], 'userinfo' => htmlentities($aChange['userinfo'], ENT_QUOTES, 'UTF-8'), 'log' => "<ul><li>".implode('</li><li>', $aChange['log'])."</li></ul>");
  1209. }
  1210. $sHtml .= $oPage->GetTable($aAttribs, $aValues);
  1211. return $sHtml;
  1212. }
  1213. }
  1214. /**
  1215. * Displays the 'Actions' menu for a given (list of) object(s)
  1216. * The 'style' of the list (see constructor of DisplayBlock) can be either 'list' or 'details'
  1217. * For backward compatibility 'popup' is equivalent to 'list'...
  1218. */
  1219. class MenuBlock extends DisplayBlock
  1220. {
  1221. /**
  1222. * Renders the "Actions" popup menu for the given set of objects
  1223. *
  1224. * Note that the menu links containing (or ending) with a hash (#) will have their fragment
  1225. * part (whatever is after the hash) dynamically replaced (by javascript) when the menu is
  1226. * displayed, to correspond to the current hash/fragment in the page. This allows modifying
  1227. * an object in with the same tab active by default as the tab that was active when selecting
  1228. * the "Modify..." action.
  1229. */
  1230. public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId)
  1231. {
  1232. if ($this->m_sStyle == 'popup') // popup is a synonym of 'list' for backward compatibility
  1233. {
  1234. $this->m_sStyle = 'list';
  1235. }
  1236. $sHtml = '';
  1237. $oAppContext = new ApplicationContext();
  1238. $sContext = $oAppContext->GetForLink();
  1239. if (!empty($sContext))
  1240. {
  1241. $sContext = '&'.$sContext;
  1242. }
  1243. $sClass = $this->m_oFilter->GetClass();
  1244. $oReflectionClass = new ReflectionClass($sClass);
  1245. $oSet = new CMDBObjectSet($this->m_oFilter);
  1246. $sFilter = $this->m_oFilter->serialize();
  1247. $sFilterDesc = $this->m_oFilter->ToOql(true);
  1248. $aActions = array();
  1249. $sUIPage = cmdbAbstractObject::ComputeStandardUIPage($sClass);
  1250. $sRootUrl = utils::GetAbsoluteUrlAppRoot();
  1251. // 1:n links, populate the target object as a default value when creating a new linked object
  1252. if (isset($aExtraParams['target_attr']))
  1253. {
  1254. $aExtraParams['default'][$aExtraParams['target_attr']] = $aExtraParams['object_id'];
  1255. }
  1256. $sDefault = '';
  1257. if (!empty($aExtraParams['default']))
  1258. {
  1259. foreach($aExtraParams['default'] as $sKey => $sValue)
  1260. {
  1261. $sDefault.= "&default[$sKey]=$sValue";
  1262. }
  1263. }
  1264. $bIsCreationAllowed = (UserRights::IsActionAllowed($sClass, UR_ACTION_CREATE) == UR_ALLOWED_YES) && ($oReflectionClass->IsSubclassOf('cmdbAbstractObject'));
  1265. $sRefreshAction = '';
  1266. switch($oSet->Count())
  1267. {
  1268. case 0:
  1269. // No object in the set, the only possible action is "new"
  1270. if ($bIsCreationAllowed) { $aActions['UI:Menu:New'] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=new&class=$sClass{$sContext}{$sDefault}"); }
  1271. break;
  1272. case 1:
  1273. $oObj = $oSet->Fetch();
  1274. if (is_null($oObj))
  1275. {
  1276. if (!isset($aExtraParams['link_attr']))
  1277. {
  1278. if ($bIsCreationAllowed) { $aActions['UI:Menu:New'] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=new&class=$sClass{$sContext}{$sDefault}"); }
  1279. }
  1280. }
  1281. else
  1282. {
  1283. $id = $oObj->GetKey();
  1284. if (utils::ReadParam('operation') == 'details')
  1285. {
  1286. if ($_SERVER['REQUEST_METHOD'] == 'GET')
  1287. {
  1288. $sRefreshAction = "window.location.reload();";
  1289. }
  1290. else
  1291. {
  1292. $sRefreshAction = "window.location.href='".ApplicationContext::MakeObjectUrl(get_class($oObj), $id)."';";
  1293. }
  1294. }
  1295. $bLocked = false;
  1296. if (MetaModel::GetConfig()->Get('concurrent_lock_enabled'))
  1297. {
  1298. $aLockInfo = iTopOwnershipLock::IsLocked(get_class($oObj), $id);
  1299. if ($aLockInfo['locked'])
  1300. {
  1301. $bLocked = true;
  1302. //$this->AddMenuSeparator($aActions);
  1303. //$aActions['concurrent_lock_unlock'] = array ('label' => Dict::S('UI:Menu:ReleaseConcurrentLock'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=kill_lock&class=$sClass&id=$id{$sContext}");
  1304. }
  1305. }
  1306. $bRawModifiedAllowed = (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet) == UR_ALLOWED_YES) && ($oReflectionClass->IsSubclassOf('cmdbAbstractObject'));
  1307. $bIsModifyAllowed = !$bLocked && $bRawModifiedAllowed;
  1308. $bIsDeleteAllowed = !$bLocked && UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, $oSet);
  1309. // Just one object in the set, possible actions are "new / clone / modify and delete"
  1310. if (!isset($aExtraParams['link_attr']))
  1311. {
  1312. if ($bIsModifyAllowed) { $aActions['UI:Menu:Modify'] = array ('label' => Dict::S('UI:Menu:Modify'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=modify&class=$sClass&id=$id{$sContext}#"); }
  1313. if ($bIsCreationAllowed) { $aActions['UI:Menu:New'] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=new&class=$sClass{$sContext}{$sDefault}"); }
  1314. if ($bIsDeleteAllowed) { $aActions['UI:Menu:Delete'] = array ('label' => Dict::S('UI:Menu:Delete'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=delete&class=$sClass&id=$id{$sContext}"); }
  1315. // Transitions / Stimuli
  1316. if (!$bLocked)
  1317. {
  1318. $aTransitions = $oObj->EnumTransitions();
  1319. if (count($aTransitions))
  1320. {
  1321. $this->AddMenuSeparator($aActions);
  1322. $aStimuli = Metamodel::EnumStimuli(get_class($oObj));
  1323. foreach($aTransitions as $sStimulusCode => $aTransitionDef)
  1324. {
  1325. $iActionAllowed = (get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction') ? UserRights::IsStimulusAllowed($sClass, $sStimulusCode, $oSet) : UR_ALLOWED_NO;
  1326. switch($iActionAllowed)
  1327. {
  1328. case UR_ALLOWED_YES:
  1329. $aActions[$sStimulusCode] = array('label' => $aStimuli[$sStimulusCode]->GetLabel(), 'url' => "{$sRootUrl}pages/UI.php?operation=stimulus&stimulus=$sStimulusCode&class=$sClass&id=$id{$sContext}");
  1330. break;
  1331. default:
  1332. // Do nothing
  1333. }
  1334. }
  1335. }
  1336. }
  1337. // Relations...
  1338. $aRelations = MetaModel::EnumRelationsEx($sClass);
  1339. if (count($aRelations))
  1340. {
  1341. $this->AddMenuSeparator($aActions);
  1342. foreach($aRelations as $sRelationCode => $aRelationInfo)
  1343. {
  1344. if (array_key_exists('down', $aRelationInfo))
  1345. {
  1346. $aActions[$sRelationCode.'_down'] = array ('label' => $aRelationInfo['down'], 'url' => "{$sRootUrl}pages/$sUIPage?operation=swf_navigator&relation=$sRelationCode&direction=down&class=$sClass&id=$id{$sContext}");
  1347. }
  1348. if (array_key_exists('up', $aRelationInfo))
  1349. {
  1350. $aActions[$sRelationCode.'_up'] = array ('label' => $aRelationInfo['up'], 'url' => "{$sRootUrl}pages/$sUIPage?operation=swf_navigator&relation=$sRelationCode&direction=up&class=$sClass&id=$id{$sContext}");
  1351. }
  1352. }
  1353. }
  1354. if ($bLocked && $bRawModifiedAllowed)
  1355. {
  1356. // Add a special menu to kill the lock, but only to allowed users who can also modify this object
  1357. $aAllowedProfiles = MetaModel::GetConfig()->Get('concurrent_lock_override_profiles');
  1358. $bCanKill = false;
  1359. $oUser = UserRights::GetUserObject();
  1360. $aUserProfiles = array();
  1361. if (!is_null($oUser))
  1362. {
  1363. $oProfileSet = $oUser->Get('profile_list');
  1364. while ($oProfile = $oProfileSet->Fetch())
  1365. {
  1366. $aUserProfiles[$oProfile->Get('profile')] = true;
  1367. }
  1368. }
  1369. foreach($aAllowedProfiles as $sProfile)
  1370. {
  1371. if (array_key_exists($sProfile, $aUserProfiles))
  1372. {
  1373. $bCanKill = true;
  1374. break;
  1375. }
  1376. }
  1377. if ($bCanKill)
  1378. {
  1379. $this->AddMenuSeparator($aActions);
  1380. $aActions['concurrent_lock_unlock'] = array ('label' => Dict::S('UI:Menu:KillConcurrentLock'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=kill_lock&class=$sClass&id=$id{$sContext}");
  1381. }
  1382. }
  1383. /*
  1384. $this->AddMenuSeparator($aActions);
  1385. // Static menus: Email this page & CSV Export
  1386. $sUrl = ApplicationContext::MakeObjectUrl($sClass, $id);
  1387. $aActions['UI:Menu:EMail'] = array ('label' => Dict::S('UI:Menu:EMail'), 'url' => "mailto:?subject=".urlencode($oObj->GetRawName())."&body=".urlencode($sUrl));
  1388. $aActions['UI:Menu:CSVExport'] = array ('label' => Dict::S('UI:Menu:CSVExport'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=search&filter=".urlencode($sFilter)."&format=csv{$sContext}");
  1389. // The style tells us whether the menu is displayed on a list of one object, or on the details of the given object
  1390. if ($this->m_sStyle == 'list')
  1391. {
  1392. // Actions specific to the list
  1393. $sOQL = addslashes($sFilterDesc);
  1394. $aActions['UI:Menu:AddToDashboard'] = array ('label' => Dict::S('UI:Menu:AddToDashboard'), 'url' => "#", 'onclick' => "return DashletCreationDlg('$sOQL')");
  1395. }
  1396. */
  1397. }
  1398. $this->AddMenuSeparator($aActions);
  1399. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  1400. {
  1401. $oSet->Rewind();
  1402. foreach($oExtensionInstance->EnumAllowedActions($oSet) as $sLabel => $sUrl)
  1403. {
  1404. $aActions[$sLabel] = array ('label' => $sLabel, 'url' => $sUrl);
  1405. }
  1406. }
  1407. }
  1408. break;
  1409. default:
  1410. // Check rights
  1411. // New / Modify
  1412. $bIsModifyAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet) && ($oReflectionClass->IsSubclassOf('cmdbAbstractObject'));
  1413. $bIsBulkModifyAllowed = (!MetaModel::IsAbstract($sClass)) && UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_MODIFY, $oSet) && ($oReflectionClass->IsSubclassOf('cmdbAbstractObject'));
  1414. $bIsBulkDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_DELETE, $oSet);
  1415. if (isset($aExtraParams['link_attr']))
  1416. {
  1417. $id = $aExtraParams['object_id'];
  1418. $sTargetAttr = $aExtraParams['target_attr'];
  1419. $oAttDef = MetaModel::GetAttributeDef($sClass, $sTargetAttr);
  1420. $sTargetClass = $oAttDef->GetTargetClass();
  1421. $bIsDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, $oSet);
  1422. 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}"); }
  1423. 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}"); }
  1424. //if ($bIsBulkDeleteAllowed) { $aActions[] = array ('label' => 'Remove All...', 'url' => "#"); }
  1425. }
  1426. else
  1427. {
  1428. // many objects in the set, possible actions are: new / modify all / delete all
  1429. if ($bIsCreationAllowed) { $aActions['UI:Menu:New'] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=new&class=$sClass{$sContext}{$sDefault}"); }
  1430. 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}"); }
  1431. 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}"); }
  1432. // Stimuli
  1433. $aStates = MetaModel::EnumStates($sClass);
  1434. // Do not perform time consuming computations if there are too may objects in the list
  1435. $iLimit = MetaModel::GetConfig()->Get('complex_actions_limit');
  1436. if ((count($aStates) > 0) && (($iLimit == 0) || ($oSet->Count() < $iLimit)))
  1437. {
  1438. // Life cycle actions may be available... if all objects are in the same state
  1439. //
  1440. // Group by <state>
  1441. $oGroupByExp = new FieldExpression(MetaModel::GetStateAttributeCode($sClass), $this->m_oFilter->GetClassAlias());
  1442. $aGroupBy = array('__state__' => $oGroupByExp);
  1443. $aQueryParams = array();
  1444. if (isset($aExtraParams['query_params']))
  1445. {
  1446. $aQueryParams = $aExtraParams['query_params'];
  1447. }
  1448. $sSql = $this->m_oFilter->MakeGroupByQuery($aQueryParams, $aGroupBy);
  1449. $aRes = CMDBSource::QueryToArray($sSql);
  1450. if (count($aRes) == 1)
  1451. {
  1452. // All objects are in the same state...
  1453. $sState = $aRes[0]['__state__'];
  1454. $aTransitions = Metamodel::EnumTransitions($sClass, $sState);
  1455. if (count($aTransitions))
  1456. {
  1457. $this->AddMenuSeparator($aActions);
  1458. $aStimuli = Metamodel::EnumStimuli($sClass);
  1459. foreach($aTransitions as $sStimulusCode => $aTransitionDef)
  1460. {
  1461. $oSet->Rewind();
  1462. // As soon as the user rights implementation will browse the object set,
  1463. // then we might consider using OptimizeColumnLoad() here
  1464. $iActionAllowed = UserRights::IsStimulusAllowed($sClass, $sStimulusCode, $oSet);
  1465. $iActionAllowed = (get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction') ? $iActionAllowed : UR_ALLOWED_NO;
  1466. switch($iActionAllowed)
  1467. {
  1468. case UR_ALLOWED_YES:
  1469. case UR_ALLOWED_DEPENDS:
  1470. $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}");
  1471. break;
  1472. default:
  1473. // Do nothing
  1474. }
  1475. }
  1476. }
  1477. }
  1478. }
  1479. /*
  1480. $this->AddMenuSeparator($aActions);
  1481. $sUrl = utils::GetAbsoluteUrlAppRoot();
  1482. $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}"));
  1483. $aActions['UI:Menu:CSVExport'] = array ('label' => Dict::S('UI:Menu:CSVExport'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=search&filter=".urlencode($sFilter)."&format=csv{$sContext}");
  1484. $sOQL = addslashes($sFilterDesc);
  1485. $aActions['UI:Menu:AddToDashboard'] = array ('label' => Dict::S('UI:Menu:AddToDashboard'), 'url' => "#", 'onclick' => "return DashletCreationDlg('$sOQL')");
  1486. */
  1487. }
  1488. }
  1489. $this->AddMenuSeparator($aActions);
  1490. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  1491. {
  1492. $oSet->Rewind();
  1493. foreach($oExtensionInstance->EnumAllowedActions($oSet) as $sLabel => $data)
  1494. {
  1495. if (is_array($data))
  1496. {
  1497. // New plugins can provide javascript handlers via the 'onclick' property
  1498. //TODO: enable extension of different menus by checking the 'target' property ??
  1499. $aActions[$sLabel] = array ('label' => $sLabel, 'url' => isset($data['url']) ? $data['url'] : '#', 'onclick' => isset($data['onclick']) ? $data['onclick'] : '');
  1500. }
  1501. else
  1502. {
  1503. // Backward compatibility with old plugins
  1504. $aActions[$sLabel] = array ('label' => $sLabel, 'url' => $data);
  1505. }
  1506. }
  1507. }
  1508. // New extensions based on iPopupMenuItem interface
  1509. switch($this->m_sStyle)
  1510. {
  1511. case 'list':
  1512. $oSet->Rewind();
  1513. $param = $oSet;
  1514. $iMenuId = iPopupMenuExtension::MENU_OBJLIST_ACTIONS;
  1515. break;
  1516. case 'details':
  1517. $oSet->Rewind();
  1518. $param = $oSet->Fetch();
  1519. $iMenuId = iPopupMenuExtension::MENU_OBJDETAILS_ACTIONS;
  1520. break;
  1521. }
  1522. utils::GetPopupMenuItems($oPage, $iMenuId, $param, $aActions);
  1523. $aFavoriteActions = array();
  1524. $aCallSpec = array($sClass, 'GetShortcutActions');
  1525. if (is_callable($aCallSpec))
  1526. {
  1527. $aShortcutActions = call_user_func($aCallSpec, $sClass);
  1528. foreach ($aActions as $key => $aAction)
  1529. {
  1530. if (in_array($key, $aShortcutActions))
  1531. {
  1532. $aFavoriteActions[] = $aAction;
  1533. unset($aActions[$key]);
  1534. }
  1535. }
  1536. }
  1537. else
  1538. {
  1539. $aShortcutActions = array();
  1540. }
  1541. if (!$oPage->IsPrintableVersion())
  1542. {
  1543. if (count($aFavoriteActions) > 0)
  1544. {
  1545. $sHtml .= "<div class=\"itop_popup actions_menu\"><ul>\n<li>".Dict::S('UI:Menu:OtherActions')."\n<ul>\n";
  1546. }
  1547. else
  1548. {
  1549. $sHtml .= "<div class=\"itop_popup actions_menu\"><ul>\n<li>".Dict::S('UI:Menu:Actions')."\n<ul>\n";
  1550. }
  1551. $sHtml .= $oPage->RenderPopupMenuItems($aActions, $aFavoriteActions);
  1552. if (!$oPage->IsPrintableVersion() && ($sRefreshAction!=''))
  1553. {
  1554. $sHtml .= "<div class=\"actions_button\" title=\"".htmlentities(Dict::S('UI:Button:Refresh'), ENT_QUOTES, 'UTF-8')."\"><span class=\"refresh-button\" onclick=\"$sRefreshAction\"></span></div>";
  1555. }
  1556. }
  1557. static $bPopupScript = false;
  1558. if (!$bPopupScript)
  1559. {
  1560. // Output this once per page...
  1561. $oPage->add_ready_script("$(\"div.itop_popup>ul\").popupmenu();\n");
  1562. $bPopupScript = true;
  1563. }
  1564. return $sHtml;
  1565. }
  1566. /**
  1567. * Appends a menu separator to the current list of actions
  1568. * @param Hash $aActions The current actions list
  1569. * @return void
  1570. */
  1571. protected function AddMenuSeparator(&$aActions)
  1572. {
  1573. $sSeparator = '<hr class="menu-separator"/>';
  1574. if (count($aActions) > 0) // Make sure that the separator is not the first item in the menu
  1575. {
  1576. $aKeys = array_keys($aActions);
  1577. $sLastKey = array_pop($aKeys);
  1578. if ($aActions[$sLastKey]['label'] != $sSeparator) // Make sure there are no 2 consecutive separators
  1579. {
  1580. $aActions['sep_'.(count($aActions)-1)] = array('label' => $sSeparator, 'url' => '');
  1581. }
  1582. }
  1583. }
  1584. }