displayblock.class.inc.php 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * DisplayBlock and derived class
  18. *
  19. * @author Erwan Taloc <erwan.taloc@combodo.com>
  20. * @author Romain Quetiez <romain.quetiez@combodo.com>
  21. * @author Denis Flaven <denis.flaven@combodo.com>
  22. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  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_sStyle;
  46. protected $m_bAsynchronous;
  47. protected $m_aParams;
  48. protected $m_oSet;
  49. public function __construct(DBObjectSearch $oFilter, $sStyle = 'list', $bAsynchronous = false, $aParams = array(), $oSet = null)
  50. {
  51. $this->m_oFilter = $oFilter;
  52. $this->m_sStyle = $sStyle;
  53. $this->m_bAsynchronous = $bAsynchronous;
  54. $this->m_aParams = $aParams;
  55. $this->m_oSet = $oSet;
  56. }
  57. /**
  58. * Constructs a DisplayBlock object from a DBObjectSet already in memory
  59. * @param $oSet DBObjectSet
  60. * @return DisplayBlock The DisplayBlock object, or null if the creation failed
  61. */
  62. public static function FromObjectSet(DBObjectSet $oSet, $sStyle, $aParams = array())
  63. {
  64. $oDummyFilter = new DBObjectSearch($oSet->GetClass());
  65. $aKeys = array();
  66. while($oObject = $oSet->Fetch())
  67. {
  68. $aKeys[] = $oObject->GetKey();
  69. }
  70. $oSet->Rewind();
  71. $oDummyFilter->AddCondition('id', $aKeys, 'IN');
  72. $oBlock = new DisplayBlock($oDummyFilter, $sStyle, false, $aParams); // DisplayBlocks built this way are synchronous
  73. return $oBlock;
  74. }
  75. /**
  76. * Constructs a DisplayBlock object from an XML template
  77. * @param $sTemplate string The XML template
  78. * @return DisplayBlock The DisplayBlock object, or null if the template is invalid
  79. */
  80. public static function FromTemplate($sTemplate)
  81. {
  82. $iStartPos = stripos($sTemplate, '<'.self::TAG_BLOCK.' ',0);
  83. $iEndPos = stripos($sTemplate, '</'.self::TAG_BLOCK.'>', $iStartPos);
  84. $iEndTag = stripos($sTemplate, '>', $iStartPos);
  85. $aParams = array();
  86. if (($iStartPos === false) || ($iEndPos === false)) return null; // invalid template
  87. $sITopBlock = substr($sTemplate,$iStartPos, $iEndPos-$iStartPos+strlen('</'.self::TAG_BLOCK.'>'));
  88. $sITopData = substr($sTemplate, 1+$iEndTag, $iEndPos - $iEndTag - 1);
  89. $sITopTag = substr($sTemplate, $iStartPos + strlen('<'.self::TAG_BLOCK), $iEndTag - $iStartPos - strlen('<'.self::TAG_BLOCK));
  90. $aMatches = array();
  91. $sBlockClass = "DisplayBlock";
  92. $bAsynchronous = false;
  93. $sBlockType = 'list';
  94. $sEncoding = 'text/serialize';
  95. if (preg_match('/ type="(.*)"/U',$sITopTag, $aMatches))
  96. {
  97. $sBlockType = strtolower($aMatches[1]);
  98. }
  99. if (preg_match('/ asynchronous="(.*)"/U',$sITopTag, $aMatches))
  100. {
  101. $bAsynchronous = (strtolower($aMatches[1]) == 'true');
  102. }
  103. if (preg_match('/ blockclass="(.*)"/U',$sITopTag, $aMatches))
  104. {
  105. $sBlockClass = $aMatches[1];
  106. }
  107. if (preg_match('/ objectclass="(.*)"/U',$sITopTag, $aMatches))
  108. {
  109. $sObjectClass = $aMatches[1];
  110. }
  111. if (preg_match('/ encoding="(.*)"/U',$sITopTag, $aMatches))
  112. {
  113. $sEncoding = strtolower($aMatches[1]);
  114. }
  115. if (preg_match('/ link_attr="(.*)"/U',$sITopTag, $aMatches))
  116. {
  117. // The list to display is a list of links to the specified object
  118. $aParams['link_attr'] = $aMatches[1]; // Name of the Ext. Key that makes this linkage
  119. }
  120. if (preg_match('/ target_attr="(.*)"/U',$sITopTag, $aMatches))
  121. {
  122. // The list to display is a list of links to the specified object
  123. $aParams['target_attr'] = $aMatches[1]; // Name of the Ext. Key that make this linkage
  124. }
  125. if (preg_match('/ object_id="(.*)"/U',$sITopTag, $aMatches))
  126. {
  127. // The list to display is a list of links to the specified object
  128. $aParams['object_id'] = $aMatches[1]; // Id of the object to be linked to
  129. }
  130. // Parameters contains a list of extra parameters for the block
  131. // the syntax is param_name1:value1;param_name2:value2;...
  132. if (preg_match('/ parameters="(.*)"/U',$sITopTag, $aMatches))
  133. {
  134. $sParameters = $aMatches[1];
  135. $aPairs = explode(';', $sParameters);
  136. foreach($aPairs as $sPair)
  137. {
  138. if (preg_match('/(.*)\:(.*)/',$sPair, $aMatches))
  139. {
  140. $aParams[trim($aMatches[1])] = trim($aMatches[2]);
  141. }
  142. }
  143. }
  144. if (!empty($aParams['link_attr']))
  145. {
  146. // Check that all mandatory parameters are present:
  147. if(empty($aParams['object_id']))
  148. {
  149. // if 'links' mode is requested the d of the object to link to must be specified
  150. throw new ApplicationException(Dict::S('UI:Error:MandatoryTemplateParameter_object_id'));
  151. }
  152. if(empty($aParams['target_attr']))
  153. {
  154. // if 'links' mode is requested the id of the object to link to must be specified
  155. throw new ApplicationException(Dict::S('UI:Error:MandatoryTemplateParameter_target_attr'));
  156. }
  157. }
  158. switch($sEncoding)
  159. {
  160. case 'text/serialize':
  161. $oFilter = CMDBSearchFilter::unserialize($sITopData);
  162. break;
  163. case 'text/oql':
  164. $oFilter = CMDBSearchFilter::FromOQL($sITopData);
  165. break;
  166. }
  167. return new $sBlockClass($oFilter, $sBlockType, $bAsynchronous, $aParams);
  168. }
  169. public function Display(WebPage $oPage, $sId, $aExtraParams = array())
  170. {
  171. $oPage->add($this->GetDisplay($oPage, $sId, $aExtraParams));
  172. }
  173. public function GetDisplay(WebPage $oPage, $sId, $aExtraParams = array())
  174. {
  175. $sHtml = '';
  176. $aExtraParams = array_merge($aExtraParams, $this->m_aParams);
  177. $aExtraParams['currentId'] = $sId;
  178. $sExtraParams = addslashes(str_replace('"', "'", json_encode($aExtraParams))); // JSON encode, change the style of the quotes and escape them
  179. $bAutoReload = false;
  180. if (isset($aExtraParams['auto_reload']))
  181. {
  182. switch($aExtraParams['auto_reload'])
  183. {
  184. case 'fast':
  185. $bAutoReload = true;
  186. $iReloadInterval = MetaModel::GetConfig()->GetFastReloadInterval()*1000;
  187. break;
  188. case 'standard':
  189. case 'true':
  190. case true:
  191. $bAutoReload = true;
  192. $iReloadInterval = MetaModel::GetConfig()->GetStandardReloadInterval()*1000;
  193. break;
  194. default:
  195. if (is_numeric($aExtraParams['auto_reload']))
  196. {
  197. $bAutoReload = true;
  198. $iReloadInterval = $aExtraParams['auto_reload']*1000;
  199. }
  200. else
  201. {
  202. // incorrect config, ignore it
  203. $bAutoReload = false;
  204. }
  205. }
  206. }
  207. $sFilter = $this->m_oFilter->serialize(); // Used either for asynchronous or auto_reload
  208. if (!$this->m_bAsynchronous)
  209. {
  210. // render now
  211. $sHtml .= "<div id=\"$sId\" class=\"display_block\">\n";
  212. $sHtml .= $this->GetRenderContent($oPage, $aExtraParams, $sId);
  213. $sHtml .= "</div>\n";
  214. }
  215. else
  216. {
  217. // render it as an Ajax (asynchronous) call
  218. $sHtml .= "<div id=\"$sId\" class=\"display_block loading\">\n";
  219. $sHtml .= $oPage->GetP("<img src=\"../images/indicator_arrows.gif\"> ".Dict::S('UI:Loading'));
  220. $sHtml .= "</div>\n";
  221. $oPage->add_script('
  222. $.post("ajax.render.php?style='.$this->m_sStyle.'",
  223. { operation: "ajax", filter: "'.$sFilter.'", extra_params: "'.$sExtraParams.'" },
  224. function(data){
  225. $("#'.$sId.'").empty();
  226. $("#'.$sId.'").append(data);
  227. $("#'.$sId.'").removeClass("loading");
  228. }
  229. );
  230. ');
  231. }
  232. if ($bAutoReload)
  233. {
  234. $oPage->add_script('setInterval("ReloadBlock(\''.$sId.'\', \''.$this->m_sStyle.'\', \''.$sFilter.'\', \"'.$sExtraParams.'\")", '.$iReloadInterval.');');
  235. }
  236. return $sHtml;
  237. }
  238. public function RenderContent(WebPage $oPage, $aExtraParams = array())
  239. {
  240. if (empty($aExtraParams['currentId']))
  241. {
  242. $sId = $oPage->GetUniqueId(); // Works only if the page is not an Ajax one !
  243. }
  244. else
  245. {
  246. $sId = $aExtraParams['currentId'];
  247. }
  248. $oPage->add($this->GetRenderContent($oPage, $aExtraParams, $sId));
  249. }
  250. public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId)
  251. {
  252. $sHtml = '';
  253. // Add the extra params into the filter if they make sense for such a filter
  254. $bDoSearch = utils::ReadParam('dosearch', false);
  255. if ($this->m_oSet == null)
  256. {
  257. $aQueryParams = array();
  258. if (isset($aExtraParams['query_params']))
  259. {
  260. $aQueryParams = $aExtraParams['query_params'];
  261. }
  262. if ($this->m_sStyle != 'links')
  263. {
  264. $oAppContext = new ApplicationContext();
  265. $sClass = $this->m_oFilter->GetClass();
  266. $aFilterCodes = array_keys(MetaModel::GetClassFilterDefs($sClass));
  267. $aCallSpec = array($sClass, 'MapContextParam');
  268. if (is_callable($aCallSpec))
  269. {
  270. foreach($oAppContext->GetNames() as $sContextParam)
  271. {
  272. $sParamCode = call_user_func($aCallSpec, $sContextParam); //Map context parameter to the value/filter code depending on the class
  273. if (!is_null($sParamCode))
  274. {
  275. $sParamValue = $oAppContext->GetCurrentValue($sContextParam, null);
  276. if (!is_null($sParamValue))
  277. {
  278. $aExtraParams[$sParamCode] = $sParamValue;
  279. }
  280. }
  281. }
  282. }
  283. foreach($aFilterCodes as $sFilterCode)
  284. {
  285. $sExternalFilterValue = utils::ReadParam($sFilterCode, '', false, 'raw_data');
  286. $condition = null;
  287. if (isset($aExtraParams[$sFilterCode]))
  288. {
  289. $condition = $aExtraParams[$sFilterCode];
  290. }
  291. // else if ($bDoSearch && $sExternalFilterValue != "")
  292. if ($bDoSearch && $sExternalFilterValue != "")
  293. {
  294. // Search takes precedence over context params...
  295. unset($aExtraParams[$sFilterCode]);
  296. $condition = trim($sExternalFilterValue);
  297. }
  298. if (!is_null($condition))
  299. {
  300. $this->AddCondition($sFilterCode, $condition);
  301. }
  302. }
  303. }
  304. $aOrderBy = array();
  305. if (isset($aExtraParams['order_by']))
  306. {
  307. // Convert the string describing the order_by parameter into an array
  308. // The syntax is +attCode1,-attCode2
  309. // attCode1 => ascending, attCode2 => descending
  310. $aTemp = explode(',', $aExtraParams['order_by']);
  311. foreach($aTemp as $sTemp)
  312. {
  313. $aMatches = array();
  314. if (preg_match('/^([+-])?(.+)$/', $sTemp, $aMatches))
  315. {
  316. $bAscending = true;
  317. if ($aMatches[1] == '-')
  318. {
  319. $bAscending = false;
  320. }
  321. $aOrderBy[$aMatches[2]] = $bAscending;
  322. }
  323. }
  324. }
  325. $this->m_oSet = new CMDBObjectSet($this->m_oFilter, $aOrderBy, $aQueryParams);
  326. }
  327. switch($this->m_sStyle)
  328. {
  329. case 'count':
  330. if (isset($aExtraParams['group_by']))
  331. {
  332. $sGroupByField = $aExtraParams['group_by'];
  333. $aGroupBy = array();
  334. $sLabels = array();
  335. $iTotalCount = $this->m_oSet->Count();
  336. while($oObj = $this->m_oSet->Fetch())
  337. {
  338. if (isset($aExtraParams['group_by_expr']))
  339. {
  340. eval("\$sValue = ".sprintf($aExtraParams['group_by_expr'], $oObj->Get($sGroupByField)).';');
  341. }
  342. else
  343. {
  344. $sValue = $oObj->Get($sGroupByField);
  345. }
  346. $aGroupBy[$sValue] = isset($aGroupBy[$sValue]) ? $aGroupBy[$sValue]+1 : 1;
  347. $sLabels[$sValue] = $oObj->GetAsHtml($sGroupByField);
  348. }
  349. $sFilter = urlencode($this->m_oFilter->serialize());
  350. $aData = array();
  351. $oAppContext = new ApplicationContext();
  352. $sParams = $oAppContext->GetForLink();
  353. foreach($aGroupBy as $sValue => $iCount)
  354. {
  355. $aData[] = array ( 'group' => $sLabels[$sValue],
  356. 'value' => "<a href=\"".utils::GetAbsoluteUrlAppRoot()."pages/UI.php?operation=search&dosearch=1&$sParams&filter=$sFilter&$sGroupByField=".urlencode($sValue)."\">$iCount</a>"); // TO DO: add the context information
  357. }
  358. $aAttribs =array(
  359. 'group' => array('label' => MetaModel::GetLabel($this->m_oFilter->GetClass(), $sGroupByField), 'description' => ''),
  360. 'value' => array('label'=> Dict::S('UI:GroupBy:Count'), 'description' => Dict::S('UI:GroupBy:Count+'))
  361. );
  362. $sFormat = isset($aExtraParams['format']) ? $aExtraParams['format'] : 'UI:Pagination:HeaderNoSelection';
  363. $sHtml .= $oPage->GetP(Dict::Format($sFormat, $iTotalCount));
  364. $sHtml .= $oPage->GetTable($aAttribs, $aData);
  365. }
  366. else
  367. {
  368. // Simply count the number of elements in the set
  369. $iCount = $this->m_oSet->Count();
  370. $sFormat = 'UI:CountOfObjects';
  371. if (isset($aExtraParams['format']))
  372. {
  373. $sFormat = $aExtraParams['format'];
  374. }
  375. $sHtml .= $oPage->GetP(Dict::Format($sFormat, $iCount));
  376. }
  377. break;
  378. case 'join':
  379. $aDisplayAliases = isset($aExtraParams['display_aliases']) ? explode(',', $aExtraParams['display_aliases']): array();
  380. if (!isset($aExtraParams['group_by']))
  381. {
  382. $sHtml .= $oPage->GetP(Dict::S('UI:Error:MandatoryTemplateParameter_group_by'));
  383. }
  384. else
  385. {
  386. $aGroupByFields = array();
  387. $aGroupBy = explode(',', $aExtraParams['group_by']);
  388. foreach($aGroupBy as $sGroupBy)
  389. {
  390. $aMatches = array();
  391. if (preg_match('/^(.+)\.(.+)$/', $sGroupBy, $aMatches) > 0)
  392. {
  393. $aGroupByFields[] = array('alias' => $aMatches[1], 'att_code' => $aMatches[2]);
  394. }
  395. }
  396. if (count($aGroupByFields) == 0)
  397. {
  398. $sHtml .= $oPage->GetP(Dict::Format('UI:Error:InvalidGroupByFields', $aExtraParams['group_by']));
  399. }
  400. else
  401. {
  402. $aResults = array();
  403. $aCriteria = array();
  404. while($aObjects = $this->m_oSet->FetchAssoc())
  405. {
  406. $aKeys = array();
  407. foreach($aGroupByFields as $aField)
  408. {
  409. $sAlias = $aField['alias'];
  410. if (is_null($aObjects[$sAlias]))
  411. {
  412. $aKeys[$sAlias.'.'.$aField['att_code']] = '';
  413. }
  414. else
  415. {
  416. $aKeys[$sAlias.'.'.$aField['att_code']] = $aObjects[$sAlias]->Get($aField['att_code']);
  417. }
  418. }
  419. $sCategory = implode($aKeys, ' ');
  420. $aResults[$sCategory][] = $aObjects;
  421. $aCriteria[$sCategory] = $aKeys;
  422. }
  423. $sHtml .= "<table>\n";
  424. // Construct a new (parametric) query that will return the content of this block
  425. $oBlockFilter = clone $this->m_oFilter;
  426. $aExpressions = array();
  427. $index = 0;
  428. foreach($aGroupByFields as $aField)
  429. {
  430. $aExpressions[] = '`'.$aField['alias'].'`.`'.$aField['att_code'].'` = :param'.$index++;
  431. }
  432. $sExpression = implode(' AND ', $aExpressions);
  433. $oExpression = Expression::FromOQL($sExpression);
  434. $oBlockFilter->AddConditionExpression($oExpression);
  435. $aExtraParams['menu'] = false;
  436. foreach($aResults as $sCategory => $aObjects)
  437. {
  438. $sHtml .= "<tr><td><h1>$sCategory</h1></td></tr>\n";
  439. if (count($aDisplayAliases) == 1)
  440. {
  441. $aSimpleArray = array();
  442. foreach($aObjects as $aRow)
  443. {
  444. $oObj = $aRow[$aDisplayAliases[0]];
  445. if (!is_null($oObj))
  446. {
  447. $aSimpleArray[] = $oObj;
  448. }
  449. }
  450. $oSet = CMDBObjectSet::FromArray($this->m_oFilter->GetClass(), $aSimpleArray);
  451. $sHtml .= "<tr><td>".cmdbAbstractObject::GetDisplaySet($oPage, $oSet, $aExtraParams)."</td></tr>\n";
  452. }
  453. else
  454. {
  455. $index = 0;
  456. $aArgs = array();
  457. foreach($aGroupByFields as $aField)
  458. {
  459. $aArgs['param'.$index] = $aCriteria[$sCategory][$aField['alias'].'.'.$aField['att_code']];
  460. $index++;
  461. }
  462. $oSet = new CMDBObjectSet($oBlockFilter, array(), $aArgs);
  463. $sHtml .= "<tr><td>".cmdbAbstractObject::GetDisplayExtendedSet($oPage, $oSet, $aExtraParams)."</td></tr>\n";
  464. }
  465. }
  466. $sHtml .= "</table>\n";
  467. }
  468. }
  469. break;
  470. case 'list':
  471. $aClasses = $this->m_oSet->GetSelectedClasses();
  472. $aAuthorizedClasses = array();
  473. if (count($aClasses) > 1)
  474. {
  475. // Check the classes that can be read (i.e authorized) by this user...
  476. foreach($aClasses as $sAlias => $sClassName)
  477. {
  478. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $this->m_oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  479. {
  480. $aAuthorizedClasses[$sAlias] = $sClassName;
  481. }
  482. }
  483. if (count($aAuthorizedClasses) > 0)
  484. {
  485. if($this->m_oSet->Count() > 0)
  486. {
  487. $sHtml .= cmdbAbstractObject::GetDisplayExtendedSet($oPage, $this->m_oSet, $aExtraParams);
  488. }
  489. else
  490. {
  491. // Empty set
  492. $sHtml .= $oPage->GetP(Dict::S('UI:NoObjectToDisplay'));
  493. }
  494. }
  495. else
  496. {
  497. // Not authorized
  498. $sHtml .= $oPage->GetP(Dict::S('UI:NoObjectToDisplay'));
  499. }
  500. }
  501. else
  502. {
  503. // The list is made of only 1 class of objects, actions on the list are possible
  504. if ( ($this->m_oSet->Count()> 0) && (UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_READ, $this->m_oSet) == UR_ALLOWED_YES) )
  505. {
  506. $sHtml .= cmdbAbstractObject::GetDisplaySet($oPage, $this->m_oSet, $aExtraParams);
  507. }
  508. else
  509. {
  510. $sHtml .= $oPage->GetP(Dict::S('UI:NoObjectToDisplay'));
  511. $sClass = $this->m_oFilter->GetClass();
  512. $bDisplayMenu = isset($aExtraParams['menu']) ? $aExtraParams['menu'] == true : true;
  513. if ($bDisplayMenu)
  514. {
  515. if ((UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES))
  516. {
  517. $oAppContext = new ApplicationContext();
  518. $sParams = $oAppContext->GetForLink();
  519. // 1:n links, populate the target object as a default value when creating a new linked object
  520. if (isset($aExtraParams['target_attr']))
  521. {
  522. $aExtraParams['default'][$aExtraParams['target_attr']] = $aExtraParams['object_id'];
  523. }
  524. $sDefault = '';
  525. if (!empty($aExtraParams['default']))
  526. {
  527. foreach($aExtraParams['default'] as $sKey => $sValue)
  528. {
  529. $sDefault.= "&default[$sKey]=$sValue";
  530. }
  531. }
  532. $sHtml .= $oPage->GetP("<a href=\"".utils::GetAbsoluteUrlAppRoot()."pages/UI.php?operation=new&class=$sClass&$sParams{$sDefault}\">".Dict::Format('UI:ClickToCreateNew', Metamodel::GetName($sClass))."</a>\n");
  533. }
  534. }
  535. }
  536. }
  537. break;
  538. case 'links':
  539. //$bDashboardMode = isset($aExtraParams['dashboard']) ? ($aExtraParams['dashboard'] == 'true') : false;
  540. //$bSelectMode = isset($aExtraParams['select']) ? ($aExtraParams['select'] == 'true') : false;
  541. if ( ($this->m_oSet->Count()> 0) && (UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_READ, $this->m_oSet) == UR_ALLOWED_YES) )
  542. {
  543. //$sLinkage = isset($aExtraParams['linkage']) ? $aExtraParams['linkage'] : '';
  544. $sHtml .= cmdbAbstractObject::GetDisplaySet($oPage, $this->m_oSet, $aExtraParams);
  545. }
  546. else
  547. {
  548. $sClass = $this->m_oFilter->GetClass();
  549. $oAttDef = MetaModel::GetAttributeDef($sClass, $this->m_aParams['target_attr']);
  550. $sTargetClass = $oAttDef->GetTargetClass();
  551. $sHtml .= $oPage->GetP(Dict::Format('UI:NoObject_Class_ToDisplay', MetaModel::GetName($sTargetClass)));
  552. $bDisplayMenu = isset($this->m_aParams['menu']) ? $this->m_aParams['menu'] == true : true;
  553. if ($bDisplayMenu)
  554. {
  555. if ((UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES))
  556. {
  557. $oAppContext = new ApplicationContext();
  558. $sParams = $oAppContext->GetForLink();
  559. $sDefaults = '';
  560. if (isset($this->m_aParams['default']))
  561. {
  562. foreach($this->m_aParams['default'] as $sName => $sValue)
  563. {
  564. $sDefaults .= '&'.urlencode($sName).'='.urlencode($sValue);
  565. }
  566. }
  567. $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");
  568. }
  569. }
  570. }
  571. break;
  572. case 'details':
  573. while($oObj = $this->m_oSet->Fetch())
  574. {
  575. $sHtml .= $oObj->GetDetails($oPage); // Still used ???
  576. }
  577. break;
  578. case 'actions':
  579. $sClass = $this->m_oFilter->GetClass();
  580. $oAppContext = new ApplicationContext();
  581. $bContextFilter = isset($aExtraParams['context_filter']) ? isset($aExtraParams['context_filter']) != 0 : false;
  582. if ($bContextFilter)
  583. {
  584. $aFilterCodes = array_keys(MetaModel::GetClassFilterDefs($this->m_oFilter->GetClass()));
  585. foreach($oAppContext->GetNames() as $sFilterCode)
  586. {
  587. $sContextParamValue = $oAppContext->GetCurrentValue($sFilterCode, null);
  588. if (!is_null($sContextParamValue) && ! empty($sContextParamValue) && MetaModel::IsValidFilterCode($sClass, $sFilterCode))
  589. {
  590. $this->AddCondition($sFilterCode, $sContextParamValue);
  591. }
  592. }
  593. $aQueryParams = array();
  594. if (isset($aExtraParams['query_params']))
  595. {
  596. $aQueryParams = $aExtraParams['query_params'];
  597. }
  598. $this->m_oSet = new CMDBObjectSet($this->m_oFilter, array(), $aQueryParams);
  599. }
  600. $iCount = $this->m_oSet->Count();
  601. $sHyperlink = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=search&'.$oAppContext->GetForLink().'&filter='.$this->m_oFilter->serialize();
  602. $sHtml .= '<p><a class="actions" href="'.$sHyperlink.'">';
  603. $sHtml .= MetaModel::GetClassIcon($sClass, true, 'float;left;margin-right:10px;');
  604. $sHtml .= MetaModel::GetName($sClass).': '.$iCount.'</a></p>';
  605. $sParams = $oAppContext->GetForLink();
  606. $sHtml .= '<p>';
  607. if (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY))
  608. {
  609. $sHtml .= "<a href=\"".utils::GetAbsoluteUrlAppRoot()."pages/UI.php?operation=new&class={$sClass}&$sParams\">".Dict::Format('UI:ClickToCreateNew', MetaModel::GetName($sClass))."</a><br/>\n";
  610. }
  611. $sHtml .= "<a href=\"".utils::GetAbsoluteUrlAppRoot()."pages/UI.php?operation=search_form&class={$sClass}&$sParams\">".Dict::Format('UI:SearchFor_Class', MetaModel::GetName($sClass))."</a>\n";
  612. $sHtml .= '</p>';
  613. break;
  614. case 'summary':
  615. $sClass = $this->m_oFilter->GetClass();
  616. $oAppContext = new ApplicationContext();
  617. $sTitle = isset($aExtraParams['title[block]']) ? $aExtraParams['title[block]'] : '';
  618. $sLabel = isset($aExtraParams['label[block]']) ? $aExtraParams['label[block]'] : '';
  619. $sStateAttrCode = isset($aExtraParams['status[block]']) ? $aExtraParams['status[block]'] : 'status';
  620. $sStatesList = isset($aExtraParams['status_codes[block]']) ? $aExtraParams['status_codes[block]'] : '';
  621. $bContextFilter = isset($aExtraParams['context_filter']) ? isset($aExtraParams['context_filter']) != 0 : false;
  622. if ($bContextFilter)
  623. {
  624. $aFilterCodes = array_keys(MetaModel::GetClassFilterDefs($this->m_oFilter->GetClass()));
  625. foreach($oAppContext->GetNames() as $sFilterCode)
  626. {
  627. $sContextParamValue = $oAppContext->GetCurrentValue($sFilterCode, null);
  628. if (!is_null($sContextParamValue) && ! empty($sContextParamValue) && MetaModel::IsValidFilterCode($sClass, $sFilterCode))
  629. {
  630. $this->AddCondition($sFilterCode, $sContextParamValue);
  631. }
  632. }
  633. $aQueryParams = array();
  634. if (isset($aExtraParams['query_params']))
  635. {
  636. $aQueryParams = $aExtraParams['query_params'];
  637. }
  638. $this->m_oSet = new CMDBObjectSet($this->m_oFilter, array(), $aQueryParams);
  639. }
  640. // Summary details
  641. $aCounts = array();
  642. $aStateLabels = array();
  643. if (!empty($sStateAttrCode) && !empty($sStatesList))
  644. {
  645. $aStates = explode(',', $sStatesList);
  646. $oAttDef = MetaModel::GetAttributeDef($sClass, $sStateAttrCode);
  647. foreach($aStates as $sStateValue)
  648. {
  649. $oFilter = clone($this->m_oFilter);
  650. $oFilter->AddCondition($sStateAttrCode, $sStateValue, '=');
  651. $oSet = new DBObjectSet($oFilter);
  652. $aCounts[$sStateValue] = $oSet->Count();
  653. $aStateLabels[$sStateValue] = $oAttDef->GetValueLabel($sStateValue);
  654. if ($aCounts[$sStateValue] == 0)
  655. {
  656. $aCounts[$sStateValue] = '-';
  657. }
  658. else
  659. {
  660. $sHyperlink = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=search&'.$oAppContext->GetForLink().'&filter='.$oFilter->serialize();
  661. $aCounts[$sStateValue] = "<a href=\"$sHyperlink\">{$aCounts[$sStateValue]}</a>";
  662. }
  663. }
  664. }
  665. $sHtml .= '<div class="summary-details"><table><tr><th>'.implode('</th><th>', $aStateLabels).'</th></tr>';
  666. $sHtml .= '<tr><td>'.implode('</td><td>', $aCounts).'</td></tr></table></div>';
  667. // Title & summary
  668. $iCount = $this->m_oSet->Count();
  669. $sHyperlink = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=search&'.$oAppContext->GetForLink().'&filter='.$this->m_oFilter->serialize();
  670. $sHtml .= '<h1>'.Dict::S(str_replace('_', ':', $sTitle)).'</h1>';
  671. $sHtml .= '<a class="summary" href="'.$sHyperlink.'">'.Dict::Format(str_replace('_', ':', $sLabel), $iCount).'</a>';
  672. break;
  673. case 'csv':
  674. $sHtml .= "<textarea style=\"width:95%;height:98%\">\n";
  675. $sHtml .= cmdbAbstractObject::GetSetAsCSV($this->m_oSet);
  676. $sHtml .= "</textarea>\n";
  677. break;
  678. case 'modify':
  679. if ((UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_MODIFY, $this->m_oSet) == UR_ALLOWED_YES))
  680. {
  681. while($oObj = $this->m_oSet->Fetch())
  682. {
  683. $sHtml .= $oObj->GetModifyForm($oPage);
  684. }
  685. }
  686. break;
  687. case 'search':
  688. $sStyle = (isset($aExtraParams['open']) && ($aExtraParams['open'] == 'true')) ? 'SearchDrawer' : 'SearchDrawer DrawerClosed';
  689. $sHtml .= "<div id=\"ds_$sId\" class=\"$sStyle\">\n";
  690. $oPage->add_ready_script(
  691. <<<EOF
  692. $("#dh_$sId").click( function() {
  693. $("#ds_$sId").slideToggle('normal', function() { $("#ds_$sId").parent().resize(); } );
  694. $("#dh_$sId").toggleClass('open');
  695. });
  696. EOF
  697. );
  698. $aExtraParams['currentId'] = $sId;
  699. $sHtml .= cmdbAbstractObject::GetSearchForm($oPage, $this->m_oSet, $aExtraParams);
  700. $sHtml .= "</div>\n";
  701. $sHtml .= "<div class=\"HRDrawer\"></div>\n";
  702. $sHtml .= "<div id=\"dh_$sId\" class=\"DrawerHandle\">".Dict::S('UI:SearchToggle')."</div>\n";
  703. break;
  704. case 'open_flash_chart':
  705. static $iChartCounter = 0;
  706. $oAppContext = new ApplicationContext();
  707. $sContext = $oAppContext->GetForLink();
  708. if (!empty($sContext))
  709. {
  710. $sContext = '&'.$sContext;
  711. }
  712. $sChartType = isset($aExtraParams['chart_type']) ? $aExtraParams['chart_type'] : 'pie';
  713. $sTitle = isset($aExtraParams['chart_title']) ? $aExtraParams['chart_title'] : '';
  714. $sGroupBy = isset($aExtraParams['group_by']) ? $aExtraParams['group_by'] : '';
  715. $sGroupByExpr = isset($aExtraParams['group_by_expr']) ? '&params[group_by_expr]='.$aExtraParams['group_by_expr'] : '';
  716. $sFilter = $this->m_oFilter->serialize();
  717. $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";
  718. $oPage->add_script("function ofc_resize(left, width, top, height) { /* do nothing special */ }");
  719. $oPage->add_ready_script("swfobject.embedSWF(\"../images/open-flash-chart.swf\", \"my_chart_$sId{$iChartCounter}\", \"100%\", \"300\",\"9.0.0\", \"expressInstall.swf\",
  720. {\"data-file\":\"".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=".$sFilter)."\"}, {wmode: 'transparent'} );\n");
  721. $iChartCounter++;
  722. if (isset($aExtraParams['group_by']))
  723. {
  724. $sGroupByField = $aExtraParams['group_by'];
  725. $aGroupBy = array();
  726. while($oObj = $this->m_oSet->Fetch())
  727. {
  728. if (isset($aExtraParams['group_by_expr']))
  729. {
  730. eval("\$sValue = ".sprintf($aExtraParams['group_by_expr'], $oObj->Get($sGroupByField)).';');
  731. }
  732. else
  733. {
  734. $sValue = $oObj->Get($sGroupByField);
  735. }
  736. $aGroupBy[$sValue] = isset($aGroupBy[$sValue]) ? $aGroupBy[$sValue]+1 : 1;
  737. }
  738. $sFilter = urlencode($this->m_oFilter->serialize());
  739. $aData = array();
  740. $aLabels = array();
  741. $idx = 0;
  742. $aURLs = array();
  743. foreach($aGroupBy as $sValue => $iValue)
  744. {
  745. $oDrillDownFilter = clone $this->m_oFilter;
  746. $oDrillDownFilter->AddCondition($sGroupByField, $sValue, '=');
  747. $aURLs[$idx] = $oDrillDownFilter->serialize();
  748. $idx++;
  749. }
  750. $sURLList = '';
  751. foreach($aURLs as $index => $sURL)
  752. {
  753. $sURLList .= "\taURLs[$index] = '".utils::GetAbsoluteUrlAppRoot()."pages/UI.php?operation=search&format=html{$sContext}&filter=".addslashes($sURL)."';\n";
  754. }
  755. $oPage->add_script(
  756. <<<EOF
  757. function ofc_drill_down_{$sId}(index)
  758. {
  759. var aURLs = new Array();
  760. {$sURLList}
  761. window.location.href=aURLs[index];
  762. }
  763. EOF
  764. );
  765. }
  766. break;
  767. case 'open_flash_chart_ajax':
  768. require_once(APPROOT.'/pages/php-ofc-library/open-flash-chart.php');
  769. $sChartType = isset($aExtraParams['chart_type']) ? $aExtraParams['chart_type'] : 'pie';
  770. $sId = utils::ReadParam('id', '');
  771. $oChart = new open_flash_chart();
  772. switch($sChartType)
  773. {
  774. case 'bars':
  775. $oChartElement = new bar_glass();
  776. if (isset($aExtraParams['group_by']))
  777. {
  778. $sGroupByField = $aExtraParams['group_by'];
  779. $aGroupBy = array();
  780. while($oObj = $this->m_oSet->Fetch())
  781. {
  782. if (isset($aExtraParams['group_by_expr']))
  783. {
  784. eval("\$sValue = ".sprintf($aExtraParams['group_by_expr'], $oObj->Get($sGroupByField)).';');
  785. }
  786. else
  787. {
  788. $sValue = $oObj->Get($sGroupByField);
  789. }
  790. $aGroupBy[$sValue] = isset($aGroupBy[$sValue]) ? $aGroupBy[$sValue]+1 : 1;
  791. }
  792. $sFilter = urlencode($this->m_oFilter->serialize());
  793. $aData = array();
  794. $aLabels = array();
  795. $maxValue = 0;
  796. foreach($aGroupBy as $sValue => $iValue)
  797. {
  798. $oBarValue = new bar_value($iValue);
  799. $oBarValue->on_click("ofc_drill_down_$sId");
  800. $aData[] = $oBarValue;
  801. if ($iValue > $maxValue) $maxValue = $iValue;
  802. $aLabels[] = $sValue;
  803. }
  804. $oYAxis = new y_axis();
  805. $aMagicValues = array(1,2,5,10);
  806. $iMultiplier = 1;
  807. $index = 0;
  808. $iTop = $aMagicValues[$index % count($aMagicValues)]*$iMultiplier;
  809. while($maxValue > $iTop)
  810. {
  811. $index++;
  812. $iTop = $aMagicValues[$index % count($aMagicValues)]*$iMultiplier;
  813. if (($index % count($aMagicValues)) == 0)
  814. {
  815. $iMultiplier = $iMultiplier * 10;
  816. }
  817. }
  818. //echo "oYAxis->set_range(0, $iTop, $iMultiplier);\n";
  819. $oYAxis->set_range(0, $iTop, $iMultiplier);
  820. $oChart->set_y_axis( $oYAxis );
  821. $oChartElement->set_values( $aData );
  822. $oXAxis = new x_axis();
  823. $oXLabels = new x_axis_labels();
  824. // set them vertical
  825. $oXLabels->set_vertical();
  826. // set the label text
  827. $oXLabels->set_labels($aLabels);
  828. // Add the X Axis Labels to the X Axis
  829. $oXAxis->set_labels( $oXLabels );
  830. $oChart->set_x_axis( $oXAxis );
  831. }
  832. break;
  833. case 'pie':
  834. default:
  835. $oChartElement = new pie();
  836. $oChartElement->set_start_angle( 35 );
  837. $oChartElement->set_animate( true );
  838. $oChartElement->set_tooltip( '#label# - #val# (#percent#)' );
  839. $oChartElement->set_colours( array('#FF8A00', '#909980', '#2C2B33', '#CCC08D', '#596664') );
  840. if (isset($aExtraParams['group_by']))
  841. {
  842. $sGroupByField = $aExtraParams['group_by'];
  843. $aGroupBy = array();
  844. while($oObj = $this->m_oSet->Fetch())
  845. {
  846. if (isset($aExtraParams['group_by_expr']))
  847. {
  848. eval("\$sValue = ".sprintf($aExtraParams['group_by_expr'], $oObj->Get($sGroupByField)).';');
  849. }
  850. else
  851. {
  852. $sValue = $oObj->Get($sGroupByField);
  853. }
  854. $aGroupBy[$sValue] = isset($aGroupBy[$sValue]) ? $aGroupBy[$sValue]+1 : 1;
  855. }
  856. $sFilter = urlencode($this->m_oFilter->serialize());
  857. $aData = array();
  858. foreach($aGroupBy as $sValue => $iValue)
  859. {
  860. $PieValue = new pie_value($iValue, $sValue); //@@ BUG: not passed via ajax !!!
  861. $PieValue->on_click("ofc_drill_down_$sId");
  862. $aData[] = $PieValue;
  863. }
  864. $oChartElement->set_values( $aData );
  865. $oChart->x_axis = null;
  866. }
  867. }
  868. if (isset($aExtraParams['chart_title']))
  869. {
  870. $oTitle = new title( Dict::S($aExtraParams['chart_title']) );
  871. $oChart->set_title( $oTitle );
  872. }
  873. $oChart->set_bg_colour('#FFFFFF');
  874. $oChart->add_element( $oChartElement );
  875. $sHtml = $oChart->toPrettyString();
  876. break;
  877. default:
  878. // Unsupported style, do nothing.
  879. $sHtml .= Dict::format('UI:Error:UnsupportedStyleOfBlock', $this->m_sStyle);
  880. }
  881. return $sHtml;
  882. }
  883. /**
  884. * Add a condition (restriction) to the current DBObjectSearch on which the display block is based
  885. * taking into account the hierarchical keys for which the condition is based on the 'below' operator
  886. */
  887. protected function AddCondition($sFilterCode, $condition)
  888. {
  889. $sClass = $this->m_oFilter->GetClass();
  890. $bConditionAdded = false;
  891. // If the condition is an external key with a class having a hierarchy, use a "below" criteria
  892. if (MetaModel::IsValidAttCode($sClass, $sFilterCode))
  893. {
  894. $oAttDef = MetaModel::GetAttributeDef($sClass, $sFilterCode);
  895. if ($oAttDef->IsExternalKey())
  896. {
  897. $sHierarchicalKeyCode = MetaModel::IsHierarchicalClass($oAttDef->GetTargetClass());
  898. if ($sHierarchicalKeyCode !== false)
  899. {
  900. $oFilter = new DBObjectSearch($oAttDef->GetTargetClass());
  901. $oFilter->AddCondition('id', $condition);
  902. $oHKFilter = new DBObjectSearch($oAttDef->GetTargetClass());
  903. $oHKFilter->AddCondition_PointingTo($oFilter, $sHierarchicalKeyCode, TREE_OPERATOR_BELOW); // Use the 'below' operator by default
  904. $this->m_oFilter->AddCondition_PointingTo($oHKFilter, $sFilterCode);
  905. $bConditionAdded = true;
  906. }
  907. }
  908. }
  909. // In all other cases, just add the condition directly
  910. if (!$bConditionAdded)
  911. {
  912. $this->m_oFilter->AddCondition($sFilterCode, $condition); // Use the default 'loose' operator
  913. }
  914. }
  915. }
  916. /**
  917. * Helper class to manage 'blocks' of HTML pieces that are parts of a page and contain some list of cmdb objects
  918. *
  919. * Each block is actually rendered as a <div></div> tag that can be rendered synchronously
  920. * or as a piece of Javascript/JQuery/Ajax that will get its content from another page (ajax.render.php).
  921. * The list of cmdbObjects to be displayed into the block is defined by a filter
  922. * Right now the type of display is either: list, count or details
  923. * - list produces a table listing the objects
  924. * - count produces a paragraphs with a sentence saying 'cont' objects found
  925. * - details display (as table) the details of each object found (best if only one)
  926. */
  927. class HistoryBlock extends DisplayBlock
  928. {
  929. public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId)
  930. {
  931. $sHtml = '';
  932. $oSet = new CMDBObjectSet($this->m_oFilter, array('date'=>false));
  933. $sHtml .= "<!-- filter: ".($this->m_oFilter->ToOQL())."-->\n";
  934. switch($this->m_sStyle)
  935. {
  936. case 'toggle':
  937. // First the latest change that the user is allowed to see
  938. do
  939. {
  940. $oLatestChangeOp = $oSet->Fetch();
  941. }
  942. while(is_object($oLatestChangeOp) && ($oLatestChangeOp->GetDescription() == ''));
  943. if (is_object($oLatestChangeOp))
  944. {
  945. // There is one change in the list... only when the object has been created !
  946. $sDate = $oLatestChangeOp->GetAsHTML('date');
  947. $oChange = MetaModel::GetObject('CMDBChange', $oLatestChangeOp->Get('change'));
  948. $sUserInfo = $oChange->GetAsHTML('userinfo');
  949. $sHtml .= $oPage->GetStartCollapsibleSection(Dict::Format('UI:History:LastModified_On_By', $sDate, $sUserInfo));
  950. $sHtml .= $this->GetHistoryTable($oPage, $oSet);
  951. $sHtml .= $oPage->GetEndCollapsibleSection();
  952. }
  953. break;
  954. case 'table':
  955. default:
  956. $sHtml .= $this->GetHistoryTable($oPage, $oSet);
  957. }
  958. return $sHtml;
  959. }
  960. protected function GetHistoryTable(WebPage $oPage, DBObjectSet $oSet)
  961. {
  962. $sHtml = '';
  963. // First the latest change that the user is allowed to see
  964. $oSet->Rewind(); // Reset the pointer to the beginning of the set
  965. $aChanges = array();
  966. while($oChangeOp = $oSet->Fetch())
  967. {
  968. $sChangeDescription = $oChangeOp->GetDescription();
  969. if ($sChangeDescription != '')
  970. {
  971. // The change is visible for the current user
  972. $changeId = $oChangeOp->Get('change');
  973. $aChanges[$changeId]['date'] = $oChangeOp->Get('date');
  974. $aChanges[$changeId]['userinfo'] = $oChangeOp->Get('userinfo');
  975. if (!isset($aChanges[$changeId]['log']))
  976. {
  977. $aChanges[$changeId]['log'] = array();
  978. }
  979. $aChanges[$changeId]['log'][] = $sChangeDescription;
  980. }
  981. }
  982. $aAttribs = array('date' => array('label' => Dict::S('UI:History:Date'), 'description' => Dict::S('UI:History:Date+')),
  983. 'userinfo' => array('label' => Dict::S('UI:History:User'), 'description' => Dict::S('UI:History:User+')),
  984. 'log' => array('label' => Dict::S('UI:History:Changes'), 'description' => Dict::S('UI:History:Changes+')),
  985. );
  986. $aValues = array();
  987. foreach($aChanges as $aChange)
  988. {
  989. $aValues[] = array('date' => $aChange['date'], 'userinfo' => htmlentities($aChange['userinfo'], ENT_QUOTES, 'UTF-8'), 'log' => "<ul><li>".implode('</li><li>', $aChange['log'])."</li></ul>");
  990. }
  991. $sHtml .= $oPage->GetTable($aAttribs, $aValues);
  992. return $sHtml;
  993. }
  994. }
  995. class MenuBlock extends DisplayBlock
  996. {
  997. /**
  998. * Renders the "Actions" popup menu for the given set of objects
  999. *
  1000. * Note that the menu links containing (or ending) with a hash (#) will have their fragment
  1001. * part (whatever is after the hash) dynamically replaced (by javascript) when the menu is
  1002. * displayed, to correspond to the current hash/fragment in the page. This allows modifying
  1003. * an object in with the same tab active by default as the tab that was active when selecting
  1004. * the "Modify..." action.
  1005. */
  1006. public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId)
  1007. {
  1008. $sHtml = '';
  1009. $oAppContext = new ApplicationContext();
  1010. $sContext = $oAppContext->GetForLink();
  1011. if (!empty($sContext))
  1012. {
  1013. $sContext = '&'.$sContext;
  1014. }
  1015. $sClass = $this->m_oFilter->GetClass();
  1016. $oSet = new CMDBObjectSet($this->m_oFilter);
  1017. $sFilter = $this->m_oFilter->serialize();
  1018. $sFilterDesc = $this->m_oFilter->ToOql(true);
  1019. $aActions = array();
  1020. $sUIPage = cmdbAbstractObject::ComputeStandardUIPage($sClass);
  1021. $sRootUrl = utils::GetAbsoluteUrlAppRoot();
  1022. // 1:n links, populate the target object as a default value when creating a new linked object
  1023. if (isset($aExtraParams['target_attr']))
  1024. {
  1025. $aExtraParams['default'][$aExtraParams['target_attr']] = $aExtraParams['object_id'];
  1026. }
  1027. $sDefault = '';
  1028. if (!empty($aExtraParams['default']))
  1029. {
  1030. foreach($aExtraParams['default'] as $sKey => $sValue)
  1031. {
  1032. $sDefault.= "&default[$sKey]=$sValue";
  1033. }
  1034. }
  1035. $bIsCreationAllowed = (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES);
  1036. switch($oSet->Count())
  1037. {
  1038. case 0:
  1039. // No object in the set, the only possible action is "new"
  1040. if ($bIsCreationAllowed) { $aActions['UI:Menu:New'] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=new&class=$sClass{$sContext}{$sDefault}"); }
  1041. break;
  1042. case 1:
  1043. $oObj = $oSet->Fetch();
  1044. $id = $oObj->GetKey();
  1045. $bIsModifyAllowed = (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet) == UR_ALLOWED_YES);
  1046. $bIsDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, $oSet);
  1047. $bIsBulkModifyAllowed = (!MetaModel::IsAbstract($sClass)) && UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_MODIFY, $oSet);
  1048. $bIsBulkDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_DELETE, $oSet);
  1049. // Just one object in the set, possible actions are "new / clone / modify and delete"
  1050. if (!isset($aExtraParams['link_attr']))
  1051. {
  1052. if ($bIsModifyAllowed) { $aActions['UI:Menu:Modify'] = array ('label' => Dict::S('UI:Menu:Modify'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=modify&class=$sClass&id=$id{$sContext}#"); }
  1053. if ($bIsCreationAllowed) { $aActions['UI:Menu:New'] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=new&class=$sClass{$sContext}{$sDefault}"); }
  1054. if ($bIsDeleteAllowed) { $aActions['UI:Menu:Delete'] = array ('label' => Dict::S('UI:Menu:Delete'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=delete&class=$sClass&id=$id{$sContext}"); }
  1055. // Transitions / Stimuli
  1056. $aTransitions = $oObj->EnumTransitions();
  1057. if (count($aTransitions))
  1058. {
  1059. $this->AddMenuSeparator($aActions);
  1060. $aStimuli = Metamodel::EnumStimuli(get_class($oObj));
  1061. foreach($aTransitions as $sStimulusCode => $aTransitionDef)
  1062. {
  1063. $iActionAllowed = (get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction') ? UserRights::IsStimulusAllowed($sClass, $sStimulusCode, $oSet) : UR_ALLOWED_NO;
  1064. switch($iActionAllowed)
  1065. {
  1066. case UR_ALLOWED_YES:
  1067. $aActions[$sStimulusCode] = array('label' => $aStimuli[$sStimulusCode]->GetLabel(), 'url' => "{$sRootUrl}pages/UI.php?operation=stimulus&stimulus=$sStimulusCode&class=$sClass&id=$id{$sContext}");
  1068. break;
  1069. default:
  1070. // Do nothing
  1071. }
  1072. }
  1073. }
  1074. // Relations...
  1075. $aRelations = MetaModel::EnumRelations($sClass);
  1076. if (count($aRelations))
  1077. {
  1078. $this->AddMenuSeparator($aActions);
  1079. foreach($aRelations as $sRelationCode)
  1080. {
  1081. $aActions[$sRelationCode] = array ('label' => MetaModel::GetRelationVerbUp($sRelationCode), 'url' => "{$sRootUrl}pages/$sUIPage?operation=swf_navigator&relation=$sRelationCode&class=$sClass&id=$id{$sContext}");
  1082. }
  1083. }
  1084. $this->AddMenuSeparator($aActions);
  1085. // Static menus: Email this page & CSV Export
  1086. $sUrl = ApplicationContext::MakeObjectUrl($sClass, $id);
  1087. $aActions['UI:Menu:EMail'] = array ('label' => Dict::S('UI:Menu:EMail'), 'url' => "mailto:?subject=".urlencode($oObj->GetRawName())."&body=".urlencode($sUrl));
  1088. $aActions['UI:Menu:CSVExport'] = array ('label' => Dict::S('UI:Menu:CSVExport'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=search&filter=$sFilter&format=csv{$sContext}");
  1089. $sOQL = addslashes($sFilterDesc);
  1090. $aActions['UI:Menu:AddToDashboard'] = array ('label' => Dict::S('UI:Menu:AddToDashboard'), 'url' => "#", 'onclick' => "return DashletCreationDlg('$sOQL')");
  1091. }
  1092. $this->AddMenuSeparator($aActions);
  1093. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  1094. {
  1095. $oSet->Rewind();
  1096. foreach($oExtensionInstance->EnumAllowedActions($oSet) as $sLabel => $sUrl)
  1097. {
  1098. $aActions[$sLabel] = array ('label' => $sLabel, 'url' => $sUrl);
  1099. }
  1100. }
  1101. break;
  1102. default:
  1103. // Check rights
  1104. // New / Modify
  1105. $bIsModifyAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet);
  1106. $bIsBulkModifyAllowed = (!MetaModel::IsAbstract($sClass)) && UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_MODIFY, $oSet);
  1107. $bIsBulkDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_DELETE, $oSet);
  1108. if (isset($aExtraParams['link_attr']))
  1109. {
  1110. $id = $aExtraParams['object_id'];
  1111. $sTargetAttr = $aExtraParams['target_attr'];
  1112. $oAttDef = MetaModel::GetAttributeDef($sClass, $sTargetAttr);
  1113. $sTargetClass = $oAttDef->GetTargetClass();
  1114. $bIsDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, $oSet);
  1115. 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}"); }
  1116. 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}"); }
  1117. //if ($bIsBulkDeleteAllowed) { $aActions[] = array ('label' => 'Remove All...', 'url' => "#"); }
  1118. }
  1119. else
  1120. {
  1121. // many objects in the set, possible actions are: new / modify all / delete all
  1122. if ($bIsCreationAllowed) { $aActions['UI:Menu:New'] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=new&class=$sClass{$sContext}{$sDefault}"); }
  1123. 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=$sFilter{$sContext}"); }
  1124. if ($bIsBulkDeleteAllowed) { $aActions['UI:Menu:BulkDelete'] = array ('label' => Dict::S('UI:Menu:BulkDelete'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=select_for_deletion&filter=$sFilter{$sContext}"); }
  1125. // Stimuli
  1126. $aStates = MetaModel::EnumStates($sClass);
  1127. if (count($aStates) > 0)
  1128. {
  1129. // Life cycle actions may be available... if all objects are in the same state
  1130. $oSet->Rewind();
  1131. $aStates = array();
  1132. while($oObj = $oSet->Fetch())
  1133. {
  1134. $aStates[$oObj->GetState()] = $oObj->GetState();
  1135. }
  1136. $oSet->Rewind();
  1137. if (count($aStates) == 1)
  1138. {
  1139. // All objects are in the same state...
  1140. $sState = array_pop($aStates);
  1141. $aTransitions = Metamodel::EnumTransitions($sClass, $sState);
  1142. if (count($aTransitions))
  1143. {
  1144. $this->AddMenuSeparator($aActions);
  1145. $aStimuli = Metamodel::EnumStimuli($sClass);
  1146. foreach($aTransitions as $sStimulusCode => $aTransitionDef)
  1147. {
  1148. $oChecker = new StimulusChecker($this->m_oFilter, $sState, $sStimulusCode);
  1149. $iActionAllowed = (get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction') ? $oChecker->IsAllowed() : UR_ALLOWED_NO;
  1150. switch($iActionAllowed)
  1151. {
  1152. case UR_ALLOWED_YES:
  1153. case UR_ALLOWED_DEPENDS:
  1154. $aActions[$sStimulusCode] = array('label' => $aStimuli[$sStimulusCode]->GetLabel(), 'url' => "{$sRootUrl}pages/UI.php?operation=select_bulk_stimulus&stimulus=$sStimulusCode&state=$sState&class=$sClass&filter=$sFilter{$sContext}");
  1155. break;
  1156. default:
  1157. // Do nothing
  1158. }
  1159. }
  1160. }
  1161. }
  1162. }
  1163. $this->AddMenuSeparator($aActions);
  1164. $sUrl = utils::GetAbsoluteUrlAppRoot();
  1165. $aActions['UI:Menu:EMail'] = array ('label' => Dict::S('UI:Menu:EMail'), 'url' => "mailto:?subject=$sFilterDesc&body=".urlencode("{$sUrl}pages/$sUIPage?operation=search&filter=$sFilter{$sContext}"));
  1166. $aActions['UI:Menu:CSVExport'] = array ('label' => Dict::S('UI:Menu:CSVExport'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=search&filter=$sFilter&format=csv{$sContext}");
  1167. $sOQL = addslashes($sFilterDesc);
  1168. $aActions['UI:Menu:AddToDashboard'] = array ('label' => Dict::S('UI:Menu:AddToDashboard'), 'url' => "#", 'onclick' => "return DashletCreationDlg('$sOQL')");
  1169. }
  1170. $this->AddMenuSeparator($aActions);
  1171. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  1172. {
  1173. $oSet->Rewind();
  1174. foreach($oExtensionInstance->EnumAllowedActions($oSet) as $sLabel => $sUrl)
  1175. {
  1176. $aActions[$sLabel] = array ('label' => $sLabel, 'url' => $sUrl);
  1177. }
  1178. }
  1179. }
  1180. $aFavoriteActions = array();
  1181. $aCallSpec = array($sClass, 'GetShortcutActions');
  1182. if (is_callable($aCallSpec))
  1183. {
  1184. $aShortcutActions = call_user_func($aCallSpec, $sClass);
  1185. foreach ($aActions as $key => $aAction)
  1186. {
  1187. if (in_array($key, $aShortcutActions))
  1188. {
  1189. $aFavoriteActions[] = $aAction;
  1190. unset($aActions[$key]);
  1191. }
  1192. }
  1193. }
  1194. else
  1195. {
  1196. $aShortcutActions = array();
  1197. }
  1198. if (count($aFavoriteActions) > 0)
  1199. {
  1200. $sHtml .= "<div class=\"itop_popup\"><ul>\n<li>".Dict::S('UI:Menu:OtherActions')."\n<ul>\n";
  1201. }
  1202. else
  1203. {
  1204. $sHtml .= "<div class=\"itop_popup\"><ul>\n<li>".Dict::S('UI:Menu:Actions')."\n<ul>\n";
  1205. }
  1206. $sPrevUrl = '';
  1207. foreach ($aActions as $key => $aAction)
  1208. {
  1209. if (in_array($key, $aShortcutActions))
  1210. {
  1211. $aFavoriteActions[] = $aAction;
  1212. }
  1213. else
  1214. {
  1215. $sClass = isset($aAction['class']) ? " class=\"{$aAction['class']}\"" : "";
  1216. $sOnClick = isset($aAction['onclick']) ? " onclick=\"{$aAction['onclick']}\"" : "";
  1217. if (empty($aAction['url']))
  1218. {
  1219. if ($sPrevUrl != '') // Don't output consecutively two separators...
  1220. {
  1221. $sHtml .= "<li>{$aAction['label']}</li>\n";
  1222. }
  1223. $sPrevUrl = '';
  1224. }
  1225. else
  1226. {
  1227. $sHtml .= "<li><a href=\"{$aAction['url']}\"$sClass $sOnClick>{$aAction['label']}</a></li>\n";
  1228. $sPrevUrl = $aAction['url'];
  1229. }
  1230. }
  1231. }
  1232. $sHtml .= "</ul>\n</li>\n</ul></div>";
  1233. foreach(array_reverse($aFavoriteActions) as $aAction)
  1234. {
  1235. $sHtml .= "<div class=\"actions_button\"><a href='{$aAction['url']}'>{$aAction['label']}</a></div>";
  1236. }
  1237. static $bPopupScript = false;
  1238. if (!$bPopupScript)
  1239. {
  1240. // Output this once per page...
  1241. $oPage->add_ready_script("$(\"div.itop_popup>ul\").popupmenu();\n");
  1242. $bPopupScript = true;
  1243. }
  1244. return $sHtml;
  1245. }
  1246. /**
  1247. * Appends a menu separator to the current list of actions
  1248. * @param Hash $aActions The current actions list
  1249. * @return void
  1250. */
  1251. protected function AddMenuSeparator(&$aActions)
  1252. {
  1253. $sSeparator = '<hr class="menu-separator"/>';
  1254. if (count($aActions) > 0) // Make sure that the separator is not the first item in the menu
  1255. {
  1256. $aKeys = array_keys($aActions);
  1257. $sLastKey = array_pop($aKeys);
  1258. if ($aActions[$sLastKey]['label'] != $sSeparator) // Make sure there are no 2 consecutive separators
  1259. {
  1260. $aActions['sep_'.(count($aActions)-1)] = array('label' => $sSeparator, 'url' => '');
  1261. }
  1262. }
  1263. }
  1264. }
  1265. ?>