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