ajaxwebpage.class.inc.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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. * Simple web page with no includes, header or fancy formatting, useful to
  20. * generate HTML fragments when called by an AJAX method
  21. *
  22. * @copyright Copyright (C) 2010-2012 Combodo SARL
  23. * @license http://opensource.org/licenses/AGPL-3.0
  24. */
  25. require_once(APPROOT."/application/webpage.class.inc.php");
  26. class ajax_page extends WebPage
  27. {
  28. /**
  29. * Jquery style ready script
  30. * @var Hash
  31. */
  32. protected $m_sReadyScript;
  33. protected $m_sCurrentTab;
  34. protected $m_sCurrentTabContainer;
  35. protected $m_aTabs;
  36. private $m_sMenu; // If set, then the menu will be updated
  37. /**
  38. * constructor for the web page
  39. * @param string $s_title Not used
  40. */
  41. function __construct($s_title)
  42. {
  43. parent::__construct($s_title);
  44. $this->m_sReadyScript = "";
  45. //$this->add_header("Content-type: text/html; charset=utf-8");
  46. $this->add_header("Cache-control: no-cache");
  47. $this->m_sCurrentTabContainer = '';
  48. $this->m_sCurrentTab = '';
  49. $this->m_aTabs = array();
  50. $this->sContentType = 'text/html';
  51. $this->sContentDisposition = 'inline';
  52. $this->m_sMenu = "";
  53. }
  54. public function AddTabContainer($sTabContainer, $sPrefix = '')
  55. {
  56. $this->m_aTabs[$sTabContainer] = array('content' =>'', 'prefix' => $sPrefix);
  57. $this->add("\$Tabs:$sTabContainer\$");
  58. }
  59. public function AddToTab($sTabContainer, $sTabLabel, $sHtml)
  60. {
  61. if (!isset($this->m_aTabs[$sTabContainer]['content'][$sTabLabel]))
  62. {
  63. // Set the content of the tab
  64. $this->m_aTabs[$sTabContainer]['content'][$sTabLabel] = $sHtml;
  65. }
  66. else
  67. {
  68. // Append to the content of the tab
  69. $this->m_aTabs[$sTabContainer]['content'][$sTabLabel] .= $sHtml;
  70. }
  71. }
  72. public function SetCurrentTabContainer($sTabContainer = '')
  73. {
  74. $sPreviousTabContainer = $this->m_sCurrentTabContainer;
  75. $this->m_sCurrentTabContainer = $sTabContainer;
  76. return $sPreviousTabContainer;
  77. }
  78. public function SetCurrentTab($sTabLabel = '')
  79. {
  80. $sPreviousTab = $this->m_sCurrentTab;
  81. $this->m_sCurrentTab = $sTabLabel;
  82. return $sPreviousTab;
  83. }
  84. public function GetCurrentTab()
  85. {
  86. return $this->m_sCurrentTab;
  87. }
  88. public function AddToMenu($sHtml)
  89. {
  90. $this->m_sMenu .= $sHtml;
  91. }
  92. /**
  93. * Echoes the content of the whole page
  94. * @return void
  95. */
  96. public function output()
  97. {
  98. if (!empty($this->sContentType))
  99. {
  100. $this->add_header('Content-type: '.$this->sContentType);
  101. }
  102. if (!empty($this->sContentDisposition))
  103. {
  104. $this->add_header('Content-Disposition: '.$this->sContentDisposition.'; filename="'.$this->sContentFileName.'"');
  105. }
  106. foreach($this->a_headers as $s_header)
  107. {
  108. header($s_header);
  109. }
  110. if (count($this->m_aTabs) > 0)
  111. {
  112. $this->add_ready_script(
  113. <<<EOF
  114. // The "tab widgets" to handle.
  115. var tabs = $('div[id^=tabbedContent]');
  116. // Ugly patch for a change in the behavior of jQuery UI:
  117. // Before jQuery UI 1.9, tabs were always considered as "local" (opposed to Ajax)
  118. // when their href was beginning by #. Starting with 1.9, a <base> tag in the page
  119. // is taken into account and causes "local" tabs to be considered as Ajax
  120. // unless their URL is equal to the URL of the page...
  121. if ($('base').length > 0)
  122. {
  123. $('div[id^=tabbedContent] ul li a').each(function() {
  124. var sHash = location.hash;
  125. var sCleanLocation = location.href.toString().replace(sHash, '').replace(/#$/, '');
  126. $(this).attr("href", sCleanLocation+$(this).attr("href"));
  127. });
  128. }
  129. if ($.bbq)
  130. {
  131. // This selector will be reused when selecting actual tab widget A elements.
  132. var tab_a_selector = 'ul.ui-tabs-nav a';
  133. // Enable tabs on all tab widgets. The `event` property must be overridden so
  134. // that the tabs aren't changed on click, and any custom event name can be
  135. // specified. Note that if you define a callback for the 'select' event, it
  136. // will be executed for the selected tab whenever the hash changes.
  137. tabs.tabs({ event: 'change' });
  138. // Define our own click handler for the tabs, overriding the default.
  139. tabs.find( tab_a_selector ).click(function()
  140. {
  141. var state = {};
  142. // Get the id of this tab widget.
  143. var id = $(this).closest( 'div[id^=tabbedContent]' ).attr( 'id' );
  144. // Get the index of this tab.
  145. var idx = $(this).parent().prevAll().length;
  146. // Set the state!
  147. state[ id ] = idx;
  148. $.bbq.pushState( state );
  149. });
  150. }
  151. else
  152. {
  153. tabs.tabs();
  154. }
  155. EOF
  156. );
  157. }
  158. // Render the tabs in the page (if any)
  159. foreach($this->m_aTabs as $sTabContainerName => $aTabContainer)
  160. {
  161. $sTabs = '';
  162. $m_aTabs = $aTabContainer['content'];
  163. $sPrefix = $aTabContainer['prefix'];
  164. $container_index = 0;
  165. if (count($m_aTabs) > 0)
  166. {
  167. $sTabs = "<!-- tabs -->\n<div id=\"tabbedContent_{$sPrefix}{$sTabContainerName}\" class=\"light\">\n";
  168. $sTabs .= "<ul>\n";
  169. // Display the unordered list that will be rendered as the tabs
  170. $i = 0;
  171. foreach($m_aTabs as $sTabName => $sTabContent)
  172. {
  173. $sTabs .= "<li><a href=\"#tab_{$sPrefix}{$sTabContainerName}$i\" class=\"tab\"><span>".htmlentities($sTabName, ENT_QUOTES, 'UTF-8')."</span></a></li>\n";
  174. $i++;
  175. }
  176. $sTabs .= "</ul>\n";
  177. // Now add the content of the tabs themselves
  178. $i = 0;
  179. foreach($m_aTabs as $sTabName => $sTabContent)
  180. {
  181. $sTabs .= "<div id=\"tab_{$sPrefix}{$sTabContainerName}$i\">".$sTabContent."</div>\n";
  182. $i++;
  183. }
  184. $sTabs .= "</div>\n<!-- end of tabs-->\n";
  185. }
  186. $this->s_content = str_replace("\$Tabs:$sTabContainerName\$", $sTabs, $this->s_content);
  187. $container_index++;
  188. }
  189. // Additional UI widgets to be activated inside the ajax fragment ??
  190. if (($this->sContentType == 'text/html') && (preg_match('/class="date-pick"/', $this->s_content) || preg_match('/class="datetime-pick"/', $this->s_content)) )
  191. {
  192. $this->add_ready_script(
  193. <<<EOF
  194. $(".date-pick").datepicker({
  195. showOn: 'button',
  196. buttonImage: '../images/calendar.png',
  197. buttonImageOnly: true,
  198. dateFormat: 'yy-mm-dd',
  199. constrainInput: false,
  200. changeMonth: true,
  201. changeYear: true
  202. });
  203. $(".datetime-pick").datepicker({
  204. showOn: 'button',
  205. buttonImage: '../images/calendar.png',
  206. buttonImageOnly: true,
  207. dateFormat: 'yy-mm-dd 00:00:00',
  208. constrainInput: false,
  209. changeMonth: true,
  210. changeYear: true
  211. });
  212. EOF
  213. );
  214. }
  215. $s_captured_output = ob_get_contents();
  216. ob_end_clean();
  217. if (($this->sContentType == 'text/html') && ($this->sContentDisposition == 'inline'))
  218. {
  219. // inline content != attachment && html => filter all scripts for malicious XSS scripts
  220. echo self::FilterXSS($this->s_content);
  221. }
  222. else
  223. {
  224. echo $this->s_content;
  225. }
  226. if (!empty($this->m_sMenu))
  227. {
  228. $uid = time();
  229. echo "<div id=\"accordion_temp_$uid\">\n";
  230. echo "<div id=\"accordion\">\n";
  231. echo "<!-- Beginning of the accordion menu -->\n";
  232. echo self::FilterXSS($this->m_sMenu);
  233. echo "<!-- End of the accordion menu-->\n";
  234. echo "</div>\n";
  235. echo "</div>\n";
  236. echo "<script type=\"text/javascript\">\n";
  237. echo "$('#inner_menu').html($('#accordion_temp_$uid').html());\n";
  238. echo "$('#accordion_temp_$uid').remove();\n";
  239. echo "$('#accordion').accordion({ header: 'h3', navigation: true, autoHeight: false, collapsible: false, icons: false });\n";
  240. echo "\n</script>\n";
  241. }
  242. //echo $this->s_deferred_content;
  243. if (count($this->a_scripts) > 0)
  244. {
  245. echo "<script type=\"text/javascript\">\n";
  246. echo implode("\n", $this->a_scripts);
  247. echo "\n</script>\n";
  248. }
  249. if (!empty($this->s_deferred_content))
  250. {
  251. echo "<script type=\"text/javascript\">\n";
  252. echo "\$('body').append('".addslashes(str_replace("\n", '', $this->s_deferred_content))."');\n";
  253. echo "\n</script>\n";
  254. }
  255. if (!empty($this->m_sReadyScript))
  256. {
  257. echo "<script type=\"text/javascript\">\n";
  258. echo $this->m_sReadyScript; // Ready Scripts are output as simple scripts
  259. echo "\n</script>\n";
  260. }
  261. if (trim($s_captured_output) != "")
  262. {
  263. echo self::FilterXSS($s_captured_output);
  264. }
  265. if (class_exists('MetaModel'))
  266. {
  267. MetaModel::RecordQueryTrace();
  268. }
  269. }
  270. /**
  271. * Adds a paragraph with a smaller font into the page
  272. * NOT implemented (i.e does nothing)
  273. * @param string $sText Content of the (small) paragraph
  274. * @return void
  275. */
  276. public function small_p($sText)
  277. {
  278. }
  279. public function add($sHtml)
  280. {
  281. if (!empty($this->m_sCurrentTabContainer) && !empty($this->m_sCurrentTab))
  282. {
  283. $this->AddToTab($this->m_sCurrentTabContainer, $this->m_sCurrentTab, $sHtml);
  284. }
  285. else
  286. {
  287. parent::add($sHtml);
  288. }
  289. }
  290. /**
  291. * Records the current state of the 'html' part of the page output
  292. * @return mixed The current state of the 'html' output
  293. */
  294. public function start_capture()
  295. {
  296. if (!empty($this->m_sCurrentTabContainer) && !empty($this->m_sCurrentTab))
  297. {
  298. $iOffset = isset($this->m_aTabs[$this->m_sCurrentTabContainer]['content'][$this->m_sCurrentTab]) ? strlen($this->m_aTabs[$this->m_sCurrentTabContainer]['content'][$this->m_sCurrentTab]): 0;
  299. return array('tc' => $this->m_sCurrentTabContainer, 'tab' => $this->m_sCurrentTab, 'offset' => $iOffset);
  300. }
  301. else
  302. {
  303. return parent::start_capture();
  304. }
  305. }
  306. /**
  307. * Returns the part of the html output that occurred since the call to start_capture
  308. * and removes this part from the current html output
  309. * @param $offset mixed The value returned by start_capture
  310. * @return string The part of the html output that was added since the call to start_capture
  311. */
  312. public function end_capture($offset)
  313. {
  314. if (is_array($offset))
  315. {
  316. if (isset($this->m_aTabs[$offset['tc']]['content'][$offset['tab']]))
  317. {
  318. $sCaptured = substr($this->m_aTabs[$offset['tc']]['content'][$offset['tab']], $offset['offset']);
  319. $this->m_aTabs[$offset['tc']]['content'][$offset['tab']] = substr($this->m_aTabs[$offset['tc']]['content'][$offset['tab']], 0, $offset['offset']);
  320. }
  321. else
  322. {
  323. $sCaptured = '';
  324. }
  325. }
  326. else
  327. {
  328. $sCaptured = parent::end_capture($offset);
  329. }
  330. return $sCaptured;
  331. }
  332. /**
  333. * Add any text or HTML fragment (identified by an ID) at the end of the body of the page
  334. * This is useful to add hidden content, DIVs or FORMs that should not
  335. * be embedded into each other.
  336. */
  337. public function add_at_the_end($s_html, $sId = '')
  338. {
  339. if ($sId != '')
  340. {
  341. $this->add_script("$('#{$sId}').remove();"); // Remove any previous instance of the same Id
  342. }
  343. $this->s_deferred_content .= $s_html;
  344. }
  345. /**
  346. * Adds a script to be executed when the DOM is ready (typical JQuery use)
  347. * NOT implemented in this version of the class.
  348. * @return void
  349. */
  350. public function add_ready_script($sScript)
  351. {
  352. $this->m_sReadyScript .= $sScript."\n";
  353. }
  354. /**
  355. * Cannot be called in this context, since Ajax pages do not share
  356. * any context with the calling page !!
  357. */
  358. public function GetUniqueId()
  359. {
  360. assert(false);
  361. return 0;
  362. }
  363. public static function FilterXSS($sHTML)
  364. {
  365. return str_ireplace(array('<script', '</script>'), array('<!-- <removed-script', '</removed-script> -->'), $sHTML);
  366. }
  367. }
  368. ?>