plugins/pageview/tx_dlf_utils.js   F
last analyzed

Complexity

Total Complexity 107
Complexity/F 2.23

Size

Lines of Code 708
Function Count 48

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 0
nc 0
dl 0
loc 708
rs 2.1818
c 0
b 0
f 0
wmc 107
mnd 4
bc 79
fnc 48
bpm 1.6458
cpm 2.2291
noi 28

22 Functions

Rating   Name   Duplication   Size   Complexity  
A dlfUtils.fetchImageData 0 49 1
A tx_dlf_utils.js ➔ buildImageV1 0 13 1
B tx_dlf_utils.js ➔ getIIIFResource 0 34 1
B tx_dlf_utils.js ➔ supportsIIIF 0 18 11
A dlfUtils.getCookie 0 12 2
A dlfUtils.getUrlParams 0 14 2
B dlfUtils.fetchStaticImageData 0 26 1
A dlfUtils.setCookie 0 4 1
B dlfUtils.isCorsEnabled 0 34 3
B dlfUtils.createOl3Layers 0 101 2
B dlfUtils.createOl3View 0 38 4
A dlfUtils.exists 0 3 1
B tx_dlf_utils.js ➔ buildImageV2 0 27 1
A dlfUtils.isNull 0 3 1
A dlfUtils.isNullEmptyUndefinedOrNoNumber 0 3 1
A dlfUtils.fetchIIPData 0 21 1
A dlfUtils.parseDataDic 0 13 2
B dlfUtils.fetchZoomifyData 0 27 1
C dlfUtils.scaleToImageSize 0 39 7
B dlfUtils.isWebGLEnabled 0 22 6
A dlfUtils.searchFeatureCollectionForText 0 9 2
A tx_dlf_utils.js ➔ removeInfoJson 0 6 2

How to fix   Complexity   

Complexity

Complex classes like plugins/pageview/tx_dlf_utils.js often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
'use strict';
2
3
/**
4
 * (c) Kitodo. Key to digital objects e.V. <[email protected]>
5
 *
6
 * This file is part of the Kitodo and TYPO3 projects.
7
 *
8
 * @license GNU General Public License version 3 or later.
9
 * For the full copyright and license information, please read the
10
 * LICENSE.txt file that was distributed with this source code.
11
 */
12
13
/**
14
 * Base namespace for utility functions used by the dlf module.
15
 *
16
 * @const
17
 */
18
var dlfUtils = dlfUtils || {};
0 ignored issues
show
Bug introduced by
The variable dlfUtils seems to be never initialized.
Loading history...
19
20
/**
21
 * @type {{ZOOMIFY: string}}
22
 */
23
dlfUtils.CUSTOM_MIMETYPE = {
24
    IIIF: 'application/vnd.kitodo.iiif',
25
    IIP: 'application/vnd.netfpx',
26
    ZOOMIFY: 'application/vnd.kitodo.zoomify'
27
};
28
29
/**
30
 * @type {number}
31
 */
32
dlfUtils.RUNNING_INDEX = 99999999;
33
34
/**
35
 * @param imageSourceObjs
36
 * @param {string} opt_origin
37
 * @return {Array.<ol.layer.Layer>}
38
 */
