Fixes ACREP-30.
[mkws-moved-to-github.git] / src / mkws-core.js
1 /*! MKWS, the MasterKey Widget Set.
2  *  Copyright (C) 2013-2015 Index Data
3  *  See the file LICENSE for details
4  */
5
6 "use strict";
7
8
9 // Set up global mkws object. Contains truly global state such as SP
10 // authentication, and a hash of team objects, indexed by team-name.
11 //
12 // We set it as a property of window to make the global explicit as
13 // some things complain about an implicit global.
14 window.mkws = {
15   $: $, // Our own local copy of the jQuery object
16   authenticated: false,
17   authenticating: false,
18   active: false,
19   logger: undefined,
20   log_level: "info",
21   teams: {},
22   widgetType2function: {},
23   defaultTemplates: {},
24
25   locale_lang: {
26     "de": {
27       "Authors": "Autoren",
28       "Subjects": "Schlagwörter",
29       "Sources": "Daten und Quellen",
30       "source": "datenquelle",
31       "Facets": "Termlisten",
32       "Next": "Weiter",
33       "Prev": "Zurück",
34       "Search": "Suche",
35       "Sort by": "Sortieren nach",
36       "and show": "und zeige",
37       "per page": "pro Seite",
38       "Displaying": "Zeige",
39       "to": "von",
40       "of": "aus",
41       "found": "gefunden",
42       "Title": "Titel",
43       "Author": "Autor",
44       "author": "autor",
45       "Date": "Datum",
46       "Subject": "Schlagwort",
47       "subject": "schlagwort",
48       "Location": "Ort",
49       "Records": "Datensätze",
50       "Targets": "Datenbanken",
51       "State": "Status",
52       "relevance": "Relevanz",
53       "title": "Titel",
54       "newest": "Neueste",
55       "oldest": "Älteste",
56
57       "dummy": "dummy"
58     },
59
60     "da": {
61       "Authors": "Forfattere",
62       "Subjects": "Emner",
63       "Sources": "Kilder",
64       "source": "kilder",
65       "Facets": "Termlists",
66       "Next": "Næste",
67       "Prev": "Forrige",
68       "Search": "Søg",
69       "Sort by": "Sorter efter",
70       "and show": "og vis",
71       "per page": "per side",
72       "Displaying": "Viser",
73       "to": "til",
74       "of": "ud af",
75       "found": "fandt",
76       "Title": "Title",
77       "Author": "Forfatter",
78       "author": "forfatter",
79       "Date": "Dato",
80       "Subject": "Emneord",
81       "subject": "emneord",
82       "Location": "Lokation",
83       "Records": "Poster",
84       "Targets": "Baser",
85       "State": "Status",
86       "relevance": "Relevans",
87       "title": "Titel",
88       "newest": "Nyeste",
89       "oldest": "Ældste",
90
91       "dummy": "dummy"
92     }
93   }
94 };
95
96 // We may be using a separate copy
97 if (typeof(mkws_jQuery) !== "undefined") {
98   mkws.$ = mkws_jQuery;
99 } else {
100   mkws.$ = jQuery;
101 }
102
103 // It's ridiculous that JSNLog doesn't provide this
104 mkws.stringToLevel = function(s) {
105   if (s === 'trace') {
106     return JL.getTraceLevel();
107   } else if (s === 'debug') {
108     return JL.getDebugLevel();
109   } else if (s === 'info') {
110     return JL.getInfoLevel();
111   } else if (s === 'warn') {
112     return JL.getWarnLevel();
113   } else if (s === 'error') {
114     return JL.getErrorLevel();
115   } else if (s === 'fatal') {
116     return JL.getFatalLevel();
117   } else {
118     throw "bad log-level '" + s + "'";
119   }
120 }
121
122 mkws.logger = JL('mkws');
123 var consoleAppender = JL.createConsoleAppender('consoleAppender');
124 mkws.logger.setOptions({ "appenders": [consoleAppender] });
125
126
127 function _log() {
128   var argsAsARealArray = Array.prototype.slice.call(arguments);
129   var fn = argsAsARealArray.shift();
130   fn.apply(mkws.logger, argsAsARealArray);
131 };
132 mkws.trace = function(x) { _log(mkws.logger.trace, x) };
133 mkws.debug = function(x) { _log(mkws.logger.debug, x) };
134 mkws.info = function(x) { _log(mkws.logger.info, x) };
135 mkws.warn = function(x) { _log(mkws.logger.warn, x) };
136 mkws.error = function(x) { _log(mkws.logger.error, x) };
137 mkws.fatal = function(x) { _log(mkws.logger.fatal, x) };
138
139
140 // Translation function.
141 mkws.M = function(word) {
142   var lang = mkws.config.lang;
143
144   if (!lang || !mkws.locale_lang[lang])
145     return word;
146
147   return mkws.locale_lang[lang][word] || word;
148 };
149
150
151 // This function is taken from a StackOverflow answer
152 // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144
153 mkws.getParameterByName = function(name, url) {
154   if (!url) url = location.search;
155   name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
156   var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
157   results = regex.exec(url);
158   return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
159 }
160
161
162 mkws.registerWidgetType = function(name, fn) {
163   if(mkws._old2new.hasOwnProperty(name)) {
164       mkws.warn("registerWidgetType old widget name: " + name + " => " + mkws._old2new[name]);
165       name = mkws._old2new[name];
166   }
167
168   mkws.widgetType2function[name] = fn;
169   mkws.info("registered widget-type '" + name + "'");
170 };
171
172 mkws.aliasWidgetType = function(newName, oldName) {
173   mkws.widgetType2function[newName] = mkws.widgetType2function[oldName];
174   mkws.info("aliased widget-type '" + newName + "' to '" + oldName + "'");
175
176 };
177
178 mkws.promotionFunction = function(name) {
179   return mkws.widgetType2function[name];
180 };
181
182
183 mkws.setMkwsConfig = function(overrides) {
184   var config_default = {
185     use_service_proxy: true,
186     pazpar2_url: undefined,
187     pp2_hostname: "sp-mkws.indexdata.com",
188     pp2_path: "service-proxy/",
189     service_proxy_auth: undefined,
190     sp_auth_path: undefined,
191     sp_auth_query: "command=auth&action=perconfig",
192     sp_auth_credentials: undefined,
193     lang: "",
194     sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
195     perpage_options: [10, 20, 30, 50],
196     sort_default: "relevance",
197     perpage_default: 20,
198     show_lang: true,    /* show/hide language menu */
199     show_sort: true,    /* show/hide sort menu */
200     show_perpage: true, /* show/hide perpage menu */
201     show_switch: true,  /* show/hide switch menu */
202     lang_options: [],   /* display languages links for given languages, [] for all */
203     facets: ["xtargets", "subject", "author"], /* display facets, in this order, [] for none */
204     responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
205     log_level: 1,     /* log level for development: 0..2 */
206     template_vars: {}, /* values that may be exposed to templates */
207
208     dummy: "dummy"
209   };
210
211   mkws.config = mkws.objectInheritingFrom(config_default);
212   for (var k in overrides) {
213     mkws.config[k] = overrides[k];
214   }
215 };
216
217
218 // This code is from Douglas Crockford's article "Prototypal Inheritance in JavaScript"
219 // http://javascript.crockford.com/prototypal.html
220 // mkws.objectInheritingFrom behaves the same as Object.create,
221 // but since the latter is not available in IE8 we can't use it.
222 //
223 mkws.objectInheritingFrom = function(o) {
224   function F() {}
225   F.prototype = o;
226   return new F();
227 }
228
229
230 // The following functions are dispatchers for team methods that
231 // are called from the UI using a team-name rather than implicit
232 // context.
233 mkws.switchView = function(tname, view) {
234   mkws.teams[tname].switchView(view);
235 };
236
237 mkws.showDetails = function(tname, prefixRecId) {
238   mkws.teams[tname].showDetails(prefixRecId);
239 };
240
241 mkws.limitTarget  = function(tname, id, name) {
242   mkws.teams[tname].limitTarget(id, name);
243 };
244
245 mkws.limitQuery  = function(tname, field, value) {
246   mkws.teams[tname].limitQuery(field, value);
247 };
248
249 mkws.limitCategory  = function(tname, id) {
250   mkws.teams[tname].limitCategory(id);
251 };
252
253 mkws.delimitTarget = function(tname, id) {
254   mkws.teams[tname].delimitTarget(id);
255 };
256
257 mkws.delimitQuery = function(tname, field, value) {
258   mkws.teams[tname].delimitQuery(field, value);
259 };
260
261 mkws.showPage = function(tname, pageNum) {
262   mkws.teams[tname].showPage(pageNum);
263 };
264
265 mkws.pagerPrev = function(tname) {
266   mkws.teams[tname].pagerPrev();
267 };
268
269 mkws.pagerNext = function(tname) {
270   mkws.teams[tname].pagerNext();
271 };
272
273
274 mkws.pazpar2_url = function() {
275   if (mkws.config.pazpar2_url) {
276     mkws.info("using pre-baked pazpar2_url '" + mkws.config.pazpar2_url + "'");
277     return mkws.config.pazpar2_url;
278   } else {
279     var s = document.location.protocol + "//" + mkws.config.pp2_hostname + "/" + mkws.config.pp2_path;
280     mkws.info("generated pazpar2_url '" + s + "'");
281     return s;
282   }
283 };
284
285
286 // We put a session token in window.name, as it's the only place to
287 // keep data that is preserved across reloads and within-site
288 // navigation. pz2.js picks this up and uses it as part of the
289 // cookie-name, to ensure we get a new session when we need one.
290 //
291 // We want to use different sessions for different windows/tabs (so
292 // they don't receive each other's messages), different hosts and
293 // different paths on a host (since in general these will
294 // authenticate as different libraries). So the window name needs to
295 // include the hostname and the path from the URL, plus the token.
296 //
297 var token;
298 if (window.name) {
299   token = window.name.replace(/.*\//, '');
300   mkws.debug("Reusing existing window token '" + token + "'");
301 } else {
302   // Incredible that the standard JavaScript runtime doesn't define a
303   // unique windowId. Instead, we have to make one up. And since there's
304   // no global area shared between windows, the best we can do for
305   // ensuring uniqueness is generating a random ID and crossing our
306   // fingers.
307   //
308   // Ten chars from 26 alpha-numerics = 36^10 = 3.65e15 combinations.
309   // At one per second, it will take 116 million years to duplicate a token
310   token = Math.random().toString(36).slice(2, 12);
311   mkws.debug("Generated new window token '" + token + "'");
312 }
313
314 window.name = window.location.hostname + window.location.pathname + '/' + token;
315 mkws.info("Using window.name '" + window.name + "'");
316
317
318 // wrapper to provide local copy of the jQuery object.
319 (function($) {
320   var _old2new = { // Maps old-style widget names to new-style
321     'Authname': 'auth-name',
322     'ConsoleBuilder': 'console-builder',
323     'Coverart': 'cover-art',
324     'GoogleImage': 'google-image',
325     'MOTD': 'motd',
326     'MOTDContainer': 'motd-container',
327     'Perpage': 'per-page',
328     'SearchForm': 'search-form',
329     'ReferenceUniverse': 'reference-universe',
330     'Termlists': 'facets'
331   };
332   // Annoyingly, there is no built-in way to invert a hash
333   var _new2old = {};
334   for (var key in _old2new) {
335     if(_old2new.hasOwnProperty(key)) {
336       _new2old[_old2new[key]] = key;
337     }
338   }
339
340   mkws._old2new = _old2new;
341
342   function handleNodeWithTeam(node, callback) {
343     // First branch for DOM objects; second branch for jQuery objects
344     var classes = node.className || node.attr('class');
345     if (!classes) {
346       // For some reason, if we try to proceed when classes is
347       // undefined, we don't get an error message, but this
348       // function and its callers, up several stack level,
349       // silently return. What a crock.
350       mkws.fatal("handleNodeWithTeam() called on node with no classes");
351       return;
352     }
353     var list = classes.split(/\s+/)
354     var teamName, type;
355
356     for (var i = 0; i < list.length; i++) {
357       var cname = list[i];
358       if (cname.match(/^mkws-team-/)) {
359         // New-style teamnames of the form mkws-team-xyz
360         teamName = cname.replace(/^mkws-team-/, '');
361       } else if (cname.match(/^mkwsTeam_/)) {
362         // Old-style teamnames of the form mkwsTeam_xyz
363         teamName = cname.replace(/^mkwsTeam_/, '');
364       } else if (cname.match(/^mkws-/)) {
365         // New-style names of the from mkws-foo-bar
366         type = cname.replace(/^mkws-/, '');
367       } else if (cname.match(/^mkws/)) {
368         // Old-style names of the form mkwsFooBar
369         var tmp = cname.replace(/^mkws/, '');
370         type = _old2new[tmp] || tmp.toLowerCase();
371       }
372     }
373
374     // Widgets without a team are on team "AUTO"
375     if (!teamName) {
376       teamName = "AUTO";
377       // Autosearch widgets don't join team AUTO if there is already an
378       // autosearch on the team or the team has otherwise gotten a query
379       if (node.getAttribute("autosearch")) {
380         if (mkws.autoHasAuto ||
381             mkws.teams["AUTO"] && mkws.teams["AUTO"].config["query"]) {
382           mkws.warn("AUTO team already has a query, using unique team");
383           teamName = "UNIQUE";
384         }
385         mkws.autoHasAuto = true;
386       }
387     }
388
389     // Widgets on team "UNIQUE" get a random team
390     if (teamName === "UNIQUE") {
391       teamName = Math.floor(Math.random() * 100000000).toString();
392     }
393
394     callback.call(node, teamName, type);
395   }
396
397
398   function resizePage() {
399     var threshhold = mkws.config.responsive_design_width;
400     var width = $(window).width();
401     var from, to, method;
402
403     if ((mkws.width === undefined || mkws.width > threshhold) &&
404         width <= threshhold) {
405       from = "wide"; to = "narrow"; method = "hide";
406     } else if ((mkws.width === undefined || mkws.width <= threshhold) &&
407                width > threshhold) {
408       from = "narrow"; to = "wide"; method = "show";
409     }
410     mkws.width = width;
411
412     if (from) {
413       mkws.info("changing from " + from + " to " + to + ": " + width);
414       for (var tname in mkws.teams) {
415         var team = mkws.teams[tname];
416         team.visitWidgets(function(t, w) {
417           var w1 = team.widget(t + "-container-" + from);
418           var w2 = team.widget(t + "-container-" + to);
419           if (w1) {
420             w1.node.hide();
421           }
422           if (w2) {
423             w2.node.show();
424             w.node.appendTo(w2.node);
425           }
426         });
427         team.queue("resize-" + to).publish();
428       }
429     }
430   };
431
432
433   /*
434    * Run service-proxy authentication in background (after page load).
435    * The username/password is configured in the apache config file
436    * for the site.
437    */
438   function authenticateSession(auth_url, auth_domain, pp2_url) {
439     mkws.authenticating = true;
440     mkws.info("service proxy authentication on URL: " + auth_url);
441
442     if (!auth_domain) {
443       auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
444       mkws.info("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
445     }
446
447     var request = new pzHttpRequest(auth_url, function(err) {
448       alert("HTTP call for authentication failed: " + err)
449       return;
450     }, auth_domain);
451
452     request.get(null, function(data) {
453       mkws.authenticating = false;
454       if (!$.isXMLDoc(data)) {
455         alert("Service Proxy authentication response is not a valid XML document");
456         return;
457       }
458       var status = $(data).find("status");
459       if (status.text() != "OK") {
460         var message = $(data).find("message");
461         alert("Service Proxy authentication response: " + status.text() + " (" + message.text() + ")");
462         return;
463       }
464
465       mkws.info("service proxy authentication successful");
466       mkws.authenticated = true;
467       var authName = $(data).find("displayName").text();
468       // You'd think there would be a better way to do this:
469       var realm = $(data).find("realm:not(realmAttributes realm)").text();
470       for (var teamName in mkws.teams) {
471         mkws.teams[teamName].queue("authenticated").publish(authName, realm);
472       }
473
474       runAutoSearches();
475     });
476   }
477
478
479   function runAutoSearches() {
480     mkws.info("running auto searches");
481
482     for (var teamName in mkws.teams) {
483       mkws.teams[teamName].queue("ready").publish();
484     }
485   }
486
487
488   function selectorForAllWidgets() {
489     if (mkws.config && mkws.config.scan_all_nodes) {
490       // This is the old version, which works by telling jQuery to
491       // find every node that has a class beginning with "mkws". In
492       // theory it should be slower than the class-based selector; but
493       // instrumentation suprisingly shows this is consistently
494       // faster. It also has the advantage that any widgets of
495       // non-registered types are logged as warnings rather than
496       // silently ignored.
497       return '[class^="mkws"],[class*=" mkws"]';
498     } else {
499       // This is the new version, which works by looking up the
500       // specific classes of all registered widget types and their
501       // resize containers. Because all it requires jQuery to do is
502       // some hash lookups in pre-built tables, it should be very
503       // fast; but it silently ignores widgets of unregistered types.
504       var s = "";
505       for (var type in mkws.widgetType2function) {
506         if (s) s += ',';
507         s += '.mkws-' + type;
508         s += ',.mkws-' + type + "-container-wide";
509         s += ',.mkws-' + type + "-container-narrow";
510         // Annoyingly, we also need to recognise old-style names
511         var oldtype = _new2old[type] || type.charAt(0).toUpperCase() + type.slice(1);
512         s += ',.mkws' + oldtype;
513         s += ',.mkws' + oldtype + "-Container-wide";
514         s += ',.mkws' + oldtype + "-Container-narrow";
515       }
516       return s;
517     }
518   }
519
520
521   function makeWidgetsWithin(level, node) {
522     if (node) var widgetNodes = node.find(selectorForAllWidgets());
523     else widgetNodes = $(selectorForAllWidgets());
524     // Return false if we parse no widgets
525     if (widgetNodes.length < 1) return false;
526     widgetNodes.each(function() {
527       handleNodeWithTeam(this, function(tname, type) {
528         var myTeam = mkws.teams[tname];
529         if (!myTeam) {
530           myTeam = mkws.teams[tname] = mkws.makeTeam($, tname);
531         }
532
533         var oldHTML = this.innerHTML;
534         var myWidget = mkws.makeWidget($, myTeam, type, this);
535         myTeam.addWidget(myWidget);
536         var newHTML = this.innerHTML;
537         if (newHTML !== oldHTML) {
538           myTeam.info("widget " + type + " HTML changed: reparsing");
539           makeWidgetsWithin(level+1, $(this));
540         }
541       });
542     });
543     return true;
544   }
545
546
547   // The second "rootsel" parameter is passed to jQuery and is a DOM node
548   // or a selector string you would like to constrain the search for widgets to.
549   //
550   // This function has no side effects if run again on an operating session,
551   // even if the element/selector passed causes existing widgets to be reparsed:
552   //
553   // (TODO: that last bit isn't true and we currently have to avoid reinitialising
554   // widgets, MKWS-261)
555   //
556   // * configuration is not regenerated
557   // * authentication is not performed again
558   // * autosearches are not re-run
559   mkws.init = function(message, rootsel) {
560     var greet = "MKWS initialised";
561     if (rootsel) greet += " (limited to " + rootsel + ")"
562     if (message) greet += " :: " + message;
563     mkws.info(greet);
564
565     // MKWS is not active until init() has been run against an object with widget nodes.
566     // We only set initial configuration when MKWS is first activated.
567     if (!mkws.isActive) {
568       var widgetSelector = selectorForAllWidgets();
569       if ($(widgetSelector).length < 1) {
570         mkws.warn("no widgets found");
571         return;
572       }
573
574       // Initial configuration
575       mkws.autoHasAuto = false;
576       var saved_config;
577       if (typeof mkws_config === 'undefined') {
578         mkws.info("setting empty config");
579         saved_config = {};
580       } else {
581         mkws.info("using config: " + $.toJSON(mkws_config));
582         saved_config = mkws_config;
583       }
584       mkws.setMkwsConfig(saved_config);
585
586       for (var key in mkws.config) {
587         if (mkws.config.hasOwnProperty(key)) {
588           if (key.match(/^language_/)) {
589             var lang = key.replace(/^language_/, "");
590             // Copy custom languages into list
591             mkws.locale_lang[lang] = mkws.config[key];
592             mkws.info("added locally configured language '" + lang + "'");
593           }
594         }
595       }
596
597       var lang = mkws.getParameterByName("lang") || mkws.config.lang;
598       if (!lang || !mkws.locale_lang[lang]) {
599         mkws.config.lang = ""
600       } else {
601         mkws.config.lang = lang;
602       }
603
604       mkws.info("using language: " + (mkws.config.lang ? mkws.config.lang : "none"));
605
606       // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
607       if (mkws.pazpar2_url().match(/^\/\//)) {
608         mkws.config.pazpar2_url = document.location.protocol + mkws.config.pazpar2_url;
609         mkws.info("adjusted protocol independent link to " + mkws.pazpar2_url());
610       }
611
612       if (mkws.config.responsive_design_width) {
613         // Responsive web design - change layout on the fly based on
614         // current screen width. Required for mobile devices.
615         $(window).resize(resizePage);
616         // initial check after page load
617         $(document).ready(resizePage);
618       }
619     }
620
621     var then = $.now();
622     // If we've made no widgets, return without starting an SP session
623     // or marking MKWS active.
624     if (makeWidgetsWithin(1, rootsel ? $(rootsel) : undefined) === false) {
625       return false;
626     }
627     var now = $.now();
628
629     mkws.info("walking MKWS nodes took " + (now-then) + " ms");
630     for (var tName in mkws.teams) {
631       var myTeam = mkws.teams[tName]
632       myTeam.makePz2();
633       myTeam.info("made PZ2 object");
634       /*
635         myTeam.visitWidgets(function(t, w) {
636           mkws.debug("  has widget of type '" + t + "': " + w);
637         });
638       */
639     }
640
641     function sp_auth_url(config) {
642       if (config.service_proxy_auth) {
643         mkws.info("using pre-baked sp_auth_url '" + config.service_proxy_auth + "'");
644         return config.service_proxy_auth;
645       } else {
646         var s = '//';
647         s += config.sp_auth_hostname ? config.sp_auth_hostname : config.pp2_hostname;
648         s += '/';
649         s += config.sp_auth_path ? config.sp_auth_path : config.pp2_path;
650         var q = config.sp_auth_query;
651         if (q) {
652           s += '?' + q;
653         }
654         var c = config.sp_auth_credentials;
655         if (c) {
656           s += ('&username=' + c.substr(0, c.indexOf('/')) +
657                 '&password=' + c.substr(c.indexOf('/')+1));
658         }
659         mkws.info("generated sp_auth_url '" + s + "'");
660         return s;
661       }
662     }
663
664     if (mkws.config.use_service_proxy && !mkws.authenticated && !mkws.authenticating) {
665       authenticateSession(sp_auth_url(mkws.config),
666                           mkws.config.service_proxy_auth_domain,
667                           mkws.pazpar2_url());
668     } else if (!mkws.authenticating) {
669       // raw pp2 or we have a session already open
670       runAutoSearches();
671       for (var teamName in mkws.teams) {
672         mkws.teams[teamName].queue("authenticated").publish();
673       }
674     }
675
676     mkws.isActive = true;
677     return true;
678   };
679
680   $(document).ready(function() {
681     if (!window.mkws_noready && !mkws.authenticating && !mkws.active) {
682        mkws.init();
683     }
684   });
685
686   // Set global log_level flag early so that _log() works
687   if (typeof mkws_config !== 'undefined') {
688     var tmp = mkws_config.log_level;
689     if (typeof tmp !== 'undefined') {
690       mkws.logger.setOptions({ "level": mkws.stringToLevel(tmp) });
691     }
692   }
693 })(mkws.$);