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