39
dlfUtils.createOl3Layers = function (imageSourceObjs, opt_origin) {
40
41
    var origin = opt_origin !== undefined ? opt_origin : null,
42
        widthSum = 0,
43
        offsetWidth = 0,
44
        layers = [];
45
46
    imageSourceObjs.forEach(function (imageSourceObj) {
47
        var tileSize = void 0;
0 ignored issues
show
Coding Style introduced by
Consider using undefined instead of void(0). It is equivalent and more straightforward to read.
Loading history...
Unused Code introduced by
The assignment to variable tileSize seems to be never used. Consider removing it.
Loading history...
48
        if (widthSum > 0) {
49
            // set offset width in case of multiple images
50
            offsetWidth = widthSum;
51
        }
52
53
        //
54
        // Create layer
55
        //
56
        var extent = [offsetWidth, 0, imageSourceObj.width + offsetWidth, imageSourceObj.height],
57
            layer = void 0;
0 ignored issues
show
Coding Style introduced by
Consider using undefined instead of void(0). It is equivalent and more straightforward to read.
Loading history...
58
59
        if (imageSourceObj.mimetype === dlfUtils.CUSTOM_MIMETYPE.ZOOMIFY) {
60
            // create zoomify layer
61
            layer = new ol.layer.Tile({
0 ignored issues
show
Bug introduced by
The variable ol seems to be never declared. If this is a global, consider adding a /** global: ol */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
62
                source: new ol.source.Zoomify({
63
                    url: imageSourceObj.src,
64
                    size: [imageSourceObj.width, imageSourceObj.height],
65
                    crossOrigin: origin,
66
                    offset: [offsetWidth, 0]
67
                })
68
            });
69
        } else if (imageSourceObj.mimetype === dlfUtils.CUSTOM_MIMETYPE.IIIF) {
70
71
            var format;
72
            var quality;
73
            tileSize = imageSourceObj.tilesize !== undefined && imageSourceObj.tilesize.length > 0
0 ignored issues
show
Comprehensibility introduced by
Usage of the sequence operator is discouraged, since it may lead to obfuscated code.

The sequence or comma operator allows the inclusion of multiple expressions where only is permitted. The result of the sequence is the value of the last expression.

This operator is most often used in for statements.

Used in another places it can make code hard to read, especially when people do not realize it even exists as a seperate operator.

This check looks for usage of the sequence operator in locations where it is not necessary and could be replaced by a series of expressions or statements.

var a,b,c;

a = 1, b = 1,  c= 3;

could just as well be written as:

var a,b,c;

a = 1;
b = 1;
c = 3;

To learn more about the sequence operator, please refer to the MDN.

Loading history...
74
                ? imageSourceObj.tilesize[0]
75
                    : 256,
76
                format = $.inArray('jpg', imageSourceObj.formats) || $.inArray('jpeg', imageSourceObj.formats)
77
                    ? 'jpg'
78
                    : imageSourceObj.formats.length > 0
79
                        ? imageSourceObj.formats[0]
80
                        : 'jpg',
81
                quality = imageSourceObj.qualities !== undefined && imageSourceObj.qualities.length > 0
82
                    ? imageSourceObj.qualities[0]
83
                    : 'native';
84
85
            layer = new ol.layer.Tile({
86
                source: new dlfViewerSource.IIIF({
0 ignored issues
show
Bug introduced by
The variable dlfViewerSource seems to be never declared. If this is a global, consider adding a /** global: dlfViewerSource */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
87
                    url: imageSourceObj.src,
88
                    size: [imageSourceObj.width, imageSourceObj.height],
89
                    crossOrigin: origin,
90
                    resolutions: imageSourceObj.resolutions,
91
                    tileSize: tileSize,
92
                    format: format,
93
                    quality: quality,
94
                    offset: [offsetWidth, 0],
95
                    projection: new ol.proj.Projection({
96
                        code: 'goobi-image',
97
                        units: 'pixels',
98
                        extent: extent
99
                    })
100
                })
101
            });
102
        } else if (imageSourceObj.mimetype === dlfUtils.CUSTOM_MIMETYPE.IIP) {
103
            tileSize = imageSourceObj.tilesize !== undefined && imageSourceObj.tilesize.length > 0
104
                ? imageSourceObj.tilesize[0]
105
                : 256;
106
107
            layer = new ol.layer.Tile({
108
                source: new dlfViewerSource.IIP({
109
                    url: imageSourceObj.src,
110
                    size: [imageSourceObj.width, imageSourceObj.height],
111
                    crossOrigin: origin,
112
                    tileSize: tileSize,
113
                    offset: [offsetWidth, 0]
114
                })
115
            });
116
        } else {
117
118
            // create static image source
119
            layer = new ol.layer.Image({
120
                source: new ol.source.ImageStatic({
121
                    url: imageSourceObj.src,
122
                    projection: new ol.proj.Projection({
123
                        code: 'goobi-image',
124
                        units: 'pixels',
125
                        extent: extent
126
                    }),
127
                    imageExtent: extent,
128
                    crossOrigin: origin
129
                })
130
            });
131
        }
132
        layers.push(layer);
133
134
        // add to cumulative width
135
        widthSum += imageSourceObj.width;
136
    });
137
138
    return layers;
139
};
140
141
/**
142
 * @param {Array.<{src: *, width: *, height: *}>} images
143
 * @return {ol.View}
144
 */
