Another attempt to fix the http blog redirects.
[WebKit-https.git] / Websites / webkit.org / blog / 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                                         return;
393                                 }
394
395                                 // Change the interval from PHP
396                                 if ( response.heartbeat_interval ) {
397                                         newInterval = response.heartbeat_interval;
398                                         delete response.heartbeat_interval;
399                                 }
400
401                                 $document.trigger( 'heartbeat-tick', [response, textStatus, jqXHR] );
402
403                                 // Do this last, can trigger the next XHR if connection time > 5 sec. and newInterval == 'fast'
404                                 if ( newInterval ) {
405                                         interval( newInterval );
406                                 }
407                         }).fail( function( jqXHR, textStatus, error ) {
408                                 setErrorState( textStatus || 'unknown', jqXHR.status );
409                                 $document.trigger( 'heartbeat-error', [jqXHR, textStatus, error] );
410                         });
411                 }
412
413                 /**
414                  * Schedule the next connection
415                  *
416                  * Fires immediately if the connection time is longer than the interval.
417                  *
418                  * @access private
419                  *
420                  * @return void
421                  */
422                 function scheduleNextTick() {
423                         var delta = time() - settings.lastTick,
424                                 interval = settings.mainInterval;
425
426                         if ( settings.suspend ) {
427                                 return;
428                         }
429
430                         if ( ! settings.hasFocus ) {
431                                 interval = 120000; // 120 sec. Post locks expire after 150 sec.
432                         } else if ( settings.countdown > 0 && settings.tempInterval ) {
433                                 interval = settings.tempInterval;
434                                 settings.countdown--;
435
436                                 if ( settings.countdown < 1 ) {
437                                         settings.tempInterval = 0;
438                                 }
439                         }
440
441                         if ( settings.minimalInterval && interval < settings.minimalInterval ) {
442                                 interval = settings.minimalInterval;
443                         }
444
445                         window.clearTimeout( settings.beatTimer );
446
447                         if ( delta < interval ) {
448                                 settings.beatTimer = window.setTimeout(
449                                         function() {
450                                                 connect();
451                                         },
452                                         interval - delta
453                                 );
454                         } else {
455                                 connect();
456                         }
457                 }
458
459                 /**
460                  * Set the internal state when the browser window becomes hidden or loses focus
461                  *
462                  * @access private
463                  *
464                  * @return void
465                  */
466                 function blurred() {
467                         settings.hasFocus = false;
468                 }
469
470                 /**
471                  * Set the internal state when the browser window becomes visible or is in focus
472                  *
473                  * @access private
474                  *
475                  * @return void
476                  */
477                 function focused() {
478                         settings.userActivity = time();
479
480                         // Resume if suspended
481                         settings.suspend = false;
482
483                         if ( ! settings.hasFocus ) {
484                                 settings.hasFocus = true;
485                                 scheduleNextTick();
486                         }
487                 }
488
489                 /**
490                  * Runs when the user becomes active after a period of inactivity
491                  *
492                  * @access private
493                  *
494                  * @return void
495                  */
496                 function userIsActive() {
497                         settings.userActivityEvents = false;
498                         $document.off( '.wp-heartbeat-active' );
499
500                         $('iframe').each( function( i, frame ) {
501                                 if ( isLocalFrame( frame ) ) {
502                                         $( frame.contentWindow ).off( '.wp-heartbeat-active' );
503                                 }
504                         });
505
506                         focused();
507                 }
508
509                 /**
510                  * Check for user activity
511                  *
512                  * Runs every 30 sec.
513                  * Sets 'hasFocus = true' if user is active and the window is in the background.
514                  * Set 'hasFocus = false' if the user has been inactive (no mouse or keyboard activity)
515                  * for 5 min. even when the window has focus.
516                  *
517                  * @access private
518                  *
519                  * @return void
520                  */
521                 function checkUserActivity() {
522                         var lastActive = settings.userActivity ? time() - settings.userActivity : 0;
523
524                         // Throttle down when no mouse or keyboard activity for 5 min.
525                         if ( lastActive > 300000 && settings.hasFocus ) {
526                                 blurred();
527                         }
528
529                         // Suspend after 10 min. of inactivity when suspending is enabled.
530                         // Always suspend after 60 min. of inactivity. This will release the post lock, etc.
531                         if ( ( settings.suspendEnabled && lastActive > 600000 ) || lastActive > 3600000 ) {
532                                 settings.suspend = true;
533                         }
534
535                         if ( ! settings.userActivityEvents ) {
536                                 $document.on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active touchend.wp-heartbeat-active', function() {
537                                         userIsActive();
538                                 });
539
540                                 $('iframe').each( function( i, frame ) {
541                                         if ( isLocalFrame( frame ) ) {
542                                                 $( frame.contentWindow ).on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active touchend.wp-heartbeat-active', function() {
543                                                         userIsActive();
544                                                 });
545                                         }
546                                 });
547
548                                 settings.userActivityEvents = true;
549                         }
550                 }
551
552                 // Public methods
553
554                 /**
555                  * Whether the window (or any local iframe in it) has focus, or the user is active
556                  *
557                  * @return bool
558                  */
559                 function hasFocus() {
560                         return settings.hasFocus;
561                 }
562
563                 /**
564                  * Whether there is a connection error
565                  *
566                  * @return bool
567                  */
568                 function hasConnectionError() {
569                         return settings.connectionError;
570                 }
571
572                 /**
573                  * Connect asap regardless of 'hasFocus'
574                  *
575                  * Will not open two concurrent connections. If a connection is in progress,
576                  * will connect again immediately after the current connection completes.
577                  *
578                  * @return void
579                  */
580                 function connectNow() {
581                         settings.lastTick = 0;
582                         scheduleNextTick();
583                 }
584
585                 /**
586                  * Disable suspending
587                  *
588                  * Should be used only when Heartbeat is performing critical tasks like autosave, post-locking, etc.
589                  * Using this on many screens may overload the user's hosting account if several
590                  * browser windows/tabs are left open for a long time.
591                  *
592                  * @return void
593                  */
594                 function disableSuspend() {
595                         settings.suspendEnabled = false;
596                 }
597
598                 /**
599                  * Get/Set the interval
600                  *
601                  * When setting to 'fast' or 5, by default interval is 5 sec. for the next 30 ticks (for 2 min and 30 sec).
602                  * In this case the number of 'ticks' can be passed as second argument.
603                  * If the window doesn't have focus, the interval slows down to 2 min.
604                  *
605                  * @param mixed speed Interval: 'fast' or 5, 15, 30, 60, 120
606                  * @param string ticks Used with speed = 'fast' or 5, how many ticks before the interval reverts back
607                  * @return int Current interval in seconds
608                  */
609                 function interval( speed, ticks ) {
610                         var newInterval,
611                                 oldInterval = settings.tempInterval ? settings.tempInterval : settings.mainInterval;
612
613                         if ( speed ) {
614                                 switch ( speed ) {
615                                         case 'fast':
616                                         case 5:
617                                                 newInterval = 5000;
618                                                 break;
619                                         case 15:
620                                                 newInterval = 15000;
621                                                 break;
622                                         case 30:
623                                                 newInterval = 30000;
624                                                 break;
625                                         case 60:
626                                                 newInterval = 60000;
627                                                 break;
628                                         case 120:
629                                                 newInterval = 120000;
630                                                 break;
631                                         case 'long-polling':
632                                                 // Allow long polling, (experimental)
633                                                 settings.mainInterval = 0;
634                                                 return 0;
635                                         default:
636                                                 newInterval = settings.originalInterval;
637                                 }
638
639                                 if ( settings.minimalInterval && newInterval < settings.minimalInterval ) {
640                                         newInterval = settings.minimalInterval;
641                                 }
642
643                                 if ( 5000 === newInterval ) {
644                                         ticks = parseInt( ticks, 10 ) || 30;
645                                         ticks = ticks < 1 || ticks > 30 ? 30 : ticks;
646
647                                         settings.countdown = ticks;
648                                         settings.tempInterval = newInterval;
649                                 } else {
650                                         settings.countdown = 0;
651                                         settings.tempInterval = 0;
652                                         settings.mainInterval = newInterval;
653                                 }
654
655                                 // Change the next connection time if new interval has been set.
656                                 // Will connect immediately if the time since the last connection
657                                 // is greater than the new interval.
658                                 if ( newInterval !== oldInterval ) {
659                                         scheduleNextTick();
660                                 }
661                         }
662
663                         return settings.tempInterval ? settings.tempInterval / 1000 : settings.mainInterval / 1000;
664                 }
665
666                 /**
667                  * Enqueue data to send with the next XHR
668                  *
669                  * As the data is send asynchronously, this function doesn't return the XHR response.
670                  * To see the response, use the custom jQuery event 'heartbeat-tick' on the document, example:
671                  *              $(document).on( 'heartbeat-tick.myname', function( event, data, textStatus, jqXHR ) {
672                  *                      // code
673                  *              });
674                  * If the same 'handle' is used more than once, the data is not overwritten when the third argument is 'true'.
675                  * Use wp.heartbeat.isQueued('handle') to see if any data is already queued for that handle.
676                  *
677                  * $param string handle Unique handle for the data. The handle is used in PHP to receive the data.
678                  * $param mixed data The data to send.
679                  * $param bool noOverwrite Whether to overwrite existing data in the queue.
680                  * $return bool Whether the data was queued or not.
681                  */
682                 function enqueue( handle, data, noOverwrite ) {
683                         if ( handle ) {
684                                 if ( noOverwrite && this.isQueued( handle ) ) {
685                                         return false;
686                                 }
687
688                                 settings.queue[handle] = data;
689                                 return true;
690                         }
691                         return false;
692                 }
693
694                 /**
695                  * Check if data with a particular handle is queued
696                  *
697                  * $param string handle The handle for the data
698                  * $return bool Whether some data is queued with this handle
699                  */
700                 function isQueued( handle ) {
701                         if ( handle ) {
702                                 return settings.queue.hasOwnProperty( handle );
703                         }
704                 }
705
706                 /**
707                  * Remove data with a particular handle from the queue
708                  *
709                  * $param string handle The handle for the data
710                  * $return void
711                  */
712                 function dequeue( handle ) {
713                         if ( handle ) {
714                                 delete settings.queue[handle];
715                         }
716                 }
717
718                 /**
719                  * Get data that was enqueued with a particular handle
720                  *
721                  * $param string handle The handle for the data
722                  * $return mixed The data or undefined
723                  */
724                 function getQueuedItem( handle ) {
725                         if ( handle ) {
726                                 return this.isQueued( handle ) ? settings.queue[handle] : undefined;
727                         }
728                 }
729
730                 initialize();
731
732                 // Expose public methods
733                 return {
734                         hasFocus: hasFocus,
735                         connectNow: connectNow,
736                         disableSuspend: disableSuspend,
737                         interval: interval,
738                         hasConnectionError: hasConnectionError,
739                         enqueue: enqueue,
740                         dequeue: dequeue,
741                         isQueued: isQueued,
742                         getQueuedItem: getQueuedItem
743                 };
744         };
745
746         // Ensure the global `wp` object exists.
747         window.wp = window.wp || {};
748         window.wp.heartbeat = new Heartbeat();
749
750 }( jQuery, window ));