ajaxwebpage.class.inc.php 12 KB

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