displayblock.class.inc.php 61 KB

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