webpage.class.inc.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. <?php
  2. // Copyright (C) 2010-2012 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Class WebPage
  20. *
  21. * @copyright Copyright (C) 2010-2012 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. /**
  25. * Generic interface common to CLI and Web pages
  26. */
  27. Interface Page
  28. {
  29. public function output();
  30. public function add($sText);
  31. public function p($sText);
  32. public function pre($sText);
  33. public function add_comment($sText);
  34. public function table($aConfig, $aData, $aParams = array());
  35. }
  36. /**
  37. * Simple helper class to ease the production of HTML pages
  38. *
  39. * This class provide methods to add content, scripts, includes... to a web page
  40. * and renders the full web page by putting the elements in the proper place & order
  41. * when the output() method is called.
  42. * Usage:
  43. * $oPage = new WebPage("Title of my page");
  44. * $oPage->p("Hello World !");
  45. * $oPage->output();
  46. */
  47. class WebPage implements Page
  48. {
  49. protected $s_title;
  50. protected $s_content;
  51. protected $s_deferred_content;
  52. protected $a_scripts;
  53. protected $a_styles;
  54. protected $a_include_scripts;
  55. protected $a_include_stylesheets;
  56. protected $a_headers;
  57. protected $a_base;
  58. protected $iNextId;
  59. protected $iTransactionId;
  60. protected $sContentType;
  61. protected $sContentDisposition;
  62. protected $sContentFileName;
  63. protected $s_sOutputFormat;
  64. protected $a_OutputOptions;
  65. public function __construct($s_title)
  66. {
  67. $this->s_title = $s_title;
  68. $this->s_content = "";
  69. $this->s_deferred_content = '';
  70. $this->a_scripts = array();
  71. $this->a_styles = array();
  72. $this->a_linked_scripts = array();
  73. $this->a_linked_stylesheets = array();
  74. $this->a_headers = array();
  75. $this->a_base = array( 'href' => '', 'target' => '');
  76. $this->iNextId = 0;
  77. $this->iTransactionId = 0;
  78. $this->sContentType = '';
  79. $this->sContentDisposition = '';
  80. $this->sContentFileName = '';
  81. $this->s_OutputFormat = utils::ReadParam('output_format', 'html');
  82. $this->a_OutputOptions = array();
  83. ob_start(); // Start capturing the output
  84. }
  85. /**
  86. * Change the title of the page after its creation
  87. */
  88. public function set_title($s_title)
  89. {
  90. $this->s_title = $s_title;
  91. }
  92. /**
  93. * Specify a default URL and a default target for all links on a page
  94. */
  95. public function set_base($s_href = '', $s_target = '')
  96. {
  97. $this->a_base['href'] = $s_href;
  98. $this->a_base['target'] = $s_target;
  99. }
  100. /**
  101. * Add any text or HTML fragment to the body of the page
  102. */
  103. public function add($s_html)
  104. {
  105. $this->s_content .= $s_html;
  106. }
  107. /**
  108. * Add any text or HTML fragment (identified by an ID) at the end of the body of the page
  109. * This is useful to add hidden content, DIVs or FORMs that should not
  110. * be embedded into each other.
  111. */
  112. public function add_at_the_end($s_html, $sId = '')
  113. {
  114. $this->s_deferred_content .= $s_html;
  115. }
  116. /**
  117. * Add a paragraph to the body of the page
  118. */
  119. public function p($s_html)
  120. {
  121. $this->add($this->GetP($s_html));
  122. }
  123. /**
  124. * Add a pre-formatted text to the body of the page
  125. */
  126. public function pre($s_html)
  127. {
  128. $this->add('<pre>'.$s_html.'</pre>');
  129. }
  130. /**
  131. * Add a comment
  132. */
  133. public function add_comment($sText)
  134. {
  135. $this->add('<!--'.$sText.'-->');
  136. }
  137. /**
  138. * Add a paragraph to the body of the page
  139. */
  140. public function GetP($s_html)
  141. {
  142. return "<p>$s_html</p>\n";
  143. }
  144. /**
  145. * Adds a tabular content to the web page
  146. * @param Hash $aConfig Configuration of the table: hash array of 'column_id' => 'Column Label'
  147. * @param Hash $aData Hash array. Data to display in the table: each row is made of 'column_id' => Data. A column 'pkey' is expected for each row
  148. * @param Hash $aParams Hash array. Extra parameters for the table.
  149. * @return void
  150. */
  151. public function table($aConfig, $aData, $aParams = array())
  152. {
  153. $this->add($this->GetTable($aConfig, $aData, $aParams));
  154. }
  155. public function GetTable($aConfig, $aData, $aParams = array())
  156. {
  157. $oAppContext = new ApplicationContext();
  158. static $iNbTables = 0;
  159. $iNbTables++;
  160. $sHtml = "";
  161. $sHtml .= "<table class=\"listResults\">\n";
  162. $sHtml .= "<thead>\n";
  163. $sHtml .= "<tr>\n";
  164. foreach($aConfig as $sName=>$aDef)
  165. {
  166. $sHtml .= "<th title=\"".$aDef['description']."\">".$aDef['label']."</th>\n";
  167. }
  168. $sHtml .= "</tr>\n";
  169. $sHtml .= "</thead>\n";
  170. $sHtml .= "<tbody>\n";
  171. foreach($aData as $aRow)
  172. {
  173. $sHtml .= $this->GetTableRow($aRow, $aConfig);
  174. }
  175. $sHtml .= "</tbody>\n";
  176. $sHtml .= "</table>\n";
  177. return $sHtml;
  178. }
  179. public function GetTableRow($aRow, $aConfig)
  180. {
  181. $sHtml = '';
  182. if (isset($aRow['@class'])) // Row specific class, for hilighting certain rows
  183. {
  184. $sHtml .= "<tr class=\"{$aRow['@class']}\">";
  185. }
  186. else
  187. {
  188. $sHtml .= "<tr>";
  189. }
  190. foreach($aConfig as $sName=>$aAttribs)
  191. {
  192. $sClass = isset($aAttribs['class']) ? 'class="'.$aAttribs['class'].'"' : '';
  193. $sValue = ($aRow[$sName] === '') ? '&nbsp;' : $aRow[$sName];
  194. $sHtml .= "<td $sClass>$sValue</td>";
  195. }
  196. $sHtml .= "</tr>";
  197. return $sHtml;
  198. }
  199. /**
  200. * Add some Javascript to the header of the page
  201. */
  202. public function add_script($s_script)
  203. {
  204. $this->a_scripts[] = $s_script;
  205. }
  206. /**
  207. * Add some Javascript to the header of the page
  208. */
  209. public function add_ready_script($s_script)
  210. {
  211. // Do nothing silently... this is not supported by this type of page...
  212. }
  213. /**
  214. * Add some CSS definitions to the header of the page
  215. */
  216. public function add_style($s_style)
  217. {
  218. $this->a_styles[] = $s_style;
  219. }
  220. /**
  221. * Add a script (as an include, i.e. link) to the header of the page
  222. */
  223. public function add_linked_script($s_linked_script)
  224. {
  225. $this->a_linked_scripts[$s_linked_script] = $s_linked_script;
  226. }
  227. /**
  228. * Add a CSS stylesheet (as an include, i.e. link) to the header of the page
  229. */
  230. public function add_linked_stylesheet($s_linked_stylesheet, $s_condition = "")
  231. {
  232. $this->a_linked_stylesheets[] = array( 'link' => $s_linked_stylesheet, 'condition' => $s_condition);
  233. }
  234. /**
  235. * Add some custom header to the page
  236. */
  237. public function add_header($s_header)
  238. {
  239. $this->a_headers[] = $s_header;
  240. }
  241. /**
  242. * Add needed headers to the page so that it will no be cached
  243. */
  244. public function no_cache()
  245. {
  246. $this->add_header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
  247. $this->add_header("Expires: Fri, 17 Jul 1970 05:00:00 GMT"); // Date in the past
  248. }
  249. /**
  250. * Build a special kind of TABLE useful for displaying the details of an object from a hash array of data
  251. */
  252. public function details($aFields)
  253. {
  254. $this->add($this->GetDetails($aFields));
  255. }
  256. /**
  257. * Records the current state of the 'html' part of the page output
  258. * @return mixed The current state of the 'html' output
  259. */
  260. public function start_capture()
  261. {
  262. return strlen($this->s_content);
  263. }
  264. /**
  265. * Returns the part of the html output that occurred since the call to start_capture
  266. * and removes this part from the current html output
  267. * @param $offset mixed The value returned by start_capture
  268. * @return string The part of the html output that was added since the call to start_capture
  269. */
  270. public function end_capture($offset)
  271. {
  272. $sCaptured = substr($this->s_content, $offset);
  273. $this->s_content = substr($this->s_content, 0, $offset);
  274. return $sCaptured;
  275. }
  276. /**
  277. * Build a special kind of TABLE useful for displaying the details of an object from a hash array of data
  278. */
  279. public function GetDetails($aFields)
  280. {
  281. $sHtml = "<table class=\"details\">\n";
  282. $sHtml .= "<tbody>\n";
  283. foreach($aFields as $aAttrib)
  284. {
  285. $sHtml .= "<tr>\n";
  286. // By Rom, for csv import, proposed to show several values for column selection
  287. if (is_array($aAttrib['value']))
  288. {
  289. $sHtml .= "<td class=\"label\">".$aAttrib['label']."</td><td>".implode("</td><td>", $aAttrib['value'])."</td>\n";
  290. }
  291. else
  292. {
  293. $sHtml .= "<td class=\"label\">".$aAttrib['label']."</td><td>".$aAttrib['value']."</td>\n";
  294. }
  295. $sComment = (isset($aAttrib['comments'])) ? $aAttrib['comments'] : '&nbsp;';
  296. $sInfo = (isset($aAttrib['infos'])) ? $aAttrib['infos'] : '&nbsp;';
  297. $sHtml .= "<td>$sComment</td><td>$sInfo</td>\n";
  298. $sHtml .= "</tr>\n";
  299. }
  300. $sHtml .= "</tbody>\n";
  301. $sHtml .= "</table>\n";
  302. return $sHtml;
  303. }
  304. /**
  305. * Build a set of radio buttons suitable for editing a field/attribute of an object (including its validation)
  306. * @param $aAllowedValues hash Array of value => display_value
  307. * @param $value mixed Current value for the field/attribute
  308. * @param $iId mixed Unique Id for the input control in the page
  309. * @param $sFieldName string The name of the field, attr_<$sFieldName> will hold the value for the field
  310. * @param $bMandatory bool Whether or not the field is mandatory
  311. * @param $bVertical bool Disposition of the radio buttons vertical or horizontal
  312. * @param $sValidationField string HTML fragment holding the validation field (exclamation icon...)
  313. * @return string The HTML fragment corresponding to the radio buttons
  314. */
  315. public function GetRadioButtons($aAllowedValues, $value, $iId, $sFieldName, $bMandatory, $bVertical, $sValidationField)
  316. {
  317. $idx = 0;
  318. $sHTMLValue = '';
  319. foreach($aAllowedValues as $key => $display_value)
  320. {
  321. if ((count($aAllowedValues) == 1) && ($bMandatory == 'true') )
  322. {
  323. // When there is only once choice, select it by default
  324. $sSelected = ' checked';
  325. }
  326. else
  327. {
  328. $sSelected = ($value == $key) ? ' checked' : '';
  329. }
  330. $sHTMLValue .= "<input type=\"radio\" id=\"{$iId}_{$key}\" name=\"radio_$sFieldName\" onChange=\"$('#{$iId}').val(this.value).trigger('change');\" value=\"$key\"$sSelected><label class=\"radio\" for=\"{$iId}_{$key}\">&nbsp;$display_value</label>&nbsp;";
  331. if ($bVertical)
  332. {
  333. if ($idx == 0)
  334. {
  335. // Validation icon at the end of the first line
  336. $sHTMLValue .= "&nbsp;{$sValidationField}\n";
  337. }
  338. $sHTMLValue .= "<br>\n";
  339. }
  340. $idx++;
  341. }
  342. $sHTMLValue .= "<input type=\"hidden\" id=\"$iId\" name=\"$sFieldName\" value=\"$value\"/>";
  343. if (!$bVertical)
  344. {
  345. // Validation icon at the end of the line
  346. $sHTMLValue .= "&nbsp;{$sValidationField}\n";
  347. }
  348. return $sHTMLValue;
  349. }
  350. /**
  351. * Discard unexpected output data
  352. * This is a MUST when the Page output is DATA (download of a document, download CSV export, download ...)
  353. */
  354. public function TrashUnexpectedOutput()
  355. {
  356. // This protection is redundant with a protection implemented in MetaModel::IncludeModule
  357. // which detects such issues while loading module files
  358. // Here, the purpose is to detect and discard characters produced by the code execution (echo)
  359. $sPreviousContent = ob_get_clean();
  360. if (trim($sPreviousContent) != '')
  361. {
  362. if (Utils::GetConfig() && Utils::GetConfig()->Get('debug_report_spurious_chars'))
  363. {
  364. IssueLog::Error("Output already started before downloading file:\nContent was:'$sPreviousContent'\n");
  365. }
  366. }
  367. }
  368. /**
  369. * Outputs (via some echo) the complete HTML page by assembling all its elements
  370. */
  371. public function output()
  372. {
  373. foreach($this->a_headers as $s_header)
  374. {
  375. header($s_header);
  376. }
  377. $s_captured_output = ob_get_contents();
  378. ob_end_clean();
  379. echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
  380. echo "<html>\n";
  381. echo "<head>\n";
  382. echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n";
  383. echo "<title>".htmlentities($this->s_title, ENT_QUOTES, 'UTF-8')."</title>\n";
  384. echo $this->get_base_tag();
  385. foreach($this->a_linked_scripts as $s_script)
  386. {
  387. // Make sure that the URL to the script contains the application's version number
  388. // so that the new script do NOT get reloaded from the cache when the application is upgraded
  389. if (strpos($s_script, '?') === false)
  390. {
  391. $s_script .= "?itopversion=".ITOP_VERSION;
  392. }
  393. else
  394. {
  395. $s_script .= "&itopversion=".ITOP_VERSION;
  396. }
  397. echo "<script type=\"text/javascript\" src=\"$s_script\"></script>\n";
  398. }
  399. if (count($this->a_scripts)>0)
  400. {
  401. echo "<script type=\"text/javascript\">\n";
  402. foreach($this->a_scripts as $s_script)
  403. {
  404. echo "$s_script\n";
  405. }
  406. echo "</script>\n";
  407. }
  408. foreach($this->a_linked_stylesheets as $a_stylesheet)
  409. {
  410. if ($a_stylesheet['condition'] != "")
  411. {
  412. echo "<!--[if {$a_stylesheet['condition']}]>\n";
  413. }
  414. echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"{$a_stylesheet['link']}\" />\n";
  415. if ($a_stylesheet['condition'] != "")
  416. {
  417. echo "<![endif]-->\n";
  418. }
  419. }
  420. if (count($this->a_styles)>0)
  421. {
  422. echo "<style>\n";
  423. foreach($this->a_styles as $s_style)
  424. {
  425. echo "$s_style\n";
  426. }
  427. echo "</style>\n";
  428. }
  429. if (class_exists('MetaModel') && MetaModel::GetConfig())
  430. {
  431. echo "<link rel=\"shortcut icon\" href=\"".utils::GetAbsoluteUrlAppRoot()."images/favicon.ico\" />\n";
  432. }
  433. echo "</head>\n";
  434. echo "<body>\n";
  435. echo self::FilterXSS($this->s_content);
  436. if (trim($s_captured_output) != "")
  437. {
  438. echo "<div class=\"raw_output\">".self::FilterXSS($s_captured_output)."</div>\n";
  439. }
  440. echo '<div id="at_the_end">'.self::FilterXSS($this->s_deferred_content).'</div>';
  441. echo "</body>\n";
  442. echo "</html>\n";
  443. }
  444. /**
  445. * Build a series of hidden field[s] from an array
  446. */
  447. // By Rom - je verrais bien une serie d'outils pour gerer des parametres que l'on retransmet entre pages d'un wizard...
  448. // ptet deriver webpage en webwizard
  449. public function add_input_hidden($sLabel, $aData)
  450. {
  451. foreach($aData as $sKey=>$sValue)
  452. {
  453. $this->add("<input type=\"hidden\" name=\"".$sLabel."[$sKey]\" value=\"$sValue\">");
  454. }
  455. }
  456. protected function get_base_tag()
  457. {
  458. $sTag = '';
  459. if (($this->a_base['href'] != '') || ($this->a_base['target'] != ''))
  460. {
  461. $sTag = '<base ';
  462. if (($this->a_base['href'] != ''))
  463. {
  464. $sTag .= "href =\"{$this->a_base['href']}\" ";
  465. }
  466. if (($this->a_base['target'] != ''))
  467. {
  468. $sTag .= "target =\"{$this->a_base['target']}\" ";
  469. }
  470. $sTag .= " />\n";
  471. }
  472. return $sTag;
  473. }
  474. /**
  475. * Get an ID (for any kind of HTML tag) that is guaranteed unique in this page
  476. * @return int The unique ID (in this page)
  477. */
  478. public function GetUniqueId()
  479. {
  480. return $this->iNextId++;
  481. }
  482. /**
  483. * Set the content-type (mime type) for the page's content
  484. * @param $sContentType string
  485. * @return void
  486. */
  487. public function SetContentType($sContentType)
  488. {
  489. $this->sContentType = $sContentType;
  490. }
  491. /**
  492. * Set the content-disposition (mime type) for the page's content
  493. * @param $sDisposition string The disposition: 'inline' or 'attachment'
  494. * @param $sFileName string The original name of the file
  495. * @return void
  496. */
  497. public function SetContentDisposition($sDisposition, $sFileName)
  498. {
  499. $this->sContentDisposition = $sDisposition;
  500. $this->sContentFileName = $sFileName;
  501. }
  502. /**
  503. * Set the transactionId of the current form
  504. * @param $iTransactionId integer
  505. * @return void
  506. */
  507. public function SetTransactionId($iTransactionId)
  508. {
  509. $this->iTransactionId = $iTransactionId;
  510. }
  511. /**
  512. * Returns the transactionId of the current form
  513. * @return integer The current transactionID
  514. */
  515. public function GetTransactionId()
  516. {
  517. return $this->iTransactionId;
  518. }
  519. public static function FilterXSS($sHTML)
  520. {
  521. return str_ireplace('<script', '&lt;script', $sHTML);
  522. }
  523. /**
  524. * What is the currently selected output format
  525. * @return string The selected output format: html, pdf...
  526. */
  527. public function GetOutputFormat()
  528. {
  529. return $this->s_OutputFormat;
  530. }
  531. /**
  532. * Check whether the desired output format is possible or not
  533. * @param string $sOutputFormat The desired output format: html, pdf...
  534. * @return bool True if the format is Ok, false otherwise
  535. */
  536. function IsOutputFormatAvailable($sOutputFormat)
  537. {
  538. $bResult = false;
  539. switch($sOutputFormat)
  540. {
  541. case 'html':
  542. $bResult = true; // Always supported
  543. break;
  544. case 'pdf':
  545. $bResult = @is_readable(APPROOT.'lib/MPDF/mpdf.php');
  546. break;
  547. }
  548. return $bResult;
  549. }
  550. /**
  551. * Retrieves the value of a named output option for the given format
  552. * @param string $sFormat The format: html or pdf
  553. * @param string $sOptionName The name of the option
  554. * @return mixed false if the option was never set or the options's value
  555. */
  556. public function GetOutputOption($sFormat, $sOptionName)
  557. {
  558. if (isset($this->a_OutputOptions[$sFormat][$sOptionName]))
  559. {
  560. return $this->a_OutputOptions[$sFormat][$sOptionName];
  561. }
  562. return false;
  563. }
  564. /**
  565. * Sets a named output option for the given format
  566. * @param string $sFormat The format for which to set the option: html or pdf
  567. * @param string $sOptionName the name of the option
  568. * @param mixed $sValue The value of the option
  569. */
  570. public function SetOutputOption($sFormat, $sOptionName, $sValue)
  571. {
  572. if (!isset($this->a_OutputOptions[$sFormat]))
  573. {
  574. $this->a_OutputOptions[$sFormat] = array($sOptionName => $sValue);
  575. }
  576. else
  577. {
  578. $this->a_OutputOptions[$sFormat][$sOptionName] = $sValue;
  579. }
  580. }
  581. public function RenderPopupMenuItems($aActions, $aFavoriteActions = array())
  582. {
  583. $sPrevUrl = '';
  584. $sHtml = '';
  585. foreach ($aActions as $aAction)
  586. {
  587. $sClass = isset($aAction['class']) ? " class=\"{$aAction['class']}\"" : "";
  588. $sOnClick = isset($aAction['onclick']) ? " onclick=\"{$aAction['onclick']}\"" : "";
  589. if (empty($aAction['url']))
  590. {
  591. if ($sPrevUrl != '') // Don't output consecutively two separators...
  592. {
  593. $sHtml .= "<li>{$aAction['label']}</li>";
  594. }
  595. $sPrevUrl = '';
  596. }
  597. else
  598. {
  599. $sHtml .= "<li><a href=\"{$aAction['url']}\"$sClass $sOnClick>{$aAction['label']}</a></li>";
  600. $sPrevUrl = $aAction['url'];
  601. }
  602. }
  603. $sHtml .= "</ul></li></ul></div>";
  604. foreach(array_reverse($aFavoriteActions) as $aAction)
  605. {
  606. $sHtml .= "<div class=\"actions_button\"><a href='{$aAction['url']}'>{$aAction['label']}</a></div>";
  607. }
  608. return $sHtml;
  609. }
  610. }
  611. ?>