displayblock.class.inc.php 60 KB

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