145
dlfUtils.createOl3View = function (images) {
146
147
    //
148
    // Calculate map extent
149
    //
150
    var maxLonX = images.reduce(function (prev, curr) {
151
        return prev + curr.width;
152
    }, 0),
153
        maxLatY = images.reduce(function (prev, curr) {
154
        return Math.max(prev, curr.height);
155
    }, 0),
156
        extent = images[0].mimetype !== dlfUtils.CUSTOM_MIMETYPE.ZOOMIFY &&
157
        images[0].mimetype !== dlfUtils.CUSTOM_MIMETYPE.IIIF &&
158
        images[0].mimetype !== dlfUtils.CUSTOM_MIMETYPE.IIP
159
            ? [0, 0, maxLonX, maxLatY]
160
            : [0, -maxLatY, maxLonX, 0];
161
162
    // globally define max zoom
163
    window.OL3_MAX_ZOOM = 8;
164
165
    // define map projection
166
    var proj = new ol.proj.Projection({
0 ignored issues
show
Bug introduced by
The variable ol seems to be never declared. If this is a global, consider adding a /** global: ol */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
167
        code: 'goobi-image',
168
        units: 'pixels',
169
        extent: extent
170
    });
171
172
    // define view
173
    var viewParams = {
174
        projection: proj,
175
        center: ol.extent.getCenter(extent),
176
        zoom: 1,
177
        maxZoom: window.OL3_MAX_ZOOM,
178
        extent: extent
179
    };
180
181
    return new ol.View(viewParams);
182
};
183
184
/**
185
 * Returns true if the specified value is not undefiend
186
 * @param {?} val
187
 * @return {boolean}
188
 */
189
dlfUtils.exists = function (val) {
190
    return val !== undefined;
191
};
192
193
/**
194
 * Fetch image data for given image sources.
195
 *
196
 * @param {Array.<{url: *, mimetype: *}>} imageSourceObjs
197
 * @return {JQueryStatic.Deferred}
198
 */
199
dlfUtils.fetchImageData = function (imageSourceObjs) {
200
201
    // use deferred for async behavior
202
    var deferredResponse = new $.Deferred();
203
204
    /**
205
     * This holds information about the loading state of the images
206
     * @type {Array.<number>}
207
     */
208
    var imageSourceData = [],
209
        loadCount = 0,
210
        finishLoading = function finishLoading() {
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable finishLoading already seems to be declared on line 210. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
211
        loadCount += 1;
212
213
        if (loadCount === imageSourceObjs.length)
214
            deferredResponse.resolve(imageSourceData);
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
215
    };
216
217
    imageSourceObjs.forEach(function (imageSourceObj, index) {
218
        if (imageSourceObj.mimetype === dlfUtils.CUSTOM_MIMETYPE.ZOOMIFY) {
219
            dlfUtils.fetchZoomifyData(imageSourceObj)
220
                .done(function (imageSourceDataObj) {
221
                    imageSourceData[index] = imageSourceDataObj;
222
                    finishLoading();
223
            });
224
        } else if (imageSourceObj.mimetype === dlfUtils.CUSTOM_MIMETYPE.IIIF) {
225
            dlfUtils.getIIIFResource(imageSourceObj)
226
                .done(function (imageSourceDataObj) {
227
                    imageSourceData[index] = imageSourceDataObj;
228
                      finishLoading();
229
            });
230
        } else if (imageSourceObj.mimetype === dlfUtils.CUSTOM_MIMETYPE.IIP) {
231
            dlfUtils.fetchIIPData(imageSourceObj)
232
                .done(function (imageSourceDataObj) {
233
                    imageSourceData[index] = imageSourceDataObj;
234
                    finishLoading();
235
            });
236
        } else {
237
            // In the worse case expect static image file
238
            dlfUtils.fetchStaticImageData(imageSourceObj)
239
                .done(function (imageSourceDataObj) {
240
                    imageSourceData[index] = imageSourceDataObj;
241
                    finishLoading();
242
            });
243
        }
244
    });
245
246
    return deferredResponse;
247
};
248
249
250
/**
251
 * Fetches the image data for static images source.
252
 *
253
 * @param {{url: *, mimetype: *}} imageSourceObj
254
 * @return {JQueryStatic.Deferred}
255
 */
