displayblock.class.inc.php 63 KB

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