displayblock.class.inc.php 64 KB

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