displayblock.class.inc.php 62 KB

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