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