]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/js/heartbeat.js
WordPress 4.4
[autoinstalls/wordpress.git] / wp-includes / js / heartbeat.js
1 /**
2  * Heartbeat API
3  *
4  * Heartbeat is a simple server polling API that sends XHR requests to
5  * the server every 15 - 60 seconds and triggers events (or callbacks) upon
6  * receiving data. Currently these 'ticks' handle transports for post locking,
7  * login-expiration warnings, autosave, and related tasks while a user is logged in.
8  *
9  * Available PHP filters (in ajax-actions.php):
10  * - heartbeat_received
11  * - heartbeat_send
12  * - heartbeat_tick
13  * - heartbeat_nopriv_received
14  * - heartbeat_nopriv_send
15  * - heartbeat_nopriv_tick
16  * @see wp_ajax_nopriv_heartbeat(), wp_ajax_heartbeat()
17  *
18  * Custom jQuery events:
19  * - heartbeat-send
20  * - heartbeat-tick
21  * - heartbeat-error
22  * - heartbeat-connection-lost
23  * - heartbeat-connection-restored
24  * - heartbeat-nonces-expired
25  *
26  * @since 3.6.0
27  */
28
29 ( function( $, window, undefined ) {
30         var Heartbeat = function() {
31                 var $document = $(document),
32                         settings = {
33                                 // Suspend/resume
34                                 suspend: false,
35
36                                 // Whether suspending is enabled
37                                 suspendEnabled: true,
38
39                                 // Current screen id, defaults to the JS global 'pagenow' when present (in the admin) or 'front'
40                                 screenId: '',
41
42                                 // XHR request URL, defaults to the JS global 'ajaxurl' when present
43                                 url: '',
44
45                                 // Timestamp, start of the last connection request
46                                 lastTick: 0,
47
48                                 // Container for the enqueued items
49                                 queue: {},
50
51                                 // Connect interval (in seconds)
52                                 mainInterval: 60,
53
54                                 // Used when the interval is set to 5 sec. temporarily
55                                 tempInterval: 0,
56
57                                 // Used when the interval is reset
58                                 originalInterval: 0,
59
60                                 // Used to limit the number of AJAX requests.
61                                 minimalInterval: 0,
62
63                                 // Used together with tempInterval
64                                 countdown: 0,
65
66                                 // Whether a connection is currently in progress
67                                 connecting: false,
68
69                                 // Whether a connection error occurred
70                                 connectionError: false,
71
72                                 // Used to track non-critical errors
73                                 errorcount: 0,
74
75                                 // Whether at least one connection has completed successfully
76                                 hasConnected: false,
77
78                                 // Whether the current browser window is in focus and the user is active
79                                 hasFocus: true,
80
81                                 // Timestamp, last time the user was active. Checked every 30 sec.
82                                 userActivity: 0,
83
84                                 // Flags whether events tracking user activity were set
85                                 userActivityEvents: false,
86
87                                 checkFocusTimer: 0,
88                                 beatTimer: 0
89                         };
90
91                 /**
92                  * Set local vars and events, then start
93                  *
94                  * @access private
95                  *
96                  * @return void
97                  */
98                 function initialize() {
99                         var options, hidden, visibilityState, visibilitychange;
100
101                         if ( typeof window.pagenow === 'string' ) {
102                                 settings.screenId = window.pagenow;
103                         }
104
105                         if ( typeof window.ajaxurl === 'string' ) {
106                                 settings.url = window.ajaxurl;
107                         }
108
109                         // Pull in options passed from PHP
110                         if ( typeof window.heartbeatSettings === 'object' ) {
111                                 options = window.heartbeatSettings;
112
113                                 // The XHR URL can be passed as option when window.ajaxurl is not set
114                                 if ( ! settings.url && options.ajaxurl ) {
115                                         settings.url = options.ajaxurl;
116                                 }
117
118                                 // The interval can be from 15 to 120 sec. and can be set temporarily to 5 sec.
119                                 // It can be set in the initial options or changed later from JS and/or from PHP.
120                                 if ( options.interval ) {
121                                         settings.mainInterval = options.interval;
122
123                                         if ( settings.mainInterval < 15 ) {
124                                                 settings.mainInterval = 15;
125                                         } else if ( settings.mainInterval > 120 ) {
126                                                 settings.mainInterval = 120;
127                                         }
128                                 }
129
130                                 // Used to limit the number of AJAX requests. Overrides all other intervals if they are shorter.
131                                 // Needed for some hosts that cannot handle frequent requests and the user may exceed the allocated server CPU time, etc.
132                                 // The minimal interval can be up to 600 sec. however setting it to longer than 120 sec. will limit or disable
133                                 // some of the functionality (like post locks).
134                                 // Once set at initialization, minimalInterval cannot be changed/overriden.
135                                 if ( options.minimalInterval ) {
136                                         options.minimalInterval = parseInt( options.minimalInterval, 10 );
137                                         settings.minimalInterval = options.minimalInterval > 0 && options.minimalInterval <= 600 ? options.minimalInterval * 1000 : 0;
138                                 }
139
140                                 if ( settings.minimalInterval && settings.mainInterval < settings.minimalInterval ) {
141                                         settings.mainInterval = settings.minimalInterval;
142                                 }
143
144                                 // 'screenId' can be added from settings on the front-end where the JS global 'pagenow' is not set
145                                 if ( ! settings.screenId ) {
146                                         settings.screenId = options.screenId || 'front';
147                                 }
148
149                                 if ( options.suspension === 'disable' ) {
150                                         settings.suspendEnabled = false;
151                                 }
152                         }
153
154                         // Convert to milliseconds
155                         settings.mainInterval = settings.mainInterval * 1000;
156                         settings.originalInterval = settings.mainInterval;
157
158                         // Switch the interval to 120 sec. by using the Page Visibility API.
159                         // If the browser doesn't support it (Safari < 7, Android < 4.4, IE < 10), the interval
160                         // will be increased to 120 sec. after 5 min. of mouse and keyboard inactivity.
161                         if ( typeof document.hidden !== 'undefined' ) {
162                                 hidden = 'hidden';
163                                 visibilitychange = 'visibilitychange';
164                                 visibilityState = 'visibilityState';
165                         } else if ( typeof document.msHidden !== 'undefined' ) { // IE10
166                                 hidden = 'msHidden';
167                                 visibilitychange = 'msvisibilitychange';
168                                 visibilityState = 'msVisibilityState';
169                         } else if ( typeof document.webkitHidden !== 'undefined' ) { // Android
170                                 hidden = 'webkitHidden';
171                                 visibilitychange = 'webkitvisibilitychange';
172                                 visibilityState = 'webkitVisibilityState';
173                         }
174
175                         if ( hidden ) {
176                                 if ( document[hidden] ) {
177                                         settings.hasFocus = false;
178                                 }
179
180                                 $document.on( visibilitychange + '.wp-heartbeat', function() {
181                                         if ( document[visibilityState] === 'hidden' ) {
182                                                 blurred();
183                                                 window.clearInterval( settings.checkFocusTimer );
184                                         } else {
185                                                 focused();
186                                                 if ( document.hasFocus ) {
187                                                         settings.checkFocusTimer = window.setInterval( checkFocus, 10000 );
188                                                 }
189                                         }
190                                 });
191                         }
192
193                         // Use document.hasFocus() if available.
194                         if ( document.hasFocus ) {
195                                 settings.checkFocusTimer = window.setInterval( checkFocus, 10000 );
196                         }
197
198                         $(window).on( 'unload.wp-heartbeat', function() {
199                                 // Don't connect any more
200                                 settings.suspend = true;
201
202                                 // Abort the last request if not completed
203                                 if ( settings.xhr && settings.xhr.readyState !== 4 ) {
204                                         settings.xhr.abort();
205                                 }
206                         });
207
208                         // Check for user activity every 30 seconds.
209                         window.setInterval( checkUserActivity, 30000 );
210
211                         // Start one tick after DOM ready
212                         $document.ready( function() {
213                                 settings.lastTick = time();
214                                 scheduleNextTick();
215                         });
216                 }
217
218                 /**
219                  * Return the current time according to the browser
220                  *
221                  * @access private
222                  *
223                  * @return int
224                  */
225                 function time() {
226                         return (new Date()).getTime();
227                 }
228
229                 /**
230                  * Check if the iframe is from the same origin
231                  *
232                  * @access private
233                  *
234                  * @return bool
235                  */
236                 function isLocalFrame( frame ) {
237                         var origin, src = frame.src;
238
239                         // Need to compare strings as WebKit doesn't throw JS errors when iframes have different origin.
240                         // It throws uncatchable exceptions.
241                         if ( src && /^https?:\/\//.test( src ) ) {
242                                 origin = window.location.origin ? window.location.origin : window.location.protocol + '//' + window.location.host;
243
244                                 if ( src.indexOf( origin ) !== 0 ) {
245                                         return false;
246                                 }
247                         }
248
249                         try {
250                                 if ( frame.contentWindow.document ) {
251                                         return true;
252                                 }
253                         } catch(e) {}
254
255                         return false;
256                 }
257
258                 /**
259                  * Check if the document's focus has changed
260                  *
261                  * @access private
262                  *
263                  * @return void
264                  */
265                 function checkFocus() {
266                         if ( settings.hasFocus && ! document.hasFocus() ) {
267                                 blurred();
268                         } else if ( ! settings.hasFocus && document.hasFocus() ) {
269                                 focused();
270                         }
271                 }
272
273                 /**
274                  * Set error state and fire an event on XHR errors or timeout
275                  *
276                  * @access private
277                  *
278                  * @param string error The error type passed from the XHR
279                  * @param int status The HTTP status code passed from jqXHR (200, 404, 500, etc.)
280                  * @return void
281                  */
282                 function setErrorState( error, status ) {
283                         var trigger;
284
285                         if ( error ) {
286                                 switch ( error ) {
287                                         case 'abort':
288                                                 // do nothing
289                                                 break;
290                                         case 'timeout':
291                                                 // no response for 30 sec.
292                                                 trigger = true;
293                                                 break;
294                                         case 'error':
295                                                 if ( 503 === status && settings.hasConnected ) {
296                                                         trigger = true;
297                                                         break;
298                                                 }
299                                                 /* falls through */
300                                         case 'parsererror':
301                                         case 'empty':
302                                         case 'unknown':
303                                                 settings.errorcount++;
304
305                                                 if ( settings.errorcount > 2 && settings.hasConnected ) {
306                                                         trigger = true;
307                                                 }
308
309                                                 break;
310                                 }
311
312                                 if ( trigger && ! hasConnectionError() ) {
313                                         settings.connectionError = true;
314                                         $document.trigger( 'heartbeat-connection-lost', [error, status] );
315                                 }
316                         }
317                 }
318
319                 /**
320                  * Clear the error state and fire an event
321                  *
322                  * @access private
323                  *
324                  * @return void
325                  */
326                 function clearErrorState() {
327                         // Has connected successfully
328                         settings.hasConnected = true;
329
330                         if ( hasConnectionError() ) {
331                                 settings.errorcount = 0;
332                                 settings.connectionError = false;
333                                 $document.trigger( 'heartbeat-connection-restored' );
334                         }
335                 }
336
337                 /**
338                  * Gather the data and connect to the server
339                  *
340                  * @access private
341                  *
342                  * @return void
343                  */
344                 function connect() {
345                         var ajaxData, heartbeatData;
346
347                         // If the connection to the server is slower than the interval,
348                         // heartbeat connects as soon as the previous connection's response is received.
349                         if ( settings.connecting || settings.suspend ) {
350                                 return;
351                         }
352
353                         settings.lastTick = time();
354
355                         heartbeatData = $.extend( {}, settings.queue );
356                         // Clear the data queue, anything added after this point will be send on the next tick
357                         settings.queue = {};
358
359                         $document.trigger( 'heartbeat-send', [ heartbeatData ] );
360
361                         ajaxData = {
362                                 data: heartbeatData,
363                                 interval: settings.tempInterval ? settings.tempInterval / 1000 : settings.mainInterval / 1000,
364                                 _nonce: typeof window.heartbeatSettings === 'object' ? window.heartbeatSettings.nonce : '',
365                                 action: 'heartbeat',
366                                 screen_id: settings.screenId,
367                                 has_focus: settings.hasFocus
368                         };
369
370                         settings.connecting = true;
371                         settings.xhr = $.ajax({
372                                 url: settings.url,
373                                 type: 'post',
374                                 timeout: 30000, // throw an error if not completed after 30 sec.
375                                 data: ajaxData,
376                                 dataType: 'json'
377                         }).always( function() {
378                                 settings.connecting = false;
379                                 scheduleNextTick();
380                         }).done( function( response, textStatus, jqXHR ) {
381                                 var newInterval;
382
383                                 if ( ! response ) {
384                                         setErrorState( 'empty' );
385                                         return;
386                                 }
387
388                                 clearErrorState();
389
390                                 if ( response.nonces_expired ) {
391                                         $document.trigger( 'heartbeat-nonces-expired' );
392                                 }
393
394                                 // Change the interval from PHP
395                                 if ( response.heartbeat_interval ) {
396                                         newInterval = response.heartbeat_interval;
397                                         delete response.heartbeat_interval;
398                                 }
399
400                                 $document.trigger( 'heartbeat-tick', [response, textStatus, jqXHR] );
401
402                                 // Do this last, can trigger the next XHR if connection time > 5 sec. and newInterval == 'fast'
403                                 if ( newInterval ) {
404                                         interval( newInterval );
405                                 }
406                         }).fail( function( jqXHR, textStatus, error ) {
407                                 setErrorState( textStatus || 'unknown', jqXHR.status );
408                                 $document.trigger( 'heartbeat-error', [jqXHR, textStatus, error] );
409                         });
410                 }
411
412                 /**
413                  * Schedule the next connection
414                  *
415                  * Fires immediately if the connection time is longer than the interval.
416                  *
417                  * @access private
418                  *
419                  * @return void
420                  */
421                 function scheduleNextTick() {
422                         var delta = time() - settings.lastTick,
423                                 interval = settings.mainInterval;
424
425                         if ( settings.suspend ) {
426                                 return;
427                         }
428
429                         if ( ! settings.hasFocus ) {
430                                 interval = 120000; // 120 sec. Post locks expire after 150 sec.
431                         } else if ( settings.countdown > 0 && settings.tempInterval ) {
432                                 interval = settings.tempInterval;
433                                 settings.countdown--;
434
435                                 if ( settings.countdown < 1 ) {
436                                         settings.tempInterval = 0;
437                                 }
438                         }
439
440                         if ( settings.minimalInterval && interval < settings.minimalInterval ) {
441                                 interval = settings.minimalInterval;
442                         }
443
444                         window.clearTimeout( settings.beatTimer );
445
446                         if ( delta < interval ) {
447                                 settings.beatTimer = window.setTimeout(
448                                         function() {
449                                                 connect();
450                                         },
451                                         interval - delta
452                                 );
453                         } else {
454                                 connect();
455                         }
456                 }
457
458                 /**
459                  * Set the internal state when the browser window becomes hidden or loses focus
460                  *
461                  * @access private
462                  *
463                  * @return void
464                  */
465                 function blurred() {
466                         settings.hasFocus = false;
467                 }
468
469                 /**
470                  * Set the internal state when the browser window becomes visible or is in focus
471                  *
472                  * @access private
473                  *
474                  * @return void
475                  */
476                 function focused() {
477                         settings.userActivity = time();
478
479                         // Resume if suspended
480                         settings.suspend = false;
481
482                         if ( ! settings.hasFocus ) {
483                                 settings.hasFocus = true;
484                                 scheduleNextTick();
485                         }
486                 }
487
488                 /**
489                  * Runs when the user becomes active after a period of inactivity
490                  *
491                  * @access private
492                  *
493                  * @return void
494                  */
495                 function userIsActive() {
496                         settings.userActivityEvents = false;
497                         $document.off( '.wp-heartbeat-active' );
498
499                         $('iframe').each( function( i, frame ) {
500                                 if ( isLocalFrame( frame ) ) {
501                                         $( frame.contentWindow ).off( '.wp-heartbeat-active' );
502                                 }
503                         });
504
505                         focused();
506                 }
507
508                 /**
509                  * Check for user activity
510                  *
511                  * Runs every 30 sec.
512                  * Sets 'hasFocus = true' if user is active and the window is in the background.
513                  * Set 'hasFocus = false' if the user has been inactive (no mouse or keyboard activity)
514                  * for 5 min. even when the window has focus.
515                  *
516                  * @access private
517                  *
518                  * @return void
519                  */
520                 function checkUserActivity() {
521                         var lastActive = settings.userActivity ? time() - settings.userActivity : 0;
522
523                         // Throttle down when no mouse or keyboard activity for 5 min.
524                         if ( lastActive > 300000 && settings.hasFocus ) {
525                                 blurred();
526                         }
527
528                         // Suspend after 10 min. of inactivity when suspending is enabled.
529                         // Always suspend after 60 min. of inactivity. This will release the post lock, etc.
530                         if ( ( settings.suspendEnabled && lastActive > 600000 ) || lastActive > 3600000 ) {
531                                 settings.suspend = true;
532                         }
533
534                         if ( ! settings.userActivityEvents ) {
535                                 $document.on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active touchend.wp-heartbeat-active', function() {
536                                         userIsActive();
537                                 });
538
539                                 $('iframe').each( function( i, frame ) {
540                                         if ( isLocalFrame( frame ) ) {
541                                                 $( frame.contentWindow ).on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active touchend.wp-heartbeat-active', function() {
542                                                         userIsActive();
543                                                 });
544                                         }
545                                 });
546
547                                 settings.userActivityEvents = true;
548                         }
549                 }
550
551                 // Public methods
552
553                 /**
554                  * Whether the window (or any local iframe in it) has focus, or the user is active
555                  *
556                  * @return bool
557                  */
558                 function hasFocus() {
559                         return settings.hasFocus;
560                 }
561
562                 /**
563                  * Whether there is a connection error
564                  *
565                  * @return bool
566                  */
567                 function hasConnectionError() {
568                         return settings.connectionError;
569                 }
570
571                 /**
572                  * Connect asap regardless of 'hasFocus'
573                  *
574                  * Will not open two concurrent connections. If a connection is in progress,
575                  * will connect again immediately after the current connection completes.
576                  *
577                  * @return void
578                  */
579                 function connectNow() {
580                         settings.lastTick = 0;
581                         scheduleNextTick();
582                 }
583
584                 /**
585                  * Disable suspending
586                  *
587                  * Should be used only when Heartbeat is performing critical tasks like autosave, post-locking, etc.
588                  * Using this on many screens may overload the user's hosting account if several
589                  * browser windows/tabs are left open for a long time.
590                  *
591                  * @return void
592                  */
593                 function disableSuspend() {
594                         settings.suspendEnabled = false;
595                 }
596
597                 /**
598                  * Get/Set the interval
599                  *
600                  * When setting to 'fast' or 5, by default interval is 5 sec. for the next 30 ticks (for 2 min and 30 sec).
601                  * In this case the number of 'ticks' can be passed as second argument.
602                  * If the window doesn't have focus, the interval slows down to 2 min.
603                  *
604                  * @param mixed speed Interval: 'fast' or 5, 15, 30, 60, 120
605                  * @param string ticks Used with speed = 'fast' or 5, how many ticks before the interval reverts back
606                  * @return int Current interval in seconds
607                  */
608                 function interval( speed, ticks ) {
609                         var newInterval,
610                                 oldInterval = settings.tempInterval ? settings.tempInterval : settings.mainInterval;
611
612                         if ( speed ) {
613                                 switch ( speed ) {
614                                         case 'fast':
615                                         case 5:
616                                                 newInterval = 5000;
617                                                 break;
618                                         case 15:
619                                                 newInterval = 15000;
620                                                 break;
621                                         case 30:
622                                                 newInterval = 30000;
623                                                 break;
624                                         case 60:
625                                                 newInterval = 60000;
626                                                 break;
627                                         case 120:
628                                                 newInterval = 120000;
629                                                 break;
630                                         case 'long-polling':
631                                                 // Allow long polling, (experimental)
632                                                 settings.mainInterval = 0;
633                                                 return 0;
634                                         default:
635                                                 newInterval = settings.originalInterval;
636                                 }
637
638                                 if ( settings.minimalInterval && newInterval < settings.minimalInterval ) {
639                                         newInterval = settings.minimalInterval;
640                                 }
641
642                                 if ( 5000 === newInterval ) {
643                                         ticks = parseInt( ticks, 10 ) || 30;
644                                         ticks = ticks < 1 || ticks > 30 ? 30 : ticks;
645
646                                         settings.countdown = ticks;
647                                         settings.tempInterval = newInterval;
648                                 } else {
649                                         settings.countdown = 0;
650                                         settings.tempInterval = 0;
651                                         settings.mainInterval = newInterval;
652                                 }
653
654                                 // Change the next connection time if new interval has been set.
655                                 // Will connect immediately if the time since the last connection
656                                 // is greater than the new interval.
657                                 if ( newInterval !== oldInterval ) {
658                                         scheduleNextTick();
659                                 }
660                         }
661
662                         return settings.tempInterval ? settings.tempInterval / 1000 : settings.mainInterval / 1000;
663                 }
664
665                 /**
666                  * Enqueue data to send with the next XHR
667                  *
668                  * As the data is send asynchronously, this function doesn't return the XHR response.
669                  * To see the response, use the custom jQuery event 'heartbeat-tick' on the document, example:
670                  *              $(document).on( 'heartbeat-tick.myname', function( event, data, textStatus, jqXHR ) {
671                  *                      // code
672                  *              });
673                  * If the same 'handle' is used more than once, the data is not overwritten when the third argument is 'true'.
674                  * Use wp.heartbeat.isQueued('handle') to see if any data is already queued for that handle.
675                  *
676                  * $param string handle Unique handle for the data. The handle is used in PHP to receive the data.
677                  * $param mixed data The data to send.
678                  * $param bool noOverwrite Whether to overwrite existing data in the queue.
679                  * $return bool Whether the data was queued or not.
680                  */
681                 function enqueue( handle, data, noOverwrite ) {
682                         if ( handle ) {
683                                 if ( noOverwrite && this.isQueued( handle ) ) {
684                                         return false;
685                                 }
686
687                                 settings.queue[handle] = data;
688                                 return true;
689                         }
690                         return false;
691                 }
692
693                 /**
694                  * Check if data with a particular handle is queued
695                  *
696                  * $param string handle The handle for the data
697                  * $return bool Whether some data is queued with this handle
698                  */
699                 function isQueued( handle ) {
700                         if ( handle ) {
701                                 return settings.queue.hasOwnProperty( handle );
702                         }
703                 }
704
705                 /**
706                  * Remove data with a particular handle from the queue
707                  *
708                  * $param string handle The handle for the data
709                  * $return void
710                  */
711                 function dequeue( handle ) {
712                         if ( handle ) {
713                                 delete settings.queue[handle];
714                         }
715                 }
716
717                 /**
718                  * Get data that was enqueued with a particular handle
719                  *
720                  * $param string handle The handle for the data
721                  * $return mixed The data or undefined
722                  */
723                 function getQueuedItem( handle ) {
724                         if ( handle ) {
725                                 return this.isQueued( handle ) ? settings.queue[handle] : undefined;
726                         }
727                 }
728
729                 initialize();
730
731                 // Expose public methods
732                 return {
733                         hasFocus: hasFocus,
734                         connectNow: connectNow,
735                         disableSuspend: disableSuspend,
736                         interval: interval,
737                         hasConnectionError: hasConnectionError,
738                         enqueue: enqueue,
739                         dequeue: dequeue,
740                         isQueued: isQueued,
741                         getQueuedItem: getQueuedItem
742                 };
743         };
744
745         // Ensure the global `wp` object exists.
746         window.wp = window.wp || {};
747         window.wp.heartbeat = new Heartbeat();
748
749 }( jQuery, window ));