256
dlfUtils.fetchStaticImageData = function (imageSourceObj) {
257
258
    // use deferred for async behavior
259
    var deferredResponse = new $.Deferred();
260
261
    // Create new Image object.
262
    var image = new Image();
0 ignored issues
show
Bug introduced by
The variable Image seems to be never declared. If this is a global, consider adding a /** global: Image */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
263
264
    // Register onload handler.
265
    image.onload = function () {
266
267
        var imageDataObj = {
268
            src: this.src,
269
            mimetype: imageSourceObj.mimetype,
270
            width: this.width,
271
            height: this.height
272
        };
273
274
        deferredResponse.resolve(imageDataObj);
275
    };
276
277
    // Initialize image loading.
278
    image.src = imageSourceObj.url;
279
280
    return deferredResponse;
281
};
282
283
/**
284
 * @param imageSourceObj
285
 * @returns {JQueryStatic.Deferred}
286
 */
287
dlfUtils.getIIIFResource = function getIIIFResource(imageSourceObj) {
288
289
    var deferredResponse = new $.Deferred();
290
    var type = 'GET';
291
    $.ajax({
292
        url: dlfViewerSource.IIIF.getMetdadataURL(imageSourceObj.url),
0 ignored issues
show
Bug introduced by
The variable dlfViewerSource seems to be never declared. If this is a global, consider adding a /** global: dlfViewerSource */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
293
        type: type,
294
        dataType: 'json'
295
    }).done(cb).fail(error);
296
297
    function cb(data) {
298
        var mimetype = imageSourceObj.mimetype;
299
        if (dlfUtils.supportsIIIF(data)) {
300
            if (data.protocol && data.protocol === 'http://iiif.io/api/image') {
301
                var uri = decodeURI(data['@id']);
302
                uri = dlfUtils.removeInfoJson(uri);
303
                var imageResource = dlfUtils.buildImageV2(mimetype, uri, data);
304
                deferredResponse.resolve(imageResource);
305
            } else {
306
                var _uri = imageSourceObj.url;
307
                _uri = dlfUtils.removeInfoJson(_uri);
308
                var _imageResource = dlfUtils.buildImageV1(mimetype, _uri, data);
309
                deferredResponse.resolve(_imageResource);
310
            }
311
        }
312
    }
313
314
    function error(jqXHR, errorThrown) {
315
        console.log("error", jqXHR.status);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
316
        console.log("status: " + errorThrown);
317
    }
318
319
    return deferredResponse;
320
};
321
322
/**
323
 * @param uri
324
 * @returns {*}
325
 */
326
dlfUtils.removeInfoJson = function removeInfoJson(uri) {
327
    if (uri.endsWith('/info.json')) {
328
        uri = uri.substr(0, uri.lastIndexOf('/'));
329
    }
330
    return uri;
331
};
332
333
/**
334
 *
335
 * @param data
336
 * @param data.protocol
337
 * @param data.identifier
338
 * @param data.width
339
 * @param data.height
340
 * @param data.profile
341
 * @param data.documentElement
342
 * @returns {boolean}
343
 */
344
dlfUtils.supportsIIIF = function supportsIIIF(data) {
345
    // Version 2.0 and forwards
346
    if (data.protocol && data.protocol === 'http://iiif.io/api/image') {
347
        return true;
348
        // Version 1.1
349
    } else if (data['@context'] && (
350
        data['@context'] === "http://library.stanford.edu/iiif/image-api/1.1/context.json" ||
351
        data['@context'] === "http://iiif.io/api/image/1/context.json")) {
352
        return true;
353
        // Version 1.0
354
    } else if (data.profile &&
355
        data.profile.indexOf("http://library.stanford.edu/iiif/image-api/compliance.html") === 0) {
356
        return true;
357
    } else if (data.identifier && data.width && data.height) {
358
        return true;
359
    } else return data.documentElement && "info" === data.documentElement.tagName &&
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
360
    "http://library.stanford.edu/iiif/image-api/ns/" === data.documentElement.namespaceURI;
361
};
362
363
/**
364
 *
365
 * @param mimetype
366
 * @param uri
367
 * @param jsonld
368
 * @param jsonld.tiles
369
 * @param jsonld.width
370
 * @param jsonld.height
371
 * @param jsonld.profile
372
 * @param jsonld.scaleFactors
373
 * @returns {{src: *, width, height, tilesize: [*,*], qualities: *, formats: *, resolutions: *, mimetype: *}}
374
 */
