eventsource.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. /**
  3. * ownCloud
  4. *
  5. * @author Robin Appelman
  6. * @copyright 2012 Robin Appelman icewind1991@gmail.com
  7. *
  8. * This library is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
  10. * License as published by the Free Software Foundation; either
  11. * version 3 of the License, or any later version.
  12. *
  13. * This library is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public
  19. * License along with this library. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. /**
  23. * wrapper for server side events (http://en.wikipedia.org/wiki/Server-sent_events)
  24. * includes a fallback for older browsers and IE
  25. *
  26. * use server side events with causion, to many open requests can hang the server
  27. */
  28. class OC_EventSource{
  29. private $fallback;
  30. private $fallBackId=0;
  31. public function __construct() {
  32. OC_Util::obEnd();
  33. header('Cache-Control: no-cache');
  34. $this->fallback=isset($_GET['fallback']) and $_GET['fallback']=='true';
  35. if($this->fallback) {
  36. $this->fallBackId=$_GET['fallback_id'];
  37. header("Content-Type: text/html");
  38. echo str_repeat('<span></span>'.PHP_EOL, 10); //dummy data to keep IE happy
  39. }else{
  40. header("Content-Type: text/event-stream");
  41. }
  42. if( !OC_Util::isCallRegistered()) {
  43. exit();
  44. }
  45. flush();
  46. }
  47. /**
  48. * send a message to the client
  49. * @param string type
  50. * @param object data
  51. *
  52. * if only one paramater is given, a typeless message will be send with that paramater as data
  53. */
  54. public function send($type, $data=null) {
  55. if(is_null($data)) {
  56. $data=$type;
  57. $type=null;
  58. }
  59. if($this->fallback) {
  60. $response='<script type="text/javascript">window.parent.OC.EventSource.fallBackCallBack('.$this->fallBackId.',"'.$type.'",'.json_encode($data).')</script>'.PHP_EOL;
  61. echo $response;
  62. }else{
  63. if($type) {
  64. echo 'event: '.$type.PHP_EOL;
  65. }
  66. echo 'data: '.json_encode($data).PHP_EOL;
  67. }
  68. echo PHP_EOL;
  69. flush();
  70. }
  71. /**
  72. * close the connection of the even source
  73. */
  74. public function close() {
  75. $this->send('__internal__', 'close');//server side closing can be an issue, let the client do it
  76. }
  77. }