displayblock.class.inc.php 63 KB

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