displayblock.class.inc.php 64 KB

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