375
dlfUtils.buildImageV2 = function buildImageV2(mimetype, uri, jsonld) {
376
377
    return {
378
        src: uri,
379
        width: jsonld.width,
380
        height: jsonld.height,
381
        tilesize: [jsonld.tiles.map(function (a) {
382
            return a.width;
383
        })[0], jsonld.tiles.map(function (a) {
384
            return a.height;
385
        })[0]],
386
        qualities: jsonld.profile.map(function (a) {
387
            return a;
388
        }).map(function (b) {
389
            return b.qualities;
390
        })[1],
391
        formats: jsonld.profile.map(function (a) {
392
            return a;
393
        }).map(function (b) {
394
            return b.formats;
395
        })[1],
396
        resolutions: jsonld.tiles.map(function (a) {
397
            return a.scaleFactors;
398
        })[0],
399
        mimetype: mimetype
400
    };
401
};
402
403
/**
404
 *
405
 * @param mimetype
406
 * @param uri
407
 * @param jsonld
408
 * @param jsonld.width
409
 * @param jsonld.height
410
 * @param jsonld.scale_factors
411
 * @param jsonld.tile_width
412
 * @param jsonld.tile_height
413
 * @param jsonld.qualities
414
 * @param jsonld.formats
415
 * @returns {{src: *, width, height, tilesize: [*,*], qualities: *, formats: *, resolutions: *, mimetype: *}}
416
 */
417
dlfUtils.buildImageV1 = function buildImageV1(mimetype, uri, jsonld) {
418
419
    return {
420
        src: uri,
421
        width: jsonld.width,
422
        height: jsonld.height,
423
        tilesize: [jsonld.tile_width, jsonld.tile_height],
424
        qualities: jsonld.qualities,
425
        formats: jsonld.formats,
426
        resolutions: jsonld.scale_factors,
427
        mimetype: mimetype
428
    };
429
};
430
431
/**
432
 * Fetches the image data for iip images source.
433
 *
434
 * @param {{url: *, mimetype: *}} imageSourceObj
435
 * @return {JQueryStatic.Deferred}
436
 */
437
dlfUtils.fetchIIPData = function (imageSourceObj) {
438
439
    // use deferred for async behavior
440
    var deferredResponse = new $.Deferred();
441
442
    $.ajax({
443
        url: dlfViewerSource.IIP.getMetdadataURL(imageSourceObj.url) //'http://localhost:8000/fcgi-bin/iipsrv.fcgi?FIF=F4713/HD7.tif&obj=IIP,1.0&obj=Max-size&obj=Tile-size&obj=Resolution-number',
0 ignored issues
show
Bug introduced by
The variable dlfViewerSource seems to be never declared. If this is a global, consider adding a /** global: dlfViewerSource */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
444
    }).done(cb);
445
    function cb(response, type) {
446
        if (type !== 'success') throw new Error('Problems while fetching ImageProperties.xml');
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
447
448
        var imageDataObj = $.extend({
449
            src: imageSourceObj.url,
450
            mimetype: imageSourceObj.mimetype
451
        }, dlfViewerSource.IIP.parseMetadata(response));
0 ignored issues
show
Bug introduced by
The variable dlfViewerSource seems to be never declared. If this is a global, consider adding a /** global: dlfViewerSource */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
452
453
        deferredResponse.resolve(imageDataObj);
454
    }
455
456
    return deferredResponse;
457
};
458
459
/**
460
 * Fetch image data for zoomify source.
461
 *
462
 * @param {{url: *, mimetype: *}} imageSourceObj
463
 * @return {JQueryStatic.Deferred}
464
 */
