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