displayblock.class.inc.php 66 KB

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