-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathutil.js
2154 lines (1958 loc) · 72.5 KB
/
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
//todo
// pageURL refURL protocol related functions
// forEachOnArray
var CONFIG = require("./config.js");
var CONSTANTS = require("./constants.js");
var conf = require("./conf.js");
var BID = require("./bid.js");
var bidManager = require("./bidManager.js");
var debugLogIsEnabled = false;
/* start-test-block */
exports.debugLogIsEnabled = debugLogIsEnabled;
/* end-test-block */
var visualDebugLogIsEnabled = false;
/* start-test-block */
exports.visualDebugLogIsEnabled = visualDebugLogIsEnabled;
/* end-test-block */
var typeArray = "Array";
var typeString = "String";
var typeFunction = "Function";
var typeNumber = "Number";
var toString = Object.prototype.toString;
var refThis = this;
refThis.idsAppendedToAdUnits = false;
var mediaTypeConfigPerSlot = {};
exports.mediaTypeConfig = mediaTypeConfigPerSlot;
var pbNameSpace = parseInt(conf[CONSTANTS.CONFIG.COMMON][CONSTANTS.COMMON.IDENTITY_ONLY] || CONSTANTS.CONFIG.DEFAULT_IDENTITY_ONLY) ? CONSTANTS.COMMON.IH_NAMESPACE : CONSTANTS.COMMON.PREBID_NAMESPACE;
exports.pbNameSpace = pbNameSpace;
function isA(object, testForType) {
return toString.call(object) === "[object " + testForType + "]";
}
/* start-test-block */
exports.isA = isA;
/* end-test-block */
exports.isFunction = function (object) {
return refThis.isA(object, typeFunction);
};
exports.isString = function (object) {
return refThis.isA(object, typeString);
};
exports.isArray = function (object) {
return refThis.isA(object, typeArray);
};
exports.isNumber = function(object) {
return refThis.isA(object, typeNumber);
};
exports.isObject = function(object){
return typeof object === "object" && object !== null;
};
exports.isOwnProperty = function(theObject, proertyName){
/* istanbul ignore else */
if(refThis.isObject(theObject) && theObject.hasOwnProperty){
return theObject.hasOwnProperty(proertyName);
}
return false;
};
exports.isUndefined = function(object){
return typeof object === "undefined";
};
exports.enableDebugLog = function(){
refThis.debugLogIsEnabled = true;
};
exports.isDebugLogEnabled = function(){
return refThis.debugLogIsEnabled;
};
exports.enableVisualDebugLog = function(){
refThis.debugLogIsEnabled = true;
refThis.visualDebugLogIsEnabled = true;
};
exports.isEmptyObject= function(object){
return refThis.isObject(object) && Object.keys(object).length === 0;
};
//todo: move...
var constDebugInConsolePrependWith = "[OpenWrap] : ";
var constErrorInConsolePrependWith = "[OpenWrap] : [Error]";
exports.log = function(data){
if( refThis.debugLogIsEnabled && console && this.isFunction(console.log) ){ // eslint-disable-line no-console
if(this.isString(data)){
console.log( (new Date()).getTime()+ " : " + constDebugInConsolePrependWith + data ); // eslint-disable-line no-console
}else{
console.log(data); // eslint-disable-line no-console
}
}
};
exports.logError = function(data){
if( refThis.debugLogIsEnabled && console && this.isFunction(console.log) ){ // eslint-disable-line no-console
if(this.isString(data)){
console.error( (new Date()).getTime()+ " : " + constDebugInConsolePrependWith + data ); // eslint-disable-line no-console
}else{
console.error(data); // eslint-disable-line no-console
}
}
};
exports.logWarning = function(data){
if( refThis.debugLogIsEnabled && console && this.isFunction(console.log) ){ // eslint-disable-line no-console
if(this.isString(data)){
console.warn( (new Date()).getTime()+ " : " + constDebugInConsolePrependWith + data ); // eslint-disable-line no-console
}else{
console.warn(data); // eslint-disable-line no-console
}
}
};
exports.error = function(data){
console.log( (new Date()).getTime()+ " : " + constErrorInConsolePrependWith, data ); // eslint-disable-line no-console
};
exports.getCurrentTimestampInMs = function(){
var date = new window.Date();
return date.getTime();
};
exports.getCurrentTimestamp = function(){
var date = new Date();
return Math.round( date.getTime()/1000 );
};
var utilGetIncrementalInteger = (function() {
var count = 0;
return function() {
count++;
return count;
};
})();
/* start-test-block */
exports.utilGetIncrementalInteger = utilGetIncrementalInteger;
/* end-test-block */
exports.getUniqueIdentifierStr = function() {
return utilGetIncrementalInteger() + window.Math.random().toString(16).substr(2);
};
// removeIf(removeLegacyAnalyticsRelatedCode)
exports.copyKeyValueObject = function(copyTo, copyFrom){
/* istanbul ignore else */
if(refThis.isObject(copyTo) && refThis.isObject(copyFrom)){
var utilRef = refThis;
refThis.forEachOnObject(copyFrom, function(key, value){
copyFrom[key] = utilRef.isArray(value) ? value : [value];
if(utilRef.isOwnProperty(copyTo, key)){
// copyTo[key].push.apply(copyTo[key], value);
if (!refThis.isArray(copyTo[key])) {
var temp = copyTo[key];
copyTo[key] = [temp];
}
copyTo[key].push(value);
}else{
copyTo[key] = [value];
}
});
}
};
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
exports.getIncrementalInteger = (function() {
var count = 0;
return function() {
count++;
return count;
};
})();
exports.generateUUID = function(){
var d = new window.Date().getTime(),
// todo: this.pageURL ???
url = window.decodeURIComponent(this.pageURL).toLowerCase().replace(/[^a-z,A-Z,0-9]/gi, ""),
urlLength = url.length
;
//todo: uncomment it, what abt performance
//if(win.performance && this.isFunction(win.performance.now)){
// d += performance.now();
//}
var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx-zzzzz".replace(/[xyz]/g, function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
var op;
switch(c){
case "x":
op = r;
break;
case "z":
op = url[Math.floor(Math.random()*urlLength)];
break;
default:
op = (r&0x3|0x8);
}
return op.toString(16);
});
return uuid;
};
var macroRegexFlag = "g";
var constCommonMacroForWidthRegExp = new RegExp(CONSTANTS.MACROS.WIDTH, macroRegexFlag);
var constCommonMacroForHeightRegExp = new RegExp(CONSTANTS.MACROS.HEIGHT, macroRegexFlag);
var constCommonMacroForAdUnitIDRegExp = new RegExp(CONSTANTS.MACROS.AD_UNIT_ID, macroRegexFlag);
var constCommonMacroForAdUnitIndexRegExp = new RegExp(CONSTANTS.MACROS.AD_UNIT_INDEX, macroRegexFlag);
var constCommonMacroForIntegerRegExp = new RegExp(CONSTANTS.MACROS.INTEGER, macroRegexFlag);
var constCommonMacroForDivRegExp = new RegExp(CONSTANTS.MACROS.DIV, macroRegexFlag);
exports.generateSlotNamesFromPattern = function(activeSlot, pattern, shouldCheckMappingForVideo, videoSlotName){
var slotNames = [],
slotName,
slotNamesObj = {},
sizeArray,
sizeArrayLength,
i
;
/* istanbul ignore else */
if(refThis.isObject(activeSlot) && refThis.isFunction(activeSlot.getSizes)){
sizeArray = activeSlot.getSizes();
var divId = refThis.isFunction(activeSlot.getDivID) ? activeSlot.getDivID() : activeSlot.getSlotId().getDomId();
if(shouldCheckMappingForVideo){
//TODO: remove below line and update above live for assigning sizeArray after remove phantom js and including chromeheadless
// This adds an size 0x0 to sizes so that multiple kgpvs can be generated
sizeArray = [].concat(activeSlot.getSizes());
var config = refThis.mediaTypeConfig[divId];
if(config && config.video){
sizeArray.unshift([0,0]);
}
}
sizeArrayLength = sizeArray.length;
/* istanbul ignore else */
if( sizeArrayLength > 0){
for(i = 0; i < sizeArrayLength; i++){
/* istanbul ignore else */
if((sizeArray[i].length == 2 && (sizeArray[i][0] && sizeArray[i][1]) || (sizeArray[i][0] == 0 && sizeArray[i][1] ==0)) || (refThis.isFunction(sizeArray[i].getWidth) && refThis.isFunction(sizeArray[i].getHeight))){ var adUnitId = refThis.isFunction(activeSlot.getAdUnitID) ? activeSlot.getAdUnitID() : activeSlot.getSlotId().getAdUnitPath();
var divId = refThis.isFunction(activeSlot.getDivID) ? activeSlot.getDivID() : activeSlot.getSlotId().getDomId();
var adUnitIndex = refThis.isFunction(activeSlot.getAdUnitIndex) ? activeSlot.getAdUnitIndex() : activeSlot.getSlotId().getId().split("_")[1];
var width = sizeArray[i][0] == 0 ? 0 : sizeArray[i][0] || sizeArray[i].getWidth();
var height = sizeArray[i][1] == 0 ? 0 : sizeArray[i][1] || sizeArray[i].getHeight();
slotName = pattern;
slotName = slotName.replace(constCommonMacroForAdUnitIDRegExp, adUnitId)
.replace(constCommonMacroForAdUnitIndexRegExp, adUnitIndex)
.replace(constCommonMacroForIntegerRegExp, refThis.getIncrementalInteger())
.replace(constCommonMacroForDivRegExp, divId)
.replace(constCommonMacroForWidthRegExp, width)
.replace(constCommonMacroForHeightRegExp, height);
// if size is 0x0 then we don't want to add it in slotNames since it will be looped in another function
// we just want to check the config for 0x0 mapping hence updating it in videoSlotName
/* istanbul ignore else */
if(width == 0 && height == 0){
videoSlotName[0] = slotName;
/* istanbul ignore else */
}
else if(! refThis.isOwnProperty(slotNamesObj, slotName)){
slotNamesObj[slotName] = "";
slotNames.push(slotName);
}
}
}
}
}
return slotNames;
};
/**
* todo:
* if direct mapping is not found
* then look for regex mapping
* separate function to handle regex mapping
* kgp: "" // should be filled with whatever value
* klm: {} // should be filled with records if required else leave it as an empty object {}
* kgp_rx: "" // regex pattern
* klm_rx: [
* {
* rx: "ABC123*",
* rx_config: {} // here goes adapyter config
* },
*
* {
* rx: "*",
* rx_config: {}
* }
* ]
*/
/**
* Algo for Regex and Normal Flow
* 1. Check for kgp key
* a). If KGP is present for partner then proceed with old flow and no change in that
* b). If KGP is not present and kgp_rx is present it is regex flow and proceed with regex flow as below
* 2. Regex Flow
* a. Generate KGPV's with kgp as _AU_@_DIV_@_W_x_H_
* b. Regex Match each KGPV with KLM_rx
* c. Get config for the partner
* d. Send the config to prebid and log the same kgpv in logger
*
* Special Case for Pubmatic
* 1. In case of regex flow we will have hashed keys which will be sent to translator for matching
* 2. These hashed keys could be same for multiple slot on the page and hence need to check how to send it to prebid for
* identification in prebid resposne.
*/
exports.forEachGeneratedKey = function(adapterID, adUnits, adapterConfig, impressionID, slotConfigMandatoryParams, activeSlots, handlerFunction, addZeroBids){
var activeSlotsLength = activeSlots.length,
keyGenerationPattern = adapterConfig[CONSTANTS.CONFIG.KEY_GENERATION_PATTERN] || adapterConfig[CONSTANTS.CONFIG.REGEX_KEY_GENERATION_PATTERN] || "";
/* istanbul ignore else */
if(activeSlotsLength > 0 && keyGenerationPattern.length > 3){
refThis.forEachOnArray(activeSlots, function(i, activeSlot){
var videoSlotName = [];
// We are passing videoSlotName because we don't want to update the sizes and just check for 0x0 config if video and banner is both enabeld
var generatedKeys = refThis.generateSlotNamesFromPattern( activeSlot, keyGenerationPattern, true, videoSlotName);
if(generatedKeys.length > 0){
refThis.callHandlerFunctionForMapping(adapterID, adUnits, adapterConfig, impressionID, slotConfigMandatoryParams, generatedKeys, activeSlot, handlerFunction, addZeroBids, keyGenerationPattern, videoSlotName);
}
});
}
};
// private
function callHandlerFunctionForMapping(adapterID, adUnits, adapterConfig, impressionID, slotConfigMandatoryParams, generatedKeys, activeSlot, handlerFunction, addZeroBids,keyGenerationPattern, videoSlotName){
var keyLookupMap = adapterConfig[CONSTANTS.CONFIG.KEY_LOOKUP_MAP] || adapterConfig[CONSTANTS.CONFIG.REGEX_KEY_LOOKUP_MAP] || null,
kgpConsistsWidthAndHeight = keyGenerationPattern.indexOf(CONSTANTS.MACROS.WIDTH) >= 0 && keyGenerationPattern.indexOf(CONSTANTS.MACROS.HEIGHT) >= 0;
var isRegexMapping = adapterConfig[CONSTANTS.CONFIG.REGEX_KEY_LOOKUP_MAP] ? true : false;
var regexPattern = undefined;
const adapterNameForAlias = CONFIG.getAdapterNameForAlias(adapterID);
var isPubMaticAlias = CONSTANTS.PUBMATIC_ALIASES.indexOf(adapterNameForAlias) > - 1 ? true : false;
var regExMappingWithNoConfig = false;
refThis.forEachOnArray(generatedKeys, function(j, generatedKey){
var keyConfig = null,
callHandlerFunction = false,
sizeArray = activeSlot.getSizes()
;
if(keyLookupMap == null){
// This block executes for pubmatic only where there are no KLM's
// Adding this check for pubmatic only to send the correct tagId for Size Level mapping. UOE-6156
if(videoSlotName && videoSlotName.length == 1){
generatedKey = videoSlotName[0];
}
callHandlerFunction = true;
}else{
if(isRegexMapping){
refThis.debugLogIsEnabled && refThis.log(console.time("Time for regexMatching for key " + generatedKey));
var config = refThis.getConfigFromRegex(keyLookupMap,generatedKey);
refThis.debugLogIsEnabled && refThis.log(console.timeEnd("Time for regexMatching for key " + generatedKey));
if(config){
keyConfig = config.config;
regexPattern = config.regexPattern;
}else{
// if klm_rx dosen't return any config and if partner is PubMatic alias we need to restrict call to handlerFunction
// so adding flag regExMappingWithNoConfig below
regExMappingWithNoConfig = isPubMaticAlias ? true : false;
}
}
else{
// Added Below Check Because of UOE-5600
if(videoSlotName && videoSlotName.length == 1){
// Commented out normal lookup and added below check to remove case sensitive check on videoSlotName[0].
// keyConfig = keyLookupMap[videoSlotName[0]];
// keyConfig = keyLookupMap[Object.keys(keyLookupMap).find(key => key.toLowerCase() === videoSlotName[0].toLowerCase())];
keyConfig = keyLookupMap[Object.keys(keyLookupMap).filter(function(key) {
return key.toLowerCase() === videoSlotName[0].toLowerCase()
})];
// We are updating the generatedKey because we want to log kgpv as 0x0 in case of video
if(keyConfig){
generatedKey = videoSlotName[0];
}
}
if(!keyConfig){
// Commented out normal lookup and added below check to remove case sensitive check on generatedKey.
// keyConfig = keyLookupMap[generatedKey];
keyConfig = keyLookupMap[Object.keys(keyLookupMap).filter(function(key) {
return key.toLowerCase() === generatedKey.toLowerCase()
})[0]];
}
}
// condition (!keyConfig && !isPubMaticAlias) will check if keyCofig is undefined and partner is not PubMatic alias then log message to console
// with "adapterID+": "+generatedKey+ config not found"
// regExMappingWithNoConfig will be true only if klm_rx dosen't return config and partner is PubMatic alias then log message to console
// with "adapterID+": "+generatedKey+ config not found"
if((!keyConfig && !isPubMaticAlias) || regExMappingWithNoConfig){
refThis.log(adapterID+": "+generatedKey+CONSTANTS.MESSAGES.M8);
}else{
callHandlerFunction = true;
}
}
/* istanbul ignore else */
if(callHandlerFunction){
/* istanbul ignore else */
if(addZeroBids == true){
var bid = BID.createBid(adapterID, generatedKey);
bid.setDefaultBidStatus(1).setReceivedTime(refThis.getCurrentTimestampInMs());
bidManager.setBidFromBidder(activeSlot.getDivID(), bid);
bid.setRegexPattern(regexPattern);
}
handlerFunction(
adapterID,
adUnits,
adapterConfig,
impressionID,
generatedKey,
kgpConsistsWidthAndHeight,
activeSlot,
refThis.getPartnerParams(keyConfig),
sizeArray[j][0],
sizeArray[j][1],
regexPattern
);
}
});
}
/* start-test-block */
exports.callHandlerFunctionForMapping = callHandlerFunctionForMapping;
/* end-test-block */
// removeIf(removeLegacyAnalyticsRelatedCode)
exports.resizeWindow = function(theDocument, width, height, divId){
/* istanbul ignore else */
if(height && width){
try{
var defaultViewFrame = theDocument.defaultView.frameElement;
var elementArray=[];
if(divId){
var adSlot = document.getElementById(divId);
var adSlot_Div = adSlot.querySelector("div");
elementArray.push(adSlot_Div);
elementArray.push(adSlot_Div.querySelector("iframe"));
defaultViewFrame = adSlot.querySelector("iframe");
}
elementArray.push(defaultViewFrame);
elementArray.forEach(function(ele){
if(ele){
ele.width ="" + width;
ele.height ="" + height;
ele.style.width = "" + width + "px";
ele.style.height = "" + height + "px";
}
});
}catch(e){
refThis.logError("Creative-Resize; Error in resizing creative");
} // eslint-disable-line no-empty
}
};
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
// removeIf(removeLegacyAnalyticsRelatedCode)
exports.writeIframe = function(theDocument, src, width, height, style){
theDocument.write("<iframe"
+ " frameborder=\"0\" allowtransparency=\"true\" marginheight=\"0\" marginwidth=\"0\" scrolling=\"no\" width=\""
+ width + "\" hspace=\"0\" vspace=\"0\" height=\""
+ height + "\""
+ (style ? " style=\""+ style+"\"" : "" )
+ " src=\"" + src + "\""
+ "></ifr" + "ame>");
};
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
// removeIf(removeLegacyAnalyticsRelatedCode)
exports.displayCreative = function(theDocument, bid){
if(bid && bid.pbbid && bid.pbbid.mediaType == "video" && bid.renderer && refThis.isObject(bid.renderer)){
if(refThis.isFunction(bid.renderer.render)){
bid.renderer.render(bid.getPbBid());
}
}
else{
refThis.resizeWindow(theDocument, bid.width, bid.height);
if(bid.adHtml){
bid.adHtml = refThis.replaceAuctionPrice(bid.adHtml, bid.getGrossEcpm());
theDocument.write(bid.adHtml);
}else if(bid.adUrl){
bid.adUrl = refThis.replaceAuctionPrice(bid.adUrl, bid.getGrossEcpm());
refThis.writeIframe(theDocument, bid.adUrl, bid.width, bid.height, "");
}else{
refThis.logError("creative details are not found");
refThis.logError(bid);
}
}
};
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
// todo: how about accepting array of arguments to be passed to callback function after key, value, arrayOfArguments
exports.forEachOnObject = function(theObject, callback){
/* istanbul ignore else */
if(!refThis.isObject(theObject)){
return;
}
/* istanbul ignore else */
if(!refThis.isFunction(callback)){
return;
}
for(var key in theObject){
/* istanbul ignore else */
if(refThis.isOwnProperty(theObject, key)){
callback(key, theObject[key]);
}
}
};
exports.forEachOnArray = function(theArray, callback){
/* istanbul ignore else */
if(!refThis.isArray(theArray)){
return;
}
/* istanbul ignore else */
if(!refThis.isFunction(callback)){
return;
}
for(var index=0, arrayLength= theArray.length; index<arrayLength; index++){
callback(index, theArray[index]);
}
};
exports.trim = function(s){
if(!refThis.isString(s)){
return s;
}else{
return s.replace(/^\s+/g,"").replace(/\s+$/g,"");
}
};
exports.getTopFrameOfSameDomain = function(cWin) {
try {
/* istanbul ignore else */
if (cWin.parent.document != cWin.document){
return refThis.getTopFrameOfSameDomain(cWin.parent);
}
} catch(e) {}
return cWin;
};
exports.metaInfo = {};
exports.getMetaInfo = function(cWin){
var obj = {}
, MAX_PAGE_URL_LEN = 512
, frame
;
obj.pageURL = "";
obj.refURL = "";
obj.protocol = "https://";
obj.secure = 1;
obj.isInIframe = refThis.isIframe(cWin);
try{
frame = refThis.getTopFrameOfSameDomain(cWin);
obj.refURL = ( frame.refurl || frame.document.referrer || '' ).substr( 0, MAX_PAGE_URL_LEN );
obj.pageURL = ( frame !== window.top && frame.document.referrer != "" ? frame.document.referrer : frame.location.href).substr(0, MAX_PAGE_URL_LEN );
obj.protocol = (function(frame){
/* istanbul ignore else */
if(frame.location.protocol === "http:"){
obj.secure = 0;
return "http://";
}
obj.secure = 1;
return "https://";
})(frame);
}catch(e){}
obj.pageDomain = refThis.getDomainFromURL(obj.pageURL);
refThis.metaInfo = obj;
return obj;
};
exports.isIframe = function(theWindow){
try{
return theWindow.self !== theWindow.top;
}catch(e){
return false;
}
};
exports.findQueryParamInURL = function(url, name){
return refThis.isOwnProperty(refThis.parseQueryParams(url), name);
};
exports.parseQueryParams = function(url){
var parser = refThis.createDocElement(window, 'a');
parser.href = url;
var params = {};
/* istanbul ignore else */
if(parser.search){
var queryString = parser.search.replace('?', '');
queryString = queryString.split('&');
refThis.forEachOnArray(queryString, function(index, keyValue){
var keyValue = keyValue.split('=');
var key = keyValue[0] || '';
var value = keyValue [1] || '';
params[key] = value;
});
}
return params;
};
exports.createDocElement = function(win, elementName) {
return win.document.createElement(elementName);
};
exports.addHookOnFunction = function(theObject, useProto, functionName, newFunction){
var callMethodOn = theObject;
theObject = useProto ? theObject.__proto__ : theObject;
if(refThis.isObject(theObject) && refThis.isFunction(theObject[functionName])){
var originalFunction = theObject[functionName];
theObject[functionName] = newFunction(callMethodOn, originalFunction);
}else{
refThis.logWarning("in assignNewDefination: oldReference is not a function");
}
};
exports.getBididForPMP = function(values, priorityArray){
values = values.split(',');
var valuesLength = values.length,
priorityArrayLength = priorityArray.length,
selectedPMPDeal = '',
bidID = ''
;
/* istanbul ignore else */
if(valuesLength == 0){
this.log('Error: Unable to find bidID as values array is empty.');
return;
}
for(var i = 0; i < priorityArrayLength; i++){
for(var j = 0; j < valuesLength; j++){
if(values[j].indexOf(priorityArray[i]) >= 0){
selectedPMPDeal = values[j];
break;
}
}
/* istanbul ignore else */
if(selectedPMPDeal != ''){
break;
}
}
if(selectedPMPDeal == ''){
selectedPMPDeal = values[0];
this.log('No PMP-Deal was found matching PriorityArray, So Selecting first PMP-Deal: '+ selectedPMPDeal);
}else{
this.log('Selecting PMP-Deal: '+ selectedPMPDeal);
}
var temp = selectedPMPDeal.split(CONSTANTS.COMMON.DEAL_KEY_VALUE_SEPARATOR);
/* istanbul ignore else */
if(temp.length == 3){
bidID = temp[2];
}
/* istanbul ignore else */
if(!bidID){
this.log('Error: bidID not found in PMP-Deal: '+ selectedPMPDeal);
return;
}
return bidID;
};
function insertElement(elm, doc, target, asLastChildChild) {
doc = doc || document;
var parentEl;
if (target) {
parentEl = doc.getElementsByTagName(target);
} else {
parentEl = doc.getElementsByTagName('head');
}
try {
parentEl = parentEl.length ? parentEl : doc.getElementsByTagName('body');
if (parentEl.length) {
parentEl = parentEl[0];
var insertBeforeEl = asLastChildChild ? null : parentEl.firstChild;
return parentEl.insertBefore(elm, insertBeforeEl);
}
} catch (e) {}
}
exports.insertHtmlIntoIframe = function(htmlCode) {
if (!htmlCode) {
return;
}
var iframe = document.createElement('iframe');
iframe.id = refThis.getUniqueIdentifierStr();
iframe.width = 0;
iframe.height = 0;
iframe.hspace = '0';
iframe.vspace = '0';
iframe.marginWidth = '0';
iframe.marginHeight = '0';
iframe.style.display = 'none';
iframe.style.height = '0px';
iframe.style.width = '0px';
iframe.scrolling = 'no';
iframe.frameBorder = '0';
iframe.allowtransparency = 'true';
insertElement(iframe, document, 'body');
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(htmlCode);
iframe.contentWindow.document.close();
}
// removeIf(removeNativeRelatedCode)
exports.createInvisibleIframe = function() {
var f = refThis.createDocElement(window, 'iframe');
f.id = refThis.getUniqueIdentifierStr();
f.height = 0;
f.width = 0;
f.border = '0px';
f.hspace = '0';
f.vspace = '0';
f.marginWidth = '0';
f.marginHeight = '0';
f.style.border = '0';
f.scrolling = 'no';
f.frameBorder = '0';
//f.src = 'about:self';//todo: test by setting empty src on safari
f.style = 'display:none';
return f;
}
// endRemoveIf(removeNativeRelatedCode)
// removeIf(removeLegacyAnalyticsRelatedCode)
exports.addMessageEventListener = function(theWindow, eventHandler){
/* istanbul ignore else */
if(typeof eventHandler !== "function"){
refThis.log("EventHandler should be a function");
return false;
}
if(theWindow.addEventListener){
theWindow.addEventListener("message", eventHandler, false);
}else{
theWindow.attachEvent("onmessage", eventHandler);
}
return true;
};
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
// removeIf(removeLegacyAnalyticsRelatedCode)
exports.safeFrameCommunicationProtocol = function(msg){
try{
var bidSlotId;
msgData = window.JSON.parse(msg.data);
/* istanbul ignore else */
if(!msgData.pwt_type){
return;
}
switch(window.parseInt(msgData.pwt_type)){
case 1:
/* istanbul ignore else */
if(window.PWT.isSafeFrame){
return;
}
var bidDetails = bidSlotId = bidManager.getBidById(msgData.pwt_bidID);
/* istanbul ignore else */
if(bidDetails){
var theBid = bidDetails.bid;
var adapterID = theBid.getAdapterID(),
divID = bidDetails.slotid,
newMsgData = {
pwt_type: 2,
pwt_bid: theBid
};
refThis.vLogInfo(divID, {type: 'disp', adapter: adapterID});
bidManager.executeMonetizationPixel(divID, theBid);
// outstream video renderer for safe frame.
if(theBid && theBid.pbbid && theBid.pbbid.mediaType == "video" && theBid.renderer && refThis.isObject(theBid.renderer)){
if(refThis.isFunction(theBid.renderer.render)){
theBid.renderer.render(theBid.getPbBid());
}
}else{
refThis.resizeWindow(window.document, theBid.width, theBid.height, divID);
msg.source.postMessage(window.JSON.stringify(newMsgData), msgData.pwt_origin);
}
}
break;
case 2:
/* istanbul ignore else */
if(!window.PWT.isSafeFrame){
return;
}
/* istanbul ignore else */
if(msgData.pwt_bid){
var theBid = msgData.pwt_bid;
if(theBid.adHtml){
try{
var iframe = refThis.createInvisibleIframe(window.document);
/* istanbul ignore else */
if(!iframe){
throw {message: 'Failed to create invisible frame.', name:""};
}
iframe.setAttribute('width', theBid.width);
iframe.setAttribute('height', theBid.height);
iframe.style = '';
window.document.body.appendChild(iframe);
/* istanbul ignore else */
if(!iframe.contentWindow){
throw {message: 'Unable to access frame window.', name:""};
}
var iframeDoc = iframe.contentWindow.document;
/* istanbul ignore else */
if(!iframeDoc){
throw {message: 'Unable to access frame window document.', name:""};
}
var content = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><base target="_top" /><scr' + 'ipt>inDapIF=true;</scr' + 'ipt></head>';
content += '<body>';
content += "<script>var $sf = window.parent.$sf;<\/script>";
content += "<script>setInterval(function(){try{var fr = window.document.defaultView.frameElement;fr.width = window.parent.document.defaultView.innerWidth;fr.height = window.parent.document.defaultView.innerHeight;}catch(e){}}, 200);</script>";
content += theBid.adHtml;
content += '</body></html>';
iframeDoc.write(content);
iframeDoc.close();
}catch(e){
refThis.logError('Error in rendering creative in safe frame.');
refThis.log(e);
refThis.log('Rendering synchronously.');
refThis.displayCreative(window.document, msgData.pwt_bid);
}
}else if(theBid.adUrl){
refThis.writeIframe(window.document, theBid.adUrl, theBid.width, theBid.height, "");
}else{
refThis.logWarning("creative details are not found");
refThis.log(theBid);
}
}
break;
// removeIf(removeNativeRelatedCode)
case 3:
if(CONFIG.isPrebidPubMaticAnalyticsEnabled()){
var msg = { message: 'Prebid Native', adId: msgData.pwt_bidID, action: msgData.pwt_action };
window.postMessage(JSON.stringify(msg), "*");
}else{
var bidDetails = bidSlotId = bidManager.getBidById(msgData.pwt_bidID);
/* istanbul ignore else */
if(bidDetails){
var theBid = bidDetails.bid,
adapterID = theBid.getAdapterID(),
divID = bidDetails.slotid;
refThis.vLogInfo(divID, {type: 'disp', adapter: adapterID});
if(msgData.pwt_action && msgData.pwt_action == "imptrackers"){
bidManager.executeMonetizationPixel(divID, theBid);
}
bidManager.fireTracker(theBid,msgData.pwt_action);
}
}
break;
// endRemoveIf(removeNativeRelatedCode)
}
// Check if browsers local storage has auction related data and update impression served count accordingly.
var frequencyDepth = JSON.parse(localStorage.getItem('PROFILE_AUCTION_INFO_' + window.location.hostname)) || {};
if (frequencyDepth !== null && frequencyDepth.slotLevelFrquencyDepth) {
frequencyDepth.slotLevelFrquencyDepth[frequencyDepth.codeAdUnitMap[bidSlotId && bidSlotId.slotid]].impressionServed = frequencyDepth.slotLevelFrquencyDepth[frequencyDepth.codeAdUnitMap[bidSlotId && bidSlotId.slotid]].impressionServed + 1;
frequencyDepth.impressionServed = frequencyDepth.impressionServed + 1;
}
localStorage.setItem('PROFILE_AUCTION_INFO_' + window.location.hostname, JSON.stringify(frequencyDepth));
}catch(e){}
};
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
// removeIf(removeLegacyAnalyticsRelatedCode)
exports.addMessageEventListenerForSafeFrame = function(theWindow){
refThis.addMessageEventListener(theWindow, refThis.safeFrameCommunicationProtocol);
};
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
exports.getElementLocation = function( el ) {
var rect,
x = 0,
y = 0
;
if(refThis.isFunction(el.getBoundingClientRect)) {
rect = el.getBoundingClientRect();
x = Math.floor(rect.left);
y = Math.floor(rect.top);
} else {
while(el) {
x += el.offsetLeft;
y += el.offsetTop;
el = el.offsetParent;
}
}
return { x: x, y: y };
}
exports.createVLogInfoPanel = function(divID, dimensionArray){
var element,
infoPanelElement,
infoPanelElementID,
doc = window.document
;
/* istanbul ignore else */
if(refThis.visualDebugLogIsEnabled){
element = doc.getElementById(divID);
/* istanbul ignore else */
if(element && dimensionArray.length && dimensionArray[0][0] && dimensionArray[0][1]){
infoPanelElementID = divID + '-pwtc-info';
/* istanbul ignore else */
if(!refThis.isUndefined(doc.getElementById(infoPanelElementID))){
var pos = refThis.getElementLocation(element);
infoPanelElement = doc.createElement('div');
infoPanelElement.id = infoPanelElementID;
infoPanelElement.style = 'position: absolute; /*top: '+pos.y+'px;*/ left: '+pos.x+'px; width: '+dimensionArray[0][0]+'px; height: '+dimensionArray[0][1]+'px; border: 1px solid rgb(255, 204, 52); padding-left: 11px; background: rgb(247, 248, 224) none repeat scroll 0% 0%; overflow: auto; z-index: 9999997; visibility: hidden;opacity:0.9;font-size:13px;font-family:monospace;';
var closeImage = doc.createElement('img');
closeImage.src = refThis.metaInfo.protocol+"ads.pubmatic.com/AdServer/js/pwt/close.png";
closeImage.style = 'cursor:pointer; position: absolute; top: 2px; left: '+(pos.x+dimensionArray[0][0]-16-15)+'px; z-index: 9999998;';
closeImage.title = 'close';
closeImage.onclick = function(){
infoPanelElement.style.display = "none";
};
infoPanelElement.appendChild(closeImage);
infoPanelElement.appendChild(doc.createElement('br'));
var text = 'Slot: '+divID+' | ';
for(var i=0; i<dimensionArray.length; i++){
text += (i != 0 ? ', ' : '') + dimensionArray[i][0] + 'x' + dimensionArray[i][1];
}
infoPanelElement.appendChild(doc.createTextNode(text));
infoPanelElement.appendChild(doc.createElement('br'));
element.parentNode.insertBefore(infoPanelElement, element);
}
}
}
};
exports.realignVLogInfoPanel = function(divID){
var element,
infoPanelElement,
infoPanelElementID,
doc = window.document
;
/* istanbul ignore else */
if(refThis.visualDebugLogIsEnabled){
element = doc.getElementById(divID);
/* istanbul ignore else */
if(element){
infoPanelElementID = divID + '-pwtc-info';
infoPanelElement = doc.getElementById(infoPanelElementID);
/* istanbul ignore else */
if(infoPanelElement){
var pos = refThis.getElementLocation(element);
infoPanelElement.style.visibility = 'visible';
infoPanelElement.style.left = pos.x + 'px';
infoPanelElement.style.height = element.clientHeight + 'px';
}
}
}
};