displayblock.class.inc.php 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  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. $aExtraParams = array_merge($aExtraParams, $this->m_aParams);
  174. $aExtraParams['block_id'] = $sId;
  175. if (!$this->m_bAsynchronous)
  176. {
  177. // render now
  178. $oPage->add("<div id=\"$sId\" class=\"display_block\">\n");
  179. $this->RenderContent($oPage, $aExtraParams);
  180. $oPage->add("</div>\n");
  181. }
  182. else
  183. {
  184. // render it as an Ajax (asynchronous) call
  185. $sFilter = $this->m_oFilter->serialize();
  186. $oPage->add("<div id=\"$sId\" class=\"display_block loading\">\n");
  187. $oPage->p("<img src=\"../images/indicator_arrows.gif\"> Loading...");
  188. $oPage->add("</div>\n");
  189. $oPage->add('
  190. <script language="javascript">
  191. $.post("ajax.render.php?style='.$this->m_sStyle.'",
  192. { operation: "ajax", filter: "$sFilter" },
  193. function(data){
  194. $("#'.$sId.'").empty();
  195. $("#'.$sId.'").append(data);
  196. $("#'.$sId.'").removeClass("loading");
  197. }
  198. );
  199. </script>'); // TO DO: add support for $aExtraParams in asynchronous/Ajax mode
  200. }
  201. */
  202. }
  203. public function GetDisplay(WebPage $oPage, $sId, $aExtraParams = array())
  204. {
  205. $sHtml = '';
  206. $aExtraParams = array_merge($aExtraParams, $this->m_aParams);
  207. $aExtraParams['currentId'] = $sId;
  208. $sExtraParams = addslashes(str_replace('"', "'", json_encode($aExtraParams))); // JSON encode, change the style of the quotes and escape them
  209. $bAutoReload = false;
  210. if (isset($aExtraParams['auto_reload']))
  211. {
  212. switch($aExtraParams['auto_reload'])
  213. {
  214. case 'fast':
  215. $bAutoReload = true;
  216. $iReloadInterval = MetaModel::GetConfig()->GetFastReloadInterval()*1000;
  217. break;
  218. case 'standard':
  219. case 'true':
  220. case true:
  221. $bAutoReload = true;
  222. $iReloadInterval = MetaModel::GetConfig()->GetStandardReloadInterval()*1000;
  223. break;
  224. default:
  225. if (is_numeric($aExtraParams['auto_reload']))
  226. {
  227. $bAutoReload = true;
  228. $iReloadInterval = $aExtraParams['auto_reload']*1000;
  229. }
  230. else
  231. {
  232. // incorrect config, ignore it
  233. $bAutoReload = false;
  234. }
  235. }
  236. }
  237. $sFilter = $this->m_oFilter->serialize(); // Used either for asynchronous or auto_reload
  238. if (!$this->m_bAsynchronous)
  239. {
  240. // render now
  241. $sHtml .= "<div id=\"$sId\" class=\"display_block\">\n";
  242. $sHtml .= $this->GetRenderContent($oPage, $aExtraParams, $sId);
  243. $sHtml .= "</div>\n";
  244. }
  245. else
  246. {
  247. // render it as an Ajax (asynchronous) call
  248. $sHtml .= "<div id=\"$sId\" class=\"display_block loading\">\n";
  249. $sHtml .= $oPage->GetP("<img src=\"../images/indicator_arrows.gif\"> ".Dict::S('UI:Loading'));
  250. $sHtml .= "</div>\n";
  251. $sHtml .= '
  252. <script language="javascript">
  253. $.post("ajax.render.php?style='.$this->m_sStyle.'",
  254. { operation: "ajax", filter: "'.$sFilter.'", extra_params: "'.$sExtraParams.'" },
  255. function(data){
  256. $("#'.$sId.'").empty();
  257. $("#'.$sId.'").append(data);
  258. $("#'.$sId.'").removeClass("loading");
  259. // Check each "listResults" table for a checkbox in the first column and make the first column sortable only if it does not contain a checkbox in the header
  260. $("#'.$sId.'".listResults").each( function()
  261. {
  262. var table = $(this);
  263. var id = $(this).parent();
  264. var checkbox = (table.find(\'th:first :checkbox\').length > 0);
  265. if (checkbox)
  266. {
  267. // There is a checkbox in the first column, do not make it sortable
  268. table.tablesorter( { headers: { 0: {sorter: false}}, widgets: [\'myZebra\', \'truncatedList\']} ); // sortable and zebra tables
  269. }
  270. else
  271. {
  272. // There is NO checkbox in the first column, all columns are considered sortable
  273. table.tablesorter( { widgets: [\'myZebra\', \'truncatedList\']} ); // sortable and zebra tables
  274. }
  275. });
  276. }
  277. );
  278. </script>';
  279. }
  280. if ($bAutoReload)
  281. {
  282. $sHtml .= '
  283. <script language="javascript">
  284. setInterval("ReloadBlock(\''.$sId.'\', \''.$this->m_sStyle.'\', \''.$sFilter.'\', \"'.$sExtraParams.'\")", '.$iReloadInterval.');
  285. </script>';
  286. }
  287. return $sHtml;
  288. }
  289. public function RenderContent(WebPage $oPage, $aExtraParams = array())
  290. {
  291. if (empty($aExtraParams['currentId']))
  292. {
  293. $sId = $oPage->GetUniqueId(); // Works only if the page is not an Ajax one !
  294. }
  295. else
  296. {
  297. $sId = $aExtraParams['currentId'];
  298. }
  299. $oPage->add($this->GetRenderContent($oPage, $aExtraParams, $sId));
  300. }
  301. public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId)
  302. {
  303. $sHtml = '';
  304. // Add the extra params into the filter if they make sense for such a filter
  305. $bDoSearch = utils::ReadParam('dosearch', false);
  306. if ($this->m_oSet == null)
  307. {
  308. $aQueryParams = array();
  309. if (isset($aExtraParams['query_params']))
  310. {
  311. $aQueryParams = $aExtraParams['query_params'];
  312. }
  313. if ($this->m_sStyle != 'links')
  314. {
  315. $oAppContext = new ApplicationContext();
  316. $sClass = $this->m_oFilter->GetClass();
  317. $aFilterCodes = array_keys(MetaModel::GetClassFilterDefs($sClass));
  318. foreach($oAppContext->GetNames() as $sContextParam)
  319. {
  320. eval("\$sParamCode = $sClass::MapContextParam('$sContextParam');"); //Map context parameter to the value/filter code depending on the class
  321. if (!is_null($sParamCode))
  322. {
  323. $sParamValue = $oAppContext->GetCurrentValue($sContextParam, null);
  324. if (!is_null($sParamValue))
  325. {
  326. $aExtraParams[$sParamCode] = $sParamValue;
  327. }
  328. }
  329. }
  330. foreach($aFilterCodes as $sFilterCode)
  331. {
  332. $sExternalFilterValue = utils::ReadParam($sFilterCode, '');
  333. $condition = null;
  334. if (isset($aExtraParams[$sFilterCode]))
  335. {
  336. $condition = $aExtraParams[$sFilterCode];
  337. }
  338. // else if ($bDoSearch && $sExternalFilterValue != "")
  339. if ($bDoSearch && $sExternalFilterValue != "")
  340. {
  341. // Search takes precedence over context params...
  342. unset($aExtraParams[$sFilterCode]);
  343. $condition = trim($sExternalFilterValue);
  344. }
  345. if (!is_null($condition))
  346. {
  347. $this->m_oFilter->AddCondition($sFilterCode, $condition); // Use the default 'loose' operator
  348. }
  349. }
  350. }
  351. $this->m_oSet = new CMDBObjectSet($this->m_oFilter, array(), $aQueryParams);
  352. }
  353. switch($this->m_sStyle)
  354. {
  355. case 'count':
  356. if (isset($aExtraParams['group_by']))
  357. {
  358. $sGroupByField = $aExtraParams['group_by'];
  359. $aGroupBy = array();
  360. $sLabels = array();
  361. while($oObj = $this->m_oSet->Fetch())
  362. {
  363. $sValue = $oObj->Get($sGroupByField);
  364. $aGroupBy[$sValue] = isset($aGroupBy[$sValue]) ? $aGroupBy[$sValue]+1 : 1;
  365. $sLabels[$sValue] = $oObj->GetAsHtml($sGroupByField);
  366. }
  367. $sFilter = urlencode($this->m_oFilter->serialize());
  368. $aData = array();
  369. $oAppContext = new ApplicationContext();
  370. $sParams = $oAppContext->GetForLink();
  371. foreach($aGroupBy as $sValue => $iCount)
  372. {
  373. $aData[] = array ( 'group' => $sLabels[$sValue],
  374. 'value' => "<a href=\"./UI.php?operation=search&dosearch=1&$sParams&filter=$sFilter&$sGroupByField=".urlencode($sValue)."\">$iCount</a>"); // TO DO: add the context information
  375. }
  376. $aAttribs =array(
  377. 'group' => array('label' => MetaModel::GetLabel($this->m_oFilter->GetClass(), $sGroupByField), 'description' => ''),
  378. 'value' => array('label'=> Dict::S('UI:GroupBy:Count'), 'description' => Dict::S('UI:GroupBy:Count+'))
  379. );
  380. $sHtml .= $oPage->GetTable($aAttribs, $aData);
  381. }
  382. else
  383. {
  384. // Simply count the number of elements in the set
  385. $iCount = $this->m_oSet->Count();
  386. $sFormat = 'UI:CountOfObjects';
  387. if (isset($aExtraParams['format']))
  388. {
  389. $sFormat = $aExtraParams['format'];
  390. }
  391. $sHtml .= $oPage->GetP(Dict::Format($sFormat, $iCount));
  392. }
  393. break;
  394. case 'join':
  395. $aDisplayAliases = isset($aExtraParams['display_aliases']) ? explode(',', $aExtraParams['display_aliases']): array();
  396. if (!isset($aExtraParams['group_by']))
  397. {
  398. $sHtml .= $oPage->GetP(Dict::S('UI:Error:MandatoryTemplateParameter_group_by'));
  399. }
  400. else
  401. {
  402. $aGroupByFields = array();
  403. $aGroupBy = explode(',', $aExtraParams['group_by']);
  404. foreach($aGroupBy as $sGroupBy)
  405. {
  406. $aMatches = array();
  407. if (preg_match('/^(.+)\.(.+)$/', $sGroupBy, $aMatches) > 0)
  408. {
  409. $aGroupByFields[] = array('alias' => $aMatches[1], 'att_code' => $aMatches[2]);
  410. }
  411. }
  412. if (count($aGroupByFields) == 0)
  413. {
  414. $sHtml .= $oPage->GetP(Dict::Format('UI:Error:InvalidGroupByFields', $aExtraParams['group_by']));
  415. }
  416. else
  417. {
  418. $aResults = array();
  419. $aCriteria = array();
  420. while($aObjects = $this->m_oSet->FetchAssoc())
  421. {
  422. $aKeys = array();
  423. foreach($aGroupByFields as $aField)
  424. {
  425. $sAlias = $aField['alias'];
  426. if (is_null($aObjects[$sAlias]))
  427. {
  428. $aKeys[$sAlias.'.'.$aField['att_code']] = '';
  429. }
  430. else
  431. {
  432. $aKeys[$sAlias.'.'.$aField['att_code']] = $aObjects[$sAlias]->Get($aField['att_code']);
  433. }
  434. }
  435. $sCategory = implode($aKeys, ' ');
  436. $aResults[$sCategory][] = $aObjects;
  437. $aCriteria[$sCategory] = $aKeys;
  438. }
  439. $sHtml .= "<table>\n";
  440. // Construct a new (parametric) query that will return the content of this block
  441. $oBlockFilter = clone $this->m_oFilter;
  442. $aExpressions = array();
  443. $index = 0;
  444. foreach($aGroupByFields as $aField)
  445. {
  446. $aExpressions[] = '`'.$aField['alias'].'`.`'.$aField['att_code'].'` = :param'.$index++;
  447. }
  448. $sExpression = implode(' AND ', $aExpressions);
  449. $oExpression = Expression::FromOQL($sExpression);
  450. $oBlockFilter->AddConditionExpression($oExpression);
  451. $aExtraParams['menu'] = false;
  452. foreach($aResults as $sCategory => $aObjects)
  453. {
  454. $sHtml .= "<tr><td><h1>$sCategory</h1></td></tr>\n";
  455. if (count($aDisplayAliases) == 1)
  456. {
  457. $aSimpleArray = array();
  458. foreach($aObjects as $aRow)
  459. {
  460. $oObj = $aRow[$aDisplayAliases[0]];
  461. if (!is_null($oObj))
  462. {
  463. $aSimpleArray[] = $oObj;
  464. }
  465. }
  466. $oSet = CMDBObjectSet::FromArray($this->m_oFilter->GetClass(), $aSimpleArray);
  467. $sHtml .= "<tr><td>".cmdbAbstractObject::GetDisplaySet($oPage, $oSet, $aExtraParams)."</td></tr>\n";
  468. }
  469. else
  470. {
  471. $index = 0;
  472. $aArgs = array();
  473. foreach($aGroupByFields as $aField)
  474. {
  475. $aArgs['param'.$index] = $aCriteria[$sCategory][$aField['alias'].'.'.$aField['att_code']];
  476. $index++;
  477. }
  478. $oSet = new CMDBObjectSet($oBlockFilter, array(), $aArgs);
  479. $sHtml .= "<tr><td>".cmdbAbstractObject::GetDisplayExtendedSet($oPage, $oSet, $aExtraParams)."</td></tr>\n";
  480. }
  481. }
  482. $sHtml .= "</table>\n";
  483. }
  484. }
  485. break;
  486. case 'list':
  487. $aClasses = $this->m_oSet->GetSelectedClasses();
  488. $aAuthorizedClasses = array();
  489. if (count($aClasses) > 1)
  490. {
  491. // Check the classes that can be read (i.e authorized) by this user...
  492. foreach($aClasses as $sAlias => $sClassName)
  493. {
  494. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $this->m_oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  495. {
  496. $aAuthorizedClasses[$sAlias] = $sClassName;
  497. }
  498. }
  499. if (count($aAuthorizedClasses) > 0)
  500. {
  501. if($this->m_oSet->Count() > 0)
  502. {
  503. $sHtml .= cmdbAbstractObject::GetDisplayExtendedSet($oPage, $this->m_oSet, $aExtraParams);
  504. }
  505. else
  506. {
  507. // Empty set
  508. $sHtml .= $oPage->GetP(Dict::S('UI:NoObjectToDisplay'));
  509. }
  510. }
  511. else
  512. {
  513. // Not authorized
  514. $sHtml .= $oPage->GetP(Dict::S('UI:NoObjectToDisplay'));
  515. }
  516. }
  517. else
  518. {
  519. // The list is made of only 1 class of objects, actions on the list are possible
  520. if ( ($this->m_oSet->Count()> 0) && (UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_READ, $this->m_oSet) == UR_ALLOWED_YES) )
  521. {
  522. $sHtml .= cmdbAbstractObject::GetDisplaySet($oPage, $this->m_oSet, $aExtraParams);
  523. }
  524. else
  525. {
  526. $sHtml .= $oPage->GetP(Dict::S('UI:NoObjectToDisplay'));
  527. $sClass = $this->m_oFilter->GetClass();
  528. $bDisplayMenu = isset($aExtraParams['menu']) ? $aExtraParams['menu'] == true : true;
  529. if ($bDisplayMenu)
  530. {
  531. if ((UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES))
  532. {
  533. $oAppContext = new ApplicationContext();
  534. $sParams = $oAppContext->GetForLink();
  535. // 1:n links, populate the target object as a default value when creating a new linked object
  536. if (isset($aExtraParams['target_attr']))
  537. {
  538. $aExtraParams['default'][$aExtraParams['target_attr']] = $aExtraParams['object_id'];
  539. }
  540. $sDefault = '';
  541. if (!empty($aExtraParams['default']))
  542. {
  543. foreach($aExtraParams['default'] as $sKey => $sValue)
  544. {
  545. $sDefault.= "&default[$sKey]=$sValue";
  546. }
  547. }
  548. $sHtml .= $oPage->GetP("<a href=\"./UI.php?operation=new&class=$sClass&$sParams{$sDefault}\">".Dict::Format('UI:ClickToCreateNew', Metamodel::GetName($sClass))."</a>\n");
  549. }
  550. }
  551. }
  552. }
  553. break;
  554. case 'links':
  555. //$bDashboardMode = isset($aExtraParams['dashboard']) ? ($aExtraParams['dashboard'] == 'true') : false;
  556. //$bSelectMode = isset($aExtraParams['select']) ? ($aExtraParams['select'] == 'true') : false;
  557. if ( ($this->m_oSet->Count()> 0) && (UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_READ, $this->m_oSet) == UR_ALLOWED_YES) )
  558. {
  559. //$sLinkage = isset($aExtraParams['linkage']) ? $aExtraParams['linkage'] : '';
  560. $sHtml .= cmdbAbstractObject::GetDisplaySet($oPage, $this->m_oSet, $aExtraParams);
  561. }
  562. else
  563. {
  564. $sClass = $this->m_oFilter->GetClass();
  565. $oAttDef = MetaModel::GetAttributeDef($sClass, $this->m_aParams['target_attr']);
  566. $sTargetClass = $oAttDef->GetTargetClass();
  567. $sHtml .= $oPage->GetP(Dict::Format('UI:NoObject_Class_ToDisplay', MetaModel::GetName($sTargetClass)));
  568. $bDisplayMenu = isset($this->m_aParams['menu']) ? $this->m_aParams['menu'] == true : true;
  569. if ($bDisplayMenu)
  570. {
  571. if ((UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES))
  572. {
  573. $oAppContext = new ApplicationContext();
  574. $sParams = $oAppContext->GetForLink();
  575. $sDefaults = '';
  576. if (isset($this->m_aParams['default']))
  577. {
  578. foreach($this->m_aParams['default'] as $sName => $sValue)
  579. {
  580. $sDefaults .= '&'.urlencode($sName).'='.urlencode($sValue);
  581. }
  582. }
  583. $sHtml .= $oPage->GetP("<a href=\"../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");
  584. }
  585. }
  586. }
  587. break;
  588. case 'details':
  589. while($oObj = $this->m_oSet->Fetch())
  590. {
  591. $sHtml .= $oObj->GetDetails($oPage); // Still used ???
  592. }
  593. break;
  594. case 'actions':
  595. $sClass = $this->m_oFilter->GetClass();
  596. $oAppContext = new ApplicationContext();
  597. $bContextFilter = isset($aExtraParams['context_filter']) ? isset($aExtraParams['context_filter']) != 0 : false;
  598. if ($bContextFilter)
  599. {
  600. $aFilterCodes = array_keys(MetaModel::GetClassFilterDefs($this->m_oFilter->GetClass()));
  601. foreach($oAppContext->GetNames() as $sFilterCode)
  602. {
  603. $sContextParamValue = $oAppContext->GetCurrentValue($sFilterCode, null);
  604. if (!is_null($sContextParamValue) && ! empty($sContextParamValue) && MetaModel::IsValidFilterCode($sClass, $sFilterCode))
  605. {
  606. $this->m_oFilter->AddCondition($sFilterCode, $sContextParamValue); // Use the default 'loose' operator
  607. }
  608. }
  609. $aQueryParams = array();
  610. if (isset($aExtraParams['query_params']))
  611. {
  612. $aQueryParams = $aExtraParams['query_params'];
  613. }
  614. $this->m_oSet = new CMDBObjectSet($this->m_oFilter, array(), $aQueryParams);
  615. }
  616. $iCount = $this->m_oSet->Count();
  617. $sHyperlink = '../pages/UI.php?operation=search&'.$oAppContext->GetForLink().'&filter='.$this->m_oFilter->serialize();
  618. $sHtml .= '<p><a class="actions" href="'.$sHyperlink.'">';
  619. $sHtml .= MetaModel::GetClassIcon($sClass, true, 'float;left;margin-right:10px;');
  620. $sHtml .= MetaModel::GetName($sClass).': '.$iCount.'</a></p>';
  621. $sParams = $oAppContext->GetForLink();
  622. $sHtml .= '<p>';
  623. if (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY))
  624. {
  625. $sHtml .= "<a href=\"../pages/UI.php?operation=new&class={$sClass}&$sParams\">".Dict::Format('UI:ClickToCreateNew', MetaModel::GetName($sClass))."</a><br/>\n";
  626. }
  627. $sHtml .= "<a href=\"../pages/UI.php?operation=search_form&class={$sClass}&$sParams\">".Dict::Format('UI:SearchFor_Class', MetaModel::GetName($sClass))."</a>\n";
  628. $sHtml .= '</p>';
  629. break;
  630. case 'summary':
  631. $sClass = $this->m_oFilter->GetClass();
  632. $oAppContext = new ApplicationContext();
  633. $sTitle = isset($aExtraParams['title[block]']) ? $aExtraParams['title[block]'] : '';
  634. $sLabel = isset($aExtraParams['label[block]']) ? $aExtraParams['label[block]'] : '';
  635. $sStateAttrCode = isset($aExtraParams['status[block]']) ? $aExtraParams['status[block]'] : 'status';
  636. $sStatesList = isset($aExtraParams['status_codes[block]']) ? $aExtraParams['status_codes[block]'] : '';
  637. $bContextFilter = isset($aExtraParams['context_filter']) ? isset($aExtraParams['context_filter']) != 0 : false;
  638. if ($bContextFilter)
  639. {
  640. $aFilterCodes = array_keys(MetaModel::GetClassFilterDefs($this->m_oFilter->GetClass()));
  641. foreach($oAppContext->GetNames() as $sFilterCode)
  642. {
  643. $sContextParamValue = $oAppContext->GetCurrentValue($sFilterCode, null);
  644. if (!is_null($sContextParamValue) && ! empty($sContextParamValue) && MetaModel::IsValidFilterCode($sClass, $sFilterCode))
  645. {
  646. $this->m_oFilter->AddCondition($sFilterCode, $sContextParamValue); // Use the default 'loose' operator
  647. }
  648. }
  649. $aQueryParams = array();
  650. if (isset($aExtraParams['query_params']))
  651. {
  652. $aQueryParams = $aExtraParams['query_params'];
  653. }
  654. $this->m_oSet = new CMDBObjectSet($this->m_oFilter, array(), $aQueryParams);
  655. }
  656. // Summary details
  657. $aCounts = array();
  658. $aStateLabels = array();
  659. if (!empty($sStateAttrCode) && !empty($sStatesList))
  660. {
  661. $aStates = explode(',', $sStatesList);
  662. $oAttDef = MetaModel::GetAttributeDef($sClass, $sStateAttrCode);
  663. foreach($aStates as $sStateValue)
  664. {
  665. $oFilter = clone($this->m_oFilter);
  666. $oFilter->AddCondition($sStateAttrCode, $sStateValue, '=');
  667. $oSet = new DBObjectSet($oFilter);
  668. $aCounts[$sStateValue] = $oSet->Count();
  669. $aStateLabels[$sStateValue] = Dict::S("Class:".$oAttDef->GetHostClass()."/Attribute:$sStateAttrCode/Value:$sStateValue");
  670. if ($aCounts[$sStateValue] == 0)
  671. {
  672. $aCounts[$sStateValue] = '-';
  673. }
  674. else
  675. {
  676. $sHyperlink = '../pages/UI.php?operation=search&'.$oAppContext->GetForLink().'&filter='.$oFilter->serialize();
  677. $aCounts[$sStateValue] = "<a href=\"$sHyperlink\">{$aCounts[$sStateValue]}</a>";
  678. }
  679. }
  680. }
  681. $sHtml .= '<div class="summary-details"><table><tr><th>'.implode('</th><th>', $aStateLabels).'</th></tr>';
  682. $sHtml .= '<tr><td>'.implode('</td><td>', $aCounts).'</td></tr></table></div>';
  683. // Title & summary
  684. $iCount = $this->m_oSet->Count();
  685. $sHyperlink = '../pages/UI.php?operation=search&'.$oAppContext->GetForLink().'&filter='.$this->m_oFilter->serialize();
  686. $sHtml .= '<h1>'.Dict::S(str_replace('_', ':', $sTitle)).'</h1>';
  687. $sHtml .= '<a class="summary" href="'.$sHyperlink.'">'.Dict::Format(str_replace('_', ':', $sLabel), $iCount).'</a>';
  688. break;
  689. case 'bare_details':
  690. while($oObj = $this->m_oSet->Fetch())
  691. {
  692. $sHtml .= $oObj->GetBareProperties($oPage);
  693. }
  694. break;
  695. case 'csv':
  696. $sHtml .= "<textarea style=\"width:95%;height:98%\">\n";
  697. $sHtml .= cmdbAbstractObject::GetSetAsCSV($this->m_oSet);
  698. $sHtml .= "</textarea>\n";
  699. break;
  700. case 'modify':
  701. if ((UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_MODIFY, $this->m_oSet) == UR_ALLOWED_YES))
  702. {
  703. while($oObj = $this->m_oSet->Fetch())
  704. {
  705. $sHtml .= $oObj->GetModifyForm($oPage);
  706. }
  707. }
  708. break;
  709. case 'search':
  710. $sStyle = (isset($aExtraParams['open']) && ($aExtraParams['open'] == 'true')) ? 'SearchDrawer' : 'SearchDrawer DrawerClosed';
  711. $sHtml .= "<div id=\"ds_$sId\" class=\"$sStyle\">\n";
  712. $oPage->add_ready_script(
  713. <<<EOF
  714. $("#dh_$sId").click( function() {
  715. $("#ds_$sId").slideToggle('normal', function() { $("#ds_$sId").parent().resize(); } );
  716. $("#dh_$sId").toggleClass('open');
  717. });
  718. EOF
  719. );
  720. $aExtraParams['currentId'] = $sId;
  721. $sHtml .= cmdbAbstractObject::GetSearchForm($oPage, $this->m_oSet, $aExtraParams);
  722. $sHtml .= "</div>\n";
  723. $sHtml .= "<div class=\"HRDrawer\"></div>\n";
  724. $sHtml .= "<div id=\"dh_$sId\" class=\"DrawerHandle\">".Dict::S('UI:SearchToggle')."</div>\n";
  725. break;
  726. case 'open_flash_chart':
  727. static $iChartCounter = 0;
  728. $sChartType = isset($aExtraParams['chart_type']) ? $aExtraParams['chart_type'] : 'pie';
  729. $sTitle = isset($aExtraParams['chart_title']) ? $aExtraParams['chart_title'] : '';
  730. $sGroupBy = isset($aExtraParams['group_by']) ? $aExtraParams['group_by'] : '';
  731. $sFilter = $this->m_oFilter->serialize();
  732. $sHtml .= "<div id=\"my_chart_{$iChartCounter}\">If the chart does not display, <a href=\"http://get.adobe.com/flash/\" target=\"_blank\">install Flash</a></div>\n";
  733. $oPage->add_script("function ofc_resize(left, width, top, height) { /* do nothing special */ }");
  734. $oPage->add_ready_script("swfobject.embedSWF(\"../images/open-flash-chart.swf\", \"my_chart_{$iChartCounter}\", \"100%\", \"300\",\"9.0.0\", \"expressInstall.swf\",
  735. {\"data-file\":\"".urlencode("../pages/ajax.render.php?operation=open_flash_chart&params[group_by]=$sGroupBy&params[chart_type]=$sChartType&params[chart_title]=$sTitle&filter=".$sFilter)."\"}, {wmode: 'transparent'} );\n");
  736. $iChartCounter++;
  737. break;
  738. case 'open_flash_chart_ajax':
  739. require_once(APPROOT.'/pages/php-ofc-library/open-flash-chart.php');
  740. $sChartType = isset($aExtraParams['chart_type']) ? $aExtraParams['chart_type'] : 'pie';
  741. $oChart = new open_flash_chart();
  742. switch($sChartType)
  743. {
  744. case 'bars':
  745. $oChartElement = new bar_glass();
  746. if (isset($aExtraParams['group_by']))
  747. {
  748. $sGroupByField = $aExtraParams['group_by'];
  749. $aGroupBy = array();
  750. while($oObj = $this->m_oSet->Fetch())
  751. {
  752. $sValue = $oObj->Get($sGroupByField);
  753. $aGroupBy[$sValue] = isset($aGroupBy[$sValue]) ? $aGroupBy[$sValue]+1 : 1;
  754. }
  755. $sFilter = urlencode($this->m_oFilter->serialize());
  756. $aData = array();
  757. $aLabels = array();
  758. foreach($aGroupBy as $sValue => $iValue)
  759. {
  760. $aData[] = $iValue;
  761. $aLabels[] = $sValue;
  762. }
  763. $maxValue = max($aData);
  764. $oYAxis = new y_axis();
  765. $aMagicValues = array(1,2,5,10);
  766. $iMultiplier = 1;
  767. $index = 0;
  768. $iTop = $aMagicValues[$index % count($aMagicValues)]*$iMultiplier;
  769. while($maxValue > $iTop)
  770. {
  771. $index++;
  772. $iTop = $aMagicValues[$index % count($aMagicValues)]*$iMultiplier;
  773. if (($index % count($aMagicValues)) == 0)
  774. {
  775. $iMultiplier = $iMultiplier * 10;
  776. }
  777. }
  778. //echo "oYAxis->set_range(0, $iTop, $iMultiplier);\n";
  779. $oYAxis->set_range(0, $iTop, $iMultiplier);
  780. $oChart->set_y_axis( $oYAxis );
  781. $oChartElement->set_values( $aData );
  782. $oXAxis = new x_axis();
  783. $oXLabels = new x_axis_labels();
  784. // set them vertical
  785. $oXLabels->set_vertical();
  786. // set the label text
  787. $oXLabels->set_labels($aLabels);
  788. // Add the X Axis Labels to the X Axis
  789. $oXAxis->set_labels( $oXLabels );
  790. $oChart->set_x_axis( $oXAxis );
  791. }
  792. break;
  793. case 'pie':
  794. default:
  795. $oChartElement = new pie();
  796. $oChartElement->set_start_angle( 35 );
  797. $oChartElement->set_animate( true );
  798. $oChartElement->set_tooltip( '#label# - #val# (#percent#)' );
  799. $oChartElement->set_colours( array('#FF8A00', '#909980', '#2C2B33', '#CCC08D', '#596664') );
  800. if (isset($aExtraParams['group_by']))
  801. {
  802. $sGroupByField = $aExtraParams['group_by'];
  803. $aGroupBy = array();
  804. while($oObj = $this->m_oSet->Fetch())
  805. {
  806. $sValue = $oObj->Get($sGroupByField);
  807. $aGroupBy[$sValue] = isset($aGroupBy[$sValue]) ? $aGroupBy[$sValue]+1 : 1;
  808. }
  809. $sFilter = urlencode($this->m_oFilter->serialize());
  810. $aData = array();
  811. foreach($aGroupBy as $sValue => $iValue)
  812. {
  813. $aData[] = new pie_value($iValue, $sValue); //@@ BUG: not passed via ajax !!!
  814. }
  815. $oChartElement->set_values( $aData );
  816. $oChart->x_axis = null;
  817. }
  818. }
  819. if (isset($aExtraParams['chart_title']))
  820. {
  821. $oTitle = new title( Dict::S($aExtraParams['chart_title']) );
  822. $oChart->set_title( $oTitle );
  823. }
  824. $oChart->set_bg_colour('#FFFFFF');
  825. $oChart->add_element( $oChartElement );
  826. $sHtml = $oChart->toPrettyString();
  827. break;
  828. default:
  829. // Unsupported style, do nothing.
  830. $sHtml .= Dict::format('UI:Error:UnsupportedStyleOfBlock', $this->m_sStyle);
  831. }
  832. return $sHtml;
  833. }
  834. }
  835. /**
  836. * Helper class to manage 'blocks' of HTML pieces that are parts of a page and contain some list of cmdb objects
  837. *
  838. * Each block is actually rendered as a <div></div> tag that can be rendered synchronously
  839. * or as a piece of Javascript/JQuery/Ajax that will get its content from another page (ajax.render.php).
  840. * The list of cmdbObjects to be displayed into the block is defined by a filter
  841. * Right now the type of display is either: list, count or details
  842. * - list produces a table listing the objects
  843. * - count produces a paragraphs with a sentence saying 'cont' objects found
  844. * - details display (as table) the details of each object found (best if only one)
  845. */
  846. class HistoryBlock extends DisplayBlock
  847. {
  848. public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId)
  849. {
  850. $sHtml = '';
  851. $oSet = new CMDBObjectSet($this->m_oFilter, array('date'=>false));
  852. $sHtml .= "<!-- filter: ".($this->m_oFilter->ToOQL())."-->\n";
  853. switch($this->m_sStyle)
  854. {
  855. case 'toggle':
  856. // First the latest change that the user is allowed to see
  857. do
  858. {
  859. $oLatestChangeOp = $oSet->Fetch();
  860. }
  861. while(is_object($oLatestChangeOp) && ($oLatestChangeOp->GetDescription() == ''));
  862. if (is_object($oLatestChangeOp))
  863. {
  864. // There is one change in the list... only when the object has been created !
  865. $sDate = $oLatestChangeOp->GetAsHTML('date');
  866. $oChange = MetaModel::GetObject('CMDBChange', $oLatestChangeOp->Get('change'));
  867. $sUserInfo = $oChange->GetAsHTML('userinfo');
  868. $sHtml .= $oPage->GetStartCollapsibleSection(Dict::Format('UI:History:LastModified_On_By', $sDate, $sUserInfo));
  869. $sHtml .= $this->GetHistoryTable($oPage, $oSet);
  870. $sHtml .= $oPage->GetEndCollapsibleSection();
  871. }
  872. break;
  873. case 'table':
  874. default:
  875. $sHtml .= $this->GetHistoryTable($oPage, $oSet);
  876. }
  877. return $sHtml;
  878. }
  879. protected function GetHistoryTable(WebPage $oPage, DBObjectSet $oSet)
  880. {
  881. $sHtml = '';
  882. // First the latest change that the user is allowed to see
  883. $oSet->Rewind(); // Reset the pointer to the beginning of the set
  884. $aChanges = array();
  885. while($oChangeOp = $oSet->Fetch())
  886. {
  887. $sChangeDescription = $oChangeOp->GetDescription();
  888. if ($sChangeDescription != '')
  889. {
  890. // The change is visible for the current user
  891. $changeId = $oChangeOp->Get('change');
  892. $aChanges[$changeId]['date'] = $oChangeOp->Get('date');
  893. $aChanges[$changeId]['userinfo'] = $oChangeOp->Get('userinfo');
  894. if (!isset($aChanges[$changeId]['log']))
  895. {
  896. $aChanges[$changeId]['log'] = array();
  897. }
  898. $aChanges[$changeId]['log'][] = $sChangeDescription;
  899. }
  900. }
  901. $aAttribs = array('date' => array('label' => Dict::S('UI:History:Date'), 'description' => Dict::S('UI:History:Date+')),
  902. 'userinfo' => array('label' => Dict::S('UI:History:User'), 'description' => Dict::S('UI:History:User+')),
  903. 'log' => array('label' => Dict::S('UI:History:Changes'), 'description' => Dict::S('UI:History:Changes+')),
  904. );
  905. $aValues = array();
  906. foreach($aChanges as $aChange)
  907. {
  908. $aValues[] = array('date' => $aChange['date'], 'userinfo' => $aChange['userinfo'], 'log' => "<ul><li>".implode('</li><li>', $aChange['log'])."</li></ul>");
  909. }
  910. $sHtml .= $oPage->GetTable($aAttribs, $aValues);
  911. return $sHtml;
  912. }
  913. }
  914. class MenuBlock extends DisplayBlock
  915. {
  916. /**
  917. * Renders the "Actions" popup menu for the given set of objects
  918. *
  919. * Note that the menu links containing (or ending) with a hash (#) will have their fragment
  920. * part (whatever is after the hash) dynamically replaced (by javascript) when the menu is
  921. * displayed, to correspond to the current hash/fragment in the page. This allows modifying
  922. * an object in with the same tab active by default as the tab that was active when selecting
  923. * the "Modify..." action.
  924. */
  925. public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId)
  926. {
  927. $sHtml = '';
  928. $oAppContext = new ApplicationContext();
  929. $sContext = $oAppContext->GetForLink();
  930. $sClass = $this->m_oFilter->GetClass();
  931. $oSet = new CMDBObjectSet($this->m_oFilter);
  932. $sFilter = $this->m_oFilter->serialize();
  933. $aActions = array();
  934. $sUIPage = cmdbAbstractObject::ComputeUIPage($sClass);
  935. // 1:n links, populate the target object as a default value when creating a new linked object
  936. if (isset($aExtraParams['target_attr']))
  937. {
  938. $aExtraParams['default'][$aExtraParams['target_attr']] = $aExtraParams['object_id'];
  939. }
  940. $sDefault = '';
  941. if (!empty($aExtraParams['default']))
  942. {
  943. foreach($aExtraParams['default'] as $sKey => $sValue)
  944. {
  945. $sDefault.= "&default[$sKey]=$sValue";
  946. }
  947. }
  948. switch($oSet->Count())
  949. {
  950. case 0:
  951. // No object in the set, the only possible action is "new"
  952. $bIsModifyAllowed = (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES);
  953. if ($bIsModifyAllowed) { $aActions[] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "../page/$sUIPage?operation=new&class=$sClass&$sContext{$sDefault}"); }
  954. break;
  955. case 1:
  956. $oObj = $oSet->Fetch();
  957. $id = $oObj->GetKey();
  958. $bIsModifyAllowed = (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet) == UR_ALLOWED_YES);
  959. $bIsDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, $oSet);
  960. $bIsBulkModifyAllowed = (!MetaModel::IsAbstract($sClass)) && UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_MODIFY, $oSet);
  961. $bIsBulkDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_DELETE, $oSet);
  962. // Just one object in the set, possible actions are "new / clone / modify and delete"
  963. if (!isset($aExtraParams['link_attr']))
  964. {
  965. $sUrl = utils::GetAbsoluteUrl(false);
  966. if ($bIsModifyAllowed) { $aActions[] = array ('label' => Dict::S('UI:Menu:Modify'), 'url' => "../pages/$sUIPage?operation=modify&class=$sClass&id=$id&$sContext#"); }
  967. if ($bIsModifyAllowed) { $aActions[] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "../pages/$sUIPage?operation=new&class=$sClass&$sContext{$sDefault}"); }
  968. if ($bIsDeleteAllowed) { $aActions[] = array ('label' => Dict::S('UI:Menu:Delete'), 'url' => "../pages/$sUIPage?operation=delete&class=$sClass&id=$id&$sContext"); }
  969. // Transitions / Stimuli
  970. $aTransitions = $oObj->EnumTransitions();
  971. if (count($aTransitions))
  972. {
  973. $this->AddMenuSeparator($aActions);
  974. $aStimuli = Metamodel::EnumStimuli($sClass);
  975. foreach($aTransitions as $sStimulusCode => $aTransitionDef)
  976. {
  977. $iActionAllowed = (get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction') ? UserRights::IsStimulusAllowed($sClass, $sStimulusCode, $oSet) : UR_ALLOWED_NO;
  978. switch($iActionAllowed)
  979. {
  980. case UR_ALLOWED_YES:
  981. $aActions[] = array('label' => $aStimuli[$sStimulusCode]->GetLabel(), 'url' => "../pages/UI.php?operation=stimulus&stimulus=$sStimulusCode&class=$sClass&id=$id&$sContext");
  982. break;
  983. default:
  984. // Do nothing
  985. }
  986. }
  987. }
  988. // Relations...
  989. $aRelations = MetaModel::EnumRelations($sClass);
  990. if (count($aRelations))
  991. {
  992. $this->AddMenuSeparator($aActions);
  993. foreach($aRelations as $sRelationCode)
  994. {
  995. $aActions[] = array ('label' => MetaModel::GetRelationVerbUp($sRelationCode), 'url' => "../pages/$sUIPage?operation=swf_navigator&relation=$sRelationCode&class=$sClass&id=$id&$sContext");
  996. }
  997. }
  998. $this->AddMenuSeparator($aActions);
  999. // Static menus: Email this page & CSV Export
  1000. $aActions[] = array ('label' => Dict::S('UI:Menu:EMail'), 'url' => "mailto:?subject=".$oObj->GetName()."&body=".urlencode("$sUrl?operation=details&class=$sClass&id=$id&$sContext"));
  1001. $aActions[] = array ('label' => Dict::S('UI:Menu:CSVExport'), 'url' => "../pages/$sUIPage?operation=search&filter=$sFilter&format=csv&$sContext");
  1002. }
  1003. else
  1004. {
  1005. // List of links, the only actions are 'Add...' and 'Manage...'
  1006. $id = $aExtraParams['object_id'];
  1007. $sTargetAttr = $aExtraParams['target_attr'];
  1008. $oAttDef = MetaModel::GetAttributeDef($sClass, $sTargetAttr);
  1009. $sTargetClass = $oAttDef->GetTargetClass();
  1010. if ($bIsModifyAllowed) { $aActions[] = array ('label' => Dict::S('UI:Menu:Add'), 'url' => "../pages/$sUIPage?operation=modify_links&class=$sClass&link_attr=".$aExtraParams['link_attr']."&target_class=$sTargetClass&id=$id&addObjects=true&$sContext"); }
  1011. if ($bIsModifyAllowed) { $aActions[] = array ('label' => Dict::S('UI:Menu:Manage'), 'url' => "../pages/$sUIPage?operation=modify_links&class=$sClass&link_attr=".$aExtraParams['link_attr']."&target_class=$sTargetClass&id=$id&sContext"); }
  1012. }
  1013. $this->AddMenuSeparator($aActions);
  1014. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  1015. {
  1016. $oSet->Rewind();
  1017. foreach($oExtensionInstance->EnumAllowedActions($oSet) as $sLabel => $sUrl)
  1018. {
  1019. $aActions[] = array ('label' => $sLabel, 'url' => $sUrl);
  1020. }
  1021. }
  1022. break;
  1023. default:
  1024. // Check rights
  1025. // New / Modify
  1026. $bIsModifyAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet);
  1027. $bIsBulkModifyAllowed = (!MetaModel::IsAbstract($sClass)) && UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_MODIFY, $oSet);
  1028. $bIsBulkDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_DELETE, $oSet);
  1029. if (isset($aExtraParams['link_attr']))
  1030. {
  1031. $id = $aExtraParams['object_id'];
  1032. $sTargetAttr = $aExtraParams['target_attr'];
  1033. $oAttDef = MetaModel::GetAttributeDef($sClass, $sTargetAttr);
  1034. $sTargetClass = $oAttDef->GetTargetClass();
  1035. $bIsDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, $oSet);
  1036. if ($bIsModifyAllowed) { $aActions[] = array ('label' => Dict::S('UI:Menu:Add'), 'url' => "../pages/$sUIPage?operation=modify_links&class=$sClass&link_attr=".$aExtraParams['link_attr']."&target_class=$sTargetClass&id=$id&addObjects=true&$sContext"); }
  1037. if ($bIsBulkModifyAllowed) { $aActions[] = array ('label' => Dict::S('UI:Menu:Manage'), 'url' => "../pages/$sUIPage?operation=modify_links&class=$sClass&link_attr=".$aExtraParams['link_attr']."&target_class=$sTargetClass&id=$id&sContext"); }
  1038. //if ($bIsBulkDeleteAllowed) { $aActions[] = array ('label' => 'Remove All...', 'url' => "#"); }
  1039. }
  1040. else
  1041. {
  1042. // many objects in the set, possible actions are: new / modify all / delete all
  1043. $sUrl = utils::GetAbsoluteUrl();
  1044. if ($bIsModifyAllowed) { $aActions[] = array ('label' => Dict::S('UI:Menu:New'), 'url' => "../pages/$sUIPage?operation=new&class=$sClass&$sContext{$sDefault}"); }
  1045. //if ($bIsBulkModifyAllowed) { $aActions[] = array ('label' => 'Modify All...', 'url' => "../pages/$sUIPage?operation=modify_all&filter=$sFilter&$sContext"); }
  1046. if ($bIsBulkDeleteAllowed) { $aActions[] = array ('label' => Dict::S('UI:Menu:BulkDelete'), 'url' => "../pages/$sUIPage?operation=select_for_deletion&filter=$sFilter&$sContext"); }
  1047. $this->AddMenuSeparator($aActions);
  1048. $aActions[] = array ('label' => Dict::S('UI:Menu:EMail'), 'url' => "mailto:?subject=".$oSet->GetFilter()->__DescribeHTML()."&body=".urlencode("$sUrl?operation=search&filter=$sFilter&$sContext"));
  1049. $aActions[] = array ('label' => Dict::S('UI:Menu:CSVExport'), 'url' => "../pages/$sUIPage?operation=search&filter=$sFilter&format=csv&$sContext");
  1050. }
  1051. $this->AddMenuSeparator($aActions);
  1052. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  1053. {
  1054. $oSet->Rewind();
  1055. foreach($oExtensionInstance->EnumAllowedActions($oSet) as $sLabel => $sUrl)
  1056. {
  1057. $aActions[] = array ('label' => $sLabel, 'url' => $sUrl);
  1058. }
  1059. }
  1060. }
  1061. $sHtml .= "<div class=\"itop_popup\"><ul>\n<li>".Dict::S('UI:Menu:Actions')."\n<ul>\n";
  1062. foreach ($aActions as $aAction)
  1063. {
  1064. $sClass = isset($aAction['class']) ? " class=\"{$aAction['class']}\"" : "";
  1065. if (empty($aAction['url']))
  1066. {
  1067. $sHtml .= "<li>{$aAction['label']}</li>\n";
  1068. }
  1069. else
  1070. {
  1071. $sHtml .= "<li><a href=\"{$aAction['url']}\"$sClass>{$aAction['label']}</a></li>\n";
  1072. }
  1073. }
  1074. $sHtml .= "</ul>\n</li>\n</ul></div>\n";
  1075. static $bPopupScript = false;
  1076. if (!$bPopupScript)
  1077. {
  1078. // Output this once per page...
  1079. $oPage->add_ready_script("$(\"div.itop_popup>ul\").popupmenu();\n");
  1080. $bPopupScript = true;
  1081. }
  1082. return $sHtml;
  1083. }
  1084. /**
  1085. * Appends a menu separator to the current list of actions
  1086. * @param Hash $aActions The current actions list
  1087. * @return void
  1088. */
  1089. protected function AddMenuSeparator(&$aActions)
  1090. {
  1091. $sSeparator = '<hr class="menu-separator"/>';
  1092. if (count($aActions) > 0) // Make sure that the separator is not the first item in the menu
  1093. {
  1094. if ($aActions[count($aActions)-1]['label'] != $sSeparator) // Make sure there are no 2 consecutive separators
  1095. {
  1096. $aActions[] = array('label' => $sSeparator, 'url' => '');
  1097. }
  1098. }
  1099. }
  1100. }
  1101. ?>