forked from oaeproject/3akai-ux
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sakai.api.util.js
executable file
·1957 lines (1795 loc) · 86.6 KB
/
sakai.api.util.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
*
* Licensed to the Sakai Foundation (SF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The SF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
/**
* @class Util
*
* @description
* General utility functions which implement commonly used low level operations
* and unifies practices across codebase.
*
* @namespace
* General utility functions
*/
define(
[
"jquery",
"sakai/sakai.api.server",
"sakai/sakai.api.l10n",
"config/config_custom",
"misc/trimpath.template",
"misc/underscore",
"jquery-plugins/jquery.ba-bbq"
],
function($, sakai_serv, sakai_l10n, sakai_conf) {
var sakai_util = {
startup : function(meData) {
// I know this is hideous
(function () {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "/dev/lib/MathJax/MathJax.js";
var config = 'MathJax.Hub.Config({ messageStyle: "none" }); ' +
'MathJax.Hub.Config({ config: "MathJax.js" }); ' +
'MathJax.Hub.Startup.onload();';
if (window.opera) {script.innerHTML = config;}
else {script.text = config;}
$("head")[0].appendChild(script);
})();
if (sakai_conf.enableChat) {
// scroll more on focus if the focused element is obscrured by the chat bar
$("input:not(.chat_with_txt), textarea, select, button:not(.chat_name_link), a:not(.chat_window_name)").live("focus", function(){
if (($(this).offset().top + $(this).height()) - $(window).scrollTop() > $(window).height() - 40) {
var scrollByAmt = 40 + $(this).height() + ($(this).offset().top - $(window).scrollTop()) - $(window).height();
window.scrollBy(0, scrollByAmt);
}
});
}
// Start polling to keep session alive when logged in
if (meData.user.userid) {
setInterval(function() {
$.ajax({
url: "/system/me",
cache: false,
success: function(data) {
if (!data.user.userid) {
document.location = "/";
}
}
});
}, 60000);
}
},
/**
* Parse a JavaScript date object to a JCR date string (2009-10-12T10:25:19)
*
* <p>
* Accepted values for the format [1-6]:
* <ol>
* <li>Year: YYYY (eg 1997)</li>
* <li>Year and month: YYYY-MM <br /> (eg 1997-07)</li>
* <li>Complete date: YYYY-MM-DD <br /> (eg 1997-07-16)</li>
* <li>Complete date plus hours and minutes: YYYY-MM-DDThh:mmTZD <br /> (eg 1997-07-16T19:20+01:00)</li>
* <li>Complete date plus hours, minutes and seconds: YYYY-MM-DDThh:mm:ssTZD <br /> (eg 1997-07-16T19:20:30+01:00)</li>
* <li>Complete date plus hours, minutes, seconds and a decimal fraction of a second YYYY-MM-DDThh:mm:ss.sTZD <br /> (eg 1997-07-16T19:20:30.45+01:00)</li>
* </ol>
* </p>
* <p>
* External links:
* <ul>
* <li><a href="http://www.w3.org/TR/NOTE-datetime">W3C datetime documentation</a></li>
* <li><a href="http://delete.me.uk/2005/03/iso8601.html">ISO8601 JavaScript function</a></li>
* <li><a href="http://confluence.sakaiproject.org/display/KERNDOC/KERN-643+Multiple+date+formats+in+the+back-end">Specification</a></li>
* </ul>
* </p>
* @param {Date} date
* JavaScript date object.
* If not set, the current date is used.
* @param {Integer} format
* The format you want to put out
* @param {String} offset
* Optional timezone offset +HH:MM or -HH:MM,
* if not set Z(ulu) or UTC is used
* @return {String} a JCR date string
*/
createSakaiDate : function(date, format, offset) {
if (!format) { format = 5; }
if (!date) { date = new Date(); }
if (!offset) {
offset = 'Z';
} else {
var d = offset.match(/([\-+])([0-9]{2}):([0-9]{2})/);
var offsetnum = (Number(d[2]) * 60) + Number(d[3]);
offsetnum *= ((d[1] === '-') ? -1 : 1);
date = new Date(Number(Number(date) + (offsetnum * 60000)));
}
var zeropad = function (num) { return ((num < 10) ? '0' : '') + num; };
var str = "";
str += date.getUTCFullYear();
if (format > 1) { str += "-" + zeropad(date.getUTCMonth() + 1); }
if (format > 2) { str += "-" + zeropad(date.getUTCDate()); }
if (format > 3) {
str += "T" + zeropad(date.getUTCHours()) +
":" + zeropad(date.getUTCMinutes());
}
if (format > 4) { str += ":" + zeropad(date.getUTCSeconds()); }
if (format > 3) { str += offset; }
if (format > 5) {
str = date.getTime();
}
return str;
},
/**
* Convert a file's size to a human readable size
* example: 2301 = 2.301kB
*
* @param (Integer) filesize The file's size to convert
* @return (String) the file's size in human readable format
*/
convertToHumanReadableFileSize : function(filesize) {
if (! filesize){
filesize = 0;
}
var i;
if (filesize.indexOf && filesize.indexOf("binary-length:") > -1) {
filesize = filesize.replace("binary-length:", "");
}
// Divide the length into its largest unit
var units = [[1024 * 1024 * 1024, 'GB'], [1024 * 1024, 'MB'], [1024, 'KB'], [1, 'bytes']];
var lengthunits;
for (i = 0, j=units.length; i < j; i++) {
var unitsize = units[i][0];
var unittext = units[i][1];
if (filesize >= unitsize) {
filesize = filesize / unitsize;
// 1 decimal place
filesize = Math.ceil(filesize * 10) / 10;
lengthunits = unittext;
break;
}
}
// Return the human readable filesize (and localized)
return sakai_l10n.transformDecimal(filesize, 1) + " " + lengthunits;
},
/**
* Formats a comma separated string of text to an array of usable tags
* Filters out unwanted tags (eg empty tags)
* Returns the array of tags, if no tags were provided or none were valid an empty array is returned
*
* Example: inputTags = "tag1, tag2, , , tag3, , tag4" returns ["tag1","tag2","tag3","tag4"]
*
* @param {String} inputTags Unformatted, comma separated, string of tags put in by a user
* @return {Array} Array of formatted tags
*/
formatTags : function(inputTags){
if ($.trim(inputTags) !== "") {
var tags = [];
var splitTags = inputTags;
if (!$.isArray(inputTags)) {
splitTags = $(inputTags.split(","));
}
$(splitTags).each(function(index){
if ($.trim(splitTags[index]).length) {
tags.push($.trim(splitTags[index]));
}
});
tags.sort(sakai_util.Sorting.naturalSort);
return tags;
} else {
return [];
}
},
/**
* Formats a comma separated string of text to an array of usable tags
* Filters out unwanted tags (eg empty tags) and especially location tags (start with "directory/")
* Returns the array of tags, if no tags were provided or none were valid an empty array is returned
*
* Example: inputTags = "tag1, tag2, , , tag3, , tag4" returns ["tag1","tag2","tag3","tag4"]
*
* @param {String} input Unformatted, comma separated, string of tags put in by a user
* @return {Array} Array of formatted tags
*/
formatTagsExcludeLocation : function(input){
var item;
var inputTags = this.formatTags(input);
if (inputTags.length) {
var tags = [];
$.each(inputTags, function(index, value){
if (value.split("/")[0] !== "directory") {
tags.push(value);
}
});
tags.sort(sakai_util.Sorting.naturalSort);
return tags;
} else {
return [];
}
},
/**
* Formats a comma separated string of text to an array of usable directory tags
* Returns the array of tags, if no tags were provided or none were valid an empty array is returned
*
* Example: inputTags = "tag1, directory/tag2, , , tag3, , directory/tag4" returns ["directory/tag2","directory/tag4"]
*
* @param {String} inputTags Unformatted, comma separated, string of tags put in by a user
* @return {Array} Array of formatted tags
*/
getDirectoryTags : function(input, returnFullTag){
var item;
var inputTags = this.formatTags(input);
if (inputTags.length) {
var tags = [];
for (item in inputTags){
if (inputTags.hasOwnProperty(item) && inputTags[item] && inputTags[item].split("/")[0] === "directory") {
if (returnFullTag){
tags.push(inputTags[item]);
} else {
tags.push(inputTags[item].split("directory/")[1].split("/"));
}
}
}
tags.sort(sakai_util.Sorting.naturalSort);
return tags;
} else {
return [];
}
},
/**
* Add and delete tags from an entity
* The two arrays, newTags and currentTags, represent the state of tags on the entity
* newTags should be the tags that you want on the entity, the whole set
* currentTags should be the set of tags the entity had before the user modified it
* tagEntity will delete any tags in currentTags but not in newTags, and add any in
* newTags that aren't in currentTags
*
* @param (String) tagLocation the URL to the tag, ie. (~userid/public/authprofile)
* @param (Array) newTags The set of tags you wish to be on the entity
* @param (Array) currentTags The set of tags on the current entity
* @param (Function) callback The callback function
*/
tagEntity : function(tagLocation, newTags, currentTags, callback) {
var setTags = function(tagLocation, tags, setTagsCallback) {
if (tags.length) {
var requests = [];
$(tags).each(function(i, val){
requests.push({
"url": "/tags/" + val,
"method": "POST",
"parameters": {
"sakai:tag-name": val,
"sling:resourceType": "sakai/tag"
}
});
});
sakai_serv.batch(requests, function(success, data) {
if (success) {
doSetTags(tags, function(_success) {
setTagsCallback(_success);
});
} else {
debug.error(val + " failed to be created");
if ($.isFunction(setTagsCallback)) {
setTagsCallback();
}
}
}, false, true);
} else {
if ($.isFunction(setTagsCallback)) {
setTagsCallback();
}
}
// set the tag on the entity
var doSetTags = function(tags, doSetTagsCallback) {
var setTagsRequests = [];
$(tags).each(function(i,val) {
setTagsRequests.push({
"url": tagLocation,
"method": "POST",
"parameters": {
"key": "/tags/" + val,
":operation": "tag"
}
});
});
sakai_serv.batch(setTagsRequests, function(success, data) {
if (!success) {
debug.error(tagLocation + " failed to be tagged as " + val);
}
if ($.isFunction(doSetTagsCallback)) {
doSetTagsCallback(success);
}
}, false, true);
};
};
/**
* Delete tags on a given node
*
* @param (String) tagLocation the URL to the tag, ie. (~userid/public/authprofile)
* @param (Array) tags Array of tags to be deleted from the entity
* @param (Function) callback The callback function
*/
var deleteTags = function(tagLocation, tags, deleteTagsCallback) {
if (tags.length) {
var requests = [];
$(tags).each(function(i,val) {
requests.push({
"url": tagLocation,
"method": "POST",
"parameters": {
"key": "/tags/" + val,
":operation": "deletetag"
}
});
});
sakai_serv.batch(requests, function(success, data) {
if (!success) {
debug.error(val + " tag failed to be removed from " + tagLocation);
}
if ($.isFunction(deleteTagsCallback)) {
deleteTagsCallback();
}
}, false, true);
} else {
if ($.isFunction(deleteTagsCallback)) {
deleteTagsCallback();
}
}
};
var tagsToAdd = [];
var tagsToDelete = [];
// determine which tags to add and which to delete
$(newTags).each(function(i,val) {
if (val.indexOf("directory/") !== 0) {
val = newTags[i] = sakai_util.makeSafeTag($.trim(val));
}
if (val && (!currentTags || $.inArray(val,currentTags) === -1)) {
if (val.length) {
if ($.inArray(val, tagsToAdd) < 0) {
tagsToAdd.push(val);
}
}
}
});
$(currentTags).each(function(i,val) {
if (val.indexOf("directory/") !== 0) {
val = currentTags[i] = sakai_util.makeSafeTag($.trim(val));
}
if (val && $.inArray(val,newTags) == -1) {
if (val.length) {
if ($.inArray(val, tagsToDelete) < 0) {
tagsToDelete.push(val);
}
}
}
});
currentTags = currentTags || [];
// determine the tags the entity has
var tags = $.unique($.merge($.merge([], currentTags), tagsToAdd)),
finalTags = [];
$(tags).each(function(i,val) {
if (val.indexOf("directory/") !== 0) {
val = sakai_util.makeSafeTag(val);
}
if ($.inArray(val, tagsToDelete) > -1) {
tags.splice(tags.indexOf(val), 1);
} else if (val && $.trim(val) !== ""){
finalTags.push(val);
}
});
deleteTags(tagLocation, tagsToDelete, function() {
setTags(tagLocation, tagsToAdd, function(success) {
if ($.isFunction(callback)) {
callback(success, finalTags);
}
});
});
},
/**
* Truncate a string of text using the threedots plugin
* @param {String} body String of text to be truncated
* @param {int} width Width of the parent element
* @param {Object} params Object containing parameters, Threedots plugin specific. The row limit for widget headers should be 4 rows.
* @param {String} Optional class(es) to give container div. Used to give specific mark-up to the content to avoid wrong calculations. e.g. s3d-bold
*/
applyThreeDots : function(body, width, params, optClass, alreadySecure){
body = sakai_util.Security.safeOutput(body);
// IE7 and IE6 have trouble with width
if(!jQuery.support.leadingWhitespace){
width = width - 10;
} else {
width = width - 5;
}
// Create elements to apply threedots
$container = $("<div class=\"" + optClass + "\" style=\"width:" + width + "px; ; word-wrap:break-word; visibility:hidden;\"><span style=\"word-wrap:break-word;\" class=\"ellipsis_text\">" + body + "</span></div>");
$("body").append($container);
// There seems to be a race condition where the
// newly-added element returns a height of zero. This
// would cause ThreeDots to truncate the input string to
// the first letter. Try a couple of times for a non-zero
// height and then give up.
for (var attempt = 0; attempt < 10; attempt++) {
if ($container.height() > 0) {
$container.ThreeDots(params);
break;
}
}
var dotted = $container.children("span").text();
$container.remove();
if (!alreadySecure) {
dotted = sakai_util.Security.safeOutput(dotted);
}
// if params contains middledots = true then the string is threedotted in the middle
if(params && params.middledots && body.length > dotted.length){
var maxlength = dotted.length - 3;
if (!alreadySecure) {
body = sakai_util.Security.safeOutput(body);
}
var prepend = body.slice(0, maxlength / 2);
var append = body.slice(body.length - (maxlength / 2), body.length);
return prepend + "..." + append;
}
return dotted;
},
/**
* Returns the correct possessive use by determining how the string ends
*
* @param {String} string The string to check
* @return {String} the possessive to use
*/
getPossessive : function(string) {
var possessive = require("sakai/sakai.api.i18n").General.getValueForKey("POSSESSIVE_S");
var key = $.trim(require("sakai/sakai.api.i18n").General.getValueForKey("POSSESSIVE_KEY")).toLowerCase();
var check = $.trim(string.charAt(string.length - 1)).toLowerCase();
if (check === key){
possessive = require("sakai/sakai.api.i18n").General.getValueForKey("POSSESSIVE");
}
return possessive;
},
/**
* Search for and replace parameters in a template (replaces both keys and properties)
* primarily used for making unique IDs for the group/course templates in config.js
*
* @param {Object} variables The variables to replace in the template with, ie. "groupid"
* @param {Object} replaceIn The object to modify
* @return {Object} the template structure with replaced variables
*/
replaceTemplateParameters : function(variables, replaceIn) {
var loopAndReplace = function(structure, variable, replace) {
var toReplace = "${" + variable + "}";
var regex = new RegExp("\\$\\{" + variable + "\\}", 'g');
for (var i in structure) {
if (structure.hasOwnProperty(i)) {
if (_.isString(structure[i]) && structure[i].indexOf(toReplace) !== -1) {
structure[i] = structure[i].replace(regex, replace);
} else if ($.isPlainObject(structure[i])) {
structure[i] = loopAndReplace(structure[i], variable, replace);
} else if (_.isArray(structure[i])) {
$.each(structure[i], function(j, elt) {
structure[i][j] = loopAndReplace(elt, variable, replace);
});
}
if (i.indexOf(toReplace) !== -1) {
var newKey = i.replace(regex, replace);
structure[newKey] = structure[i];
delete structure[i];
}
}
}
return structure;
};
$.each(variables, function(variable,value) {
replaceIn = loopAndReplace(replaceIn, variable, value);
});
return replaceIn;
},
/**
* Check whether there is a valid picture for the user
* @param {Object} profile The profile object that could contain the profile picture
* @param {String} type The type of profile we're getting the picture for (group or user)
* @return {String}
* The link of the profile picture
* Will be an empty string if there is no picture
*/
constructProfilePicture : function(profile, type){
// profile.basic.elements object should not have picture information
// if there is profile picture and userId
// return the picture links
var imgUrl = sakai_conf.URL.USER_DEFAULT_ICON_URL;
if (type === "group"){
imgUrl = sakai_conf.URL.GROUP_DEFAULT_ICON_URL;
}
var id = null, picture_name = null;
if (profile["rep:userId"] || profile["sakai:group-id"] || profile["uuid"] || profile["userid"]){
if (profile["rep:userId"]){
id = profile["rep:userId"];
} else if (profile["sakai:group-id"]){
id = profile["sakai:group-id"];
} else if (profile["uuid"]){
id = profile["uuid"];
} else if (profile["userid"]){
id = profile["userid"];
}
if (profile.picture) {
if (profile.picture.name) {
picture_name = profile.picture.name;
} else {
//change string to json object and get name from picture object
picture_name = $.parseJSON(profile.picture).name;
}
imgUrl = "/~" + sakai_util.safeURL(id) + "/public/profile/" + sakai_util.safeURL(picture_name);
} else if (profile.basic && profile.basic.elements && profile.basic.elements.picture && profile.basic.elements.picture.value) {
if (profile.basic.elements.picture.value.name) {
picture_name = profile.basic.elements.picture.value.name;
} else {
//change string to json object and get name from picture object
picture_name = $.parseJSON(profile.basic.elements.picture.value).name;
}
//change string to json object and get name from picture object
return "/~" + id + "/public/profile/" + picture_name;
} else if (profile.basic && profile.basic.elements && profile.basic.elements.picture && _.isString(profile.basic.elements.picture)) {
return profile.basic.elements.picture;
} else {
return imgUrl;
}
}
return imgUrl;
},
/**
* @class notification
*
* @description
* Utility functions related to notifications messages in Sakai3
*
* @namespace
* Notifications messages
*/
notification : {
/**
* Show notification messages
* @example sakai.api.Util.notification.show("Title Message", "z2", "z01");
* @param {String} title The notification title (if it is an empty string, the title isn't shown)
* @param {String} text The text you want to see appear in the body of the notification
* @param {Constant} [type] The type of the notification. If this is not supplied, we use the type "information"
* @param {Boolean} sticky The sticky (if it is true, the notification doesn't disappear without using action)
*/
show : function(title, text, type, sticky){
// Check whether the text parameter is supplied.
if(!text){
// Log an error message
debug.info("sakai.api.Util.notification.show: You need to fill out the 'text' parameter");
// Make sure the execution in this function stops
return;
}
// Check whether the type is an actual object if it is supplied
if (type && !$.isPlainObject(type)) {
// Log an error message
debug.info("sakai.api.Util.notification.show: Make sure you supplied a correct type parameter");
// Stop the function execution
return;
}
// Set the notification type
var notification = type || this.type.INFORMATION;
// Set the title and text
notification.title = title;
notification.text = text;
notification.sticky = sticky;
// Show a the actual notification to the user
$.gritter.add(notification);
},
/**
* Remove all the notification messages that are currently visible to the user
*/
removeAll : function(){
// Remove gritter notification messages
// We don't use the $.gritter.removeAll method since that causes pop-ups to flicker
$('#gritter-notice-wrapper').remove();
},
/**
* @class type
*
* @description
* Namespace that contains all the different notification types
*
* @namespace
* Notifications types
*/
type : {
/**
* Object containing settings for the information notification type
*/
INFORMATION : $.extend(true, {}, sakai_conf.notification.type.INFORMATION),
/**
* Object containing settings for the error notification type
*/
ERROR : $.extend(true, {}, sakai_conf.notification.type.ERROR)
}
},
/**
* Parse a ISO8601 date into a JavaScript date object.
*
* <p>
* Supported date formats:
* <ul>
* <li>2010</li>
* <li>2010-02</li>
* <li>2010-02-18</li>
* <li>2010-02-18T07:44Z</li>
* <li>1997-07-16T19:20+01:00</li>
* <li>1997-07-16T19:20:30+01:00</li>
* <li>1269331220896</li>
* </ul>
* </p>
*
* <p>
* External links:
* <ul>
* <li><a href="http://www.w3.org/TR/NOTE-datetime">W3C datetime documentation</a></li>
* <li><a href="http://delete.me.uk/2005/03/iso8601.html">ISO8601 JavaScript function</a></li>
* <li><a href="http://confluence.sakaiproject.org/display/KERNDOC/KERN-643+Multiple+date+formats+in+the+back-end">Specification</a></li>
* </ul>
* </p>
*
* @param {String|Integer} dateInput
* The date that needs to be converted to a JavaScript date object.
* If the format is in milliseconds, you need to provide an integer, otherwise a string
* @return {Date} JavaScript date object
*/
parseSakaiDate : function(dateInput) {
// Define the regular expressions that look for the format of
// the dateInput field
var regexpInteger = /^\d+$/;
var regexpISO8601 = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
"(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\\.([0-9]+))?)?" +
"(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
// Test whether the format is in milliseconds
if(regexpInteger.test(dateInput) && typeof dateInput !== "string") {
return new Date(dateInput);
}
// Test whether you get an ISO8601 format back
var d = dateInput.match(new RegExp(regexpISO8601));
var offset = 0;
var date = new Date(d[1], 0, 1);
var dateOutput = new Date();
if (d[3]) { date.setMonth(d[3] - 1); }
if (d[5]) { date.setDate(d[5]); }
if (d[7]) { date.setHours(d[7]); }
if (d[8]) { date.setMinutes(d[8]); }
if (d[10]) { date.setSeconds(d[10]); }
if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
if (d[14]) {
offset = (Number(d[16]) * 60) + Number(d[17]);
offset *= ((d[15] === '-') ? 1 : -1);
}
// Set the timezone for the date object
offset -= date.getTimezoneOffset();
var time = (Number(date) + (offset * 60 * 1000));
dateOutput.setTime(Number(time));
// Return the date output
return dateOutput;
},
/**
* Parse an RFC822 date into a JavaScript date object.
* Examples of RFC822 dates:
* Wed, 02 Oct 2002 13:00:00 GMT
* Wed, 02 Oct 2002 13:00:00 +0200
*
* @param {String} dateString
* @return {Date} a Javascript date object
*/
parseRFC822Date : function(dateString) {
var dateOutput = new Date();
var dateElements = dateString.split(" ");
var dateElementsTime = dateElements[4].split(":");
var months = {"Jan":0,"Feb":1,"Mar":2,"Apr":3,"May":4,"Jun":5,"Jul":6,"Aug":7,"Sep":8,"Oct":9,"Nov":10,"Dec":11};
var zones = {
"UT": 0,
"GMT": 0,
"EST": -5,
"EDT": -4,
"CST": -6,
"CDT": -5,
"MST": -7,
"MDT": -6,
"PST": -8,
"PDT": -7,
"Z": 0,
"A":-1,
"M":-12,
"N": 1,
"Y": 12
};
// Set day
if (dateElements[1]) { dateOutput.setDate(Number(dateElements[1])); }
//Set month
if (dateElements[2]) { dateOutput.setMonth(months[dateElements[2]]); }
// Set year
if (dateElements[3]) { dateOutput.setFullYear(Number(dateElements[3])); }
// Set hour
if (dateElements[4] && dateElementsTime[0]) {
// Take timezone offset into account
if (zones[dateElements[5]]) {
dateOutput.setHours(Number(dateElementsTime[0]) + zones[dateElements[5]]);
} else if (!isNaN(parseInt(dateElements[5], 10))) {
var zoneTimeHour = Number(dateElements[5].substring(0,2));
dateOutput.setHours(Number(dateElementsTime[0]) + zoneTimeHour);
}
}
// Set minutes
if (dateElements[4] && dateElementsTime[1]) {
if (!isNaN(parseInt(dateElements[5], 10))) {
var zoneTimeMinutes = Number(dateElements[5].substring(3,4));
dateOutput.setMinutes(Number(dateElementsTime[1]) + zoneTimeMinutes);
} else {
dateOutput.setMinutes(Number(dateElementsTime[1]));
}
}
// Set seconds
if (dateElements[4] && dateElementsTime[2]) { dateOutput.setSeconds(dateElementsTime[2]); }
return dateOutput;
},
/**
* Shorten a string and add 3 dots if the string is too long
*
* @param {String} input The string you want to shorten
* @param {Int} maxlength Maximum length of the string
* @returns {String} The shortened string with 3 dots
*/
shortenString : function(input, maxlength){
var return_string = "";
if ((typeof input === "string") && (input.length > maxlength)) {
return_string = input.substr(0, maxlength) + "...";
} else {
return_string = input;
}
return return_string;
},
/**
* Sets the chat bullets after update of status by
* adding the right status css class on an element.
* @param {Object} element the jquery element you wish to add the class to
* @param {Object} status the status
*/
updateChatStatusElement : function(element, chatstatus) {
element.removeClass("chat_available_status_online");
element.removeClass("chat_available_status_busy");
element.removeClass("chat_available_status_offline");
element.addClass("chat_available_status_" + chatstatus);
},
include : {
/**
* Generic function that will insert an HTML tag into the head of the document. This
* will be used to both insert CSS and JS files
* @param {Object} tagname
* Name of the tag we want to insert. This is supposed to be "link" or "script".
* @param {Object} attributes
* A JSON object that contains all of the attributes we want to attach to the tag we're
* inserting. The keys in this object are the attribute names, the values in the object
* are the attribute values
*/
insertTag : function(tagname, attributes) {
var tag = document.createElement(tagname);
var head = document.getElementsByTagName('head').item(0);
for (var a in attributes){
if(attributes.hasOwnProperty(a)){
tag[a] = attributes[a];
}
}
head.appendChild(tag);
},
/**
* Check to see if the tag+attributes combination currently exists in the DOM
*
* @param {Object} tagname
* Name of the tag we want to insert. This is supposed to be "link" or "script".
* @param {Object} attributes
* A JSON object that contains all of the attributes we want to attach to the tag we're
* inserting. The keys in this object are the attribute names, the values in the object
* are the attribute values
* @return {jQuery|Boolean} returns the selected objects if found, otherwise returns false
*/
checkForTag : function(tagname, attributes) {
var selector = tagname;
for (var i in attributes) {
if (i && attributes.hasOwnProperty(i)) {
selector += "[" + i + "*='" + attributes[i] + "']";
}
}
if ($(selector).length) {
return $(selector);
}
else {
return false;
}
},
/**
* Load a JavaScript file into the document
* @param {String} URL of the JavaScript file relative to the parent dom.
*/
js : function(url) {
var attributes = {"src": url, "type": "text/javascript"};
var existingScript = this.checkForTag("script", attributes);
if (existingScript) {
// Remove the existing script so we can place in a new one
// We need to do this otherwise the init functions that need to be called
// at the end of widgets never get called again
existingScript.remove();
}
this.insertTag("script", {"src" : url, "type" : "text/javascript"});
},
/**
* Load a CSS file into the document
* @param {String} URL of the CSS file relative to the parent dom.
*/
css : function(url) {
var attributes = {"href" : url, "type" : "text/css", "rel" : "stylesheet"};
var existingStylesheet = this.checkForTag("link", attributes);
// if the stylesheet already exists, don't add it again
if (!existingStylesheet) {
this.insertTag("link", attributes);
}
}
},
/**
* @class Sorting
*
* @description
* Sorting algorithms
*
* @namespace
* Sorting functions
*/
Sorting : {
/**
* Natural sorting algorithm, for sorting file lists etc.
* @example sakai.api.Util.Sorting("z1", "z2", "z01");
* @param {String|Integer|Number} a The first element you want to sort
* @param {String|Integer|Number} b The second element you want to sort
* @return {Integer} [0 | 1 | -1]
* <ul>
* <li>-1: sort a so it has a lower index than b</li>
* <li>0: a and b are equal</li>
* <li>1: sort b so it has a lower index than a</li>
* </ul>
*/
naturalSort: function(a, b) {
/*
* Natural Sort algorithm for Javascript - Version 0.5 - Released under MIT license
* Author: Jim Palmer (based on chunking idea from Dave Koelle)
* Contributors: Mike Grier (mgrier.com), Clint Priest, Kyle Adams, guillermo
* Released under MIT license.
* http://code.google.com/p/js-naturalsort/source/browse/trunk/naturalSort.js
*/
// setup temp-scope variables for comparison evauluation
var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|-?[0-9]+)/gi,
sre = /(^[ ]*|[ ]*$)/g,
hre = /^0x[0-9a-f]+$/i,
dre = /(^[0-9\-\.\/]{5,}$)|[0-9]+:[0-9]+|( [0-9]{4})/i,
ore = /^0/,
// convert all to strings and trim()
x = a.toString().toLowerCase().replace(sre, '') || '',
y = b.toString().toLowerCase().replace(sre, '') || '',
// chunk/tokenize
xN = x.replace(re, String.fromCharCode(0) + "$1" + String.fromCharCode(0)).replace(/\0$/,'').replace(/^\0/,'').split(String.fromCharCode(0)),
yN = y.replace(re, String.fromCharCode(0) + "$1" + String.fromCharCode(0)).replace(/\0$/,'').replace(/^\0/,'').split(String.fromCharCode(0)),
// numeric, hex or date detection
xD = parseInt(x.match(hre), 10) || (xN.length != 1 && x.match(dre) && (new Date(x)).getTime()),
yD = parseInt(y.match(hre), 10) || xD && (new Date(y)).getTime() || null;
// natural sorting of hex or dates - prevent '1.2.3' valid date
if (yD) {
if ( xD < yD ) {return -1;}
else if ( xD > yD ) {return 1;}
}
// natural sorting through split numeric strings and default strings
for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
// find floats not starting with '0', string or 0 if not defined (Clint Priest)
oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
// handle numeric vs string comparison - number < string - (Kyle Adams)
if (isNaN(oFxNcL) !== isNaN(oFyNcL)) {
return (isNaN(oFxNcL)) ? 1 : -1;
}