displayblock.class.inc.php 62 KB

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