displayblock.class.inc.php 64 KB

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