eventsource.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. @ob_end_clean();
  33. header('Cache-Control: no-cache');
  34. $this->fallback=isset($_GET['fallback']) and $_GET['fallback']=='true';
  35. if($this->fallback){
  36. $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. flush();
  43. }
  44. /**
  45. * send a message to the client
  46. * @param string type
  47. * @param object data
  48. *
  49. * if only one paramater is given, a typeless message will be send with that paramater as data
  50. */
  51. public function send($type,$data=null){
  52. if(is_null($data)){
  53. $data=$type;
  54. $type=null;
  55. }
  56. if($this->fallback){
  57. $response='<script type="text/javascript">window.parent.OC.EventSource.fallBackCallBack('.$this->fallBackId.',"'.$type.'",'.json_encode($data).')</script>'.PHP_EOL;
  58. echo $response;
  59. }else{
  60. if($type){
  61. echo 'event: '.$type.PHP_EOL;
  62. }
  63. echo 'data: '.json_encode($data).PHP_EOL;
  64. }
  65. echo PHP_EOL;
  66. flush();
  67. }
  68. /**
  69. * close the connection of the even source
  70. */
  71. public function close(){
  72. $this->send('__internal__','close');//server side closing can be an issue, let the client do it
  73. }
  74. }