displayblock.class.inc.php 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694
  1. <?php
  2. // Copyright (C) 2010-2015 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-2015 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. if (isset($aExtraParams[$sFilterCode]))
  306. {
  307. $condition = $aExtraParams[$sFilterCode];
  308. }
  309. if ($bDoSearch && $externalFilterValue != "")
  310. {
  311. // Search takes precedence over context params...
  312. unset($aExtraParams[$sFilterCode]);
  313. if (!is_array($externalFilterValue))
  314. {
  315. $condition = trim($externalFilterValue);
  316. }
  317. else if (count($externalFilterValue) == 1)
  318. {
  319. $condition = trim($externalFilterValue[0]);
  320. }
  321. else
  322. {
  323. $condition = $externalFilterValue;
  324. }
  325. }
  326. if (!is_null($condition))
  327. {
  328. $sOpCode = null; // default operator
  329. if (is_array($condition))
  330. {
  331. // Multiple values, add them as AND X IN (v1, v2, v3...)
  332. $sOpCode = 'IN';
  333. }
  334. $this->AddCondition($sFilterCode, $condition, $sOpCode);
  335. }
  336. }
  337. if ($bDoSearch)
  338. {
  339. // Keep the table_id identifying this table if we're performing a search
  340. $sTableId = utils::ReadParam('_table_id_', null, false, 'raw_data');
  341. if ($sTableId != null)
  342. {
  343. $aExtraParams['table_id'] = $sTableId;
  344. }
  345. }
  346. }
  347. $aOrderBy = array();
  348. if (isset($aExtraParams['order_by']))
  349. {
  350. // Convert the string describing the order_by parameter into an array
  351. // The syntax is +attCode1,-attCode2
  352. // attCode1 => ascending, attCode2 => descending
  353. $aTemp = explode(',', $aExtraParams['order_by']);
  354. foreach($aTemp as $sTemp)
  355. {
  356. $aMatches = array();
  357. if (preg_match('/^([+-])?(.+)$/', $sTemp, $aMatches))
  358. {
  359. $bAscending = true;
  360. if ($aMatches[1] == '-')
  361. {
  362. $bAscending = false;
  363. }
  364. $aOrderBy[$aMatches[2]] = $bAscending;
  365. }
  366. }
  367. }
  368. $this->m_oSet = new CMDBObjectSet($this->m_oFilter, $aOrderBy, $aQueryParams);
  369. }
  370. switch($this->m_sStyle)
  371. {
  372. case 'count':
  373. if (isset($aExtraParams['group_by']))
  374. {
  375. if (isset($aExtraParams['group_by_label']))
  376. {
  377. $oGroupByExp = Expression::FromOQL($aExtraParams['group_by']);
  378. $sGroupByLabel = $aExtraParams['group_by_label'];
  379. }
  380. else
  381. {
  382. // Backward compatibility: group_by is simply a field id
  383. $sAlias = $this->m_oFilter->GetClassAlias();
  384. $oGroupByExp = new FieldExpression($aExtraParams['group_by'], $sAlias);
  385. $sGroupByLabel = MetaModel::GetLabel($this->m_oFilter->GetClass(), $aExtraParams['group_by']);
  386. }
  387. $aGroupBy = array();
  388. $aGroupBy['grouped_by_1'] = $oGroupByExp;
  389. $sSql = $this->m_oFilter->MakeGroupByQuery($aQueryParams, $aGroupBy, true);
  390. $aRes = CMDBSource::QueryToArray($sSql);
  391. $aGroupBy = array();
  392. $aLabels = array();
  393. $aValues = array();
  394. $iTotalCount = 0;
  395. foreach ($aRes as $iRow => $aRow)
  396. {
  397. $sValue = $aRow['grouped_by_1'];
  398. $aValues[$iRow] = $sValue;
  399. $sHtmlValue = $oGroupByExp->MakeValueLabel($this->m_oFilter, $sValue, $sValue);
  400. $aLabels[$iRow] = $sHtmlValue;
  401. $aGroupBy[$iRow] = (int) $aRow['_itop_count_'];
  402. $iTotalCount += $aRow['_itop_count_'];
  403. }
  404. $aData = array();
  405. $oAppContext = new ApplicationContext();
  406. $sParams = $oAppContext->GetForLink();
  407. foreach($aGroupBy as $iRow => $iCount)
  408. {
  409. // Build the search for this subset
  410. $oSubsetSearch = $this->m_oFilter->DeepClone();
  411. $oCondition = new BinaryExpression($oGroupByExp, '=', new ScalarExpression($aValues[$iRow]));
  412. $oSubsetSearch->AddConditionExpression($oCondition);
  413. $sFilter = urlencode($oSubsetSearch->serialize());
  414. $aData[] = array ( 'group' => $aLabels[$iRow],
  415. 'value' => "<a href=\"".utils::GetAbsoluteUrlAppRoot()."pages/UI.php?operation=search&dosearch=1&$sParams&filter=$sFilter\">$iCount</a>"); // TO DO: add the context information
  416. }
  417. $aAttribs =array(
  418. 'group' => array('label' => $sGroupByLabel, 'description' => ''),
  419. 'value' => array('label'=> Dict::S('UI:GroupBy:Count'), 'description' => Dict::S('UI:GroupBy:Count+'))
  420. );
  421. $sFormat = isset($aExtraParams['format']) ? $aExtraParams['format'] : 'UI:Pagination:HeaderNoSelection';
  422. $sHtml .= $oPage->GetP(Dict::Format($sFormat, $iTotalCount));
  423. $sHtml .= $oPage->GetTable($aAttribs, $aData);
  424. }
  425. else
  426. {
  427. // Simply count the number of elements in the set
  428. $iCount = $this->m_oSet->Count();
  429. $sFormat = 'UI:CountOfObjects';
  430. if (isset($aExtraParams['format']))
  431. {
  432. $sFormat = $aExtraParams['format'];
  433. }
  434. $sHtml .= $oPage->GetP(Dict::Format($sFormat, $iCount));
  435. }
  436. break;
  437. case 'join':
  438. $aDisplayAliases = isset($aExtraParams['display_aliases']) ? explode(',', $aExtraParams['display_aliases']): array();
  439. if (!isset($aExtraParams['group_by']))
  440. {
  441. $sHtml .= $oPage->GetP(Dict::S('UI:Error:MandatoryTemplateParameter_group_by'));
  442. }
  443. else
  444. {
  445. $aGroupByFields = array();
  446. $aGroupBy = explode(',', $aExtraParams['group_by']);
  447. foreach($aGroupBy as $sGroupBy)
  448. {
  449. $aMatches = array();
  450. if (preg_match('/^(.+)\.(.+)$/', $sGroupBy, $aMatches) > 0)
  451. {
  452. $aGroupByFields[] = array('alias' => $aMatches[1], 'att_code' => $aMatches[2]);
  453. }
  454. }
  455. if (count($aGroupByFields) == 0)
  456. {
  457. $sHtml .= $oPage->GetP(Dict::Format('UI:Error:InvalidGroupByFields', $aExtraParams['group_by']));
  458. }
  459. else
  460. {
  461. $aResults = array();
  462. $aCriteria = array();
  463. while($aObjects = $this->m_oSet->FetchAssoc())
  464. {
  465. $aKeys = array();
  466. foreach($aGroupByFields as $aField)
  467. {
  468. $sAlias = $aField['alias'];
  469. if (is_null($aObjects[$sAlias]))
  470. {
  471. $aKeys[$sAlias.'.'.$aField['att_code']] = '';
  472. }
  473. else
  474. {
  475. $aKeys[$sAlias.'.'.$aField['att_code']] = $aObjects[$sAlias]->Get($aField['att_code']);
  476. }
  477. }
  478. $sCategory = implode($aKeys, ' ');
  479. $aResults[$sCategory][] = $aObjects;
  480. $aCriteria[$sCategory] = $aKeys;
  481. }
  482. $sHtml .= "<table>\n";
  483. // Construct a new (parametric) query that will return the content of this block
  484. $oBlockFilter = $this->m_oFilter->DeepClone();
  485. $aExpressions = array();
  486. $index = 0;
  487. foreach($aGroupByFields as $aField)
  488. {
  489. $aExpressions[] = '`'.$aField['alias'].'`.`'.$aField['att_code'].'` = :param'.$index++;
  490. }
  491. $sExpression = implode(' AND ', $aExpressions);
  492. $oExpression = Expression::FromOQL($sExpression);
  493. $oBlockFilter->AddConditionExpression($oExpression);
  494. $aExtraParams['menu'] = false;
  495. foreach($aResults as $sCategory => $aObjects)
  496. {
  497. $sHtml .= "<tr><td><h1>$sCategory</h1></td></tr>\n";
  498. if (count($aDisplayAliases) == 1)
  499. {
  500. $aSimpleArray = array();
  501. foreach($aObjects as $aRow)
  502. {
  503. $oObj = $aRow[$aDisplayAliases[0]];
  504. if (!is_null($oObj))
  505. {
  506. $aSimpleArray[] = $oObj;
  507. }
  508. }
  509. $oSet = CMDBObjectSet::FromArray($this->m_oFilter->GetClass(), $aSimpleArray);
  510. $sHtml .= "<tr><td>".cmdbAbstractObject::GetDisplaySet($oPage, $oSet, $aExtraParams)."</td></tr>\n";
  511. }
  512. else
  513. {
  514. $index = 0;
  515. $aArgs = array();
  516. foreach($aGroupByFields as $aField)
  517. {
  518. $aArgs['param'.$index] = $aCriteria[$sCategory][$aField['alias'].'.'.$aField['att_code']];
  519. $index++;
  520. }
  521. $oSet = new CMDBObjectSet($oBlockFilter, array(), $aArgs);
  522. $sHtml .= "<tr><td>".cmdbAbstractObject::GetDisplayExtendedSet($oPage, $oSet, $aExtraParams)."</td></tr>\n";
  523. }
  524. }
  525. $sHtml .= "</table>\n";
  526. }
  527. }
  528. break;
  529. case 'list':
  530. $aClasses = $this->m_oSet->GetSelectedClasses();
  531. $aAuthorizedClasses = array();
  532. if (count($aClasses) > 1)
  533. {
  534. // Check the classes that can be read (i.e authorized) by this user...
  535. foreach($aClasses as $sAlias => $sClassName)
  536. {
  537. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $this->m_oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  538. {
  539. $aAuthorizedClasses[$sAlias] = $sClassName;
  540. }
  541. }
  542. if (count($aAuthorizedClasses) > 0)
  543. {
  544. if($this->m_oSet->Count() > 0)
  545. {
  546. $sHtml .= cmdbAbstractObject::GetDisplayExtendedSet($oPage, $this->m_oSet, $aExtraParams);
  547. }
  548. else
  549. {
  550. // Empty set
  551. $sHtml .= $oPage->GetP(Dict::S('UI:NoObjectToDisplay'));
  552. }
  553. }
  554. else
  555. {
  556. // Not authorized
  557. $sHtml .= $oPage->GetP(Dict::S('UI:NoObjectToDisplay'));
  558. }
  559. }
  560. else
  561. {
  562. // The list is made of only 1 class of objects, actions on the list are possible
  563. if ( ($this->m_oSet->Count()> 0) && (UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_READ, $this->m_oSet) == UR_ALLOWED_YES) )
  564. {
  565. $sHtml .= cmdbAbstractObject::GetDisplaySet($oPage, $this->m_oSet, $aExtraParams);
  566. }
  567. else
  568. {
  569. $sHtml .= $oPage->GetP(Dict::S('UI:NoObjectToDisplay'));
  570. $sClass = $this->m_oFilter->GetClass();
  571. $bDisplayMenu = isset($aExtraParams['menu']) ? $aExtraParams['menu'] == true : true;
  572. if ($bDisplayMenu)
  573. {
  574. if ((UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES))
  575. {
  576. $sLinkTarget = '';
  577. $oAppContext = new ApplicationContext();
  578. $sParams = $oAppContext->GetForLink();
  579. // 1:n links, populate the target object as a default value when creating a new linked object
  580. if (isset($aExtraParams['target_attr']))
  581. {
  582. $sLinkTarget = ' target="_blank" ';
  583. $aExtraParams['default'][$aExtraParams['target_attr']] = $aExtraParams['object_id'];
  584. }
  585. $sDefault = '';
  586. if (!empty($aExtraParams['default']))
  587. {
  588. foreach($aExtraParams['default'] as $sKey => $sValue)
  589. {
  590. $sDefault.= "&default[$sKey]=$sValue";
  591. }
  592. }
  593. $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");
  594. }
  595. }
  596. }
  597. }
  598. break;
  599. case 'links':
  600. //$bDashboardMode = isset($aExtraParams['dashboard']) ? ($aExtraParams['dashboard'] == 'true') : false;
  601. //$bSelectMode = isset($aExtraParams['select']) ? ($aExtraParams['select'] == 'true') : false;
  602. if ( ($this->m_oSet->Count()> 0) && (UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_READ, $this->m_oSet) == UR_ALLOWED_YES) )
  603. {
  604. //$sLinkage = isset($aExtraParams['linkage']) ? $aExtraParams['linkage'] : '';
  605. $sHtml .= cmdbAbstractObject::GetDisplaySet($oPage, $this->m_oSet, $aExtraParams);
  606. }
  607. else
  608. {
  609. $sClass = $this->m_oFilter->GetClass();
  610. $oAttDef = MetaModel::GetAttributeDef($sClass, $this->m_aParams['target_attr']);
  611. $sTargetClass = $oAttDef->GetTargetClass();
  612. $sHtml .= $oPage->GetP(Dict::Format('UI:NoObject_Class_ToDisplay', MetaModel::GetName($sTargetClass)));
  613. $bDisplayMenu = isset($this->m_aParams['menu']) ? $this->m_aParams['menu'] == true : true;
  614. if ($bDisplayMenu)
  615. {
  616. if ((UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES))
  617. {
  618. $oAppContext = new ApplicationContext();
  619. $sParams = $oAppContext->GetForLink();
  620. $sDefaults = '';
  621. if (isset($this->m_aParams['default']))
  622. {
  623. foreach($this->m_aParams['default'] as $sName => $sValue)
  624. {
  625. $sDefaults .= '&'.urlencode($sName).'='.urlencode($sValue);
  626. }
  627. }
  628. $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");
  629. }
  630. }
  631. }
  632. break;
  633. case 'details':
  634. while($oObj = $this->m_oSet->Fetch())
  635. {
  636. $sHtml .= $oObj->GetDetails($oPage); // Still used ???
  637. }
  638. break;
  639. case 'actions':
  640. $sClass = $this->m_oFilter->GetClass();
  641. $oAppContext = new ApplicationContext();
  642. $bContextFilter = isset($aExtraParams['context_filter']) ? isset($aExtraParams['context_filter']) != 0 : false;
  643. if ($bContextFilter)
  644. {
  645. $aFilterCodes = array_keys(MetaModel::GetClassFilterDefs($this->m_oFilter->GetClass()));
  646. foreach($oAppContext->GetNames() as $sFilterCode)
  647. {
  648. $sContextParamValue = $oAppContext->GetCurrentValue($sFilterCode, null);
  649. if (!is_null($sContextParamValue) && ! empty($sContextParamValue) && MetaModel::IsValidFilterCode($sClass, $sFilterCode))
  650. {
  651. $this->AddCondition($sFilterCode, $sContextParamValue);
  652. }
  653. }
  654. $aQueryParams = array();
  655. if (isset($aExtraParams['query_params']))
  656. {
  657. $aQueryParams = $aExtraParams['query_params'];
  658. }
  659. $this->m_oSet = new CMDBObjectSet($this->m_oFilter, array(), $aQueryParams);
  660. }
  661. $iCount = $this->m_oSet->Count();
  662. $sHyperlink = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=search&'.$oAppContext->GetForLink().'&filter='.urlencode($this->m_oFilter->serialize());
  663. $sHtml .= '<p><a class="actions" href="'.$sHyperlink.'">';
  664. // Note: border set to 0 due to various browser interpretations (IE9 adding a 2px border)
  665. $sHtml .= MetaModel::GetClassIcon($sClass, true, 'float;left;margin-right:10px;border:0;');
  666. $sHtml .= MetaModel::GetName($sClass).': '.$iCount.'</a></p>';
  667. $sParams = $oAppContext->GetForLink();
  668. $sHtml .= '<p>';
  669. if (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY))
  670. {
  671. $sHtml .= "<a href=\"".utils::GetAbsoluteUrlAppRoot()."pages/UI.php?operation=new&class={$sClass}&$sParams\">".Dict::Format('UI:ClickToCreateNew', MetaModel::GetName($sClass))."</a><br/>\n";
  672. }
  673. $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";
  674. $sHtml .= '</p>';
  675. break;
  676. case 'summary':
  677. $sClass = $this->m_oFilter->GetClass();
  678. $oAppContext = new ApplicationContext();
  679. $sTitle = isset($aExtraParams['title[block]']) ? $aExtraParams['title[block]'] : '';
  680. $sLabel = isset($aExtraParams['label[block]']) ? $aExtraParams['label[block]'] : '';
  681. $sStateAttrCode = isset($aExtraParams['status[block]']) ? $aExtraParams['status[block]'] : 'status';
  682. $sStatesList = isset($aExtraParams['status_codes[block]']) ? $aExtraParams['status_codes[block]'] : '';
  683. $bContextFilter = isset($aExtraParams['context_filter']) ? isset($aExtraParams['context_filter']) != 0 : false;
  684. if ($bContextFilter)
  685. {
  686. $aFilterCodes = array_keys(MetaModel::GetClassFilterDefs($this->m_oFilter->GetClass()));
  687. foreach($oAppContext->GetNames() as $sFilterCode)
  688. {
  689. $sContextParamValue = $oAppContext->GetCurrentValue($sFilterCode, null);
  690. if (!is_null($sContextParamValue) && ! empty($sContextParamValue) && MetaModel::IsValidFilterCode($sClass, $sFilterCode))
  691. {
  692. $this->AddCondition($sFilterCode, $sContextParamValue);
  693. }
  694. }
  695. $aQueryParams = array();
  696. if (isset($aExtraParams['query_params']))
  697. {
  698. $aQueryParams = $aExtraParams['query_params'];
  699. }
  700. $this->m_oSet = new CMDBObjectSet($this->m_oFilter, array(), $aQueryParams);
  701. }
  702. // Summary details
  703. $aCounts = array();
  704. $aStateLabels = array();
  705. if (!empty($sStateAttrCode) && !empty($sStatesList))
  706. {
  707. $aStates = explode(',', $sStatesList);
  708. $oAttDef = MetaModel::GetAttributeDef($sClass, $sStateAttrCode);
  709. foreach($aStates as $sStateValue)
  710. {
  711. $oFilter = $this->m_oFilter->DeepClone();
  712. $oFilter->AddCondition($sStateAttrCode, $sStateValue, '=');
  713. $oSet = new DBObjectSet($oFilter);
  714. $aCounts[$sStateValue] = $oSet->Count();
  715. $aStateLabels[$sStateValue] = htmlentities($oAttDef->GetValueLabel($sStateValue), ENT_QUOTES, 'UTF-8');
  716. if ($aCounts[$sStateValue] == 0)
  717. {
  718. $aCounts[$sStateValue] = '-';
  719. }
  720. else
  721. {
  722. $sHyperlink = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=search&'.$oAppContext->GetForLink().'&filter='.urlencode($oFilter->serialize());
  723. $aCounts[$sStateValue] = "<a href=\"$sHyperlink\">{$aCounts[$sStateValue]}</a>";
  724. }
  725. }
  726. }
  727. $sHtml .= '<div class="summary-details"><table><tr><th>'.implode('</th><th>', $aStateLabels).'</th></tr>';
  728. $sHtml .= '<tr><td>'.implode('</td><td>', $aCounts).'</td></tr></table></div>';
  729. // Title & summary
  730. $iCount = $this->m_oSet->Count();
  731. $sHyperlink = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=search&'.$oAppContext->GetForLink().'&filter='.urlencode($this->m_oFilter->serialize());
  732. $sHtml .= '<h1>'.Dict::S(str_replace('_', ':', $sTitle)).'</h1>';
  733. $sHtml .= '<a class="summary" href="'.$sHyperlink.'">'.Dict::Format(str_replace('_', ':', $sLabel), $iCount).'</a>';
  734. $sHtml .= '<div style="clear:both;"></div>';
  735. break;
  736. case 'csv':
  737. $bAdvancedMode = utils::ReadParam('advanced', false);
  738. $sCsvFile = strtolower($this->m_oFilter->GetClass()).'.csv';
  739. $sDownloadLink = utils::GetAbsoluteUrlAppRoot().'webservices/export.php?expression='.urlencode($this->m_oFilter->ToOQL(true)).'&format=csv&filename='.urlencode($sCsvFile);
  740. $sLinkToToggle = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=search&'.$oAppContext->GetForLink().'&filter='.urlencode($this->m_oFilter->serialize()).'&format=csv';
  741. if ($bAdvancedMode)
  742. {
  743. $sDownloadLink .= '&fields_advanced=1';
  744. $sChecked = 'CHECKED';
  745. }
  746. else
  747. {
  748. $sLinkToToggle = $sLinkToToggle.'&advanced=1';
  749. $sChecked = '';
  750. }
  751. $sAjaxLink = $sDownloadLink.'&charset=UTF-8'; // Includes &fields_advanced=1 if in advanced mode
  752. /*
  753. $sCSVData = cmdbAbstractObject::GetSetAsCSV($this->m_oSet, array('fields_advanced' => $bAdvancedMode));
  754. $sCharset = MetaModel::GetConfig()->Get('csv_file_default_charset');
  755. if ($sCharset == 'UTF-8')
  756. {
  757. $bLostChars = false;
  758. }
  759. else
  760. {
  761. $sConverted = @iconv('UTF-8', $sCharset, $sCSVData);
  762. $sRestored = @iconv($sCharset, 'UTF-8', $sConverted);
  763. $bLostChars = ($sRestored != $sCSVData);
  764. }
  765. if ($bLostChars)
  766. {
  767. $sCharsetNotice = "&nbsp;&nbsp;<span id=\"csv_charset_issue\">";
  768. $sCharsetNotice .= '<img src="../images/error.png" style="vertical-align:middle"/>';
  769. $sCharsetNotice .= "</span>";
  770. $sTip = "<p>".htmlentities(Dict::S('UI:CSVExport:LostChars'), ENT_QUOTES, 'UTF-8')."</p>";
  771. $sTip .= "<p>".htmlentities(Dict::Format('UI:CSVExport:LostChars+', $sCharset), ENT_QUOTES, 'UTF-8')."</p>";
  772. $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' }} } );");
  773. }
  774. else
  775. {
  776. $sCharsetNotice = '';
  777. }
  778. */
  779. $sCharsetNotice = false;
  780. $sHtml .= "<div>";
  781. $sHtml .= '<table style="width:100%" class="transparent">';
  782. $sHtml .= '<tr>';
  783. $sHtml .= '<td><a href="'.$sDownloadLink.'">'.Dict::Format('UI:Download-CSV', $sCsvFile).'</a>'.$sCharsetNotice.'</td>';
  784. $sHtml .= '<td style="text-align:right"><input type="checkbox" '.$sChecked.' onClick="window.location.href=\''.$sLinkToToggle.'\'">&nbsp;'.Dict::S('UI:CSVExport:AdvancedMode').'</td>';
  785. $sHtml .= '</tr>';
  786. $sHtml .= '</table>';
  787. if ($bAdvancedMode)
  788. {
  789. $sHtml .= "<p>";
  790. $sHtml .= htmlentities(Dict::S('UI:CSVExport:AdvancedMode+'), ENT_QUOTES, 'UTF-8');
  791. $sHtml .= "</p>";
  792. }
  793. $sHtml .= "</div>";
  794. $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";
  795. //$sHtml .= htmlentities($sCSVData, ENT_QUOTES, 'UTF-8');
  796. $sHtml .= "</textarea>\n";
  797. $oPage->add_ready_script("$.post('$sAjaxLink', {}, function(data) { $('#csv_content').html(data); $('#csv_content_loading').hide(); $('#csv_content').show();} );");
  798. break;
  799. case 'modify':
  800. if ((UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_MODIFY, $this->m_oSet) == UR_ALLOWED_YES))
  801. {
  802. while($oObj = $this->m_oSet->Fetch())
  803. {
  804. $sHtml .= $oObj->GetModifyForm($oPage);
  805. }
  806. }
  807. break;
  808. case 'search':
  809. if (!$oPage->IsPrintableVersion())
  810. {
  811. $sStyle = (isset($aExtraParams['open']) && ($aExtraParams['open'] == 'true')) ? 'SearchDrawer' : 'SearchDrawer DrawerClosed';
  812. $sHtml .= "<div id=\"ds_$sId\" class=\"$sStyle\">\n";
  813. $oPage->add_ready_script(
  814. <<<EOF
  815. $("#dh_$sId").click( function() {
  816. $("#ds_$sId").slideToggle('normal', function() { $("#ds_$sId").parent().resize(); FixSearchFormsDisposition(); } );
  817. $("#dh_$sId").toggleClass('open');
  818. });
  819. EOF
  820. );
  821. $aExtraParams['currentId'] = $sId;
  822. $sHtml .= cmdbAbstractObject::GetSearchForm($oPage, $this->m_oSet, $aExtraParams);
  823. $sHtml .= "</div>\n";
  824. $sHtml .= "<div class=\"HRDrawer\"></div>\n";
  825. $sHtml .= "<div id=\"dh_$sId\" class=\"DrawerHandle\">".Dict::S('UI:SearchToggle')."</div>\n";
  826. }
  827. break;
  828. case 'open_flash_chart':
  829. static $iChartCounter = 0;
  830. $oAppContext = new ApplicationContext();
  831. $sContext = $oAppContext->GetForLink();
  832. if (!empty($sContext))
  833. {
  834. $sContext = '&'.$sContext;
  835. }
  836. $sChartType = isset($aExtraParams['chart_type']) ? $aExtraParams['chart_type'] : 'pie';
  837. $sTitle = isset($aExtraParams['chart_title']) ? $aExtraParams['chart_title'] : '';
  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. $sHtml .= "<div id=\"my_chart_$sId{$iChartCounter}\">If the chart does not display, <a href=\"http://get.adobe.com/flash/\" target=\"_blank\">install Flash</a></div>\n";
  842. $oPage->add_script("function ofc_resize(left, width, top, height) { /* do nothing special */ }");
  843. if (isset($aExtraParams['group_by_label']))
  844. {
  845. $sUrl = urlencode(utils::GetAbsoluteUrlAppRoot()."pages/ajax.render.php?operation=open_flash_chart&params[group_by]=$sGroupBy{$sGroupByExpr}&params[group_by_label]={$aExtraParams['group_by_label']}&params[chart_type]=$sChartType&params[chart_title]=$sTitle&params[currentId]=$sId&id=$sId&filter=".urlencode($sFilter));
  846. }
  847. else
  848. {
  849. $sUrl = urlencode(utils::GetAbsoluteUrlAppRoot()."pages/ajax.render.php?operation=open_flash_chart&params[group_by]=$sGroupBy{$sGroupByExpr}&params[chart_type]=$sChartType&params[chart_title]=$sTitle&params[currentId]=$sId&id=$sId&filter=".urlencode($sFilter));
  850. }
  851. $oPage->add_ready_script("swfobject.embedSWF(\"../images/open-flash-chart.swf\", \"my_chart_$sId{$iChartCounter}\", \"100%\", \"300\",\"9.0.0\", \"expressInstall.swf\",
  852. {\"data-file\":\"".$sUrl."\"}, {wmode: 'transparent'} );\n");
  853. $iChartCounter++;
  854. if (isset($aExtraParams['group_by']))
  855. {
  856. if (isset($aExtraParams['group_by_label']))
  857. {
  858. $oGroupByExp = Expression::FromOQL($aExtraParams['group_by']);
  859. $sGroupByLabel = $aExtraParams['group_by_label'];
  860. }
  861. else
  862. {
  863. // Backward compatibility: group_by is simply a field id
  864. $sAlias = $this->m_oFilter->GetClassAlias();
  865. $oGroupByExp = new FieldExpression($aExtraParams['group_by'], $sAlias);
  866. $sGroupByLabel = MetaModel::GetLabel($this->m_oFilter->GetClass(), $aExtraParams['group_by']);
  867. }
  868. $aGroupBy = array();
  869. $aGroupBy['grouped_by_1'] = $oGroupByExp;
  870. $sSql = $this->m_oFilter->MakeGroupByQuery($aQueryParams, $aGroupBy, true);
  871. $aRes = CMDBSource::QueryToArray($sSql);
  872. $aGroupBy = array();
  873. $aLabels = array();
  874. $aValues = array();
  875. $iTotalCount = 0;
  876. foreach ($aRes as $iRow => $aRow)
  877. {
  878. $sValue = $aRow['grouped_by_1'];
  879. $aValues[$iRow] = $sValue;
  880. $sHtmlValue = $oGroupByExp->MakeValueLabel($this->m_oFilter, $sValue, $sValue);
  881. $aLabels[$iRow] = $sHtmlValue;
  882. $aGroupBy[$iRow] = (int) $aRow['_itop_count_'];
  883. $iTotalCount += $aRow['_itop_count_'];
  884. }
  885. $aData = array();
  886. $idx = 0;
  887. $aURLs = array();
  888. foreach($aGroupBy as $iRow => $iCount)
  889. {
  890. // Build the search for this subset
  891. $oSubsetSearch = $this->m_oFilter->DeepClone();
  892. $oCondition = new BinaryExpression($oGroupByExp, '=', new ScalarExpression($aValues[$iRow]));
  893. $oSubsetSearch->AddConditionExpression($oCondition);
  894. $aURLs[$idx] = $oSubsetSearch->serialize();
  895. $idx++;
  896. }
  897. $sURLList = '';
  898. foreach($aURLs as $index => $sURL)
  899. {
  900. $sURLList .= "\taURLs[$index] = '".utils::GetAbsoluteUrlAppRoot()."pages/UI.php?operation=search&format=html{$sContext}&filter=".urlencode($sURL)."';\n";
  901. }
  902. $oPage->add_script(
  903. <<<EOF
  904. function ofc_drill_down_{$sId}(index)
  905. {
  906. var aURLs = new Array();
  907. {$sURLList}
  908. window.location.href=aURLs[index];
  909. }
  910. EOF
  911. );
  912. }
  913. break;
  914. case 'open_flash_chart_ajax':
  915. require_once(APPROOT.'/pages/php-ofc-library/open-flash-chart.php');
  916. $sChartType = isset($aExtraParams['chart_type']) ? $aExtraParams['chart_type'] : 'pie';
  917. $sId = utils::ReadParam('id', '');
  918. $oChart = new open_flash_chart();
  919. switch($sChartType)
  920. {
  921. case 'bars':
  922. $oChartElement = new bar_glass();
  923. if (isset($aExtraParams['group_by']))
  924. {
  925. if (isset($aExtraParams['group_by_label']))
  926. {
  927. $oGroupByExp = Expression::FromOQL($aExtraParams['group_by']);
  928. $sGroupByLabel = $aExtraParams['group_by_label'];
  929. }
  930. else
  931. {
  932. // Backward compatibility: group_by is simply a field id
  933. $sAlias = $this->m_oFilter->GetClassAlias();
  934. $oGroupByExp = new FieldExpression($aExtraParams['group_by'], $sAlias);
  935. $sGroupByLabel = MetaModel::GetLabel($this->m_oFilter->GetClass(), $aExtraParams['group_by']);
  936. }
  937. $aGroupBy = array();
  938. $aGroupBy['grouped_by_1'] = $oGroupByExp;
  939. $sSql = $this->m_oFilter->MakeGroupByQuery($aQueryParams, $aGroupBy, true);
  940. $aRes = CMDBSource::QueryToArray($sSql);
  941. $aGroupBy = array();
  942. $aLabels = array();
  943. $iTotalCount = 0;
  944. foreach ($aRes as $iRow => $aRow)
  945. {
  946. $sValue = $aRow['grouped_by_1'];
  947. $sHtmlValue = $oGroupByExp->MakeValueLabel($this->m_oFilter, $sValue, $sValue);
  948. $aLabels[$iRow] = strip_tags($sHtmlValue);
  949. $aGroupBy[$iRow] = (int) $aRow['_itop_count_'];
  950. $iTotalCount += $aRow['_itop_count_'];
  951. }
  952. $aData = array();
  953. $aChartLabels = array();
  954. $maxValue = 0;
  955. foreach($aGroupBy as $iRow => $iCount)
  956. {
  957. $oBarValue = new bar_value($iCount);
  958. $oBarValue->on_click("ofc_drill_down_$sId");
  959. $aData[] = $oBarValue;
  960. if ($iCount > $maxValue) $maxValue = $iCount;
  961. $aChartLabels[] = html_entity_decode($aLabels[$iRow], ENT_QUOTES, 'UTF-8');
  962. }
  963. $oYAxis = new y_axis();
  964. $aMagicValues = array(1,2,5,10);
  965. $iMultiplier = 1;
  966. $index = 0;
  967. $iTop = $aMagicValues[$index % count($aMagicValues)]*$iMultiplier;
  968. while($maxValue > $iTop)
  969. {
  970. $index++;
  971. $iTop = $aMagicValues[$index % count($aMagicValues)]*$iMultiplier;
  972. if (($index % count($aMagicValues)) == 0)
  973. {
  974. $iMultiplier = $iMultiplier * 10;
  975. }
  976. }
  977. //echo "oYAxis->set_range(0, $iTop, $iMultiplier);\n";
  978. $oYAxis->set_range(0, $iTop, $iMultiplier);
  979. $oChart->set_y_axis( $oYAxis );
  980. $oChartElement->set_values( $aData );
  981. $oXAxis = new x_axis();
  982. $oXLabels = new x_axis_labels();
  983. // set them vertical
  984. $oXLabels->set_vertical();
  985. // set the label text
  986. $oXLabels->set_labels($aChartLabels);
  987. // Add the X Axis Labels to the X Axis
  988. $oXAxis->set_labels( $oXLabels );
  989. $oChart->set_x_axis( $oXAxis );
  990. }
  991. break;
  992. case 'pie':
  993. default:
  994. $oChartElement = new pie();
  995. $oChartElement->set_start_angle( 35 );
  996. $oChartElement->set_animate( true );
  997. $oChartElement->set_tooltip( '#label# - #val# (#percent#)' );
  998. $oChartElement->set_colours( array('#FF8A00', '#909980', '#2C2B33', '#CCC08D', '#596664') );
  999. if (isset($aExtraParams['group_by']))
  1000. {
  1001. if (isset($aExtraParams['group_by_label']))
  1002. {
  1003. $oGroupByExp = Expression::FromOQL($aExtraParams['group_by']);
  1004. $sGroupByLabel = $aExtraParams['group_by_label'];
  1005. }
  1006. else
  1007. {
  1008. // Backward compatibility: group_by is simply a field id
  1009. $sAlias = $this->m_oFilter->GetClassAlias();
  1010. $oGroupByExp = new FieldExpression($aExtraParams['group_by'], $sAlias);
  1011. $sGroupByLabel = MetaModel::GetLabel($this->m_oFilter->GetClass(), $aExtraParams['group_by']);
  1012. }
  1013. $aGroupBy = array();
  1014. $aGroupBy['grouped_by_1'] = $oGroupByExp;
  1015. $sSql = $this->m_oFilter->MakeGroupByQuery($aQueryParams, $aGroupBy, true);
  1016. $aRes = CMDBSource::QueryToArray($sSql);
  1017. $aGroupBy = array();
  1018. $aLabels = array();
  1019. $iTotalCount = 0;
  1020. foreach ($aRes as $iRow => $aRow)
  1021. {
  1022. $sValue = $aRow['grouped_by_1'];
  1023. $sHtmlValue = $oGroupByExp->MakeValueLabel($this->m_oFilter, $sValue, $sValue);
  1024. $aLabels[$iRow] = strip_tags($sHtmlValue);
  1025. $aGroupBy[$iRow] = (int) $aRow['_itop_count_'];
  1026. $iTotalCount += $aRow['_itop_count_'];
  1027. }
  1028. $aData = array();
  1029. foreach($aGroupBy as $iRow => $iCount)
  1030. {
  1031. $sFlashLabel = html_entity_decode($aLabels[$iRow], ENT_QUOTES, 'UTF-8');
  1032. $PieValue = new pie_value($iCount, $sFlashLabel); //@@ BUG: not passed via ajax !!!
  1033. $PieValue->on_click("ofc_drill_down_$sId");
  1034. $aData[] = $PieValue;
  1035. }
  1036. $oChartElement->set_values( $aData );
  1037. $oChart->x_axis = null;
  1038. }
  1039. }
  1040. if (isset($aExtraParams['chart_title']))
  1041. {
  1042. // The title has been given in an url, and urlencoded...
  1043. // and urlencode transforms utf-8 into something similar to ISO-8859-1
  1044. // Example: é (C3A9 becomes %E9)
  1045. // As a consequence, json_encode (called within open-flash-chart.php)
  1046. // was returning 'null' and the graph was not displayed at all
  1047. // To make sure that the graph is displayed AND to get a correct title
  1048. // (at least for european characters) let's transform back into utf-8 !
  1049. $sTitle = iconv("ISO-8859-1", "UTF-8//IGNORE", $aExtraParams['chart_title']);
  1050. // If the title is a dictionnary entry, fetch it
  1051. $sTitle = Dict::S($sTitle);
  1052. $oTitle = new title($sTitle);
  1053. $oChart->set_title( $oTitle );
  1054. $oTitle->set_style("{font-size: 16px; font-family: Tahoma; font-weight: bold; text-align: center;}");
  1055. }
  1056. $oChart->set_bg_colour('#FFFFFF');
  1057. $oChart->add_element( $oChartElement );
  1058. $sHtml = $oChart->toPrettyString();
  1059. break;
  1060. default:
  1061. // Unsupported style, do nothing.
  1062. $sHtml .= Dict::format('UI:Error:UnsupportedStyleOfBlock', $this->m_sStyle);
  1063. }
  1064. return $sHtml;
  1065. }
  1066. /**
  1067. * Add a condition (restriction) to the current DBSearch on which the display block is based
  1068. * taking into account the hierarchical keys for which the condition is based on the 'below' operator
  1069. */
  1070. protected function AddCondition($sFilterCode, $condition, $sOpCode = null)
  1071. {
  1072. // Workaround to an issue revealed whenever a condition on org_id is applied twice (with a hierarchy of organizations)
  1073. // Moreover, it keeps the query as simple as possible
  1074. if (isset($this->m_aConditions[$sFilterCode]) && $condition == $this->m_aConditions[$sFilterCode])
  1075. {
  1076. // Skip
  1077. return;
  1078. }
  1079. $this->m_aConditions[$sFilterCode] = $condition;
  1080. $sClass = $this->m_oFilter->GetClass();
  1081. $bConditionAdded = false;
  1082. // If the condition is an external key with a class having a hierarchy, use a "below" criteria
  1083. if (MetaModel::IsValidAttCode($sClass, $sFilterCode))
  1084. {
  1085. $oAttDef = MetaModel::GetAttributeDef($sClass, $sFilterCode);
  1086. if ($oAttDef->IsExternalKey())
  1087. {
  1088. $sHierarchicalKeyCode = MetaModel::IsHierarchicalClass($oAttDef->GetTargetClass());
  1089. if ($sHierarchicalKeyCode !== false)
  1090. {
  1091. $oFilter = new DBObjectSearch($oAttDef->GetTargetClass());
  1092. if (($sOpCode == 'IN') && is_array($condition))
  1093. {
  1094. $oFilter->AddConditionExpression(self::GetConditionIN($oFilter, 'id', $condition));
  1095. }
  1096. else
  1097. {
  1098. $oFilter->AddCondition('id', $condition);
  1099. }
  1100. $oHKFilter = new DBObjectSearch($oAttDef->GetTargetClass());
  1101. $oHKFilter->AddCondition_PointingTo($oFilter, $sHierarchicalKeyCode, TREE_OPERATOR_BELOW); // Use the 'below' operator by default
  1102. $this->m_oFilter->AddCondition_PointingTo($oHKFilter, $sFilterCode);
  1103. $bConditionAdded = true;
  1104. }
  1105. else if (($sOpCode == 'IN') && is_array($condition))
  1106. {
  1107. $this->m_oFilter->AddConditionExpression(self::GetConditionIN($this->m_oFilter, $sFilterCode, $condition));
  1108. $bConditionAdded = true;
  1109. }
  1110. }
  1111. else if (($sOpCode == 'IN') && is_array($condition))
  1112. {
  1113. $this->m_oFilter->AddConditionExpression(self::GetConditionIN($this->m_oFilter, $sFilterCode, $condition));
  1114. $bConditionAdded = true;
  1115. }
  1116. }
  1117. // In all other cases, just add the condition directly
  1118. if (!$bConditionAdded)
  1119. {
  1120. $this->m_oFilter->AddCondition($sFilterCode, $condition); // Use the default 'loose' operator
  1121. }
  1122. }
  1123. static protected function GetConditionIN($oFilter, $sFilterCode, $condition)
  1124. {
  1125. $oField = new FieldExpression($sFilterCode, $oFilter->GetClassAlias());
  1126. $sListExpr = '('.implode(', ', CMDBSource::Quote($condition)).')';
  1127. $sOQLCondition = $oField->Render()." IN $sListExpr";
  1128. $oNewCondition = Expression::FromOQL($sOQLCondition);
  1129. return $oNewCondition;
  1130. }
  1131. }
  1132. /**
  1133. * Helper class to manage 'blocks' of HTML pieces that are parts of a page and contain some list of cmdb objects
  1134. *
  1135. * Each block is actually rendered as a <div></div> tag that can be rendered synchronously
  1136. * or as a piece of Javascript/JQuery/Ajax that will get its content from another page (ajax.render.php).
  1137. * The list of cmdbObjects to be displayed into the block is defined by a filter
  1138. * Right now the type of display is either: list, count or details
  1139. * - list produces a table listing the objects
  1140. * - count produces a paragraphs with a sentence saying 'cont' objects found
  1141. * - details display (as table) the details of each object found (best if only one)
  1142. */
  1143. class HistoryBlock extends DisplayBlock
  1144. {
  1145. protected $iLimitCount;
  1146. protected $iLimitStart;
  1147. public function __construct(DBSearch $oFilter, $sStyle = 'list', $bAsynchronous = false, $aParams = array(), $oSet = null)
  1148. {
  1149. parent::__construct($oFilter, $sStyle, $bAsynchronous, $aParams, $oSet);
  1150. $this->iLimitStart = 0;
  1151. $this->iLimitCount = 0;
  1152. }
  1153. public function SetLimit($iCount, $iStart = 0)
  1154. {
  1155. $this->iLimitStart = $iStart;
  1156. $this->iLimitCount = $iCount;
  1157. }
  1158. public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId)
  1159. {
  1160. $sHtml = '';
  1161. $bTruncated = false;
  1162. $oSet = new CMDBObjectSet($this->m_oFilter, array('date'=>false));
  1163. if (!$oPage->IsPrintableVersion())
  1164. {
  1165. if (($this->iLimitStart > 0) || ($this->iLimitCount > 0))
  1166. {
  1167. $oSet->SetLimit($this->iLimitCount, $this->iLimitStart);
  1168. if (($this->iLimitCount - $this->iLimitStart) < $oSet->Count())
  1169. {
  1170. $bTruncated = true;
  1171. }
  1172. }
  1173. }
  1174. $sHtml .= "<!-- filter: ".($this->m_oFilter->ToOQL())."-->\n";
  1175. switch($this->m_sStyle)
  1176. {
  1177. case 'toggle':
  1178. // First the latest change that the user is allowed to see
  1179. do
  1180. {
  1181. $oLatestChangeOp = $oSet->Fetch();
  1182. }
  1183. while(is_object($oLatestChangeOp) && ($oLatestChangeOp->GetDescription() == ''));
  1184. if (is_object($oLatestChangeOp))
  1185. {
  1186. // There is one change in the list... only when the object has been created !
  1187. $sDate = $oLatestChangeOp->GetAsHTML('date');
  1188. $oChange = MetaModel::GetObject('CMDBChange', $oLatestChangeOp->Get('change'));
  1189. $sUserInfo = $oChange->GetAsHTML('userinfo');
  1190. $sHtml .= $oPage->GetStartCollapsibleSection(Dict::Format('UI:History:LastModified_On_By', $sDate, $sUserInfo));
  1191. $sHtml .= $this->GetHistoryTable($oPage, $oSet);
  1192. $sHtml .= $oPage->GetEndCollapsibleSection();
  1193. }
  1194. break;
  1195. case 'table':
  1196. default:
  1197. if ($bTruncated)
  1198. {
  1199. $sFilter = $this->m_oFilter->serialize();
  1200. $sHtml .= '<div id="history_container"><p>';
  1201. $sHtml .= Dict::Format('UI:TruncatedResults', $this->iLimitCount, $oSet->Count());
  1202. $sHtml .= ' ';
  1203. $sHtml .= '<a href="#" onclick="DisplayHistory(\'#history_container\', \''.$sFilter.'\', 0, 0); return false;">'.Dict::S('UI:DisplayAll').'</a>';
  1204. $sHtml .= $this->GetHistoryTable($oPage, $oSet);
  1205. $sHtml .= '</p></div>';
  1206. $oPage->add_ready_script("$('#{$sId} table.listResults tr:last td').addClass('truncated');");
  1207. }
  1208. else
  1209. {
  1210. $sHtml .= $this->GetHistoryTable($oPage, $oSet);
  1211. }
  1212. }
  1213. return $sHtml;
  1214. }
  1215. protected function GetHistoryTable(WebPage $oPage, DBObjectSet $oSet)
  1216. {
  1217. $sHtml = '';
  1218. // First the latest change that the user is allowed to see
  1219. $oSet->Rewind(); // Reset the pointer to the beginning of the set
  1220. $aChanges = array();
  1221. while($oChangeOp = $oSet->Fetch())
  1222. {
  1223. $sChangeDescription = $oChangeOp->GetDescription();
  1224. if ($sChangeDescription != '')
  1225. {
  1226. // The change is visible for the current user
  1227. $changeId = $oChangeOp->Get('change');
  1228. $aChanges[$changeId]['date'] = $oChangeOp->Get('date');
  1229. $aChanges[$changeId]['userinfo'] = $oChangeOp->Get('userinfo');
  1230. if (!isset($aChanges[$changeId]['log']))
  1231. {
  1232. $aChanges[$changeId]['log'] = array();
  1233. }
  1234. $aChanges[$changeId]['log'][] = $sChangeDescription;
  1235. }
  1236. }
  1237. $aAttribs = array('date' => array('label' => Dict::S('UI:History:Date'), 'description' => Dict::S('UI:History:Date+')),
  1238. 'userinfo' => array('label' => Dict::S('UI:History:User'), 'description' => Dict::S('UI:History:User+')),
  1239. 'log' => array('label' => Dict::S('UI:History:Changes'), 'description' => Dict::S('UI:History:Changes+')),
  1240. );
  1241. $aValues = array();
  1242. foreach($aChanges as $aChange)
  1243. {
  1244. $aValues[] = array('date' => $aChange['date'], 'userinfo' => htmlentities($aChange['userinfo'], ENT_QUOTES, 'UTF-8'), 'log' => "<ul><li>".implode('</li><li>', $aChange['log'])."</li></ul>");
  1245. }
  1246. $sHtml .= $oPage->GetTable($aAttribs, $aValues);
  1247. return $sHtml;
  1248. }
  1249. }
  1250. /**
  1251. * Displays the 'Actions' menu for a given (list of) object(s)
  1252. * The 'style' of the list (see constructor of DisplayBlock) can be either 'list' or 'details'
  1253. * For backward compatibility 'popup' is equivalent to 'list'...
  1254. */
  1255. class MenuBlock extends DisplayBlock
  1256. {
  1257. /**
  1258. * Renders the "Actions" popup menu for the given set of objects
  1259. *
  1260. * Note that the menu links containing (or ending) with a hash (#) will have their fragment
  1261. * part (whatever is after the hash) dynamically replaced (by javascript) when the menu is
  1262. * displayed, to correspond to the current hash/fragment in the page. This allows modifying
  1263. * an object in with the same tab active by default as the tab that was active when selecting
  1264. * the "Modify..." action.
  1265. */
  1266. public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId)
  1267. {
  1268. if ($this->m_sStyle == 'popup') // popup is a synonym of 'list' for backward compatibility
  1269. {
  1270. $this->m_sStyle = 'list';
  1271. }
  1272. $sHtml = '';
  1273. $oAppContext = new ApplicationContext();
  1274. $sContext = $oAppContext->GetForLink();
  1275. if (!empty($sContext))
  1276. {
  1277. $sContext = '&'.$sContext;
  1278. }
  1279. $sClass = $this->m_oFilter->GetClass();
  1280. $oReflectionClass = new ReflectionClass($sClass);
  1281. $oSet = new CMDBObjectSet($this->m_oFilter);
  1282. $sFilter = $this->m_oFilter->serialize();
  1283. $sFilterDesc = $this->m_oFilter->ToOql(true);
  1284. $aActions = array();
  1285. $sUIPage = cmdbAbstractObject::ComputeStandardUIPage($sClass);
  1286. $sRootUrl = utils::GetAbsoluteUrlAppRoot();
  1287. // 1:n links, populate the target object as a default value when creating a new linked object
  1288. if (isset($aExtraParams['target_attr']))
  1289. {
  1290. $aExtraParams['default'][$aExtraParams['target_attr']] = $aExtraParams['object_id'];
  1291. }
  1292. $sDefault = '';
  1293. if (!empty($aExtraParams['default']))
  1294. {
  1295. foreach($aExtraParams['default'] as $sKey => $sValue)
  1296. {
  1297. $sDefault.= "&default[$sKey]=$sValue";
  1298. }
  1299. }
  1300. $bIsCreationAllowed = (UserRights::IsActionAllowed($sClass, UR_ACTION_CREATE) == UR_ALLOWED_YES) && ($oReflectionClass->IsSubclassOf('cmdbAbstractObject'));
  1301. switch($oSet->Count())
  1302. {
  1303. case 0:
  1304. // No object in the set, the only possible action is "new"
  1305. if ($bIsCreationAllowed) { $aActions['UI:Menu:New'] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=new&class=$sClass{$sContext}{$sDefault}"); }
  1306. break;
  1307. case 1:
  1308. $oObj = $oSet->Fetch();
  1309. $id = $oObj->GetKey();
  1310. $bLocked = false;
  1311. if (MetaModel::GetConfig()->Get('concurrent_lock_enabled'))
  1312. {
  1313. $aLockInfo = iTopOwnershipLock::IsLocked(get_class($oObj), $id);
  1314. if ($aLockInfo['locked'])
  1315. {
  1316. $bLocked = true;
  1317. //$this->AddMenuSeparator($aActions);
  1318. //$aActions['concurrent_lock_unlock'] = array ('label' => Dict::S('UI:Menu:ReleaseConcurrentLock'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=kill_lock&class=$sClass&id=$id{$sContext}");
  1319. }
  1320. }
  1321. $bRawModifiedAllowed = (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet) == UR_ALLOWED_YES) && ($oReflectionClass->IsSubclassOf('cmdbAbstractObject'));
  1322. $bIsModifyAllowed = !$bLocked && $bRawModifiedAllowed;
  1323. $bIsDeleteAllowed = !$bLocked && UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, $oSet);
  1324. // Just one object in the set, possible actions are "new / clone / modify and delete"
  1325. if (!isset($aExtraParams['link_attr']))
  1326. {
  1327. if ($bIsModifyAllowed) { $aActions['UI:Menu:Modify'] = array ('label' => Dict::S('UI:Menu:Modify'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=modify&class=$sClass&id=$id{$sContext}#"); }
  1328. if ($bIsCreationAllowed) { $aActions['UI:Menu:New'] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=new&class=$sClass{$sContext}{$sDefault}"); }
  1329. if ($bIsDeleteAllowed) { $aActions['UI:Menu:Delete'] = array ('label' => Dict::S('UI:Menu:Delete'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=delete&class=$sClass&id=$id{$sContext}"); }
  1330. // Transitions / Stimuli
  1331. if (!$bLocked)
  1332. {
  1333. $aTransitions = $oObj->EnumTransitions();
  1334. if (count($aTransitions))
  1335. {
  1336. $this->AddMenuSeparator($aActions);
  1337. $aStimuli = Metamodel::EnumStimuli(get_class($oObj));
  1338. foreach($aTransitions as $sStimulusCode => $aTransitionDef)
  1339. {
  1340. $iActionAllowed = (get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction') ? UserRights::IsStimulusAllowed($sClass, $sStimulusCode, $oSet) : UR_ALLOWED_NO;
  1341. switch($iActionAllowed)
  1342. {
  1343. case UR_ALLOWED_YES:
  1344. $aActions[$sStimulusCode] = array('label' => $aStimuli[$sStimulusCode]->GetLabel(), 'url' => "{$sRootUrl}pages/UI.php?operation=stimulus&stimulus=$sStimulusCode&class=$sClass&id=$id{$sContext}");
  1345. break;
  1346. default:
  1347. // Do nothing
  1348. }
  1349. }
  1350. }
  1351. }
  1352. // Relations...
  1353. $aRelations = MetaModel::EnumRelationsEx($sClass);
  1354. if (count($aRelations))
  1355. {
  1356. $this->AddMenuSeparator($aActions);
  1357. foreach($aRelations as $sRelationCode => $aRelationInfo)
  1358. {
  1359. if (array_key_exists('down', $aRelationInfo))
  1360. {
  1361. $aActions[$sRelationCode.'_down'] = array ('label' => $aRelationInfo['down'], 'url' => "{$sRootUrl}pages/$sUIPage?operation=swf_navigator&relation=$sRelationCode&direction=down&class=$sClass&id=$id{$sContext}");
  1362. }
  1363. if (array_key_exists('up', $aRelationInfo))
  1364. {
  1365. $aActions[$sRelationCode.'_up'] = array ('label' => $aRelationInfo['up'], 'url' => "{$sRootUrl}pages/$sUIPage?operation=swf_navigator&relation=$sRelationCode&direction=up&class=$sClass&id=$id{$sContext}");
  1366. }
  1367. }
  1368. }
  1369. if ($bLocked && $bRawModifiedAllowed)
  1370. {
  1371. // Add a special menu to kill the lock, but only to allowed users who can also modify this object
  1372. $aAllowedProfiles = MetaModel::GetConfig()->Get('concurrent_lock_override_profiles');
  1373. $bCanKill = false;
  1374. $oUser = UserRights::GetUserObject();
  1375. $aUserProfiles = array();
  1376. if (!is_null($oUser))
  1377. {
  1378. $oProfileSet = $oUser->Get('profile_list');
  1379. while ($oProfile = $oProfileSet->Fetch())
  1380. {
  1381. $aUserProfiles[$oProfile->Get('profile')] = true;
  1382. }
  1383. }
  1384. foreach($aAllowedProfiles as $sProfile)
  1385. {
  1386. if (array_key_exists($sProfile, $aUserProfiles))
  1387. {
  1388. $bCanKill = true;
  1389. break;
  1390. }
  1391. }
  1392. if ($bCanKill)
  1393. {
  1394. $this->AddMenuSeparator($aActions);
  1395. $aActions['concurrent_lock_unlock'] = array ('label' => Dict::S('UI:Menu:KillConcurrentLock'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=kill_lock&class=$sClass&id=$id{$sContext}");
  1396. }
  1397. }
  1398. /*
  1399. $this->AddMenuSeparator($aActions);
  1400. // Static menus: Email this page & CSV Export
  1401. $sUrl = ApplicationContext::MakeObjectUrl($sClass, $id);
  1402. $aActions['UI:Menu:EMail'] = array ('label' => Dict::S('UI:Menu:EMail'), 'url' => "mailto:?subject=".urlencode($oObj->GetRawName())."&body=".urlencode($sUrl));
  1403. $aActions['UI:Menu:CSVExport'] = array ('label' => Dict::S('UI:Menu:CSVExport'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=search&filter=".urlencode($sFilter)."&format=csv{$sContext}");
  1404. // The style tells us whether the menu is displayed on a list of one object, or on the details of the given object
  1405. if ($this->m_sStyle == 'list')
  1406. {
  1407. // Actions specific to the list
  1408. $sOQL = addslashes($sFilterDesc);
  1409. $aActions['UI:Menu:AddToDashboard'] = array ('label' => Dict::S('UI:Menu:AddToDashboard'), 'url' => "#", 'onclick' => "return DashletCreationDlg('$sOQL')");
  1410. }
  1411. */
  1412. }
  1413. $this->AddMenuSeparator($aActions);
  1414. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  1415. {
  1416. $oSet->Rewind();
  1417. foreach($oExtensionInstance->EnumAllowedActions($oSet) as $sLabel => $sUrl)
  1418. {
  1419. $aActions[$sLabel] = array ('label' => $sLabel, 'url' => $sUrl);
  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. }
  1567. static $bPopupScript = false;
  1568. if (!$bPopupScript)
  1569. {
  1570. // Output this once per page...
  1571. $oPage->add_ready_script("$(\"div.itop_popup>ul\").popupmenu();\n");
  1572. $bPopupScript = true;
  1573. }
  1574. return $sHtml;
  1575. }
  1576. /**
  1577. * Appends a menu separator to the current list of actions
  1578. * @param Hash $aActions The current actions list
  1579. * @return void
  1580. */
  1581. protected function AddMenuSeparator(&$aActions)
  1582. {
  1583. $sSeparator = '<hr class="menu-separator"/>';
  1584. if (count($aActions) > 0) // Make sure that the separator is not the first item in the menu
  1585. {
  1586. $aKeys = array_keys($aActions);
  1587. $sLastKey = array_pop($aKeys);
  1588. if ($aActions[$sLastKey]['label'] != $sSeparator) // Make sure there are no 2 consecutive separators
  1589. {
  1590. $aActions['sep_'.(count($aActions)-1)] = array('label' => $sSeparator, 'url' => '');
  1591. }
  1592. }
  1593. }
  1594. }