displayblock.class.inc.php 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630
  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(MetaModel::GetConfig()->Get('min_reload_interval'), $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. $sHtml .= '<div style="clear:both;"></div>';
  734. break;
  735. case 'csv':
  736. $bAdvancedMode = utils::ReadParam('advanced', false);
  737. $sCsvFile = strtolower($this->m_oFilter->GetClass()).'.csv';
  738. $sDownloadLink = utils::GetAbsoluteUrlAppRoot().'webservices/export.php?expression='.urlencode($this->m_oFilter->ToOQL(true)).'&format=csv&filename='.urlencode($sCsvFile);
  739. $sLinkToToggle = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=search&'.$oAppContext->GetForLink().'&filter='.urlencode($this->m_oFilter->serialize()).'&format=csv';
  740. if ($bAdvancedMode)
  741. {
  742. $sDownloadLink .= '&fields_advanced=1';
  743. $sChecked = 'CHECKED';
  744. }
  745. else
  746. {
  747. $sLinkToToggle = $sLinkToToggle.'&advanced=1';
  748. $sChecked = '';
  749. }
  750. $sAjaxLink = $sDownloadLink.'&charset=UTF-8'; // Includes &fields_advanced=1 if in advanced mode
  751. /*
  752. $sCSVData = cmdbAbstractObject::GetSetAsCSV($this->m_oSet, array('fields_advanced' => $bAdvancedMode));
  753. $sCharset = MetaModel::GetConfig()->Get('csv_file_default_charset');
  754. if ($sCharset == 'UTF-8')
  755. {
  756. $bLostChars = false;
  757. }
  758. else
  759. {
  760. $sConverted = @iconv('UTF-8', $sCharset, $sCSVData);
  761. $sRestored = @iconv($sCharset, 'UTF-8', $sConverted);
  762. $bLostChars = ($sRestored != $sCSVData);
  763. }
  764. if ($bLostChars)
  765. {
  766. $sCharsetNotice = "&nbsp;&nbsp;<span id=\"csv_charset_issue\">";
  767. $sCharsetNotice .= '<img src="../images/error.png" style="vertical-align:middle"/>';
  768. $sCharsetNotice .= "</span>";
  769. $sTip = "<p>".htmlentities(Dict::S('UI:CSVExport:LostChars'), ENT_QUOTES, 'UTF-8')."</p>";
  770. $sTip .= "<p>".htmlentities(Dict::Format('UI:CSVExport:LostChars+', $sCharset), ENT_QUOTES, 'UTF-8')."</p>";
  771. $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' }} } );");
  772. }
  773. else
  774. {
  775. $sCharsetNotice = '';
  776. }
  777. */
  778. $sCharsetNotice = false;
  779. $sHtml .= "<div>";
  780. $sHtml .= '<table style="width:100%" class="transparent">';
  781. $sHtml .= '<tr>';
  782. $sHtml .= '<td><a href="'.$sDownloadLink.'">'.Dict::Format('UI:Download-CSV', $sCsvFile).'</a>'.$sCharsetNotice.'</td>';
  783. $sHtml .= '<td style="text-align:right"><input type="checkbox" '.$sChecked.' onClick="window.location.href=\''.$sLinkToToggle.'\'">&nbsp;'.Dict::S('UI:CSVExport:AdvancedMode').'</td>';
  784. $sHtml .= '</tr>';
  785. $sHtml .= '</table>';
  786. if ($bAdvancedMode)
  787. {
  788. $sHtml .= "<p>";
  789. $sHtml .= htmlentities(Dict::S('UI:CSVExport:AdvancedMode+'), ENT_QUOTES, 'UTF-8');
  790. $sHtml .= "</p>";
  791. }
  792. $sHtml .= "</div>";
  793. $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";
  794. //$sHtml .= htmlentities($sCSVData, ENT_QUOTES, 'UTF-8');
  795. $sHtml .= "</textarea>\n";
  796. $oPage->add_ready_script("$.post('$sAjaxLink', {}, function(data) { $('#csv_content').html(data); $('#csv_content_loading').hide(); $('#csv_content').show();} );");
  797. break;
  798. case 'modify':
  799. if ((UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_MODIFY, $this->m_oSet) == UR_ALLOWED_YES))
  800. {
  801. while($oObj = $this->m_oSet->Fetch())
  802. {
  803. $sHtml .= $oObj->GetModifyForm($oPage);
  804. }
  805. }
  806. break;
  807. case 'search':
  808. $sStyle = (isset($aExtraParams['open']) && ($aExtraParams['open'] == 'true')) ? 'SearchDrawer' : 'SearchDrawer DrawerClosed';
  809. $sHtml .= "<div id=\"ds_$sId\" class=\"$sStyle\">\n";
  810. $oPage->add_ready_script(
  811. <<<EOF
  812. $("#dh_$sId").click( function() {
  813. $("#ds_$sId").slideToggle('normal', function() { $("#ds_$sId").parent().resize(); } );
  814. $("#dh_$sId").toggleClass('open');
  815. });
  816. EOF
  817. );
  818. $aExtraParams['currentId'] = $sId;
  819. $sHtml .= cmdbAbstractObject::GetSearchForm($oPage, $this->m_oSet, $aExtraParams);
  820. $sHtml .= "</div>\n";
  821. $sHtml .= "<div class=\"HRDrawer\"></div>\n";
  822. $sHtml .= "<div id=\"dh_$sId\" class=\"DrawerHandle\">".Dict::S('UI:SearchToggle')."</div>\n";
  823. break;
  824. case 'open_flash_chart':
  825. static $iChartCounter = 0;
  826. $oAppContext = new ApplicationContext();
  827. $sContext = $oAppContext->GetForLink();
  828. if (!empty($sContext))
  829. {
  830. $sContext = '&'.$sContext;
  831. }
  832. $sChartType = isset($aExtraParams['chart_type']) ? $aExtraParams['chart_type'] : 'pie';
  833. $sTitle = isset($aExtraParams['chart_title']) ? $aExtraParams['chart_title'] : '';
  834. $sGroupBy = isset($aExtraParams['group_by']) ? $aExtraParams['group_by'] : '';
  835. $sGroupByExpr = isset($aExtraParams['group_by_expr']) ? '&params[group_by_expr]='.$aExtraParams['group_by_expr'] : '';
  836. $sFilter = $this->m_oFilter->serialize();
  837. $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";
  838. $oPage->add_script("function ofc_resize(left, width, top, height) { /* do nothing special */ }");
  839. if (isset($aExtraParams['group_by_label']))
  840. {
  841. $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));
  842. }
  843. else
  844. {
  845. $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));
  846. }
  847. $oPage->add_ready_script("swfobject.embedSWF(\"../images/open-flash-chart.swf\", \"my_chart_$sId{$iChartCounter}\", \"100%\", \"300\",\"9.0.0\", \"expressInstall.swf\",
  848. {\"data-file\":\"".$sUrl."\"}, {wmode: 'transparent'} );\n");
  849. $iChartCounter++;
  850. if (isset($aExtraParams['group_by']))
  851. {
  852. if (isset($aExtraParams['group_by_label']))
  853. {
  854. $oGroupByExp = Expression::FromOQL($aExtraParams['group_by']);
  855. $sGroupByLabel = $aExtraParams['group_by_label'];
  856. }
  857. else
  858. {
  859. // Backward compatibility: group_by is simply a field id
  860. $sAlias = $this->m_oFilter->GetClassAlias();
  861. $oGroupByExp = new FieldExpression($aExtraParams['group_by'], $sAlias);
  862. $sGroupByLabel = MetaModel::GetLabel($this->m_oFilter->GetClass(), $aExtraParams['group_by']);
  863. }
  864. $aGroupBy = array();
  865. $aGroupBy['grouped_by_1'] = $oGroupByExp;
  866. $sSql = MetaModel::MakeGroupByQuery($this->m_oFilter, $aQueryParams, $aGroupBy, true);
  867. $aRes = CMDBSource::QueryToArray($sSql);
  868. $aGroupBy = array();
  869. $aLabels = array();
  870. $aValues = array();
  871. $iTotalCount = 0;
  872. foreach ($aRes as $iRow => $aRow)
  873. {
  874. $sValue = $aRow['grouped_by_1'];
  875. $aValues[$iRow] = $sValue;
  876. $sHtmlValue = $oGroupByExp->MakeValueLabel($this->m_oFilter, $sValue, $sValue);
  877. $aLabels[$iRow] = $sHtmlValue;
  878. $aGroupBy[$iRow] = (int) $aRow['_itop_count_'];
  879. $iTotalCount += $aRow['_itop_count_'];
  880. }
  881. $aData = array();
  882. $idx = 0;
  883. $aURLs = array();
  884. foreach($aGroupBy as $iRow => $iCount)
  885. {
  886. // Build the search for this subset
  887. $oSubsetSearch = $this->m_oFilter->DeepClone();
  888. $oCondition = new BinaryExpression($oGroupByExp, '=', new ScalarExpression($aValues[$iRow]));
  889. $oSubsetSearch->AddConditionExpression($oCondition);
  890. $aURLs[$idx] = $oSubsetSearch->serialize();
  891. $idx++;
  892. }
  893. $sURLList = '';
  894. foreach($aURLs as $index => $sURL)
  895. {
  896. $sURLList .= "\taURLs[$index] = '".utils::GetAbsoluteUrlAppRoot()."pages/UI.php?operation=search&format=html{$sContext}&filter=".urlencode($sURL)."';\n";
  897. }
  898. $oPage->add_script(
  899. <<<EOF
  900. function ofc_drill_down_{$sId}(index)
  901. {
  902. var aURLs = new Array();
  903. {$sURLList}
  904. window.location.href=aURLs[index];
  905. }
  906. EOF
  907. );
  908. }
  909. break;
  910. case 'open_flash_chart_ajax':
  911. require_once(APPROOT.'/pages/php-ofc-library/open-flash-chart.php');
  912. $sChartType = isset($aExtraParams['chart_type']) ? $aExtraParams['chart_type'] : 'pie';
  913. $sId = utils::ReadParam('id', '');
  914. $oChart = new open_flash_chart();
  915. switch($sChartType)
  916. {
  917. case 'bars':
  918. $oChartElement = new bar_glass();
  919. if (isset($aExtraParams['group_by']))
  920. {
  921. if (isset($aExtraParams['group_by_label']))
  922. {
  923. $oGroupByExp = Expression::FromOQL($aExtraParams['group_by']);
  924. $sGroupByLabel = $aExtraParams['group_by_label'];
  925. }
  926. else
  927. {
  928. // Backward compatibility: group_by is simply a field id
  929. $sAlias = $this->m_oFilter->GetClassAlias();
  930. $oGroupByExp = new FieldExpression($aExtraParams['group_by'], $sAlias);
  931. $sGroupByLabel = MetaModel::GetLabel($this->m_oFilter->GetClass(), $aExtraParams['group_by']);
  932. }
  933. $aGroupBy = array();
  934. $aGroupBy['grouped_by_1'] = $oGroupByExp;
  935. $sSql = MetaModel::MakeGroupByQuery($this->m_oFilter, $aQueryParams, $aGroupBy, true);
  936. $aRes = CMDBSource::QueryToArray($sSql);
  937. $aGroupBy = array();
  938. $aLabels = array();
  939. $iTotalCount = 0;
  940. foreach ($aRes as $iRow => $aRow)
  941. {
  942. $sValue = $aRow['grouped_by_1'];
  943. $sHtmlValue = $oGroupByExp->MakeValueLabel($this->m_oFilter, $sValue, $sValue);
  944. $aLabels[$iRow] = strip_tags($sHtmlValue);
  945. $aGroupBy[$iRow] = (int) $aRow['_itop_count_'];
  946. $iTotalCount += $aRow['_itop_count_'];
  947. }
  948. $aData = array();
  949. $aChartLabels = array();
  950. $maxValue = 0;
  951. foreach($aGroupBy as $iRow => $iCount)
  952. {
  953. $oBarValue = new bar_value($iCount);
  954. $oBarValue->on_click("ofc_drill_down_$sId");
  955. $aData[] = $oBarValue;
  956. if ($iCount > $maxValue) $maxValue = $iCount;
  957. $aChartLabels[] = html_entity_decode($aLabels[$iRow], ENT_QUOTES, 'UTF-8');
  958. }
  959. $oYAxis = new y_axis();
  960. $aMagicValues = array(1,2,5,10);
  961. $iMultiplier = 1;
  962. $index = 0;
  963. $iTop = $aMagicValues[$index % count($aMagicValues)]*$iMultiplier;
  964. while($maxValue > $iTop)
  965. {
  966. $index++;
  967. $iTop = $aMagicValues[$index % count($aMagicValues)]*$iMultiplier;
  968. if (($index % count($aMagicValues)) == 0)
  969. {
  970. $iMultiplier = $iMultiplier * 10;
  971. }
  972. }
  973. //echo "oYAxis->set_range(0, $iTop, $iMultiplier);\n";
  974. $oYAxis->set_range(0, $iTop, $iMultiplier);
  975. $oChart->set_y_axis( $oYAxis );
  976. $oChartElement->set_values( $aData );
  977. $oXAxis = new x_axis();
  978. $oXLabels = new x_axis_labels();
  979. // set them vertical
  980. $oXLabels->set_vertical();
  981. // set the label text
  982. $oXLabels->set_labels($aChartLabels);
  983. // Add the X Axis Labels to the X Axis
  984. $oXAxis->set_labels( $oXLabels );
  985. $oChart->set_x_axis( $oXAxis );
  986. }
  987. break;
  988. case 'pie':
  989. default:
  990. $oChartElement = new pie();
  991. $oChartElement->set_start_angle( 35 );
  992. $oChartElement->set_animate( true );
  993. $oChartElement->set_tooltip( '#label# - #val# (#percent#)' );
  994. $oChartElement->set_colours( array('#FF8A00', '#909980', '#2C2B33', '#CCC08D', '#596664') );
  995. if (isset($aExtraParams['group_by']))
  996. {
  997. if (isset($aExtraParams['group_by_label']))
  998. {
  999. $oGroupByExp = Expression::FromOQL($aExtraParams['group_by']);
  1000. $sGroupByLabel = $aExtraParams['group_by_label'];
  1001. }
  1002. else
  1003. {
  1004. // Backward compatibility: group_by is simply a field id
  1005. $sAlias = $this->m_oFilter->GetClassAlias();
  1006. $oGroupByExp = new FieldExpression($aExtraParams['group_by'], $sAlias);
  1007. $sGroupByLabel = MetaModel::GetLabel($this->m_oFilter->GetClass(), $aExtraParams['group_by']);
  1008. }
  1009. $aGroupBy = array();
  1010. $aGroupBy['grouped_by_1'] = $oGroupByExp;
  1011. $sSql = MetaModel::MakeGroupByQuery($this->m_oFilter, $aQueryParams, $aGroupBy, true);
  1012. $aRes = CMDBSource::QueryToArray($sSql);
  1013. $aGroupBy = array();
  1014. $aLabels = array();
  1015. $iTotalCount = 0;
  1016. foreach ($aRes as $iRow => $aRow)
  1017. {
  1018. $sValue = $aRow['grouped_by_1'];
  1019. $sHtmlValue = $oGroupByExp->MakeValueLabel($this->m_oFilter, $sValue, $sValue);
  1020. $aLabels[$iRow] = strip_tags($sHtmlValue);
  1021. $aGroupBy[$iRow] = (int) $aRow['_itop_count_'];
  1022. $iTotalCount += $aRow['_itop_count_'];
  1023. }
  1024. $aData = array();
  1025. foreach($aGroupBy as $iRow => $iCount)
  1026. {
  1027. $sFlashLabel = html_entity_decode($aLabels[$iRow], ENT_QUOTES, 'UTF-8');
  1028. $PieValue = new pie_value($iCount, $sFlashLabel); //@@ BUG: not passed via ajax !!!
  1029. $PieValue->on_click("ofc_drill_down_$sId");
  1030. $aData[] = $PieValue;
  1031. }
  1032. $oChartElement->set_values( $aData );
  1033. $oChart->x_axis = null;
  1034. }
  1035. }
  1036. if (isset($aExtraParams['chart_title']))
  1037. {
  1038. // The title has been given in an url, and urlencoded...
  1039. // and urlencode transforms utf-8 into something similar to ISO-8859-1
  1040. // Example: é (C3A9 becomes %E9)
  1041. // As a consequence, json_encode (called within open-flash-chart.php)
  1042. // was returning 'null' and the graph was not displayed at all
  1043. // To make sure that the graph is displayed AND to get a correct title
  1044. // (at least for european characters) let's transform back into utf-8 !
  1045. $sTitle = iconv("ISO-8859-1", "UTF-8//IGNORE", $aExtraParams['chart_title']);
  1046. // If the title is a dictionnary entry, fetch it
  1047. $sTitle = Dict::S($sTitle);
  1048. $oTitle = new title($sTitle);
  1049. $oChart->set_title( $oTitle );
  1050. $oTitle->set_style("{font-size: 16px; font-family: Tahoma; font-weight: bold; text-align: center;}");
  1051. }
  1052. $oChart->set_bg_colour('#FFFFFF');
  1053. $oChart->add_element( $oChartElement );
  1054. $sHtml = $oChart->toPrettyString();
  1055. break;
  1056. default:
  1057. // Unsupported style, do nothing.
  1058. $sHtml .= Dict::format('UI:Error:UnsupportedStyleOfBlock', $this->m_sStyle);
  1059. }
  1060. return $sHtml;
  1061. }
  1062. /**
  1063. * Add a condition (restriction) to the current DBObjectSearch on which the display block is based
  1064. * taking into account the hierarchical keys for which the condition is based on the 'below' operator
  1065. */
  1066. protected function AddCondition($sFilterCode, $condition, $sOpCode = null)
  1067. {
  1068. // Workaround to an issue revealed whenever a condition on org_id is applied twice (with a hierarchy of organizations)
  1069. // Moreover, it keeps the query as simple as possible
  1070. if (isset($this->m_aConditions[$sFilterCode]) && $condition == $this->m_aConditions[$sFilterCode])
  1071. {
  1072. // Skip
  1073. return;
  1074. }
  1075. $this->m_aConditions[$sFilterCode] = $condition;
  1076. $sClass = $this->m_oFilter->GetClass();
  1077. $bConditionAdded = false;
  1078. // If the condition is an external key with a class having a hierarchy, use a "below" criteria
  1079. if (MetaModel::IsValidAttCode($sClass, $sFilterCode))
  1080. {
  1081. $oAttDef = MetaModel::GetAttributeDef($sClass, $sFilterCode);
  1082. if ($oAttDef->IsExternalKey())
  1083. {
  1084. $sHierarchicalKeyCode = MetaModel::IsHierarchicalClass($oAttDef->GetTargetClass());
  1085. if ($sHierarchicalKeyCode !== false)
  1086. {
  1087. $oFilter = new DBObjectSearch($oAttDef->GetTargetClass());
  1088. if (($sOpCode == 'IN') && is_array($condition))
  1089. {
  1090. $oFilter->AddConditionExpression(self::GetConditionIN($oFilter, 'id', $condition));
  1091. }
  1092. else
  1093. {
  1094. $oFilter->AddCondition('id', $condition);
  1095. }
  1096. $oHKFilter = new DBObjectSearch($oAttDef->GetTargetClass());
  1097. $oHKFilter->AddCondition_PointingTo($oFilter, $sHierarchicalKeyCode, TREE_OPERATOR_BELOW); // Use the 'below' operator by default
  1098. $this->m_oFilter->AddCondition_PointingTo($oHKFilter, $sFilterCode);
  1099. $bConditionAdded = true;
  1100. }
  1101. else if (($sOpCode == 'IN') && is_array($condition))
  1102. {
  1103. $this->m_oFilter->AddConditionExpression(self::GetConditionIN($this->m_oFilter, $sFilterCode, $condition));
  1104. $bConditionAdded = true;
  1105. }
  1106. }
  1107. else if (($sOpCode == 'IN') && is_array($condition))
  1108. {
  1109. $this->m_oFilter->AddConditionExpression(self::GetConditionIN($this->m_oFilter, $sFilterCode, $condition));
  1110. $bConditionAdded = true;
  1111. }
  1112. }
  1113. // In all other cases, just add the condition directly
  1114. if (!$bConditionAdded)
  1115. {
  1116. $this->m_oFilter->AddCondition($sFilterCode, $condition); // Use the default 'loose' operator
  1117. }
  1118. }
  1119. static protected function GetConditionIN($oFilter, $sFilterCode, $condition)
  1120. {
  1121. $oField = new FieldExpression($sFilterCode, $oFilter->GetClassAlias());
  1122. $sListExpr = '('.implode(', ', CMDBSource::Quote($condition)).')';
  1123. $sOQLCondition = $oField->Render()." IN $sListExpr";
  1124. $oNewCondition = Expression::FromOQL($sOQLCondition);
  1125. return $oNewCondition;
  1126. }
  1127. }
  1128. /**
  1129. * Helper class to manage 'blocks' of HTML pieces that are parts of a page and contain some list of cmdb objects
  1130. *
  1131. * Each block is actually rendered as a <div></div> tag that can be rendered synchronously
  1132. * or as a piece of Javascript/JQuery/Ajax that will get its content from another page (ajax.render.php).
  1133. * The list of cmdbObjects to be displayed into the block is defined by a filter
  1134. * Right now the type of display is either: list, count or details
  1135. * - list produces a table listing the objects
  1136. * - count produces a paragraphs with a sentence saying 'cont' objects found
  1137. * - details display (as table) the details of each object found (best if only one)
  1138. */
  1139. class HistoryBlock extends DisplayBlock
  1140. {
  1141. protected $iLimitCount;
  1142. protected $iLimitStart;
  1143. public function __construct(DBObjectSearch $oFilter, $sStyle = 'list', $bAsynchronous = false, $aParams = array(), $oSet = null)
  1144. {
  1145. parent::__construct($oFilter, $sStyle, $bAsynchronous, $aParams, $oSet);
  1146. $this->iLimitStart = 0;
  1147. $this->iLimitCount = 0;
  1148. }
  1149. public function SetLimit($iCount, $iStart = 0)
  1150. {
  1151. $this->iLimitStart = $iStart;
  1152. $this->iLimitCount = $iCount;
  1153. }
  1154. public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId)
  1155. {
  1156. $sHtml = '';
  1157. $bTruncated = false;
  1158. $oSet = new CMDBObjectSet($this->m_oFilter, array('date'=>false));
  1159. if (($this->iLimitStart > 0) || ($this->iLimitCount > 0))
  1160. {
  1161. $oSet->SetLimit($this->iLimitCount, $this->iLimitStart);
  1162. if (($this->iLimitCount - $this->iLimitStart) < $oSet->Count())
  1163. {
  1164. $bTruncated = true;
  1165. }
  1166. }
  1167. $sHtml .= "<!-- filter: ".($this->m_oFilter->ToOQL())."-->\n";
  1168. switch($this->m_sStyle)
  1169. {
  1170. case 'toggle':
  1171. // First the latest change that the user is allowed to see
  1172. do
  1173. {
  1174. $oLatestChangeOp = $oSet->Fetch();
  1175. }
  1176. while(is_object($oLatestChangeOp) && ($oLatestChangeOp->GetDescription() == ''));
  1177. if (is_object($oLatestChangeOp))
  1178. {
  1179. // There is one change in the list... only when the object has been created !
  1180. $sDate = $oLatestChangeOp->GetAsHTML('date');
  1181. $oChange = MetaModel::GetObject('CMDBChange', $oLatestChangeOp->Get('change'));
  1182. $sUserInfo = $oChange->GetAsHTML('userinfo');
  1183. $sHtml .= $oPage->GetStartCollapsibleSection(Dict::Format('UI:History:LastModified_On_By', $sDate, $sUserInfo));
  1184. $sHtml .= $this->GetHistoryTable($oPage, $oSet);
  1185. $sHtml .= $oPage->GetEndCollapsibleSection();
  1186. }
  1187. break;
  1188. case 'table':
  1189. default:
  1190. if ($bTruncated)
  1191. {
  1192. $sFilter = $this->m_oFilter->serialize();
  1193. $sHtml .= '<div id="history_container"><p>';
  1194. $sHtml .= Dict::Format('UI:TruncatedResults', $this->iLimitCount, $oSet->Count());
  1195. $sHtml .= ' ';
  1196. $sHtml .= '<a href="#" onclick="DisplayHistory(\'#history_container\', \''.$sFilter.'\', 0, 0); return false;">'.Dict::S('UI:DisplayAll').'</a>';
  1197. $sHtml .= $this->GetHistoryTable($oPage, $oSet);
  1198. $sHtml .= '</p></div>';
  1199. $oPage->add_ready_script("$('#{$sId} table.listResults tr:last td').addClass('truncated');");
  1200. }
  1201. else
  1202. {
  1203. $sHtml .= $this->GetHistoryTable($oPage, $oSet);
  1204. }
  1205. }
  1206. return $sHtml;
  1207. }
  1208. protected function GetHistoryTable(WebPage $oPage, DBObjectSet $oSet)
  1209. {
  1210. $sHtml = '';
  1211. // First the latest change that the user is allowed to see
  1212. $oSet->Rewind(); // Reset the pointer to the beginning of the set
  1213. $aChanges = array();
  1214. while($oChangeOp = $oSet->Fetch())
  1215. {
  1216. $sChangeDescription = $oChangeOp->GetDescription();
  1217. if ($sChangeDescription != '')
  1218. {
  1219. // The change is visible for the current user
  1220. $changeId = $oChangeOp->Get('change');
  1221. $aChanges[$changeId]['date'] = $oChangeOp->Get('date');
  1222. $aChanges[$changeId]['userinfo'] = $oChangeOp->Get('userinfo');
  1223. if (!isset($aChanges[$changeId]['log']))
  1224. {
  1225. $aChanges[$changeId]['log'] = array();
  1226. }
  1227. $aChanges[$changeId]['log'][] = $sChangeDescription;
  1228. }
  1229. }
  1230. $aAttribs = array('date' => array('label' => Dict::S('UI:History:Date'), 'description' => Dict::S('UI:History:Date+')),
  1231. 'userinfo' => array('label' => Dict::S('UI:History:User'), 'description' => Dict::S('UI:History:User+')),
  1232. 'log' => array('label' => Dict::S('UI:History:Changes'), 'description' => Dict::S('UI:History:Changes+')),
  1233. );
  1234. $aValues = array();
  1235. foreach($aChanges as $aChange)
  1236. {
  1237. $aValues[] = array('date' => $aChange['date'], 'userinfo' => htmlentities($aChange['userinfo'], ENT_QUOTES, 'UTF-8'), 'log' => "<ul><li>".implode('</li><li>', $aChange['log'])."</li></ul>");
  1238. }
  1239. $sHtml .= $oPage->GetTable($aAttribs, $aValues);
  1240. return $sHtml;
  1241. }
  1242. }
  1243. /**
  1244. * Displays the 'Actions' menu for a given (list of) object(s)
  1245. * The 'style' of the list (see constructor of DisplayBlock) can be either 'list' or 'details'
  1246. * For backward compatibility 'popup' is equivalent to 'list'...
  1247. */
  1248. class MenuBlock extends DisplayBlock
  1249. {
  1250. /**
  1251. * Renders the "Actions" popup menu for the given set of objects
  1252. *
  1253. * Note that the menu links containing (or ending) with a hash (#) will have their fragment
  1254. * part (whatever is after the hash) dynamically replaced (by javascript) when the menu is
  1255. * displayed, to correspond to the current hash/fragment in the page. This allows modifying
  1256. * an object in with the same tab active by default as the tab that was active when selecting
  1257. * the "Modify..." action.
  1258. */
  1259. public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId)
  1260. {
  1261. if ($this->m_sStyle == 'popup') // popup is a synonym of 'list' for backward compatibility
  1262. {
  1263. $this->m_sStyle = 'list';
  1264. }
  1265. $sHtml = '';
  1266. $oAppContext = new ApplicationContext();
  1267. $sContext = $oAppContext->GetForLink();
  1268. if (!empty($sContext))
  1269. {
  1270. $sContext = '&'.$sContext;
  1271. }
  1272. $sClass = $this->m_oFilter->GetClass();
  1273. $oReflectionClass = new ReflectionClass($sClass);
  1274. $oSet = new CMDBObjectSet($this->m_oFilter);
  1275. $sFilter = $this->m_oFilter->serialize();
  1276. $sFilterDesc = $this->m_oFilter->ToOql(true);
  1277. $aActions = array();
  1278. $sUIPage = cmdbAbstractObject::ComputeStandardUIPage($sClass);
  1279. $sRootUrl = utils::GetAbsoluteUrlAppRoot();
  1280. // 1:n links, populate the target object as a default value when creating a new linked object
  1281. if (isset($aExtraParams['target_attr']))
  1282. {
  1283. $aExtraParams['default'][$aExtraParams['target_attr']] = $aExtraParams['object_id'];
  1284. }
  1285. $sDefault = '';
  1286. if (!empty($aExtraParams['default']))
  1287. {
  1288. foreach($aExtraParams['default'] as $sKey => $sValue)
  1289. {
  1290. $sDefault.= "&default[$sKey]=$sValue";
  1291. }
  1292. }
  1293. $bIsCreationAllowed = (UserRights::IsActionAllowed($sClass, UR_ACTION_CREATE) == UR_ALLOWED_YES) && ($oReflectionClass->IsSubclassOf('cmdbAbstractObject'));
  1294. switch($oSet->Count())
  1295. {
  1296. case 0:
  1297. // No object in the set, the only possible action is "new"
  1298. if ($bIsCreationAllowed) { $aActions['UI:Menu:New'] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=new&class=$sClass{$sContext}{$sDefault}"); }
  1299. break;
  1300. case 1:
  1301. $oObj = $oSet->Fetch();
  1302. $id = $oObj->GetKey();
  1303. $bIsModifyAllowed = (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet) == UR_ALLOWED_YES) && ($oReflectionClass->IsSubclassOf('cmdbAbstractObject'));
  1304. $bIsDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, $oSet);
  1305. // Just one object in the set, possible actions are "new / clone / modify and delete"
  1306. if (!isset($aExtraParams['link_attr']))
  1307. {
  1308. if ($bIsModifyAllowed) { $aActions['UI:Menu:Modify'] = array ('label' => Dict::S('UI:Menu:Modify'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=modify&class=$sClass&id=$id{$sContext}#"); }
  1309. if ($bIsCreationAllowed) { $aActions['UI:Menu:New'] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=new&class=$sClass{$sContext}{$sDefault}"); }
  1310. if ($bIsDeleteAllowed) { $aActions['UI:Menu:Delete'] = array ('label' => Dict::S('UI:Menu:Delete'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=delete&class=$sClass&id=$id{$sContext}"); }
  1311. // Transitions / Stimuli
  1312. $aTransitions = $oObj->EnumTransitions();
  1313. if (count($aTransitions))
  1314. {
  1315. $this->AddMenuSeparator($aActions);
  1316. $aStimuli = Metamodel::EnumStimuli(get_class($oObj));
  1317. foreach($aTransitions as $sStimulusCode => $aTransitionDef)
  1318. {
  1319. $iActionAllowed = (get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction') ? UserRights::IsStimulusAllowed($sClass, $sStimulusCode, $oSet) : UR_ALLOWED_NO;
  1320. switch($iActionAllowed)
  1321. {
  1322. case UR_ALLOWED_YES:
  1323. $aActions[$sStimulusCode] = array('label' => $aStimuli[$sStimulusCode]->GetLabel(), 'url' => "{$sRootUrl}pages/UI.php?operation=stimulus&stimulus=$sStimulusCode&class=$sClass&id=$id{$sContext}");
  1324. break;
  1325. default:
  1326. // Do nothing
  1327. }
  1328. }
  1329. }
  1330. // Relations...
  1331. $aRelations = MetaModel::EnumRelations($sClass);
  1332. if (count($aRelations))
  1333. {
  1334. $this->AddMenuSeparator($aActions);
  1335. foreach($aRelations as $sRelationCode)
  1336. {
  1337. $aActions[$sRelationCode] = array ('label' => MetaModel::GetRelationVerbUp($sRelationCode), 'url' => "{$sRootUrl}pages/$sUIPage?operation=swf_navigator&relation=$sRelationCode&class=$sClass&id=$id{$sContext}");
  1338. }
  1339. }
  1340. /*
  1341. $this->AddMenuSeparator($aActions);
  1342. // Static menus: Email this page & CSV Export
  1343. $sUrl = ApplicationContext::MakeObjectUrl($sClass, $id);
  1344. $aActions['UI:Menu:EMail'] = array ('label' => Dict::S('UI:Menu:EMail'), 'url' => "mailto:?subject=".urlencode($oObj->GetRawName())."&body=".urlencode($sUrl));
  1345. $aActions['UI:Menu:CSVExport'] = array ('label' => Dict::S('UI:Menu:CSVExport'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=search&filter=".urlencode($sFilter)."&format=csv{$sContext}");
  1346. // The style tells us whether the menu is displayed on a list of one object, or on the details of the given object
  1347. if ($this->m_sStyle == 'list')
  1348. {
  1349. // Actions specific to the list
  1350. $sOQL = addslashes($sFilterDesc);
  1351. $aActions['UI:Menu:AddToDashboard'] = array ('label' => Dict::S('UI:Menu:AddToDashboard'), 'url' => "#", 'onclick' => "return DashletCreationDlg('$sOQL')");
  1352. }
  1353. */
  1354. }
  1355. $this->AddMenuSeparator($aActions);
  1356. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  1357. {
  1358. $oSet->Rewind();
  1359. foreach($oExtensionInstance->EnumAllowedActions($oSet) as $sLabel => $sUrl)
  1360. {
  1361. $aActions[$sLabel] = array ('label' => $sLabel, 'url' => $sUrl);
  1362. }
  1363. }
  1364. break;
  1365. default:
  1366. // Check rights
  1367. // New / Modify
  1368. $bIsModifyAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet) && ($oReflectionClass->IsSubclassOf('cmdbAbstractObject'));
  1369. $bIsBulkModifyAllowed = (!MetaModel::IsAbstract($sClass)) && UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_MODIFY, $oSet) && ($oReflectionClass->IsSubclassOf('cmdbAbstractObject'));
  1370. $bIsBulkDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_DELETE, $oSet);
  1371. if (isset($aExtraParams['link_attr']))
  1372. {
  1373. $id = $aExtraParams['object_id'];
  1374. $sTargetAttr = $aExtraParams['target_attr'];
  1375. $oAttDef = MetaModel::GetAttributeDef($sClass, $sTargetAttr);
  1376. $sTargetClass = $oAttDef->GetTargetClass();
  1377. $bIsDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, $oSet);
  1378. 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}"); }
  1379. 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}"); }
  1380. //if ($bIsBulkDeleteAllowed) { $aActions[] = array ('label' => 'Remove All...', 'url' => "#"); }
  1381. }
  1382. else
  1383. {
  1384. // many objects in the set, possible actions are: new / modify all / delete all
  1385. if ($bIsCreationAllowed) { $aActions['UI:Menu:New'] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=new&class=$sClass{$sContext}{$sDefault}"); }
  1386. 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}"); }
  1387. 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}"); }
  1388. // Stimuli
  1389. $aStates = MetaModel::EnumStates($sClass);
  1390. // Do not perform time consuming computations if there are too may objects in the list
  1391. $iLimit = MetaModel::GetConfig()->Get('complex_actions_limit');
  1392. if ((count($aStates) > 0) && (($iLimit == 0) || ($oSet->Count() < $iLimit)))
  1393. {
  1394. // Life cycle actions may be available... if all objects are in the same state
  1395. //
  1396. // Group by <state>
  1397. $oGroupByExp = new FieldExpression(MetaModel::GetStateAttributeCode($sClass), $this->m_oFilter->GetClassAlias());
  1398. $aGroupBy = array('__state__' => $oGroupByExp);
  1399. $aQueryParams = array();
  1400. if (isset($aExtraParams['query_params']))
  1401. {
  1402. $aQueryParams = $aExtraParams['query_params'];
  1403. }
  1404. $sSql = MetaModel::MakeGroupByQuery($this->m_oFilter, $aQueryParams, $aGroupBy);
  1405. $aRes = CMDBSource::QueryToArray($sSql);
  1406. if (count($aRes) == 1)
  1407. {
  1408. // All objects are in the same state...
  1409. $sState = $aRes[0]['__state__'];
  1410. $aTransitions = Metamodel::EnumTransitions($sClass, $sState);
  1411. if (count($aTransitions))
  1412. {
  1413. $this->AddMenuSeparator($aActions);
  1414. $aStimuli = Metamodel::EnumStimuli($sClass);
  1415. foreach($aTransitions as $sStimulusCode => $aTransitionDef)
  1416. {
  1417. $oSet->Rewind();
  1418. // As soon as the user rights implementation will browse the object set,
  1419. // then we might consider using OptimizeColumnLoad() here
  1420. $iActionAllowed = UserRights::IsStimulusAllowed($sClass, $sStimulusCode, $oSet);
  1421. $iActionAllowed = (get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction') ? $iActionAllowed : UR_ALLOWED_NO;
  1422. switch($iActionAllowed)
  1423. {
  1424. case UR_ALLOWED_YES:
  1425. case UR_ALLOWED_DEPENDS:
  1426. $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}");
  1427. break;
  1428. default:
  1429. // Do nothing
  1430. }
  1431. }
  1432. }
  1433. }
  1434. }
  1435. /*
  1436. $this->AddMenuSeparator($aActions);
  1437. $sUrl = utils::GetAbsoluteUrlAppRoot();
  1438. $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}"));
  1439. $aActions['UI:Menu:CSVExport'] = array ('label' => Dict::S('UI:Menu:CSVExport'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=search&filter=".urlencode($sFilter)."&format=csv{$sContext}");
  1440. $sOQL = addslashes($sFilterDesc);
  1441. $aActions['UI:Menu:AddToDashboard'] = array ('label' => Dict::S('UI:Menu:AddToDashboard'), 'url' => "#", 'onclick' => "return DashletCreationDlg('$sOQL')");
  1442. */
  1443. }
  1444. }
  1445. $this->AddMenuSeparator($aActions);
  1446. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  1447. {
  1448. $oSet->Rewind();
  1449. foreach($oExtensionInstance->EnumAllowedActions($oSet) as $sLabel => $data)
  1450. {
  1451. if (is_array($data))
  1452. {
  1453. // New plugins can provide javascript handlers via the 'onclick' property
  1454. //TODO: enable extension of different menus by checking the 'target' property ??
  1455. $aActions[$sLabel] = array ('label' => $sLabel, 'url' => isset($data['url']) ? $data['url'] : '#', 'onclick' => isset($data['onclick']) ? $data['onclick'] : '');
  1456. }
  1457. else
  1458. {
  1459. // Backward compatibility with old plugins
  1460. $aActions[$sLabel] = array ('label' => $sLabel, 'url' => $data);
  1461. }
  1462. }
  1463. }
  1464. // New extensions based on iPopupMenuItem interface
  1465. switch($this->m_sStyle)
  1466. {
  1467. case 'list':
  1468. $oSet->Rewind();
  1469. $param = $oSet;
  1470. $iMenuId = iPopupMenuExtension::MENU_OBJLIST_ACTIONS;
  1471. break;
  1472. case 'details':
  1473. $oSet->Rewind();
  1474. $param = $oSet->Fetch();
  1475. $iMenuId = iPopupMenuExtension::MENU_OBJDETAILS_ACTIONS;
  1476. break;
  1477. }
  1478. utils::GetPopupMenuItems($oPage, $iMenuId, $param, $aActions);
  1479. $aFavoriteActions = array();
  1480. $aCallSpec = array($sClass, 'GetShortcutActions');
  1481. if (is_callable($aCallSpec))
  1482. {
  1483. $aShortcutActions = call_user_func($aCallSpec, $sClass);
  1484. foreach ($aActions as $key => $aAction)
  1485. {
  1486. if (in_array($key, $aShortcutActions))
  1487. {
  1488. $aFavoriteActions[] = $aAction;
  1489. unset($aActions[$key]);
  1490. }
  1491. }
  1492. }
  1493. else
  1494. {
  1495. $aShortcutActions = array();
  1496. }
  1497. if (count($aFavoriteActions) > 0)
  1498. {
  1499. $sHtml .= "<div class=\"itop_popup actions_menu\"><ul>\n<li>".Dict::S('UI:Menu:OtherActions')."\n<ul>\n";
  1500. }
  1501. else
  1502. {
  1503. $sHtml .= "<div class=\"itop_popup actions_menu\"><ul>\n<li>".Dict::S('UI:Menu:Actions')."\n<ul>\n";
  1504. }
  1505. $sHtml .= $oPage->RenderPopupMenuItems($aActions, $aFavoriteActions);
  1506. static $bPopupScript = false;
  1507. if (!$bPopupScript)
  1508. {
  1509. // Output this once per page...
  1510. $oPage->add_ready_script("$(\"div.itop_popup>ul\").popupmenu();\n");
  1511. $bPopupScript = true;
  1512. }
  1513. return $sHtml;
  1514. }
  1515. /**
  1516. * Appends a menu separator to the current list of actions
  1517. * @param Hash $aActions The current actions list
  1518. * @return void
  1519. */
  1520. protected function AddMenuSeparator(&$aActions)
  1521. {
  1522. $sSeparator = '<hr class="menu-separator"/>';
  1523. if (count($aActions) > 0) // Make sure that the separator is not the first item in the menu
  1524. {
  1525. $aKeys = array_keys($aActions);
  1526. $sLastKey = array_pop($aKeys);
  1527. if ($aActions[$sLastKey]['label'] != $sSeparator) // Make sure there are no 2 consecutive separators
  1528. {
  1529. $aActions['sep_'.(count($aActions)-1)] = array('label' => $sSeparator, 'url' => '');
  1530. }
  1531. }
  1532. }
  1533. }