displayblock.class.inc.php 42 KB

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