displayblock.class.inc.php 64 KB

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