eventsource.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. $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. }