displayblock.class.inc.php 61 KB

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