465
dlfUtils.fetchZoomifyData = function (imageSourceObj) {
466
467
    // use deferred for async behavior
468
    var deferredResponse = new $.Deferred();
469
470
    $.ajax({
471
        url: imageSourceObj.url
472
    }).done(cb);
473
    function cb(response, type) {
474
        if (type !== 'success')
475
            throw new Error('Problems while fetching ImageProperties.xml');
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
476
477
        var properties = $(response).find('IMAGE_PROPERTIES');
478
479
        var imageDataObj = {
480
            src: response.URL.substring(0, response.URL.lastIndexOf("/") + 1),
481
            width: parseInt(properties.attr('WIDTH')),
482
            height: parseInt(properties.attr('HEIGHT')),
483
            tilesize: parseInt(properties.attr('TILESIZE')),
484
            mimetype: imageSourceObj.mimetype
485
        };
486
487
        deferredResponse.resolve(imageDataObj);
488
    }
489
490
    return deferredResponse;
491
};
492
493
/**
494
 * @param {string} name Name of the cookie
495
 * @return {string|null} Value of the cookie
496
 * @TODO replace unescape function
497
 */
498
dlfUtils.getCookie = function (name) {
499
500
    var results = document.cookie.match("(^|;) ?" + name + "=([^;]*)(;|$)");
501
502
    if (results) {
503
504
        return decodeURI(results[2]);
505
    } else {
506
507
        return null;
508
    }
509
};
510
511
/**
512
 * Returns url parameters
513
 * @returns {Object|undefined}
514
 */
515
dlfUtils.getUrlParams = function () {
516
    if (Object.prototype.hasOwnProperty.call(location, 'search')) {
517
        var search = decodeURIComponent(location.search).slice(1).split('&'),
518
            params = {};
519
520
        search.forEach(function (item) {
521
            var s = item.split('=');
522
            params[s[0]] = s[1];
523
        });
524
525
        return params;
526
    }
527
    return undefined;
528
};
529
530
/**
531
 * Returns true if the specified value is null.
532
 * @param {?} val
533
 * @return {boolean}
534
 */
535
dlfUtils.isNull = function (val) {
536
    return val === null;
537
};
538
539
/**
540
 * Returns true if the specified value is null, empty or undefined.
541
 * @param {?} val
542
 * @return {boolean}
543
 */
544
dlfUtils.isNullEmptyUndefinedOrNoNumber = function (val) {
545
    return val === null || val === undefined || val === '' || isNaN(val);
546
};
547
548
/**
549
 * @param {Array.<{url: *, mimetype: *}>} imageObjs
550
 * @return {boolean}
551
 */
552
dlfUtils.isCorsEnabled = function (imageObjs) {
553
    // fix for proper working with ie
554
    if (!window.location.origin) {
555
        window.location.origin = window.location.protocol + '//' + window.location.hostname +
556
            (window.location.port ? ':' + window.location.port : '');
557
    }
558
559
    // fetch data from server
560
    // with access control allowed
561
    var response = true;
562
563
    imageObjs.forEach(function (imageObj) {
564
        var url = imageObj.mimetype === dlfUtils.CUSTOM_MIMETYPE.ZOOMIFY
565
            ? imageObj.url.replace('ImageProperties.xml', 'TileGroup0/0-0-0.jpg')
566
            :
567
            imageObj.mimetype === dlfUtils.CUSTOM_MIMETYPE.IIIF
568
                ? dlfViewerSource.IIIF.getMetdadataURL(imageObj.url)
0 ignored issues
show
Bug introduced by
The variable dlfViewerSource seems to be never declared. If this is a global, consider adding a /** global: dlfViewerSource */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
569
                : imageObj.mimetype === dlfUtils.CUSTOM_MIMETYPE.IIP
570
                ? dlfViewerSource.IIP.getMetdadataURL(imageObj.url)
571
                : imageObj.url;
572
573
        url = window.location.origin + window.location.pathname + '?eID=tx_dlf_geturl_eid&url=' + encodeURIComponent(url) + '&header=2';
574
575
        $.ajax({
576
            url: url,
577
            async: false
578
        }).done(function (data, type) {
579
            response = type === 'success' && data.indexOf('Access-Control-Allow-Origin') !== -1;
580
        }).error(function (data, type) {
0 ignored issues
show
Unused Code introduced by
The parameter data is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter type is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
581
            response = false;
582
        });
583
    });
584
    return response;
585
};
586
587
/**
588
 * Functions checks if WebGL is enabled in the browser
589
 * @return {boolean}
590
 */
