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