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