Completed
Pull Request — release-2.1 (#4823)
by
unknown
08:48
created

Themes/default/scripts/alerts.js (3 issues)

Labels

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
var pingTime = 10000;
2
3
var updateAlerts = function ()
4
{
5
    var unreadAlerts;
6
7
    // Prevent multiple notifications across browsers
8
    if (typeof localStorage != 'undefined')
9
    {
10
        unreadAlerts = localStorage.getItem('alertsCounter');
11
12
        if (unreadAlerts !== parseInt(unreadAlerts))
13
            return true;
14
15
        if ($('.amt:first').is(':visible'))
16
            $('.amt:first').text(unreadAlerts);
17
        else if (!$('.amt:first').is(':visible') && unreadAlerts != 0)
18
            $('#alerts_menu_top').append(' <span class="amt">' + unreadAlerts + '</span>');
19
20
        if (localStorage.getItem('alertsPoll') != null && (+(new Date()) - localStorage.getItem('alertsPoll')) < pingTime)
21
        {
22
            setTimeout(updateAlerts, 1000);
23
            return true;
24
        }
25
        localStorage.setItem('alertsPoll', +(new Date()));
26
    }
27
    else
28
        unreadAlerts = $('.amt:first').text() ? $('.amt:first').text() : 0;
29
30
    unreadAlerts = parseInt(unreadAlerts);
31
32
    $.get(smf_scripturl + '?action=profile;area=alerts_popup;counter=' + unreadAlerts + ';u=' + smf_member_id, function (data)
33
    {
34
        var alerts = $(data).find('.unread');
35
        if (alerts.length == 0)
36
            return true;
37
38
        unreadAlerts += alerts.length;
39
40
        if (unreadAlerts !== parseInt(unreadAlerts))
41
            return true;
42
43
        if (typeof localStorage != 'undefined')
44
            localStorage.setItem('alertsCounter', unreadAlerts);
45
46
        if ($('.amt:first').is(':visible'))
47
            $('.amt:first').text(unreadAlerts);
48
        else if (!$('.amt:first').is(':visible') && unreadAlerts != 0)
49
            $('#alerts_menu_top').append('<span class="amt">' + unreadAlerts + '</span>');
50
51
        $.each(alerts, function(index, item)
52
        {
53
            var notification = notify.createNotification(new_alert_title, {
54
                body: $(item).find('div.details:first > span').text(),
55
                icon: smf_images_url + '/blank.png'
56
            });
57
58
            notification.click(function()
59
            {
60
                window.focus();
61
                if (!$('#alerts_menu').is(':visible'))
62
                    $('#alerts_menu_top').click();
63
            });
64
65
            if (alert_timeout > 0)
66
                setTimeout(function()
67
                {
68
                    notification.close();
69
                }, alert_timeout);
70
        });
71
    });
72
73
    setTimeout(updateAlerts, pingTime);
74
}
75
76
$(function ()
77
{
78
    var permission = notify.permissionLevel();
79
    if (permission == notify.PERMISSION_DEFAULT)
80
    {
81
        $('#alerts_menu_top').click(function()
82
        {
83
            window.notify.requestPermission(function()
84
            {
85
                if (notify.permissionLevel() == notify.PERMISSION_GRANTED)
86
                    updateAlerts();
87
            });
88
        });
89
    }
90
    else if (permission == notify.PERMISSION_GRANTED)
91
    {
92
        setTimeout(updateAlerts, pingTime);
93
        if (typeof localStorage != 'undefined')
94
            localStorage.setItem('alertsCounter', parseInt($('.amt:first').text() ? $('.amt:first').text() : 0));
95
    }
96
});
97
98
/**
99
* Copyright 2012 Tsvetan Tsvetkov
100
*
101
* Licensed under the Apache License, Version 2.0 (the "License");
102
* you may not use this file except in compliance with the License.
103
* You may obtain a copy of the License at
104
*
105
*     https://www.apache.org/licenses/LICENSE-2.0
106
*
107
* Unless required by applicable law or agreed to in writing, software
108
* distributed under the License is distributed on an "AS IS" BASIS,
109
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
110
* See the License for the specific language governing permissions and
111
* limitations under the License.
112
*
113
* Author: Tsvetan Tsvetkov ([email protected])
114
*/
115
(function (win) {
116
	/*
117
	 Safari native methods required for Notifications do NOT run in strict mode.
118
	 */
119
	//"use strict";
120
	var PERMISSION_DEFAULT = "default",
121
		PERMISSION_GRANTED = "granted",
122
		PERMISSION_DENIED = "denied",
123
		PERMISSION = [PERMISSION_GRANTED, PERMISSION_DEFAULT, PERMISSION_DENIED],
124
		defaultSetting = {
125
			pageVisibility: false,
126
			autoClose: 0
127
		},
128
		empty = {},
129
		emptyString = "",
130
		isSupported = (function () {
131
			var isSupported = false;
132
			/*
133
			 * Use try {} catch() {} because the check for IE may throws an exception
134
			 * if the code is run on browser that is not Safar/Chrome/IE or
135
			 * Firefox with html5notifications plugin.
136
			 *
137
			 * Also, we canNOT detect if msIsSiteMode method exists, as it is
138
			 * a method of host object. In IE check for existing method of host
139
			 * object returns undefined. So, we try to run it - if it runs
140
			 * successfully - then it is IE9+, if not - an exceptions is thrown.
141
			 */
142
			try {
143
				isSupported = !!(/* Safari, Chrome */win.Notification || /* Chrome & ff-html5notifications plugin */win.webkitNotifications || /* Firefox Mobile */navigator.mozNotification || /* IE9+ */(win.external && win.external.msIsSiteMode() !== undefined));
144
			} catch (e) {
145
			}
146
			return isSupported;
147
		}()),
148
		ieVerification = Math.floor((Math.random() * 10) + 1),
149
		isFunction = function (value) {
150
			return (value && (value).constructor === Function);
151
		},
152
		isString = function (value) {
153
			return (value && (value).constructor === String);
154
		},
155
		isObject = function (value) {
156
			return (value && (value).constructor === Object);
157
		},
158
		/**
159
		 * Dojo Mixin
160
		 */
161
			mixin = function (target, source) {
162
			var name, s;
163
			for (name in source) {
164
				s = source[name];
165
				if (!(name in target) || (target[name] !== s && (!(name in empty) || empty[name] !== s))) {
166
					target[name] = s;
167
				}
168
			}
169
			return target; // Object
170
		},
171
		noop = function () {
172
		},
173
		settings = defaultSetting;
174
175
	function getNotification(title, options) {
176
		var notification;
177
		if (win.Notification) { /* Safari 6, Chrome (23+) */
178
			notification = new win.Notification(title, {
179
				/* The notification's icon - For Chrome in Windows, Linux & Chrome OS */
180
				icon: isString(options.icon) ? options.icon : options.icon.x32,
181
				/* The notification’s subtitle. */
182
				body: options.body || emptyString,
183
				/*
184
				 The notification’s unique identifier.
185
				 This prevents duplicate entries from appearing if the user has multiple instances of your website open at once.
186
				 */
187
				tag: options.tag || emptyString
188
			});
189
		} else if (win.webkitNotifications) { /* FF with html5Notifications plugin installed */
190
			notification = win.webkitNotifications.createNotification(options.icon, title, options.body);
191
			notification.show();
192
		} else if (navigator.mozNotification) { /* Firefox Mobile */
193
			notification = navigator.mozNotification.createNotification(title, options.body, options.icon);
194
			notification.show();
195
		} else if (win.external && win.external.msIsSiteMode()) { /* IE9+ */
196
			//Clear any previous notifications
197
			win.external.msSiteModeClearIconOverlay();
198
			win.external.msSiteModeSetIconOverlay((isString(options.icon) ? options.icon : options.icon.x16), title);
199
			win.external.msSiteModeActivate();
200
			notification = {
201
				"ieVerification": ieVerification + 1
202
			};
203
		}
204
		return notification;
0 ignored issues
show
The variable notification does not seem to be initialized in case win.external && win.external.msIsSiteMode() on line 195 is false. Are you sure this can never be the case?
Loading history...
205
	}
206
207
	function getWrapper(notification) {
208
		return {
209
			close: function () {
210
				if (notification) {
211
					if (notification.close) {
212
						//https://code.google.com/p/ff-html5notifications/issues/detail?id=58
213
						notification.close();
214
					} else if (win.external && win.external.msIsSiteMode()) {
215
						if (notification.ieVerification === ieVerification) {
216
							win.external.msSiteModeClearIconOverlay();
217
						}
218
					}
219
				}
220
			},
221
			click: function(callback) {
222
				notification.addEventListener('click', callback);
223
			}
224
		};
225
	}
226
227
	function requestPermission(callback) {
228
		if (!isSupported) {
229
			return;
230
		}
231
		var callbackFunction = isFunction(callback) ? callback : noop;
232
		if (win.webkitNotifications && win.webkitNotifications.checkPermission) {
233
			/*
234
			 * Chrome 23 supports win.Notification.requestPermission, but it
235
			 * breaks the browsers, so use the old-webkit-prefixed
236
			 * win.webkitNotifications.checkPermission instead.
237
			 *
238
			 * Firefox with html5notifications plugin supports this method
239
			 * for requesting permissions.
240
			 */
241
			win.webkitNotifications.requestPermission(callbackFunction);
242
		} else if (win.Notification && win.Notification.requestPermission) {
243
			win.Notification.requestPermission(callbackFunction);
244
		}
245
	}
246
247
	function permissionLevel() {
248
		var permission;
249
		if (!isSupported) {
250
			return;
251
		}
252
		if (win.Notification && win.Notification.permissionLevel) {
253
			//Safari 6
254
			permission = win.Notification.permissionLevel();
255
		} else if (win.webkitNotifications && win.webkitNotifications.checkPermission) {
256
			//Chrome & Firefox with html5-notifications plugin installed
257
			permission = PERMISSION[win.webkitNotifications.checkPermission()];
258
		} else if (navigator.mozNotification) {
259
			//Firefox Mobile
260
			permission = PERMISSION_GRANTED;
261
		} else if (win.Notification && win.Notification.permission) {
262
			// Firefox 23+
263
			permission = win.Notification.permission;
264
		} else if (win.external && (win.external.msIsSiteMode() !== undefined)) { /* keep last */
265
			//IE9+
266
			permission = win.external.msIsSiteMode() ? PERMISSION_GRANTED : PERMISSION_DEFAULT;
267
		}
268
		return permission;
0 ignored issues
show
The variable permission does not seem to be initialized in case win.external && win.exte...iteMode() !== undefined on line 264 is false. Are you sure this can never be the case?
Loading history...
269
	}
270
271
	/**
272
	 *
273
	 */
274
	function config(params) {
275
		if (params && isObject(params)) {
276
			mixin(settings, params);
277
		}
278
		return settings;
279
	}
280
281
	function isDocumentHidden() {
282
		return settings.pageVisibility ? (document.hidden || document.msHidden || document.mozHidden || document.webkitHidden) : true;
283
	}
284
285
	function createNotification(title, options) {
286
		var notification,
287
			notificationWrapper;
288
		/*
289
		 Return undefined if notifications are not supported.
290
291
		 Return undefined if no permissions for displaying notifications.
292
293
		 Title and icons are required. Return undefined if not set.
294
		 */
295
		if (isSupported && isDocumentHidden() && isString(title) && (options && (isString(options.icon) || isObject(options.icon))) && (permissionLevel() === PERMISSION_GRANTED)) {
296
			notification = getNotification(title, options);
297
		}
298
		notificationWrapper = getWrapper(notification);
0 ignored issues
show
The variable notification does not seem to be initialized in case isSupported && isDocumen... === PERMISSION_GRANTED on line 295 is false. Are you sure the function getWrapper handles undefined variables?
Loading history...
299
		//Auto-close notification
300
		if (settings.autoClose && notification && !notification.ieVerification && notification.addEventListener) {
301
			notification.addEventListener("show", function () {
302
				var notification = notificationWrapper;
303
				win.setTimeout(function () {
304
					notification.close();
305
				}, settings.autoClose);
306
			});
307
		}
308
		return notificationWrapper;
309
	}
310
311
	win.notify = {
312
		PERMISSION_DEFAULT: PERMISSION_DEFAULT,
313
		PERMISSION_GRANTED: PERMISSION_GRANTED,
314
		PERMISSION_DENIED: PERMISSION_DENIED,
315
		isSupported: isSupported,
316
		config: config,
317
		createNotification: createNotification,
318
		permissionLevel: permissionLevel,
319
		requestPermission: requestPermission
320
	};
321
	if (isFunction(Object.seal)) {
322
		Object.seal(win.notify);
323
	}
324
}(window));