591
dlfUtils.isWebGLEnabled = function () {
592
    if (!!window.WebGLRenderingContext) {
593
        var canvas = document.createElement("canvas"),
594
            rendererNames = ["webgl", "experimental-webgl", "moz-webgl", "webkit-3d"],
595
            context = false;
0 ignored issues
show
Unused Code introduced by
The assignment to variable context seems to be never used. Consider removing it.
Loading history...
596
597
        for (var i = 0; i < rendererNames.length; i++) {
598
            try {
599
                context = canvas.getContext(rendererNames[i]);
600
                if (context && typeof context.getParameter === "function") {
601
                    // WebGL is enabled;
602
                    return true;
603
                }
604
            } catch (e) {}
0 ignored issues
show
Coding Style Comprehensibility Best Practice introduced by
Empty catch clauses should be used with caution; consider adding a comment why this is needed.
Loading history...
605
        }
606
        // WebGL not supported
607
        return false;
608
    }
609
610
    // WebGL not supported
611
    return false;
612
};
613
614
/**
615
 * @param {Element} element
616
 * @return {Object}
617
 */
618
dlfUtils.parseDataDic = function (element) {
619
    var dataDicString = $(element).attr('data-dic'),
620
        dataDicRecords = dataDicString.split(';'),
621
        dataDic = {};
622
623
    for (var i = 0, ii = dataDicRecords.length; i < ii; i++) {
624
        var key = dataDicRecords[i].split(':')[0],
625
            value = dataDicRecords[i].split(':')[1];
626
        dataDic[key] = value;
627
    }
628
629
    return dataDic;
630
};
631
632
/**
633
 * Set a cookie value
634
 *
635
 * @param {string} name The key of the value
636
 * @param {?} value The value to save
637
 */
638
dlfUtils.setCookie = function (name, value) {
639
640
    document.cookie = name + "=" + decodeURI(value) + "; path=/";
641
};
642
643
/**
644
 * Scales down the given features geometries. as a further improvement this function
645
 * adds a unique id to every feature
646
 * @param {Array.<ol.Feature>} features
647
 * @param {Object} imageObj
648
 * @param {number} width
649
 * @param {number} height
650
 * @param {number=} opt_offset
651
 * @deprecated
652
 * @return {Array.<ol.Feature>}
653
 */
654
dlfUtils.scaleToImageSize = function (features, imageObj, width, height, opt_offset) {
655
656
    // update size / scale settings of imageObj
657
    var image = void 0;
0 ignored issues
show
Coding Style introduced by
Consider using undefined instead of void(0). It is equivalent and more straightforward to read.
Loading history...
658
    if (width && height) {
659
660
        image = {
661
            'width': width,
662
            'height': height,
663
            'scale': imageObj.width / width
664
        };
665
    }
666
667
    if (image === undefined) return [];
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
668
669
    var scale = image.scale,
670
        displayImageHeight = imageObj.height,
671
        offset = opt_offset !== undefined ? opt_offset : 0;
672
673
    // do rescaling and set a id
674
    for (var i in features) {
0 ignored issues
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
675
676
        var oldCoordinates = features[i].getGeometry().getCoordinates()[0],
677
            newCoordinates = [];
678
679
        for (var j = 0; j < oldCoordinates.length; j++) {
680
            newCoordinates.push(
681
              [offset + scale * oldCoordinates[j][0], displayImageHeight - scale * oldCoordinates[j][1]]);
682
        }
683
684
        features[i].setGeometry(new ol.geom.Polygon([newCoordinates]));
0 ignored issues
show
Bug introduced by
The variable ol seems to be never declared. If this is a global, consider adding a /** global: ol */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
685
686
        // set index
687
        dlfUtils.RUNNING_INDEX += 1;
688
        features[i].setId('' + dlfUtils.RUNNING_INDEX);
689
    }
690
691
    return features;
692
};
693
694
/**
695
 * Search a feature collcetion for a feature with the given text
696
 * @param {Array.<ol.Feature>} featureCollection
697
 * @param {string} text
698
 * @return {Array.<ol.Feature>|undefined}
699
 */
700
dlfUtils.searchFeatureCollectionForText = function (featureCollection, text) {
701
    var features = [];
702
    featureCollection.forEach(function (ft) {
703
        if (ft.get('fulltext') !== undefined) {
704
            if (ft.get('fulltext').toLowerCase().indexOf(text.toLowerCase()) > -1) features.push(ft);
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
705
        }
706
    });
707
    return features.length > 0 ? features : undefined;
708
};
709