displayblock.class.inc.php 43 KB

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