PageRenderTime 25ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/blog.old/wp-includes/js/heartbeat.js

https://github.com/chopsuei3/oscc
JavaScript | 490 lines | 317 code | 80 blank | 93 comment | 72 complexity | 8548d05cee37b20058732f38c6613fe0 MD5 | raw file
  1. /**
  2. * Heartbeat API
  3. *
  4. * Note: this API is "experimental" meaning it will likely change a lot
  5. * in the next few releases based on feedback from 3.6.0. If you intend
  6. * to use it, please follow the development closely.
  7. *
  8. * Heartbeat is a simple server polling API that sends XHR requests to
  9. * the server every 15 seconds and triggers events (or callbacks) upon
  10. * receiving data. Currently these 'ticks' handle transports for post locking,
  11. * login-expiration warnings, and related tasks while a user is logged in.
  12. *
  13. * Available filters in ajax-actions.php:
  14. * - heartbeat_received
  15. * - heartbeat_send
  16. * - heartbeat_tick
  17. * - heartbeat_nopriv_received
  18. * - heartbeat_nopriv_send
  19. * - heartbeat_nopriv_tick
  20. * @see wp_ajax_nopriv_heartbeat(), wp_ajax_heartbeat()
  21. *
  22. * @since 3.6.0
  23. */
  24. // Ensure the global `wp` object exists.
  25. window.wp = window.wp || {};
  26. (function($){
  27. var Heartbeat = function() {
  28. var self = this,
  29. running,
  30. beat,
  31. screenId = typeof pagenow != 'undefined' ? pagenow : '',
  32. url = typeof ajaxurl != 'undefined' ? ajaxurl : '',
  33. settings,
  34. tick = 0,
  35. queue = {},
  36. interval,
  37. connecting,
  38. countdown = 0,
  39. errorcount = 0,
  40. tempInterval,
  41. hasFocus = true,
  42. isUserActive,
  43. userActiveEvents,
  44. winBlurTimeout,
  45. frameBlurTimeout = -1,
  46. hasConnectionError = null;
  47. /**
  48. * Returns a boolean that's indicative of whether or not there is a connection error
  49. *
  50. * @returns boolean
  51. */
  52. this.hasConnectionError = function() {
  53. return !! hasConnectionError;
  54. };
  55. if ( typeof( window.heartbeatSettings ) == 'object' ) {
  56. settings = $.extend( {}, window.heartbeatSettings );
  57. // Add private vars
  58. url = settings.ajaxurl || url;
  59. delete settings.ajaxurl;
  60. delete settings.nonce;
  61. interval = settings.interval || 15; // default interval
  62. delete settings.interval;
  63. // The interval can be from 15 to 60 sec. and can be set temporarily to 5 sec.
  64. if ( interval < 15 )
  65. interval = 15;
  66. else if ( interval > 60 )
  67. interval = 60;
  68. interval = interval * 1000;
  69. // 'screenId' can be added from settings on the front-end where the JS global 'pagenow' is not set
  70. screenId = screenId || settings.screenId || 'front';
  71. delete settings.screenId;
  72. // Add or overwrite public vars
  73. $.extend( this, settings );
  74. }
  75. function time(s) {
  76. if ( s )
  77. return parseInt( (new Date()).getTime() / 1000 );
  78. return (new Date()).getTime();
  79. }
  80. function isLocalFrame( frame ) {
  81. var origin, src = frame.src;
  82. if ( src && /^https?:\/\//.test( src ) ) {
  83. origin = window.location.origin ? window.location.origin : window.location.protocol + '//' + window.location.host;
  84. if ( src.indexOf( origin ) !== 0 )
  85. return false;
  86. }
  87. try {
  88. if ( frame.contentWindow.document )
  89. return true;
  90. } catch(e) {}
  91. return false;
  92. }
  93. // Set error state and fire an event on XHR errors or timeout
  94. function errorstate( error, status ) {
  95. var trigger;
  96. if ( error ) {
  97. switch ( error ) {
  98. case 'abort':
  99. // do nothing
  100. break;
  101. case 'timeout':
  102. // no response for 30 sec.
  103. trigger = true;
  104. break;
  105. case 'parsererror':
  106. case 'error':
  107. case 'empty':
  108. case 'unknown':
  109. errorcount++;
  110. if ( errorcount > 2 )
  111. trigger = true;
  112. break;
  113. }
  114. if ( 503 == status && false === hasConnectionError ) {
  115. trigger = true;
  116. }
  117. if ( trigger && ! self.hasConnectionError() ) {
  118. hasConnectionError = true;
  119. $(document).trigger( 'heartbeat-connection-lost', [error, status] );
  120. }
  121. } else if ( self.hasConnectionError() ) {
  122. errorcount = 0;
  123. hasConnectionError = false;
  124. $(document).trigger( 'heartbeat-connection-restored' );
  125. } else if ( null === hasConnectionError ) {
  126. hasConnectionError = false;
  127. }
  128. }
  129. function connect() {
  130. var send = {}, data, i, empty = true,
  131. nonce = typeof window.heartbeatSettings == 'object' ? window.heartbeatSettings.nonce : '';
  132. tick = time();
  133. data = $.extend( {}, queue );
  134. // Clear the data queue, anything added after this point will be send on the next tick
  135. queue = {};
  136. $(document).trigger( 'heartbeat-send', [data] );
  137. for ( i in data ) {
  138. if ( data.hasOwnProperty( i ) ) {
  139. empty = false;
  140. break;
  141. }
  142. }
  143. // If nothing to send (nothing is expecting a response),
  144. // schedule the next tick and bail
  145. if ( empty && ! self.hasConnectionError() ) {
  146. connecting = false;
  147. next();
  148. return;
  149. }
  150. send.data = data;
  151. send.interval = interval / 1000;
  152. send._nonce = nonce;
  153. send.action = 'heartbeat';
  154. send.screen_id = screenId;
  155. send.has_focus = hasFocus;
  156. connecting = true;
  157. self.xhr = $.ajax({
  158. url: url,
  159. type: 'post',
  160. timeout: 30000, // throw an error if not completed after 30 sec.
  161. data: send,
  162. dataType: 'json'
  163. }).done( function( response, textStatus, jqXHR ) {
  164. var new_interval;
  165. if ( ! response )
  166. return errorstate( 'empty' );
  167. // Clear error state
  168. if ( self.hasConnectionError() )
  169. errorstate();
  170. if ( response.nonces_expired ) {
  171. $(document).trigger( 'heartbeat-nonces-expired' );
  172. return;
  173. }
  174. // Change the interval from PHP
  175. if ( response.heartbeat_interval ) {
  176. new_interval = response.heartbeat_interval;
  177. delete response.heartbeat_interval;
  178. }
  179. self.tick( response, textStatus, jqXHR );
  180. // do this last, can trigger the next XHR if connection time > 5 sec. and new_interval == 'fast'
  181. if ( new_interval )
  182. self.interval.call( self, new_interval );
  183. }).always( function() {
  184. connecting = false;
  185. next();
  186. }).fail( function( jqXHR, textStatus, error ) {
  187. errorstate( textStatus || 'unknown', jqXHR.status );
  188. self.error( jqXHR, textStatus, error );
  189. });
  190. }
  191. function next() {
  192. var delta = time() - tick, t = interval;
  193. if ( ! running )
  194. return;
  195. if ( ! hasFocus ) {
  196. t = 100000; // 100 sec. Post locks expire after 120 sec.
  197. } else if ( countdown > 0 && tempInterval ) {
  198. t = tempInterval;
  199. countdown--;
  200. }
  201. window.clearTimeout(beat);
  202. if ( delta < t ) {
  203. beat = window.setTimeout(
  204. function(){
  205. if ( running )
  206. connect();
  207. },
  208. t - delta
  209. );
  210. } else {
  211. connect();
  212. }
  213. }
  214. function blurred() {
  215. window.clearTimeout(winBlurTimeout);
  216. window.clearTimeout(frameBlurTimeout);
  217. winBlurTimeout = frameBlurTimeout = 0;
  218. hasFocus = false;
  219. }
  220. function focused() {
  221. window.clearTimeout(winBlurTimeout);
  222. window.clearTimeout(frameBlurTimeout);
  223. winBlurTimeout = frameBlurTimeout = 0;
  224. isUserActive = time();
  225. if ( hasFocus )
  226. return;
  227. hasFocus = true;
  228. window.clearTimeout(beat);
  229. if ( ! connecting )
  230. next();
  231. }
  232. function setFrameEvents() {
  233. $('iframe').each( function( i, frame ){
  234. if ( ! isLocalFrame( frame ) )
  235. return;
  236. if ( $.data( frame, 'wp-heartbeat-focus' ) )
  237. return;
  238. $.data( frame, 'wp-heartbeat-focus', 1 );
  239. $( frame.contentWindow ).on( 'focus.wp-heartbeat-focus', function(e) {
  240. focused();
  241. }).on('blur.wp-heartbeat-focus', function(e) {
  242. setFrameEvents();
  243. frameBlurTimeout = window.setTimeout( function(){ blurred(); }, 500 );
  244. });
  245. });
  246. }
  247. $(window).on( 'blur.wp-heartbeat-focus', function(e) {
  248. setFrameEvents();
  249. winBlurTimeout = window.setTimeout( function(){ blurred(); }, 500 );
  250. }).on( 'focus.wp-heartbeat-focus', function() {
  251. $('iframe').each( function( i, frame ) {
  252. if ( !isLocalFrame( frame ) )
  253. return;
  254. $.removeData( frame, 'wp-heartbeat-focus' );
  255. $( frame.contentWindow ).off( '.wp-heartbeat-focus' );
  256. });
  257. focused();
  258. });
  259. function userIsActive() {
  260. userActiveEvents = false;
  261. $(document).off( '.wp-heartbeat-active' );
  262. $('iframe').each( function( i, frame ) {
  263. if ( ! isLocalFrame( frame ) )
  264. return;
  265. $( frame.contentWindow ).off( '.wp-heartbeat-active' );
  266. });
  267. focused();
  268. }
  269. // Set 'hasFocus = true' if user is active and the window is in the background.
  270. // Set 'hasFocus = false' if the user has been inactive (no mouse or keyboard activity) for 5 min. even when the window has focus.
  271. function checkUserActive() {
  272. var lastActive = isUserActive ? time() - isUserActive : 0;
  273. // Throttle down when no mouse or keyboard activity for 5 min
  274. if ( lastActive > 300000 && hasFocus )
  275. blurred();
  276. if ( ! userActiveEvents ) {
  277. $(document).on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active', function(){ userIsActive(); } );
  278. $('iframe').each( function( i, frame ) {
  279. if ( ! isLocalFrame( frame ) )
  280. return;
  281. $( frame.contentWindow ).on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active', function(){ userIsActive(); } );
  282. });
  283. userActiveEvents = true;
  284. }
  285. }
  286. // Check for user activity every 30 seconds.
  287. window.setInterval( function(){ checkUserActive(); }, 30000 );
  288. $(document).ready( function() {
  289. // Start one tick (15 sec) after DOM ready
  290. running = true;
  291. tick = time();
  292. next();
  293. });
  294. this.hasFocus = function() {
  295. return hasFocus;
  296. };
  297. /**
  298. * Get/Set the interval
  299. *
  300. * When setting to 'fast', the interval is 5 sec. for the next 30 ticks (for 2 min and 30 sec).
  301. * If the window doesn't have focus, the interval slows down to 2 min.
  302. *
  303. * @param string speed Interval speed: 'fast' (5sec), 'standard' (15sec) default, 'slow' (60sec)
  304. * @param string ticks Used with speed = 'fast', how many ticks before the speed reverts back
  305. * @return int Current interval in seconds
  306. */
  307. this.interval = function( speed, ticks ) {
  308. var reset, seconds;
  309. ticks = parseInt( ticks, 10 ) || 30;
  310. ticks = ticks < 1 || ticks > 30 ? 30 : ticks;
  311. if ( speed ) {
  312. switch ( speed ) {
  313. case 'fast':
  314. seconds = 5;
  315. countdown = ticks;
  316. break;
  317. case 'slow':
  318. seconds = 60;
  319. countdown = 0;
  320. break;
  321. case 'long-polling':
  322. // Allow long polling, (experimental)
  323. interval = 0;
  324. return 0;
  325. break;
  326. default:
  327. seconds = 15;
  328. countdown = 0;
  329. }
  330. // Reset when the new interval value is lower than the current one
  331. reset = seconds * 1000 < interval;
  332. if ( countdown > 0 ) {
  333. tempInterval = seconds * 1000;
  334. } else {
  335. interval = seconds * 1000;
  336. tempInterval = 0;
  337. }
  338. if ( reset )
  339. next();
  340. }
  341. if ( ! hasFocus )
  342. return 120;
  343. return tempInterval ? tempInterval / 1000 : interval / 1000;
  344. };
  345. /**
  346. * Enqueue data to send with the next XHR
  347. *
  348. * As the data is sent later, this function doesn't return the XHR response.
  349. * To see the response, use the custom jQuery event 'heartbeat-tick' on the document, example:
  350. * $(document).on( 'heartbeat-tick.myname', function( event, data, textStatus, jqXHR ) {
  351. * // code
  352. * });
  353. * If the same 'handle' is used more than once, the data is not overwritten when the third argument is 'true'.
  354. * Use wp.heartbeat.isQueued('handle') to see if any data is already queued for that handle.
  355. *
  356. * $param string handle Unique handle for the data. The handle is used in PHP to receive the data.
  357. * $param mixed data The data to send.
  358. * $param bool dont_overwrite Whether to overwrite existing data in the queue.
  359. * $return bool Whether the data was queued or not.
  360. */
  361. this.enqueue = function( handle, data, dont_overwrite ) {
  362. if ( handle ) {
  363. if ( dont_overwrite && this.isQueued( handle ) )
  364. return false;
  365. queue[handle] = data;
  366. return true;
  367. }
  368. return false;
  369. };
  370. /**
  371. * Check if data with a particular handle is queued
  372. *
  373. * $param string handle The handle for the data
  374. * $return bool Whether some data is queued with this handle
  375. */
  376. this.isQueued = function( handle ) {
  377. if ( handle )
  378. return queue.hasOwnProperty( handle );
  379. };
  380. /**
  381. * Remove data with a particular handle from the queue
  382. *
  383. * $param string handle The handle for the data
  384. * $return void
  385. */
  386. this.dequeue = function( handle ) {
  387. if ( handle )
  388. delete queue[handle];
  389. };
  390. /**
  391. * Get data that was enqueued with a particular handle
  392. *
  393. * $param string handle The handle for the data
  394. * $return mixed The data or undefined
  395. */
  396. this.getQueuedItem = function( handle ) {
  397. if ( handle )
  398. return this.isQueued( handle ) ? queue[handle] : undefined;
  399. };
  400. };
  401. $.extend( Heartbeat.prototype, {
  402. tick: function( data, textStatus, jqXHR ) {
  403. $(document).trigger( 'heartbeat-tick', [data, textStatus, jqXHR] );
  404. },
  405. error: function( jqXHR, textStatus, error ) {
  406. $(document).trigger( 'heartbeat-error', [jqXHR, textStatus, error] );
  407. }
  408. });
  409. wp.heartbeat = new Heartbeat();
  410. }(jQuery));