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