displayblock.class.inc.php 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590
  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. /*
  750. $sCSVData = cmdbAbstractObject::GetSetAsCSV($this->m_oSet, array('fields_advanced' => $bAdvancedMode));
  751. $sCharset = MetaModel::GetConfig()->Get('csv_file_default_charset');
  752. if ($sCharset == 'UTF-8')
  753. {
  754. $bLostChars = false;
  755. }
  756. else
  757. {
  758. $sConverted = @iconv('UTF-8', $sCharset, $sCSVData);
  759. $sRestored = @iconv($sCharset, 'UTF-8', $sConverted);
  760. $bLostChars = ($sRestored != $sCSVData);
  761. }
  762. if ($bLostChars)
  763. {
  764. $sCharsetNotice = "&nbsp;&nbsp;<span id=\"csv_charset_issue\">";
  765. $sCharsetNotice .= '<img src="../images/error.png" style="vertical-align:middle"/>';
  766. $sCharsetNotice .= "</span>";
  767. $sTip = "<p>".htmlentities(Dict::S('UI:CSVExport:LostChars'), ENT_QUOTES, 'UTF-8')."</p>";
  768. $sTip .= "<p>".htmlentities(Dict::Format('UI:CSVExport:LostChars+', $sCharset), ENT_QUOTES, 'UTF-8')."</p>";
  769. $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' }} } );");
  770. }
  771. else
  772. {
  773. $sCharsetNotice = '';
  774. }
  775. */
  776. $sCharsetNotice = false;
  777. $sHtml .= "<div>";
  778. $sHtml .= '<table style="width:100%" class="transparent">';
  779. $sHtml .= '<tr>';
  780. $sHtml .= '<td><a href="'.$sDownloadLink.'">'.Dict::Format('UI:Download-CSV', $sCsvFile).'</a>'.$sCharsetNotice.'</td>';
  781. $sHtml .= '<td style="text-align:right"><input type="checkbox" '.$sChecked.' onClick="window.location.href=\''.$sLinkToToggle.'\'">&nbsp;'.Dict::S('UI:CSVExport:AdvancedMode').'</td>';
  782. $sHtml .= '</tr>';
  783. $sHtml .= '</table>';
  784. if ($bAdvancedMode)
  785. {
  786. $sHtml .= "<p>";
  787. $sHtml .= htmlentities(Dict::S('UI:CSVExport:AdvancedMode+'), ENT_QUOTES, 'UTF-8');
  788. $sHtml .= "</p>";
  789. }
  790. $sHtml .= "</div>";
  791. $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";
  792. //$sHtml .= htmlentities($sCSVData, ENT_QUOTES, 'UTF-8');
  793. $sHtml .= "</textarea>\n";
  794. $oPage->add_ready_script("$.post('$sDownloadLink', {}, function(data) { $('#csv_content').html(data); $('#csv_content_loading').hide(); $('#csv_content').show();} );");
  795. break;
  796. case 'modify':
  797. if ((UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_MODIFY, $this->m_oSet) == UR_ALLOWED_YES))
  798. {
  799. while($oObj = $this->m_oSet->Fetch())
  800. {
  801. $sHtml .= $oObj->GetModifyForm($oPage);
  802. }
  803. }
  804. break;
  805. case 'search':
  806. $sStyle = (isset($aExtraParams['open']) && ($aExtraParams['open'] == 'true')) ? 'SearchDrawer' : 'SearchDrawer DrawerClosed';
  807. $sHtml .= "<div id=\"ds_$sId\" class=\"$sStyle\">\n";
  808. $oPage->add_ready_script(
  809. <<<EOF
  810. $("#dh_$sId").click( function() {
  811. $("#ds_$sId").slideToggle('normal', function() { $("#ds_$sId").parent().resize(); } );
  812. $("#dh_$sId").toggleClass('open');
  813. });
  814. EOF
  815. );
  816. $aExtraParams['currentId'] = $sId;
  817. $sHtml .= cmdbAbstractObject::GetSearchForm($oPage, $this->m_oSet, $aExtraParams);
  818. $sHtml .= "</div>\n";
  819. $sHtml .= "<div class=\"HRDrawer\"></div>\n";
  820. $sHtml .= "<div id=\"dh_$sId\" class=\"DrawerHandle\">".Dict::S('UI:SearchToggle')."</div>\n";
  821. break;
  822. case 'open_flash_chart':
  823. static $iChartCounter = 0;
  824. $oAppContext = new ApplicationContext();
  825. $sContext = $oAppContext->GetForLink();
  826. if (!empty($sContext))
  827. {
  828. $sContext = '&'.$sContext;
  829. }
  830. $sChartType = isset($aExtraParams['chart_type']) ? $aExtraParams['chart_type'] : 'pie';
  831. $sTitle = isset($aExtraParams['chart_title']) ? $aExtraParams['chart_title'] : '';
  832. $sGroupBy = isset($aExtraParams['group_by']) ? $aExtraParams['group_by'] : '';
  833. $sGroupByExpr = isset($aExtraParams['group_by_expr']) ? '&params[group_by_expr]='.$aExtraParams['group_by_expr'] : '';
  834. $sFilter = $this->m_oFilter->serialize();
  835. $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";
  836. $oPage->add_script("function ofc_resize(left, width, top, height) { /* do nothing special */ }");
  837. if (isset($aExtraParams['group_by_label']))
  838. {
  839. $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));
  840. }
  841. else
  842. {
  843. $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));
  844. }
  845. $oPage->add_ready_script("swfobject.embedSWF(\"../images/open-flash-chart.swf\", \"my_chart_$sId{$iChartCounter}\", \"100%\", \"300\",\"9.0.0\", \"expressInstall.swf\",
  846. {\"data-file\":\"".$sUrl."\"}, {wmode: 'transparent'} );\n");
  847. $iChartCounter++;
  848. if (isset($aExtraParams['group_by']))
  849. {
  850. if (isset($aExtraParams['group_by_label']))
  851. {
  852. $oGroupByExp = Expression::FromOQL($aExtraParams['group_by']);
  853. $sGroupByLabel = $aExtraParams['group_by_label'];
  854. }
  855. else
  856. {
  857. // Backward compatibility: group_by is simply a field id
  858. $sAlias = $this->m_oFilter->GetClassAlias();
  859. $oGroupByExp = new FieldExpression($aExtraParams['group_by'], $sAlias);
  860. $sGroupByLabel = MetaModel::GetLabel($this->m_oFilter->GetClass(), $aExtraParams['group_by']);
  861. }
  862. $aGroupBy = array();
  863. $aGroupBy['grouped_by_1'] = $oGroupByExp;
  864. $sSql = MetaModel::MakeGroupByQuery($this->m_oFilter, $aQueryParams, $aGroupBy, true);
  865. $aRes = CMDBSource::QueryToArray($sSql);
  866. $aGroupBy = array();
  867. $aLabels = array();
  868. $aValues = array();
  869. $iTotalCount = 0;
  870. foreach ($aRes as $iRow => $aRow)
  871. {
  872. $sValue = $aRow['grouped_by_1'];
  873. $aValues[$iRow] = $sValue;
  874. $sHtmlValue = $oGroupByExp->MakeValueLabel($this->m_oFilter, $sValue, $sValue);
  875. $aLabels[$iRow] = $sHtmlValue;
  876. $aGroupBy[$iRow] = (int) $aRow['_itop_count_'];
  877. $iTotalCount += $aRow['_itop_count_'];
  878. }
  879. $aData = array();
  880. $idx = 0;
  881. $aURLs = array();
  882. foreach($aGroupBy as $iRow => $iCount)
  883. {
  884. // Build the search for this subset
  885. $oSubsetSearch = $this->m_oFilter->DeepClone();
  886. $oCondition = new BinaryExpression($oGroupByExp, '=', new ScalarExpression($aValues[$iRow]));
  887. $oSubsetSearch->AddConditionExpression($oCondition);
  888. $aURLs[$idx] = $oSubsetSearch->serialize();
  889. $idx++;
  890. }
  891. $sURLList = '';
  892. foreach($aURLs as $index => $sURL)
  893. {
  894. $sURLList .= "\taURLs[$index] = '".utils::GetAbsoluteUrlAppRoot()."pages/UI.php?operation=search&format=html{$sContext}&filter=".urlencode($sURL)."';\n";
  895. }
  896. $oPage->add_script(
  897. <<<EOF
  898. function ofc_drill_down_{$sId}(index)
  899. {
  900. var aURLs = new Array();
  901. {$sURLList}
  902. window.location.href=aURLs[index];
  903. }
  904. EOF
  905. );
  906. }
  907. break;
  908. case 'open_flash_chart_ajax':
  909. require_once(APPROOT.'/pages/php-ofc-library/open-flash-chart.php');
  910. $sChartType = isset($aExtraParams['chart_type']) ? $aExtraParams['chart_type'] : 'pie';
  911. $sId = utils::ReadParam('id', '');
  912. $oChart = new open_flash_chart();
  913. switch($sChartType)
  914. {
  915. case 'bars':
  916. $oChartElement = new bar_glass();
  917. if (isset($aExtraParams['group_by']))
  918. {
  919. if (isset($aExtraParams['group_by_label']))
  920. {
  921. $oGroupByExp = Expression::FromOQL($aExtraParams['group_by']);
  922. $sGroupByLabel = $aExtraParams['group_by_label'];
  923. }
  924. else
  925. {
  926. // Backward compatibility: group_by is simply a field id
  927. $sAlias = $this->m_oFilter->GetClassAlias();
  928. $oGroupByExp = new FieldExpression($aExtraParams['group_by'], $sAlias);
  929. $sGroupByLabel = MetaModel::GetLabel($this->m_oFilter->GetClass(), $aExtraParams['group_by']);
  930. }
  931. $aGroupBy = array();
  932. $aGroupBy['grouped_by_1'] = $oGroupByExp;
  933. $sSql = MetaModel::MakeGroupByQuery($this->m_oFilter, $aQueryParams, $aGroupBy, true);
  934. $aRes = CMDBSource::QueryToArray($sSql);
  935. $aGroupBy = array();
  936. $aLabels = array();
  937. $iTotalCount = 0;
  938. foreach ($aRes as $iRow => $aRow)
  939. {
  940. $sValue = $aRow['grouped_by_1'];
  941. $sHtmlValue = $oGroupByExp->MakeValueLabel($this->m_oFilter, $sValue, $sValue);
  942. $aLabels[$iRow] = strip_tags($sHtmlValue);
  943. $aGroupBy[$iRow] = (int) $aRow['_itop_count_'];
  944. $iTotalCount += $aRow['_itop_count_'];
  945. }
  946. $aData = array();
  947. $aChartLabels = array();
  948. $maxValue = 0;
  949. foreach($aGroupBy as $iRow => $iCount)
  950. {
  951. $oBarValue = new bar_value($iCount);
  952. $oBarValue->on_click("ofc_drill_down_$sId");
  953. $aData[] = $oBarValue;
  954. if ($iCount > $maxValue) $maxValue = $iCount;
  955. $aChartLabels[] = html_entity_decode($aLabels[$iRow], ENT_QUOTES, 'UTF-8');
  956. }
  957. $oYAxis = new y_axis();
  958. $aMagicValues = array(1,2,5,10);
  959. $iMultiplier = 1;
  960. $index = 0;
  961. $iTop = $aMagicValues[$index % count($aMagicValues)]*$iMultiplier;
  962. while($maxValue > $iTop)
  963. {
  964. $index++;
  965. $iTop = $aMagicValues[$index % count($aMagicValues)]*$iMultiplier;
  966. if (($index % count($aMagicValues)) == 0)
  967. {
  968. $iMultiplier = $iMultiplier * 10;
  969. }
  970. }
  971. //echo "oYAxis->set_range(0, $iTop, $iMultiplier);\n";
  972. $oYAxis->set_range(0, $iTop, $iMultiplier);
  973. $oChart->set_y_axis( $oYAxis );
  974. $oChartElement->set_values( $aData );
  975. $oXAxis = new x_axis();
  976. $oXLabels = new x_axis_labels();
  977. // set them vertical
  978. $oXLabels->set_vertical();
  979. // set the label text
  980. $oXLabels->set_labels($aChartLabels);
  981. // Add the X Axis Labels to the X Axis
  982. $oXAxis->set_labels( $oXLabels );
  983. $oChart->set_x_axis( $oXAxis );
  984. }
  985. break;
  986. case 'pie':
  987. default:
  988. $oChartElement = new pie();
  989. $oChartElement->set_start_angle( 35 );
  990. $oChartElement->set_animate( true );
  991. $oChartElement->set_tooltip( '#label# - #val# (#percent#)' );
  992. $oChartElement->set_colours( array('#FF8A00', '#909980', '#2C2B33', '#CCC08D', '#596664') );
  993. if (isset($aExtraParams['group_by']))
  994. {
  995. if (isset($aExtraParams['group_by_label']))
  996. {
  997. $oGroupByExp = Expression::FromOQL($aExtraParams['group_by']);
  998. $sGroupByLabel = $aExtraParams['group_by_label'];
  999. }
  1000. else
  1001. {
  1002. // Backward compatibility: group_by is simply a field id
  1003. $sAlias = $this->m_oFilter->GetClassAlias();
  1004. $oGroupByExp = new FieldExpression($aExtraParams['group_by'], $sAlias);
  1005. $sGroupByLabel = MetaModel::GetLabel($this->m_oFilter->GetClass(), $aExtraParams['group_by']);
  1006. }
  1007. $aGroupBy = array();
  1008. $aGroupBy['grouped_by_1'] = $oGroupByExp;
  1009. $sSql = MetaModel::MakeGroupByQuery($this->m_oFilter, $aQueryParams, $aGroupBy, true);
  1010. $aRes = CMDBSource::QueryToArray($sSql);
  1011. $aGroupBy = array();
  1012. $aLabels = array();
  1013. $iTotalCount = 0;
  1014. foreach ($aRes as $iRow => $aRow)
  1015. {
  1016. $sValue = $aRow['grouped_by_1'];
  1017. $sHtmlValue = $oGroupByExp->MakeValueLabel($this->m_oFilter, $sValue, $sValue);
  1018. $aLabels[$iRow] = strip_tags($sHtmlValue);
  1019. $aGroupBy[$iRow] = (int) $aRow['_itop_count_'];
  1020. $iTotalCount += $aRow['_itop_count_'];
  1021. }
  1022. $aData = array();
  1023. foreach($aGroupBy as $iRow => $iCount)
  1024. {
  1025. $sFlashLabel = html_entity_decode($aLabels[$iRow], ENT_QUOTES, 'UTF-8');
  1026. $PieValue = new pie_value($iCount, $sFlashLabel); //@@ BUG: not passed via ajax !!!
  1027. $PieValue->on_click("ofc_drill_down_$sId");
  1028. $aData[] = $PieValue;
  1029. }
  1030. $oChartElement->set_values( $aData );
  1031. $oChart->x_axis = null;
  1032. }
  1033. }
  1034. if (isset($aExtraParams['chart_title']))
  1035. {
  1036. // The title has been given in an url, and urlencoded...
  1037. // and urlencode transforms utf-8 into something similar to ISO-8859-1
  1038. // Example: é (C3A9 becomes %E9)
  1039. // As a consequence, json_encode (called within open-flash-chart.php)
  1040. // was returning 'null' and the graph was not displayed at all
  1041. // To make sure that the graph is displayed AND to get a correct title
  1042. // (at least for european characters) let's transform back into utf-8 !
  1043. $sTitle = iconv("ISO-8859-1", "UTF-8//IGNORE", $aExtraParams['chart_title']);
  1044. // If the title is a dictionnary entry, fetch it
  1045. $sTitle = Dict::S($sTitle);
  1046. $oTitle = new title($sTitle);
  1047. $oChart->set_title( $oTitle );
  1048. $oTitle->set_style("{font-size: 16px; font-family: Tahoma; font-weight: bold; text-align: center;}");
  1049. }
  1050. $oChart->set_bg_colour('#FFFFFF');
  1051. $oChart->add_element( $oChartElement );
  1052. $sHtml = $oChart->toPrettyString();
  1053. break;
  1054. default:
  1055. // Unsupported style, do nothing.
  1056. $sHtml .= Dict::format('UI:Error:UnsupportedStyleOfBlock', $this->m_sStyle);
  1057. }
  1058. return $sHtml;
  1059. }
  1060. /**
  1061. * Add a condition (restriction) to the current DBObjectSearch on which the display block is based
  1062. * taking into account the hierarchical keys for which the condition is based on the 'below' operator
  1063. */
  1064. protected function AddCondition($sFilterCode, $condition, $sOpCode = null)
  1065. {
  1066. // Workaround to an issue revealed whenever a condition on org_id is applied twice (with a hierarchy of organizations)
  1067. // Moreover, it keeps the query as simple as possible
  1068. if (isset($this->m_aConditions[$sFilterCode]) && $condition == $this->m_aConditions[$sFilterCode])
  1069. {
  1070. // Skip
  1071. return;
  1072. }
  1073. $this->m_aConditions[$sFilterCode] = $condition;
  1074. $sClass = $this->m_oFilter->GetClass();
  1075. $bConditionAdded = false;
  1076. // If the condition is an external key with a class having a hierarchy, use a "below" criteria
  1077. if (MetaModel::IsValidAttCode($sClass, $sFilterCode))
  1078. {
  1079. $oAttDef = MetaModel::GetAttributeDef($sClass, $sFilterCode);
  1080. if ($oAttDef->IsExternalKey())
  1081. {
  1082. $sHierarchicalKeyCode = MetaModel::IsHierarchicalClass($oAttDef->GetTargetClass());
  1083. if ($sHierarchicalKeyCode !== false)
  1084. {
  1085. $oFilter = new DBObjectSearch($oAttDef->GetTargetClass());
  1086. if (($sOpCode == 'IN') && is_array($condition))
  1087. {
  1088. $oFilter->AddConditionExpression(self::GetConditionIN($oFilter, 'id', $condition));
  1089. }
  1090. else
  1091. {
  1092. $oFilter->AddCondition('id', $condition);
  1093. }
  1094. $oHKFilter = new DBObjectSearch($oAttDef->GetTargetClass());
  1095. $oHKFilter->AddCondition_PointingTo($oFilter, $sHierarchicalKeyCode, TREE_OPERATOR_BELOW); // Use the 'below' operator by default
  1096. $this->m_oFilter->AddCondition_PointingTo($oHKFilter, $sFilterCode);
  1097. $bConditionAdded = true;
  1098. }
  1099. else if (($sOpCode == 'IN') && is_array($condition))
  1100. {
  1101. $this->m_oFilter->AddConditionExpression(self::GetConditionIN($this->m_oFilter, $sFilterCode, $condition));
  1102. $bConditionAdded = true;
  1103. }
  1104. }
  1105. else if (($sOpCode == 'IN') && is_array($condition))
  1106. {
  1107. $this->m_oFilter->AddConditionExpression(self::GetConditionIN($this->m_oFilter, $sFilterCode, $condition));
  1108. $bConditionAdded = true;
  1109. }
  1110. }
  1111. // In all other cases, just add the condition directly
  1112. if (!$bConditionAdded)
  1113. {
  1114. $this->m_oFilter->AddCondition($sFilterCode, $condition); // Use the default 'loose' operator
  1115. }
  1116. }
  1117. static protected function GetConditionIN($oFilter, $sFilterCode, $condition)
  1118. {
  1119. $oField = new FieldExpression($sFilterCode, $oFilter->GetClassAlias());
  1120. $sListExpr = '('.implode(', ', CMDBSource::Quote($condition)).')';
  1121. $sOQLCondition = $oField->Render()." IN $sListExpr";
  1122. $oNewCondition = Expression::FromOQL($sOQLCondition);
  1123. return $oNewCondition;
  1124. }
  1125. }
  1126. /**
  1127. * Helper class to manage 'blocks' of HTML pieces that are parts of a page and contain some list of cmdb objects
  1128. *
  1129. * Each block is actually rendered as a <div></div> tag that can be rendered synchronously
  1130. * or as a piece of Javascript/JQuery/Ajax that will get its content from another page (ajax.render.php).
  1131. * The list of cmdbObjects to be displayed into the block is defined by a filter
  1132. * Right now the type of display is either: list, count or details
  1133. * - list produces a table listing the objects
  1134. * - count produces a paragraphs with a sentence saying 'cont' objects found
  1135. * - details display (as table) the details of each object found (best if only one)
  1136. */
  1137. class HistoryBlock extends DisplayBlock
  1138. {
  1139. public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId)
  1140. {
  1141. $sHtml = '';
  1142. $oSet = new CMDBObjectSet($this->m_oFilter, array('date'=>false));
  1143. $sHtml .= "<!-- filter: ".($this->m_oFilter->ToOQL())."-->\n";
  1144. switch($this->m_sStyle)
  1145. {
  1146. case 'toggle':
  1147. // First the latest change that the user is allowed to see
  1148. do
  1149. {
  1150. $oLatestChangeOp = $oSet->Fetch();
  1151. }
  1152. while(is_object($oLatestChangeOp) && ($oLatestChangeOp->GetDescription() == ''));
  1153. if (is_object($oLatestChangeOp))
  1154. {
  1155. // There is one change in the list... only when the object has been created !
  1156. $sDate = $oLatestChangeOp->GetAsHTML('date');
  1157. $oChange = MetaModel::GetObject('CMDBChange', $oLatestChangeOp->Get('change'));
  1158. $sUserInfo = $oChange->GetAsHTML('userinfo');
  1159. $sHtml .= $oPage->GetStartCollapsibleSection(Dict::Format('UI:History:LastModified_On_By', $sDate, $sUserInfo));
  1160. $sHtml .= $this->GetHistoryTable($oPage, $oSet);
  1161. $sHtml .= $oPage->GetEndCollapsibleSection();
  1162. }
  1163. break;
  1164. case 'table':
  1165. default:
  1166. $sHtml .= $this->GetHistoryTable($oPage, $oSet);
  1167. }
  1168. return $sHtml;
  1169. }
  1170. protected function GetHistoryTable(WebPage $oPage, DBObjectSet $oSet)
  1171. {
  1172. $sHtml = '';
  1173. // First the latest change that the user is allowed to see
  1174. $oSet->Rewind(); // Reset the pointer to the beginning of the set
  1175. $aChanges = array();
  1176. while($oChangeOp = $oSet->Fetch())
  1177. {
  1178. $sChangeDescription = $oChangeOp->GetDescription();
  1179. if ($sChangeDescription != '')
  1180. {
  1181. // The change is visible for the current user
  1182. $changeId = $oChangeOp->Get('change');
  1183. $aChanges[$changeId]['date'] = $oChangeOp->Get('date');
  1184. $aChanges[$changeId]['userinfo'] = $oChangeOp->Get('userinfo');
  1185. if (!isset($aChanges[$changeId]['log']))
  1186. {
  1187. $aChanges[$changeId]['log'] = array();
  1188. }
  1189. $aChanges[$changeId]['log'][] = $sChangeDescription;
  1190. }
  1191. }
  1192. $aAttribs = array('date' => array('label' => Dict::S('UI:History:Date'), 'description' => Dict::S('UI:History:Date+')),
  1193. 'userinfo' => array('label' => Dict::S('UI:History:User'), 'description' => Dict::S('UI:History:User+')),
  1194. 'log' => array('label' => Dict::S('UI:History:Changes'), 'description' => Dict::S('UI:History:Changes+')),
  1195. );
  1196. $aValues = array();
  1197. foreach($aChanges as $aChange)
  1198. {
  1199. $aValues[] = array('date' => $aChange['date'], 'userinfo' => htmlentities($aChange['userinfo'], ENT_QUOTES, 'UTF-8'), 'log' => "<ul><li>".implode('</li><li>', $aChange['log'])."</li></ul>");
  1200. }
  1201. $sHtml .= $oPage->GetTable($aAttribs, $aValues);
  1202. return $sHtml;
  1203. }
  1204. }
  1205. /**
  1206. * Displays the 'Actions' menu for a given (list of) object(s)
  1207. * The 'style' of the list (see constructor of DisplayBlock) can be either 'list' or 'details'
  1208. * For backward compatibility 'popup' is equivalent to 'list'...
  1209. */
  1210. class MenuBlock extends DisplayBlock
  1211. {
  1212. /**
  1213. * Renders the "Actions" popup menu for the given set of objects
  1214. *
  1215. * Note that the menu links containing (or ending) with a hash (#) will have their fragment
  1216. * part (whatever is after the hash) dynamically replaced (by javascript) when the menu is
  1217. * displayed, to correspond to the current hash/fragment in the page. This allows modifying
  1218. * an object in with the same tab active by default as the tab that was active when selecting
  1219. * the "Modify..." action.
  1220. */
  1221. public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId)
  1222. {
  1223. if ($this->m_sStyle == 'popup') // popup is a synonym of 'list' for backward compatibility
  1224. {
  1225. $this->m_sStyle = 'list';
  1226. }
  1227. $sHtml = '';
  1228. $oAppContext = new ApplicationContext();
  1229. $sContext = $oAppContext->GetForLink();
  1230. if (!empty($sContext))
  1231. {
  1232. $sContext = '&'.$sContext;
  1233. }
  1234. $sClass = $this->m_oFilter->GetClass();
  1235. $oSet = new CMDBObjectSet($this->m_oFilter);
  1236. $sFilter = $this->m_oFilter->serialize();
  1237. $sFilterDesc = $this->m_oFilter->ToOql(true);
  1238. $aActions = array();
  1239. $sUIPage = cmdbAbstractObject::ComputeStandardUIPage($sClass);
  1240. $sRootUrl = utils::GetAbsoluteUrlAppRoot();
  1241. // 1:n links, populate the target object as a default value when creating a new linked object
  1242. if (isset($aExtraParams['target_attr']))
  1243. {
  1244. $aExtraParams['default'][$aExtraParams['target_attr']] = $aExtraParams['object_id'];
  1245. }
  1246. $sDefault = '';
  1247. if (!empty($aExtraParams['default']))
  1248. {
  1249. foreach($aExtraParams['default'] as $sKey => $sValue)
  1250. {
  1251. $sDefault.= "&default[$sKey]=$sValue";
  1252. }
  1253. }
  1254. $bIsCreationAllowed = (UserRights::IsActionAllowed($sClass, UR_ACTION_CREATE) == UR_ALLOWED_YES);
  1255. switch($oSet->Count())
  1256. {
  1257. case 0:
  1258. // No object in the set, the only possible action is "new"
  1259. if ($bIsCreationAllowed) { $aActions['UI:Menu:New'] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=new&class=$sClass{$sContext}{$sDefault}"); }
  1260. break;
  1261. case 1:
  1262. $oObj = $oSet->Fetch();
  1263. $id = $oObj->GetKey();
  1264. $bIsModifyAllowed = (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet) == UR_ALLOWED_YES);
  1265. $bIsDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, $oSet);
  1266. $bIsBulkModifyAllowed = (!MetaModel::IsAbstract($sClass)) && UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_MODIFY, $oSet);
  1267. $bIsBulkDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_DELETE, $oSet);
  1268. // Just one object in the set, possible actions are "new / clone / modify and delete"
  1269. if (!isset($aExtraParams['link_attr']))
  1270. {
  1271. if ($bIsModifyAllowed) { $aActions['UI:Menu:Modify'] = array ('label' => Dict::S('UI:Menu:Modify'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=modify&class=$sClass&id=$id{$sContext}#"); }
  1272. if ($bIsCreationAllowed) { $aActions['UI:Menu:New'] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=new&class=$sClass{$sContext}{$sDefault}"); }
  1273. if ($bIsDeleteAllowed) { $aActions['UI:Menu:Delete'] = array ('label' => Dict::S('UI:Menu:Delete'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=delete&class=$sClass&id=$id{$sContext}"); }
  1274. // Transitions / Stimuli
  1275. $aTransitions = $oObj->EnumTransitions();
  1276. if (count($aTransitions))
  1277. {
  1278. $this->AddMenuSeparator($aActions);
  1279. $aStimuli = Metamodel::EnumStimuli(get_class($oObj));
  1280. foreach($aTransitions as $sStimulusCode => $aTransitionDef)
  1281. {
  1282. $iActionAllowed = (get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction') ? UserRights::IsStimulusAllowed($sClass, $sStimulusCode, $oSet) : UR_ALLOWED_NO;
  1283. switch($iActionAllowed)
  1284. {
  1285. case UR_ALLOWED_YES:
  1286. $aActions[$sStimulusCode] = array('label' => $aStimuli[$sStimulusCode]->GetLabel(), 'url' => "{$sRootUrl}pages/UI.php?operation=stimulus&stimulus=$sStimulusCode&class=$sClass&id=$id{$sContext}");
  1287. break;
  1288. default:
  1289. // Do nothing
  1290. }
  1291. }
  1292. }
  1293. // Relations...
  1294. $aRelations = MetaModel::EnumRelations($sClass);
  1295. if (count($aRelations))
  1296. {
  1297. $this->AddMenuSeparator($aActions);
  1298. foreach($aRelations as $sRelationCode)
  1299. {
  1300. $aActions[$sRelationCode] = array ('label' => MetaModel::GetRelationVerbUp($sRelationCode), 'url' => "{$sRootUrl}pages/$sUIPage?operation=swf_navigator&relation=$sRelationCode&class=$sClass&id=$id{$sContext}");
  1301. }
  1302. }
  1303. /*
  1304. $this->AddMenuSeparator($aActions);
  1305. // Static menus: Email this page & CSV Export
  1306. $sUrl = ApplicationContext::MakeObjectUrl($sClass, $id);
  1307. $aActions['UI:Menu:EMail'] = array ('label' => Dict::S('UI:Menu:EMail'), 'url' => "mailto:?subject=".urlencode($oObj->GetRawName())."&body=".urlencode($sUrl));
  1308. $aActions['UI:Menu:CSVExport'] = array ('label' => Dict::S('UI:Menu:CSVExport'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=search&filter=".urlencode($sFilter)."&format=csv{$sContext}");
  1309. // The style tells us whether the menu is displayed on a list of one object, or on the details of the given object
  1310. if ($this->m_sStyle == 'list')
  1311. {
  1312. // Actions specific to the list
  1313. $sOQL = addslashes($sFilterDesc);
  1314. $aActions['UI:Menu:AddToDashboard'] = array ('label' => Dict::S('UI:Menu:AddToDashboard'), 'url' => "#", 'onclick' => "return DashletCreationDlg('$sOQL')");
  1315. }
  1316. */
  1317. }
  1318. $this->AddMenuSeparator($aActions);
  1319. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  1320. {
  1321. $oSet->Rewind();
  1322. foreach($oExtensionInstance->EnumAllowedActions($oSet) as $sLabel => $sUrl)
  1323. {
  1324. $aActions[$sLabel] = array ('label' => $sLabel, 'url' => $sUrl);
  1325. }
  1326. }
  1327. break;
  1328. default:
  1329. // Check rights
  1330. // New / Modify
  1331. $bIsModifyAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet);
  1332. $bIsBulkModifyAllowed = (!MetaModel::IsAbstract($sClass)) && UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_MODIFY, $oSet);
  1333. $bIsBulkDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_DELETE, $oSet);
  1334. if (isset($aExtraParams['link_attr']))
  1335. {
  1336. $id = $aExtraParams['object_id'];
  1337. $sTargetAttr = $aExtraParams['target_attr'];
  1338. $oAttDef = MetaModel::GetAttributeDef($sClass, $sTargetAttr);
  1339. $sTargetClass = $oAttDef->GetTargetClass();
  1340. $bIsDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, $oSet);
  1341. 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}"); }
  1342. 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}"); }
  1343. //if ($bIsBulkDeleteAllowed) { $aActions[] = array ('label' => 'Remove All...', 'url' => "#"); }
  1344. }
  1345. else
  1346. {
  1347. // many objects in the set, possible actions are: new / modify all / delete all
  1348. if ($bIsCreationAllowed) { $aActions['UI:Menu:New'] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=new&class=$sClass{$sContext}{$sDefault}"); }
  1349. 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}"); }
  1350. 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}"); }
  1351. // Stimuli
  1352. $aStates = MetaModel::EnumStates($sClass);
  1353. // Do not perform time consuming computations if there are too may objects in the list
  1354. $iLimit = MetaModel::GetConfig()->Get('complex_actions_limit');
  1355. if ((count($aStates) > 0) && (($iLimit == 0) || ($oSet->Count() < $iLimit)))
  1356. {
  1357. // Life cycle actions may be available... if all objects are in the same state
  1358. //
  1359. // Group by <state>
  1360. $oGroupByExp = new FieldExpression(MetaModel::GetStateAttributeCode($sClass), $this->m_oFilter->GetClassAlias());
  1361. $aGroupBy = array('__state__' => $oGroupByExp);
  1362. $aQueryParams = array();
  1363. if (isset($aExtraParams['query_params']))
  1364. {
  1365. $aQueryParams = $aExtraParams['query_params'];
  1366. }
  1367. $sSql = MetaModel::MakeGroupByQuery($this->m_oFilter, $aQueryParams, $aGroupBy);
  1368. $aRes = CMDBSource::QueryToArray($sSql);
  1369. if (count($aRes) == 1)
  1370. {
  1371. // All objects are in the same state...
  1372. $sState = $aRes[0]['__state__'];
  1373. $aTransitions = Metamodel::EnumTransitions($sClass, $sState);
  1374. if (count($aTransitions))
  1375. {
  1376. $this->AddMenuSeparator($aActions);
  1377. $aStimuli = Metamodel::EnumStimuli($sClass);
  1378. foreach($aTransitions as $sStimulusCode => $aTransitionDef)
  1379. {
  1380. $oSet->Rewind();
  1381. // As soon as the user rights implementation will browse the object set,
  1382. // then we might consider using OptimizeColumnLoad() here
  1383. $iActionAllowed = UserRights::IsStimulusAllowed($sClass, $sStimulusCode, $oSet);
  1384. $iActionAllowed = (get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction') ? $iActionAllowed : UR_ALLOWED_NO;
  1385. switch($iActionAllowed)
  1386. {
  1387. case UR_ALLOWED_YES:
  1388. case UR_ALLOWED_DEPENDS:
  1389. $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}");
  1390. break;
  1391. default:
  1392. // Do nothing
  1393. }
  1394. }
  1395. }
  1396. }
  1397. }
  1398. /*
  1399. $this->AddMenuSeparator($aActions);
  1400. $sUrl = utils::GetAbsoluteUrlAppRoot();
  1401. $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}"));
  1402. $aActions['UI:Menu:CSVExport'] = array ('label' => Dict::S('UI:Menu:CSVExport'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=search&filter=".urlencode($sFilter)."&format=csv{$sContext}");
  1403. $sOQL = addslashes($sFilterDesc);
  1404. $aActions['UI:Menu:AddToDashboard'] = array ('label' => Dict::S('UI:Menu:AddToDashboard'), 'url' => "#", 'onclick' => "return DashletCreationDlg('$sOQL')");
  1405. */
  1406. }
  1407. }
  1408. $this->AddMenuSeparator($aActions);
  1409. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  1410. {
  1411. $oSet->Rewind();
  1412. foreach($oExtensionInstance->EnumAllowedActions($oSet) as $sLabel => $data)
  1413. {
  1414. if (is_array($data))
  1415. {
  1416. // New plugins can provide javascript handlers via the 'onclick' property
  1417. //TODO: enable extension of different menus by checking the 'target' property ??
  1418. $aActions[$sLabel] = array ('label' => $sLabel, 'url' => isset($data['url']) ? $data['url'] : '#', 'onclick' => isset($data['onclick']) ? $data['onclick'] : '');
  1419. }
  1420. else
  1421. {
  1422. // Backward compatibility with old plugins
  1423. $aActions[$sLabel] = array ('label' => $sLabel, 'url' => $data);
  1424. }
  1425. }
  1426. }
  1427. // New extensions based on iPopupMenuItem interface
  1428. switch($this->m_sStyle)
  1429. {
  1430. case 'list':
  1431. $oSet->Rewind();
  1432. $param = $oSet;
  1433. $iMenuId = iPopupMenuExtension::MENU_OBJLIST_ACTIONS;
  1434. break;
  1435. case 'details':
  1436. $oSet->Rewind();
  1437. $param = $oSet->Fetch();
  1438. $iMenuId = iPopupMenuExtension::MENU_OBJDETAILS_ACTIONS;
  1439. break;
  1440. }
  1441. utils::GetPopupMenuItems($oPage, $iMenuId, $param, $aActions);
  1442. $aFavoriteActions = array();
  1443. $aCallSpec = array($sClass, 'GetShortcutActions');
  1444. if (is_callable($aCallSpec))
  1445. {
  1446. $aShortcutActions = call_user_func($aCallSpec, $sClass);
  1447. foreach ($aActions as $key => $aAction)
  1448. {
  1449. if (in_array($key, $aShortcutActions))
  1450. {
  1451. $aFavoriteActions[] = $aAction;
  1452. unset($aActions[$key]);
  1453. }
  1454. }
  1455. }
  1456. else
  1457. {
  1458. $aShortcutActions = array();
  1459. }
  1460. if (count($aFavoriteActions) > 0)
  1461. {
  1462. $sHtml .= "<div class=\"itop_popup actions_menu\"><ul>\n<li>".Dict::S('UI:Menu:OtherActions')."\n<ul>\n";
  1463. }
  1464. else
  1465. {
  1466. $sHtml .= "<div class=\"itop_popup actions_menu\"><ul>\n<li>".Dict::S('UI:Menu:Actions')."\n<ul>\n";
  1467. }
  1468. $sHtml .= $oPage->RenderPopupMenuItems($aActions, $aFavoriteActions);
  1469. static $bPopupScript = false;
  1470. if (!$bPopupScript)
  1471. {
  1472. // Output this once per page...
  1473. $oPage->add_ready_script("$(\"div.itop_popup>ul\").popupmenu();\n");
  1474. $bPopupScript = true;
  1475. }
  1476. return $sHtml;
  1477. }
  1478. /**
  1479. * Appends a menu separator to the current list of actions
  1480. * @param Hash $aActions The current actions list
  1481. * @return void
  1482. */
  1483. protected function AddMenuSeparator(&$aActions)
  1484. {
  1485. $sSeparator = '<hr class="menu-separator"/>';
  1486. if (count($aActions) > 0) // Make sure that the separator is not the first item in the menu
  1487. {
  1488. $aKeys = array_keys($aActions);
  1489. $sLastKey = array_pop($aKeys);
  1490. if ($aActions[$sLastKey]['label'] != $sSeparator) // Make sure there are no 2 consecutive separators
  1491. {
  1492. $aActions['sep_'.(count($aActions)-1)] = array('label' => $sSeparator, 'url' => '');
  1493. }
  1494. }
  1495. }
  1496. }