-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
sharepointplus-5.0.js
4982 lines (4690 loc) · 241 KB
/
sharepointplus-5.0.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
/*!
* SharepointPlus v5.0
* Copyright 2017, Aymeric (@aymkdn)
* Contact: http://kodono.info
* Documentation: http://aymkdn.github.com/SharepointPlus/
* License: LGPL-3 (http://aymkdn.github.com/SharepointPlus/license.md)
*/
/**
* @name SPArrayChunk
* @category utils
* @function
* @description Permits to cut an array into smaller blocks
* @param {Array} b The array to split
* @param {Number} e The size of each block
* @return {Array} An array that contains several arrays with the required size
*/
var SPArrayChunk=function(b,e){var d=[];for(var c=0,a=b.length;c<a;c+=e){d.push(b.slice(c,c+e))}return d}
/**
* @name SPExtend
* @category utils
* @function
* @description It will clone an object (see https://blog.kodono.info/wordpress/2017/04/12/deep-clone-an-object-in-javascript/)
* @param {Boolean} [deep=false] If we want a deep clone
* @param {Object} objectDestination The object that will be extended
* @param {Object} objectSource The object the copy
*/
var SPExtend=function(){var r,t,n,o,e=arguments[0]||{},f=1,i=arguments.length,u=!1,y=function(r){if(null===r||"object"!=typeof r||r.nodeType||null!==r&&r===r.window)return!1;try{if(r.constructor&&!this.hasOwnProperty.call(r.constructor.prototype,"isPrototypeOf"))return!1}catch(t){return!1}return!0};for("boolean"==typeof e&&(u=e,e=arguments[f]||{},f++),"object"!=typeof e&&"function"!=typeof e&&(e={}),!1;i>f;f+=1)if(null!==(r=arguments[f]))for(t in r)e!==r[t]&&"undefined"==typeof e[t]&&(u&&r[t]&&(y(r[t])||(n=Array.isArray(r[t])))?(n?(n=!1,o=e[t]&&Array.isArray(e[t])?e[t]:[]):o=e[t]&&y(e[t])?e[t]:{},e[t]=SPExtend(u,o,r[t])):void 0!==r[t]&&(e[t]=r[t]));return e}
// Encode an ArrayBuffer as a base64 string
// source: https://gist.github.com/jonleighton/958841
var SPArrayBufferToBase64=function(arrayBuffer) {
var base64 = ''
var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
var bytes = new Uint8Array(arrayBuffer)
var byteLength = bytes.byteLength
var byteRemainder = byteLength % 3
var mainLength = byteLength - byteRemainder
var a, b, c, d, chunk
// Main loop deals with bytes in chunks of 3
for (var i = 0; i < mainLength; i = i + 3) {
// Combine the three bytes into a single integer
chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]
// Use bitmasks to extract 6-bit segments from the triplet
a = (chunk & 16515072) >> 18 // 16515072 = (2^6 - 1) << 18
b = (chunk & 258048) >> 12 // 258048 = (2^6 - 1) << 12
c = (chunk & 4032) >> 6 // 4032 = (2^6 - 1) << 6
d = chunk & 63 // 63 = 2^6 - 1
// Convert the raw binary segments to the appropriate ASCII encoding
base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]
}
// Deal with the remaining bytes and padding
if (byteRemainder == 1) {
chunk = bytes[mainLength]
a = (chunk & 252) >> 2 // 252 = (2^6 - 1) << 2
// Set the 4 least significant bits to zero
b = (chunk & 3) << 4 // 3 = 2^2 - 1
base64 += encodings[a] + encodings[b] + '=='
} else if (byteRemainder == 2) {
chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1]
a = (chunk & 64512) >> 10 // 64512 = (2^6 - 1) << 10
b = (chunk & 1008) >> 4 // 1008 = (2^6 - 1) << 4
// Set the 2 least significant bits to zero
c = (chunk & 15) << 2 // 15 = 2^4 - 1
base64 += encodings[a] + encodings[b] + encodings[c] + '='
}
return base64
}
// Global
var _SP_CACHE_CONTENTTYPES=[];
var _SP_CACHE_CONTENTTYPE=[];
var _SP_CACHE_SAVEDVIEW=[];
var _SP_CACHE_SAVEDVIEWS=[];
var _SP_CACHE_SAVEDLISTS=[];
var _SP_CACHE_USERGROUPS=[]
var _SP_CACHE_GROUPMEMBERS=[];
var _SP_CACHE_DISTRIBUTIONLISTS=[];
var _SP_CACHE_REGIONALSETTINGS=void 0;
var _SP_CACHE_DATEFORMAT=void 0;
var _SP_CACHE_HASREST={};
var _SP_CACHE_REQUESTDIGEST={};
var _SP_ADD_PROGRESSVAR={};
var _SP_UPDATE_PROGRESSVAR={};
var _SP_MODERATE_PROGRESSVAR={};
var _SP_REMOVE_PROGRESSVAR={};
var _SP_BASEURL=void 0;
var _SP_NOTIFY_READY=false;
var _SP_NOTIFY_QUEUE=[];
var _SP_NOTIFY=[];
var _SP_PLUGINS={};
var _SP_MODALDIALOG_LOADED=false;
var _SP_MAXWHERE_ONLOOKUP=30;
var _SP_ISBROWSER=(new Function("try {return this===window;}catch(e){ return false;}"))();
var _SP_JSON_ACCEPT="verbose"; // other options are "minimalmetadata" and "nometadata"
(function(window, document, undefined) {
// define a faster way to apply a function to an array
var fastMap = function(source,fn) {
var iterations = source.length;
var dest = new Array(iterations);
var _n = iterations / 8;
var _caseTest = iterations % 8;
for (var i = iterations-1; i > -1; i--) {
var n = _n;
var caseTest = _caseTest;
do {
switch (caseTest) {
case 0: dest[i]=fn(source[i]); i--; // eslint-disable-line
case 7: dest[i]=fn(source[i]); i--; // eslint-disable-line
case 6: dest[i]=fn(source[i]); i--; // eslint-disable-line
case 5: dest[i]=fn(source[i]); i--; // eslint-disable-line
case 4: dest[i]=fn(source[i]); i--; // eslint-disable-line
case 3: dest[i]=fn(source[i]); i--; // eslint-disable-line
case 2: dest[i]=fn(source[i]); i--; // eslint-disable-line
case 1: dest[i]=fn(source[i]); i--; // eslint-disable-line
}
caseTest = 0;
} while (--n > 0);
}
return dest;
};
/**
@name $SP()
@class This is the object uses for all SharepointPlus related actions
*/
function SharepointPlus() {
if (!(this instanceof arguments.callee)) return new arguments.callee();
}
SharepointPlus.prototype = {
data:[],
length:0,
listQueue:[],
needQueue:false,
module_sprequest:null,
credentialOptions:null,
proxyweb:null,
/**
@name $SP().getVersion
@function
@category core
@description Returns the SP version
@return {String} The current SharepointPlus version
*/
getVersion:function() { return "5.0" },
/**
* @ignore
* @name $SP()._promise
* @function
* @description (internal use only) If will reduce the code after compression
* @param {Function} fct
* @return {Promise}
*/
_promise:function(fct) { return new Promise(fct) },
/**
@name $SP().hasREST
@function
@category utils
@description Verify if the website supports REST API (Sharepoint 2013 and later)
@param {Object} settings
@param {String} [settings.url=current] To check another URL (or if you need on a Node server)
@return {Promise} A resolved Promise that gives TRUE or FALSE
*/
hasREST:function(settings) {
var _this=this;
return _this._promise(function(prom_resolve) {
settings = settings||{};
var url=(settings.url || _this.url || window.location.href).split("/").slice(0,3).join("/");
// check cache
if (typeof _SP_CACHE_HASREST[url] === "boolean") {
prom_resolve(_SP_CACHE_HASREST[url]);
return
}
var hasREST, needAjax=(settings.url || !_SP_ISBROWSER || typeof SP === "undefined" ? true : false);
if (!needAjax) {
if (typeof SP !== "undefined" && SP.ClientSchemaVersions) { // eslint-disable-line
// cache
hasREST=(parseInt(SP.ClientSchemaVersions.currentVersion)>14); // eslint-disable-line
_SP_CACHE_HASREST[url]=hasREST;
prom_resolve(hasREST);
return;
}
else needAjax=true;
}
if (needAjax) {
_this.ajax({url:url + "/_api/web/Url"}).then(function() { _SP_CACHE_HASREST[url]=true; prom_resolve(true) }, function() { _SP_CACHE_HASREST[url]=false; prom_resolve(false) })
} else {
_SP_CACHE_HASREST[url]=false;
prom_resolve(false);
}
})
},
/**
* @name $SP().getRequestDigest
* @function
* @category utils
* @description Retrieve a Request Digest (and it will change the value of document.querySelector("#__REQUESTDIGEST") when a new Request Digest is created)
* @param {Object} settings
* @param {String} [settings.url=current] To check another URL (or if you use it on a Node server)
* @param {Boolean} [settings.cache=true] TRUE to use the cache and/or the one into the page for the digest, FALSE to get a new one
* @return {Promise} resolve(Request Digest), reject(reject from $SP().ajax())
*
* @example
* $SP().getRequestDigest(false).then(function(digest) { console.log("The new digest is "+digest)})
*/
getRequestDigest:function(settings) {
var _this=this;
return _this._promise(function(prom_resolve, prom_reject){
settings=settings||{};
settings.cache=(settings.cache===false?false:true);
var e, digest, url=(settings.url||_this.url||window.location.href).split("/").slice(0,3).join("/");
// check cache
if (settings.cache) digest=_SP_CACHE_REQUESTDIGEST[url];
if (digest) {
// check date to be less than 24h
if (new Date().getTime() - new Date(digest.split(",")[1]).getTime() < 86400000) {
prom_resolve(digest);
return;
}
}
if (_SP_ISBROWSER && document && settings.cache) {
e=document.querySelector("#__REQUESTDIGEST");
if (e) {
digest=e.value;
// cache
_SP_CACHE_REQUESTDIGEST[url]=digest;
prom_resolve(digest);
return
}
}
// do a request
_this.ajax({
url:url + "/_api/contextinfo",
method:"POST"
}).then(function(data) {
digest=data.d.GetContextWebInformation.FormDigestValue
// cache
_SP_CACHE_REQUESTDIGEST[url]=digest;
if (document) {
e=document.querySelector("#__REQUESTDIGEST");
if (e) e.value=digest;
}
prom_resolve(digest);
}, function(rej) {
prom_reject(rej)
})
})
},
/**
@name $SP().ajax
@function
@category utils
@description Permits to do an Ajax request based on https://github.com/yanatan16/nanoajax
@param {Object} settings (See options below)
@param {String} settings.url The url to call
@param {String} [settings.method="GET"|"POST"] The HTTP Method ("GET" or "POST" if "body" is provided)
@param {Object} [settings.headers] the headers
@param {String} [settings.body] The data to send to the server
@param {Function} [settings.onprogress=function(event){}] The "upload.onprogress" object for XHR
@param {Function} [settings.getXHR=function(xhr){}] Pass the XMLHttpRequest object as a parameter
@return {Promise} resolve(responseText||responseXML), reject({response, statusCode, responseText})
@example
// for a regular request
$SP().ajax({url:'https://my.web.site'}).then(function(data) { console.log(data) })
// manipulate xhr for specific needs
$SP().ajax({url:'https://url.com/file.jpg', getXHR:function(xhr){ xhr.responseType = 'arraybuffer' }}).then(function(data) {
// ArrayBuffer result
})
// for a CORS/cross-domain request you may need to use 'false' for 'Content-Type'
$SP().ajax({url:'https://my.cross-domain.web/site', headers:{"Content-Type":false}}).then(function(data) { console.log(data) })
*/
ajax:function(settings) {
var _this=this;
settings.headers=settings.headers||{};
// https://github.com/yanatan16/nanoajax — not the original version (include upload.onprogress and getXHR)
// eslint-disable-next-line
!function(e,t){function n(e){return e&&t.XDomainRequest&&!/MSIE 1/.test(navigator.userAgent)?new XDomainRequest:t.XMLHttpRequest?new XMLHttpRequest:void 0}function o(e,t,n){e[t]=e[t]||n}var r=["responseType","withCredentials","timeout"];e.ajax=function(e,a){function s(e,t){return function(){p||(a(void 0===c.status?e:c.status,0===c.status?"Error":c.response||c.responseText||t,c),p=!0)}}var u=e.headers||{},i=e.body,d=e.method||(i?"POST":"GET"),p=!1,c=n(e.cors);c.open(d,e.url,!0);var l=c.onload=s(200);c.onreadystatechange=function(){4===c.readyState&&l()},c.onerror=s(null,"Error"),c.ontimeout=s(null,"Timeout"),c.onabort=s(null,"Abort"),i&&(t.FormData&&i instanceof t.FormData||o(u,"Content-Type","application/x-www-form-urlencoded"));for(var f,v=0,g=r.length;g>v;v++)f=r[v],void 0!==e[f]&&(c[f]=e[f]);for(var f in u)u[f]!==!1&&c.setRequestHeader(f,u[f]);return e.onprogress&&c.upload.addEventListener("progress",e.onprogress,!1),e.getXHR&&e.getXHR(c),c.send(i),c},t.nanoajax=e}({},function(){return this}());
return _this._promise(function(prom_resolve, prom_reject) {
var addRequestDigest=false;
// add "Accept": "application/json;odata=verbose" for headers if there is "_api/" in URL, except for "_api/web/Url"
if (settings.url.toLowerCase().indexOf("/_api/") > -1 && settings.url.toLowerCase().indexOf("_api/web/url") === -1) {
if (typeof settings.headers["Accept"]==="undefined") settings.headers.Accept = "application/json;odata="+_SP_JSON_ACCEPT;
if (typeof settings.headers["Content-Type"]==="undefined") settings.headers["Content-Type"] = "application/json;odata="+_SP_JSON_ACCEPT;
if (typeof settings.headers["X-RequestDigest"]==="undefined" && settings.url.indexOf("contextinfo") === -1) {
addRequestDigest=true;
}
}
// if "_vti_bin/client.svc/ProcessQuery" we want to add the RequestDigest
if (settings.url.toLowerCase().indexOf("_vti_bin/client.svc/processquery") > -1 && typeof settings.headers["X-RequestDigest"]==="undefined") {
addRequestDigest=true
}
if (addRequestDigest) {
// we need to retrieve the Request Digest
_this.getRequestDigest()
.then(function(requestDigest) {
settings.headers["X-RequestDigest"]=requestDigest;
return _this.ajax(settings)
})
.then(function(res) { prom_resolve(res) })
.catch(function(rej) { prom_reject(rej) });
return;
}
// use XML as the default content type
if (typeof settings.headers["Content-Type"]==="undefined") settings.headers["Content-Type"]="text/xml; charset=utf-8";
// check if it's NodeJS
if (_SP_ISBROWSER) {
// IE will return an "400 Bad Request" if it's a POST with no body
if (settings.method==="POST" && !settings.body) settings.body="";
// eslint-disable-next-line
nanoajax.ajax(settings, function(code, responseText, request) {
if (code >= 200 && code < 300 && responseText !== "Error" && responseText !== "Abort" && responseText !== "Timeout") {
var body=(!request.responseType || request.responseType==='document'?request.responseXML || request.responseText : responseText);
if (request.getResponseHeader("Content-Type").indexOf("/json") > -1 && typeof body==="string") body=JSON.parse(body); // parse JSON
prom_resolve(body)
} else {
// check if it's an issue with validation code
if (code == 403 && responseText.indexOf("The security validation for this page is invalid and might be corrupted. Please use your web browser's Back button to try your operation again.") > -1) {
// then we retry
delete settings.headers["X-RequestDigest"];
_this.getRequestDigest({cache:false})
.then(function(requestDigest) {
settings.headers["X-RequestDigest"]=requestDigest;
return _this.ajax(settings)
})
.then(function(res) { prom_resolve(res) })
.catch(function(rej) { prom_reject(rej) });
} else prom_reject({statusCode:code, responseText:responseText, request:request});
}
})
} else {
// we use the module 'sp-request' from https://github.com/s-KaiNet/sp-request
if (_this.module_sprequest === null) {
if (_this.credentialOptions === null) {
throw "[SharepointPlus 'ajax'] please use `$SP().auth()` to provide your credentials first";
}
_this.module_sprequest = require('sp-request').create(_this.credentialOptions);
}
if (settings.headers['Content-Type'].indexOf('xml') > -1) settings.headers['Accept'] = 'application/xml, text/xml, */*; q=0.01';
if (!settings.method || settings.method.toUpperCase() === "POST") settings.headers['Content-Length'] = Buffer.byteLength(settings.body);
// add User Agent
settings.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:52.0) Gecko/20100101 Firefox/52.0';
var opts = {
json:false,
method:settings.method || (settings.body?"POST":"GET"),
strictSSL: false,
headers: settings.headers,
jar:true
};
if (settings.body) opts.body=settings.body;
if (_this.proxyweb) opts.proxy=_this.proxyweb;
// looks like the Content-Length creates some issues
if (opts.headers) delete opts.headers["Content-Length"]
_this.module_sprequest(settings.url, opts)
.then(function(response) {
if (response.statusCode === 200 && response.statusMessage !== "Error" && response.statusMessage !== "Abort" && response.statusMessage !== "Timeout") {
// check if it's XML, then parse it
if (response.headers['content-type'].indexOf('xml') > -1 && response.body.slice(0,5) === '<?xml') {
var DOMParser = require('xmldom').DOMParser;
var result = new DOMParser().parseFromString(response.body);
prom_resolve(result);
} else {
if (response.headers['content-type'].indexOf('json') > -1 && typeof response.body === "string") response.body=JSON.parse(response.body)
prom_resolve(response.body);
}
} else {
prom_reject({response:response, statusCode:response.statusCode, responseText:response.body});
}
}, function(err) {
prom_reject({statusCode:err.statusCode, response:err.response, responseText:(err.response?err.response.body:'')});
});
}
})
},
/**
@name $SP().auth
@function
@category node
@description Permits to use credentials when doing requests (for Node module only)
@param {Object} credentialOptions Options from https://github.com/s-KaiNet/node-sp-auth
@return {Object} the current SharepointPlus object
@example
var user1 = {username:'aymeric', password:'sharepointplus', domain:'kodono'};
$SP().auth(user1)
.list("My List","http://my.sharpoi.nt/other.directory/")
.get({...});
// or :
var sp = $SP().auth(user1);
sp.list("My List", "https://web.si.te").get({...});
sp.list("Other List"; "http://my.sharpoi.nt/other.directory/").update(...);
*/
auth:function(credentialOptions) {
this.credentialOptions = credentialOptions;
return this;
},
/**
@name $SP().proxy
@function
@category node
@description Permits to define a proxy server (for Node module only)
@param {String} proxyURL Looks like "http://domain%5Cusername:password@proxy.something:80"
@return {Object} the current SharepointPlus object
@example
var user1 = {username:'aymeric', password:'sharepointplus', domain:'kodono'};
var proxy = "http://" + user1.domain + "%5C" + user1.username + ":" + user1.password + "@proxy:80";
$SP().proxy(proxy).auth(user1)
.list("My List","http://my.sharpoi.nt/other.directory/")
.get({...});
// or :
var sp = $SP().proxy(proxy).auth(user1);
sp.list("My List", "https://web.si.te").get({...});
sp.list("Other List"; "http://my.sharpoi.nt/other.directory/").update(...);
*/
proxy:function(proxy) {
this.proxyweb = proxy;
return this;
},
/**
@name $SP().list
@namespace
@description Permits to define the list ID/name
@param {String} listID Ths list ID or the list name
@param {String} [url] If the list name is provided, then you need to make sure URL is provided too (then no need to define the URL again for the chained functions like 'get' or 'update')
@return {Object} the current SharepointPlus object
@example
$SP().list("My List");
$SP().list("My List","http://my.sharpoi.nt/other.directory/");
*/
list:function(list,url) {
var _this=this.reset();
if (url) {
// make sure we don't have a '/' at the end
_this.url=(url.slice(-1)==='/'?url.slice(0,-1):url);
}
else _this._getURL();
_this.listID = list.replace(/&/g,"&");
return _this;
},
/**
@ignore
@name $SP()._getURL
@function
@param {Boolean} [setURL=true] If we don't want to set this.url but just return the URL found
@description (internal use only) Store the current URL website into this.url
@return {Promise} resolve(url), reject(error)
*/
_getURL:function(setURL) {
var _this=this;
setURL=(setURL===false?false:true);
return _this._promise(function(prom_resolve, prom_reject) {
if (typeof _this.url === "undefined") {
// search for the local base URL
if (typeof _SP_BASEURL !== "undefined") {
if (setURL) _this.url=_SP_BASEURL;
prom_resolve(_SP_BASEURL)
} else {
// try to build it
if (typeof L_Menu_BaseUrl!=="undefined") {
if (setURL) _this.url=_SP_BASEURL=L_Menu_BaseUrl; // eslint-disable-line
prom_resolve(L_Menu_BaseUrl) // eslint-disable-line
} else {
// eslint-disable-next-line
if (typeof _spPageContextInfo !== "undefined" && typeof _spPageContextInfo.webServerRelativeUrl !== "undefined") {
if (setURL) _this.url=_SP_BASEURL=_spPageContextInfo.webServerRelativeUrl; // eslint-disable-line
prom_resolve(_spPageContextInfo.webServerRelativeUrl) // eslint-disable-line
} else {
// we'll use the Webs.asmx service to find the base URL
_this.needQueue=true;
_this.ajax({
url: "/_vti_bin/Webs.asmx",
body: _this._buildBodyForSOAP("WebUrlFromPageUrl", "<pageUrl>"+window.location.href.replace(/&/g,"&")+"</pageUrl>"),
}).then(function(data) {
var result=data.getElementsByTagName('WebUrlFromPageUrlResult');
if (result.length) {
var u=result[0].firstChild.nodeValue.toLowerCase();
if (setURL) _this.url = _SP_BASEURL = u;
prom_resolve(u);
} else {
prom_reject("[SharepointPlus '_getURL'] Unable to retrieve the URL")
}
_this.needQueue=false;
}, function(error) { prom_reject(error) })
return;
}
}
}
}
prom_reject("[SharepointPlus '_getURL'] Unable to retrieve the URL");
})
},
/**
@name $SP().getURL
@function
@category utils
@description Return the current base URL website
@return {Promise} resolve(The current base URL website), reject(error)
*/
getURL:function() { return this._getURL(false) },
/**
@ignore
@name $SP()._buildBodyForSOAP
@function
@param {String} methodName
@param {String} bodyContent
@param {String} [xmlns="http://schemas.microsoft.com/sharepoint/soap/"]
@description (internal use only) Permits to create the body for a SOAP request
*/
_buildBodyForSOAP:function(methodName, bodyContent, xmlns) {
xmlns = xmlns || "http://schemas.microsoft.com/sharepoint/soap/";
return '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><'+methodName+' xmlns="'+xmlns+'">' + bodyContent + '</'+methodName+'></soap:Body></soap:Envelope>';
},
/**
* @name $SP().webService
* @function
* @category core
* @description Permits to directly deal with a WebService (similar to SPServices http://sympmarc.github.io/SPServices/core/web-services.html)
* @param {Object} options
* @param {String} operation The method name to use (e.g. UpdateList, GetList, ....)
* @param {String} service The name of the service (Lists, Versions, PublishedLinksService, ...) it's the ".asmx" name without the extension
* @param {Object} [properties={}] The properties to call
* @param {String} [webURL=current website] The URL of the website
* @param {String|Boolean} [soapURL='http://schemas.microsoft.com/sharepoint/soap/'] If the SOAP url is not the default one, then you can customize it... it will be send in the request's headers as "SOAPAction"
* @param {Boolean} [soapAction=true] Some web services don't want the "SOAPAction" header
* @return {Promise} resolve(responseBody), reject(see $SP().ajax())
*
* @example
* $SP().webService({ // http://sympmarc.github.io/SPServices/core/web-services/Lists/UpdateList.html
* service:"Lists",
* operation:"Updatelist",
* webURL:"http://what.ever/"
* properties:{
* listName:"Test",
* listProperties:"...",
* newFields:"...",
* updateFields:"...",
* deleteFields:"...",
* listVersion:"..."
* }
* }).then(function(response) {
* // do something with the response
* }, function(error) {
* console.log("Error => ",error)
* });
*
* // to remove a person from a group
* $SP().webService({
* service:"UserGroup",
* operation:"RemoveUserFromGroup",
* soapURL:"http://schemas.microsoft.com/sharepoint/soap/directory/",
* properties:{
* groupName:"Group",
* userLoginName:"domain\\user"
* }
* }).then(function(response) {
* console.log("OK => ",response)
* }, function(error) { console.log("Error => ",error) });
*/
webService:function(options) {
var _this=this;
return _this._promise(function(prom_resolve, prom_reject) {
var bodyContent="", prop, params;
if (!options.service) throw "Error 'webService': the option 'service' is required";
if (!options.operation) throw "Error 'webService': the option 'operation' is required";
options.webURL = options.webURL || _this.url;
// if we didn't define the url in the parameters, then we need to find it
if (!options.webURL) {
_this._getURL().then(function(url) {
options.webURL=url;
_this.webService(options).then(function(res) {
prom_resolve(res);
}, function(rej) {
prom_reject(rej)
})
}, function(rej) {
prom_reject(rej)
})
return;
}
options.properties = options.properties || {};
for (prop in options.properties) {
if (options.properties.hasOwnProperty(prop)) {
bodyContent += '<'+prop+'>'+options.properties[prop]+'</'+prop+'>'
}
}
options.soapAction=(options.soapAction===false?false:true);
options.soapURL=options.soapURL||'http://schemas.microsoft.com/sharepoint/soap/';
if (!options.soapAction) options.soapURL=options.soapURL.replace(/\/$/,"");
bodyContent = _this._buildBodyForSOAP(options.operation, bodyContent, options.soapURL);
params={
url: options.webURL+"/_vti_bin/"+options.service+".asmx",
body: bodyContent
};
if (options.soapAction) params.headers={'SOAPAction':options.soapURL+options.operation };
_this.ajax(params).then(function(data) { prom_resolve(data) }, function(rej) { prom_reject(rej) });
})
},
/**
@ignore
@name $SP()._addInQueue
@function
@description (internal use only) Add a function in the queue
*/
_addInQueue:function(args) {
var _this=this;
_this.listQueue.push(args);
if (_this.listQueue.length===1) _this._testQueue();
return _this
},
/**
@ignore
@name $SP()._testQueue
@function
@description (internal use only) Permits to treat the queue
*/
_testQueue:function() {
var _this=this;
if (_this.needQueue) {
setTimeout(function() { _this._testQueue.call(_this) }, 25);
} else {
if (_this.listQueue.length > 0) {
var todo = _this.listQueue.shift();
todo.callee.apply(_this, Array.prototype.slice.call(todo));
}
_this.needQueue=(_this.listQueue.length>0);
if (_this.needQueue) {
setTimeout(function() { _this._testQueue.call(_this) }, 25);
}
}
},
/**
@name $SP().parse
@function
@category lists
@description Use a WHERE sentence to transform it into a CAML Syntax sentence
@param {String} where The WHERE sentence to change
@param {String} [escapeChar=true] Determines if we want to escape the special chars that will cause an error (for example '&' will be automatically converted to '&amp;')
@example
$SP().parse('ContentType = "My Content Type" OR Description <> null AND Fiscal_x0020_Week >= 43 AND Result_x0020_Date < "2012-02-03"');
// -> return <And><And><Or><Eq><FieldRef Name="ContentType" /><Value Type="Text">My Content Type</Value></Eq><IsNotNull><FieldRef Name="Description" /></IsNotNull></Or><Geq><FieldRef Name="Fiscal_x0020_Week" /><Value Type="Number">43</Value></Geq></And><Lt><FieldRef Name="Result_x0020_Date" /><Value Type="DateTime">2012-02-03</Value></Lt></And>
// available operators :
// "<" : less than
// "<=" : less than or equal to
// ">" : greater than
// ">=" : greater than or equal to
// "<>" : different
// "~=" : this must be only used when comparing to a number that represents the User ID (e.g. 'User ~= 328') - that permits to query a list with too many items but with the User column that is indexed
// " AND "
// " OR "
// " LIKE " : for example 'Title LIKE "foo"' will return "foobar" "foo" "barfoobar" "barfoo" and so on
// " IN " : for example 'Location IN ["Los Angeles","San Francisco","New York"]', equivalent to 'Location = "Los Angeles" OR Location = "San Francisco" OR Location = "New York"' — SP2013 limits each IN to 60 items. If you want to check Lookup IDs instead of text you can use '~' followed by the ID, for example 'Location IN ["~23", "~26", "~30"]'
// special words:
// '[Me]' : for the current user
// '[Today]' : to use the today date
// '[Today+X]' : to use today + X days
// Null : for the Null value
// TRUE : for the Yes/No columns
// FALSE : for the Yes/No columns
// in the below example, on the "&" will be escaped
var bar="Bob & Marley";
var foo="O'Conney";
$SP().parse('Bar = "'+bar+'" AND Foo = "'+foo+'"'); // -> <And><Eq><FieldRef Name="Bar" /><Value Type="Text">Bob & Marley</Value></Eq><Eq><FieldRef Name="Foo" /><Value Type="Text">O'Conney</Value></Eq></And>
$SP().parse("Bar = '"+bar+"' AND Foo = '"+foo+"'"); // don't put the simple and double quotes this way because it'll cause an issue with O'Conney
*/
parse:function(q, escapeChar) {
var queryString = q.replace(/(\s+)?(=|~=|<=|>=|<>|<|>| LIKE | IN )(\s+)?/g,"$2").replace(/""|''/g,"Null").replace(/==/g,"="); // remove unnecessary white space & replace '
var factory = [];
escapeChar = (escapeChar===false ? false : true)
var limitMax = q.length;
var closeOperator="", closeTag = "", ignoreNextChar=false;
var lastField = "";
var parenthesis = {open:0};
var lookupId = false;
for (var i=0; i < queryString.length; i++) {
var letter = queryString.charAt(i);
switch (letter) {
case "(": // find the deepest (
var start = i;
var openedApos=false;
while (queryString.charAt(i) == "(" && i < limitMax) { i++; parenthesis.open++; }
// find the corresponding )
while (parenthesis.open>0 && i < limitMax) {
i++;
// if there is a ' opened then ignore the ) until the next '
var charAtI = queryString.charAt(i);
if (charAtI=="\\") ignoreNextChar=true; // when we have a backslash \then ignore the next char
else if (!ignoreNextChar && (charAtI=="'" || charAtI=='"')) openedApos=!openedApos;
else if (!ignoreNextChar && charAtI==")" && !openedApos) parenthesis.open--;
else ignoreNextChar=false;
}
var lastIndex = factory.length-1;
// concat with the first index
if (lastIndex>=0) {
if (closeOperator != "") factory[0] = "<"+closeOperator+">"+factory[0];
factory[0] += this.parse(queryString.substring(start+1, i));
if (closeOperator != "") factory[0] += "</"+closeOperator+">";
closeOperator = "";
} else factory[0] = this.parse(queryString.substring(start+1, i));
break;
case "[": // for operator IN
var start = i; // eslint-disable-line
var openedApos=false; // eslint-disable-line
// find the corresponding ]
while (i < limitMax) {
i++;
// if there is a ' opened then ignore the ) until the next '
var charAtI = queryString.charAt(i); // eslint-disable-line
if (charAtI=="\\") ignoreNextChar=true; // when we have a backslash \then ignore the next char
else if (!ignoreNextChar && (charAtI=="'" || charAtI=='"')) openedApos=!openedApos;
else if (!ignoreNextChar && !openedApos && charAtI=="]") break;
else ignoreNextChar=false;
}
var lastIndex = factory.length-1; // eslint-disable-line
var arrIn = JSON.parse('[' + queryString.substring(start+1, i) + ']');
// we want to detect the type for the values
var typeIn = "Text";
switch(typeof arrIn[0]) {
case "number": typeIn = "Number"; break;
default: {
// check if it starts with ~ and then it's a number -- lookupid
if (arrIn[0].charAt(0) === "~" && typeof (arrIn[0].slice(1)*1) === "number") {
typeIn = "Integer";
// change all array values
arrIn.forEach(function(e,i) { arrIn[i]=e.slice(1) })
}
}
}
factory[lastIndex] += '<FieldRef Name="'+lastField+'" '+(typeIn==="Integer"?'LookupId="True"':'')+' /><Values><Value Type="'+typeIn+'">' + arrIn.join('</Value><Value Type="'+typeIn+'">') + '</Value></Values>' + closeTag;
lastField = "";
closeTag = "";
// concat with the first index
if (lastIndex>0) {
if (closeOperator != "") factory[0] = "<"+closeOperator+">"+factory[0];
factory[0] += factory[lastIndex];
if (closeOperator != "") factory[0] += "</"+closeOperator+">";
delete(factory[lastIndex]);
closeOperator = "";
}
break;
case ">": // look at the operand
case "<":
i++;
if (queryString.charAt(i) == "=") { // >= or <=
factory.push("<"+(letter==">"?"G":"L")+"eq>");
closeTag = "</"+(letter==">"?"G":"L")+"eq>";
} else if (letter == "<" && queryString.charAt(i) == ">") { // <>
factory.push("<Neq>");
closeTag = "</Neq>";
} else {
i--;
factory.push("<"+(letter==">"?"G":"L")+"t>");
closeTag = "</"+(letter==">"?"G":"L")+"t>";
}
break;
case "~": // special operator '~=' for People
if (queryString.charAt(i+1) == "=") lookupId=true
break;
case "=":
factory.push("<Eq>");
closeTag = "</Eq>";
break;
case " ": // check if it's AND or OR
if (queryString.substring(i,i+5).toUpperCase() == " AND ") {
// add the open tag in the array
closeOperator = "And";
i+=4;
}
else if (queryString.substring(i,i+4).toUpperCase() == " OR ") {
// add the open tag in the array
closeOperator = "Or";
i+=3;
}
else if (queryString.slice(i,i+6).toUpperCase() == " LIKE ") {
i+=5;
factory.push("<Contains>");
closeTag = "</Contains>";
}
else if (queryString.slice(i,i+4).toUpperCase() == " IN ") {
i+=3;
factory.push("<In>");
closeTag = "</In>";
}
else lastField += letter;
break;
case '"': // look now for the next "
case "'":
var apos = letter;
var word = "", other="";
while ((letter = queryString.charAt(++i)) != apos && i < limitMax) {
if (letter == "\\") letter = queryString.charAt(++i);
word+=letter;
}
lastIndex = factory.length-1;
factory[lastIndex] += '<FieldRef Name="'+lastField+'" '+(word=="[Me]"?'LookupId="True" ':'')+'/>';
lastField = "";
var type = "Text"; //(isNaN(word) ? "Text" : "Number"); // check the type
// check automatically if it's a DateTime
if (/\d{4}-\d\d?-\d\d?((T| )\d{2}:\d{2}:\d{2})?/.test(word)) {
type="DateTime";
// check if we want to evaluate the TIME also
if (/\d{4}-\d\d?-\d\d?((T| )\d{2}:\d{2}:\d{2})/.test(word)) other=' IncludeTimeValue="TRUE"';
}
if (escapeChar) word = this._cleanString(word);
// special words ([Today] and [Me])
if (word === "[Me]") {
word = '<UserID Type="Integer" />';
type = "Integer";
} else if (word.slice(0,6) == "[Today") {
type="DateTime";
// find the offset if defined
word = '<Today OffsetDays="'+(1*word.slice(6,-1))+'" />';
}
factory[lastIndex] += '<Value Type="'+type+'"'+other+'>'+word+'</Value>';
factory[lastIndex] += closeTag;
closeTag = "";
// concat with the first index
if (lastIndex>0) {
if (closeOperator != "") factory[0] = "<"+closeOperator+">"+factory[0];
factory[0] += factory[lastIndex];
if (closeOperator != "") factory[0] += "</"+closeOperator+">";
delete(factory[lastIndex]);
closeOperator = "";
}
break;
case "0": case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9":
if (closeTag != "") { // it's the value
var value = letter;
while (!isNaN(letter = queryString.charAt(++i)) && i < limitMax) value+=""+letter;
lastIndex = factory.length-1;
factory[lastIndex] += '<FieldRef Name="'+lastField+'"'+(lookupId?' LookupId="True"':'')+' />';
lastField = "";
factory[lastIndex] += '<Value Type="'+(lookupId?"Integer":"Number")+'">'+value.replace(/ $/,"")+'</Value>';
factory[lastIndex] += closeTag;
closeTag = "";
// concat with the first index
if (lastIndex>0) {
if (closeOperator != "") factory[0] = "<"+closeOperator+">"+factory[0];
factory[0] += factory[lastIndex];
if (closeOperator != "") factory[0] += "</"+closeOperator+">";
delete(factory[lastIndex]);
closeOperator = "";
}
i-=2;
break;
}
default: // eslint-disable-line
if (closeTag == "") lastField += letter;
else if (letter.toLowerCase() == "n" && queryString.substring(i,i+4).toLowerCase() == "null") { // if we have NULL as the value
lastIndex = factory.length-1;
if (closeTag == "</Neq>") { // <>
factory[lastIndex] = "<IsNotNull>";
closeTag = "</IsNotNull>";
} else if (closeTag == "</Eq>") { // =
factory[lastIndex] = "<IsNull>";
closeTag = "</IsNull>";
}
i+=3;
factory[lastIndex] += '<FieldRef Name="'+lastField+'" />';
lastField = "";
factory[lastIndex] += closeTag;
closeTag = "";
// concat with the first index
if (lastIndex>0) {
if (closeOperator != "") factory[0] = "<"+closeOperator+">"+factory[0];
factory[0] += factory[lastIndex];
if (closeOperator != "") factory[0] += "</"+closeOperator+">";
delete(factory[lastIndex]);
closeOperator = "";
}
}
else if ((letter.toLowerCase() === "t" && queryString.substring(i,i+4).toLowerCase() === "true") || (letter.toLowerCase() === "f" && queryString.substring(i,i+5).toLowerCase() === "false")) { // when we have TRUE/FALSE as the value
lastIndex = factory.length-1;
i+=3;
if (letter.toLowerCase() === "f") i++;
factory[lastIndex] += '<FieldRef Name="'+lastField+'" /><Value Type="Boolean">'+(letter.toLowerCase() === "t"?1:0)+'</Value>';
lastField = "";
factory[lastIndex] += closeTag;
closeTag = "";
// concat with the first index
if (lastIndex>0) {
if (closeOperator != "") factory[0] = "<"+closeOperator+">"+factory[0];
factory[0] += factory[lastIndex];
if (closeOperator != "") factory[0] += "</"+closeOperator+">";
delete(factory[lastIndex]);
closeOperator = "";
}
}
}
}
return factory.join("");
},
/**
@ignore
@name $SP()._parseOn
@function
@description (internal use only) Look at the ON clause to convert it
@param {String} on The ON clause
@return {Array} array of clauses
@example
$SP()._parseOn("'List1'.field1 = 'List2'.field2 AND 'List1'.Other_x0020_Field = 'List2'.Some_x0020_Field")
*/
_parseOn:function(q) {
var factory = [], i=0, mtch, queryString = q.replace(/(\s+)?(=)(\s+)?/g,"$2").replace(/==/g,"=").split(" AND ");
for (; i<queryString.length; i++) {
mtch = queryString[i].match(/'([^']+)'\.([a-zA-Z0-9_]+)='([^']+)'\.([a-zA-Z0-9_]+)/);
if (mtch && mtch.length==5) {
var tmp={};
tmp[mtch[1]] = mtch[2];
tmp[mtch[3]] = mtch[4];
factory.push(tmp);
}
}
return factory;
},
/**
@ignore
@name $SP()._cleanString
@function
@description clean a string to remove the bad characters when using AJAX over Sharepoint web services (like <, > and &)
Note: That should only be used as an internal function
@param {String} string The string to clean
*/
_cleanString:function(str) {
return str.replace(/&(?!amp;|lt;|gt;)/g, "&").replace(/</g, "<").replace(/>/g, ">");
},
/**
@name $SP().cleanResult
@function
@category lists
@description clean a string returned by a GET (remove ";#" and "string;#" and null becomes "")
@param {String} str The string to clean
@param {String} [separator=";"] When it's a list we may want to have a different output (see examples)
@return {String} the cleaned string
@example
$SP().cleanResult("15;#Paul"); // -> "Paul"
$SP().cleanResult("string;#Paul"); // -> "Paul"
$SP().cleanResult("string;#"); // -> ""
$SP().cleanResult(";#Paul;#Jacques;#Aymeric;#"); // -> "Paul;Jacques;Aymeric"
$SP().cleanResult(";#Paul;#Jacques;#Aymeric;#", ", "); // -> "Paul, Jacques, Aymeric"
*/
cleanResult:function(str,separator) {
if (str===null || typeof str==="undefined") return "";
separator = separator || ";";
return (typeof str==="string"?str.replace(/^(string;|float;|datetime;)#?/,"").replace(/;#[0-9]+;#/g,separator).replace(/^[0-9]+;#/,"").replace(/^;#|;#$/g,"").replace(/;#/g,separator):str);
},
/**
@name $SP().list.get
@function
@description Get the content of the list based on different criteria (by default the default view is used)
@param {Object} [options] Options (see below)
@param {String} [options.fields=""] The fields you want to grab (be sure to add "Attachments" as a field if you want to know the direct link to an attachment)
@param {String} [options.view=""] If you specify a viewID or a viewName that exists for that list, then the fields/where/order settings for this view will be used in addition to the FIELDS/WHERE/ORDERBY you have defined (the user settings will be used first)
@param {String|Array} [options.where=""] The query string (like SQL syntax) (you'll need to use double \\ before the inside ' -- see example below); you can use an array that will make the sequential requests but it will return all the data into one array (useful for the Sharepoint 2010 throttling limit)
@param {Boolean} [options.whereCAML=false] If you want to pass a WHERE clause that is with CAML Syntax only instead of SQL-like syntax -- see $SP().parse() for more info
@param {Boolean} [options.whereEscapeChar=true] Determines if we want to escape the special chars that will cause an error (for example '&' will be automatically converted to '&') -- this is applied to the WHERE clause only
@param {Function} [options.whereFct=function(w){return w}] Permits to apply your own function on the WHERE clause after conversion to CAML (can be useful also when you use the "view" parameter)
@param {Function} [options.progress] When using an array for the WHERE or the PAGING option then you can call the progress function (see the example)
@param {String} [options.orderby=""] The field used to sort the list result (you can also add "ASC" -default- or "DESC")
@param {String} [options.groupby=""] The field used to group by the list result
@param {Integer} [options.rowlimit=0] You can define the number of rows you want to receive back (0 is infinite)
@param {Boolean} [options.paging=false] If you have defined the 'rowlimit' then you can use 'paging' to cut by packets your full request -- this is useful when there is a list view threshold (attention: we cannot use "WHERE" or "ORDERBY" with this option)
@param {Integer} [options.page=infinite] When you use the `paging` option, several requests will be done until we get all the data, but using the `page` option you can define the number of requests/pages you want to get
@param {String} [options.listItemCollectionPositionNext=""] When doing paging, this is the index used by Sharepoint to get the next page
@param {Boolean} [options.useIndexForOrderBy=false] Based on https://spservices.codeplex.com/discussions/280642#post1323410 it permits to override the 5,000 items limit in an unique call (for Sharepoint 2010 only) -- see the example below to know how to use it