displayblock.class.inc.php 63 KB

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