]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/xul/staff_client/chrome/content/main/main.js
Client Permission Overhaul
[working/Evergreen.git] / Open-ILS / xul / staff_client / chrome / content / main / main.js
1 dump('entering main/main.js\n');
2 // vim:noet:sw=4:ts=4:
3
4 var xulG;
5 var offlineStrings;
6 var authStrings;
7 var openTabs = new Array();
8 var tempWindow = null;
9 var tempFocusWindow = null;
10
11 function grant_perms(url) {
12     var perms = "UniversalXPConnect UniversalPreferencesWrite UniversalBrowserWrite UniversalPreferencesRead UniversalBrowserRead UniversalFileRead";
13     dump('Granting ' + perms + ' to ' + url + '\n');
14     if (G.pref) {
15         G.pref.setCharPref("capability.principal.codebase.p0.granted", perms);
16         G.pref.setCharPref("capability.principal.codebase.p0.id", url);
17         G.pref.setCharPref("capability.principal.codebase.p1.granted", perms);
18         G.pref.setCharPref("capability.principal.codebase.p1.id", url.replace('http:','https:'));
19         G.pref.setBoolPref("dom.disable_open_during_load",false);
20         G.pref.setBoolPref("browser.popups.showPopupBlocker",false);
21     }
22
23 }
24
25 function clear_the_cache() {
26     try {
27         var cacheClass         = Components.classes["@mozilla.org/network/cache-service;1"];
28         var cacheService    = cacheClass.getService(Components.interfaces.nsICacheService);
29         cacheService.evictEntries(Components.interfaces.nsICache.STORE_ON_DISK);
30         cacheService.evictEntries(Components.interfaces.nsICache.STORE_IN_MEMORY);
31     } catch(E) {
32         dump(E+'\n');alert(E);
33     }
34 }
35
36 function toOpenWindowByType(inType, uri) { /* for Venkman */
37     try {
38         var winopts = "chrome,extrachrome,menubar,resizable,scrollbars,status,toolbar";
39         window.open(uri, "_blank", winopts);
40     } catch(E) {
41         alert(E); throw(E);
42     }
43 }
44
45 function start_debugger() {
46     setTimeout(
47         function() {
48             try { start_venkman(); } catch(E) { alert(E); }
49         }, 0
50     );
51 };
52
53 function start_inspector() {
54     setTimeout(
55         function() {
56             try { inspectDOMDocument(); } catch(E) { alert(E); }
57         }, 0
58     );
59 };
60
61 function start_chrome_list() {
62     setTimeout(
63         function() {
64             try { startChromeList(); } catch(E) { alert(E); }
65         }, 0
66     );
67 };
68
69 function start_js_shell() {
70     setTimeout(
71         function() {
72             try { window.open('chrome://open_ils_staff_client/content/util/shell.html','shell','chrome,resizable,scrollbars'); } catch(E) { alert(E); }
73         }, 0
74     );
75 };
76
77 function new_tabs(aTabList, aContinue) {
78     if(aTabList != null) {
79         openTabs = openTabs.concat(aTabList);
80     }
81     if(G.data.session) { // Just add to the list of stuff to open unless we are logged in
82         netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
83         var targetwindow = null;
84         var focuswindow = null;
85         var focustab = {'focus' : true};
86         if(aContinue == true && tempWindow.closed == false) {
87             if(tempWindow.g == undefined || tempWindow.g.menu == undefined) {
88                 setTimeout(
89                     function() {
90                         new_tabs(null, true);
91                     }, 300);
92                 return null;
93             }
94             targetwindow = tempWindow;
95             tempWindow = null;
96             focuswindow = tempFocusWindow;
97             tempFocusWindow = null;
98             focustab = {'nofocus' : true};
99         }
100         else if(tempWindow != null) { // In theory, we are waiting on a setTimeout
101             if(tempWindow.closed == true) // But someone closed our window?
102             {
103                 tempWindow = null;
104                 tempFocusWindow = null;
105             }
106             else
107             {
108                 return null;
109             }
110         }
111         var newTab;
112         var firstURL;
113         var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"].
114             getService(Components.interfaces.nsIWindowMediator);
115             // This may look out of place, but this is so we can continue this loop from down below
116 opentabs:
117             while(openTabs.length > 0) {
118             newTab = openTabs.shift();
119             if(newTab == 'new' || newTab == 'init') {
120                 if(newTab != 'init' && openTabs.length > 0 && openTabs[0] != 'new') {
121                     firstURL = openTabs.shift();
122                     if(firstURL != 'tab') { // 'new' followed by 'tab' should be equal to 'init' in functionality, this should do that
123                         if(urls[firstURL]) {
124                             firstURL = urls[firstURL];
125                         }
126                         firstURL = '&firstURL=' + window.escape(firstURL);
127                     }
128                     else {
129                         firstURL = '';
130                     }
131                 }
132                 else {
133                     firstURL = '';
134                 }
135                 targetwindow = xulG.window.open(urls.XUL_MENU_FRAME
136                     + '?server='+window.escape(G.data.server) + firstURL,
137                     '_blank','chrome,resizable'
138                 );
139                 targetwindow.xulG = xulG;
140                 if (focuswindow == null) {
141                     focuswindow = targetwindow;
142                 }
143                 tempWindow = targetwindow;
144                 tempFocusWindow = focuswindow;
145                 setTimeout(
146                     function() {
147                         new_tabs(null, true);
148                     }, 300);
149                 return null;
150             }
151             else {
152                 if(newTab == 'tab') {
153                     newTab = null;
154                 }
155                 else if(urls[newTab]) {
156                     newTab = urls[newTab];
157                 }
158                 if(targetwindow != null) { // Already have a previous target window? Use it first.
159                     if(targetwindow.g.menu.new_tab(newTab,focustab,null)) {
160                         focustab = {'nofocus' : true};
161                         continue;
162                     }
163                 }
164                 var enumerator = wm.getEnumerator('eg_menu');
165                 while(enumerator.hasMoreElements()) {
166                     targetwindow = enumerator.getNext();
167                     if(targetwindow.g.menu.new_tab(newTab,focustab,null)) {
168                         focustab = {'nofocus' : true};
169                         if (focuswindow == null) {
170                             focuswindow = targetwindow;
171                         }
172                         continue opentabs;
173                     }
174                 }
175                 // No windows found to add the tab to? Make a new one.
176                 if(newTab == null) { // Were we making a "default" tab?
177                     openTabs.unshift('init'); // 'init' does that for us!
178                 }
179                 else {
180                     openTabs.unshift('new',newTab);
181                 }
182             }
183         }
184         if(focuswindow != null) {
185             focuswindow.focus();
186         }
187     }
188 }
189
190 // Returns false if we can't get an actual perm list
191 // Returns an array of perms with boolean has/hasn't flag
192 function get_menu_perms(indocument) {
193     // If we don't have our static perm list, and we have a remote window, go looking.
194     // We never need to look twice unless a dev is manually editing their files.
195     // Shame on them, they can restart the entire client ;)
196     if(typeof(get_menu_perms.perm_list) == 'undefined' && indocument != null)
197     {
198         get_menu_perms.perm_list = [ ];
199         var commands = indocument.getElementById('universal_cmds').getElementsByTagName('command');
200         for (var i = 0; i < commands.length; i++) { 
201             if (commands[i].hasAttribute('perm')) {
202                 get_menu_perms.perm_list = get_menu_perms.perm_list.concat(commands[i].getAttribute('perm').split(' '));
203             }           
204         }
205     }
206     // 
207     if(typeof(get_menu_perms.perm_list) == 'object') {
208         G.data.stash_retrieve();
209         if(!G.data.menu_perms) {
210             JSAN.use('util.network');
211             var network = new util.network();
212             var r = network.simple_request('BATCH_PERM_RETRIEVE_WORK_OU', [ G.data.session.key, get_menu_perms.perm_list ]);
213             for(p in r)
214                 r[p] = (typeof(r[p][0]) == 'number');
215             G.data.menu_perms = r;
216             G.data.stash('menu_perms');
217         }
218         return G.data.menu_perms;
219     }
220     return false;
221 }
222
223 function main_init() {
224     dump('entering main_init()\n');
225     try {
226         clear_the_cache();
227         if("arguments" in window && window.arguments.length > 0 && window.arguments[0].wrappedJSObject != undefined && window.arguments[0].wrappedJSObject.openTabs != undefined) {
228             openTabs = openTabs.concat(window.arguments[0].wrappedJSObject.openTabs);
229         }
230
231         // Now we can safely load the strings without the cache getting wiped
232         offlineStrings = document.getElementById('offlineStrings');
233         authStrings = document.getElementById('authStrings');
234
235         if (typeof JSAN == 'undefined') {
236             throw(
237                 offlineStrings.getString('common.jsan.missing')
238             );
239         }
240         /////////////////////////////////////////////////////////////////////////////
241
242         JSAN.errorLevel = "die"; // none, warn, or die
243         JSAN.addRepository('..');
244
245         //JSAN.use('test.test'); test.test.hello_world();
246
247         var mw = self;
248         G =  {};
249         
250         G.pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
251         if (! G.pref.prefHasUserValue('general.useragent.override')) {
252             G.pref.setCharPref('general.useragent.override',navigator.userAgent + ' oils_xulrunner /xul/server/');
253         }
254
255         JSAN.use('util.error');
256         G.error = new util.error();
257         G.error.sdump('D_ERROR', offlineStrings.getString('main.testing'));
258
259         JSAN.use('util.window');
260         G.window = new util.window();
261
262         JSAN.use('auth.controller');
263         G.auth = new auth.controller( { 'window' : mw } );
264
265         JSAN.use('OpenILS.data');
266         G.data = new OpenILS.data();
267         G.data.on_error = G.auth.logoff;
268
269         JSAN.use('util.file');
270         G.file = new util.file();
271         try {
272             G.file.get('ws_info');
273             G.ws_info = G.file.get_object(); G.file.close();
274         } catch(E) {
275             G.ws_info = {};
276         }
277         G.data.ws_info = G.ws_info; G.data.stash('ws_info');
278
279         G.auth.on_login = function() {
280
281             var url = G.auth.controller.view.server_prompt.value || urls.remote;
282
283             G.data.server_unadorned = url; G.data.stash('server_unadorned'); G.data.stash_retrieve();
284
285             if (! url.match( '^http://' ) ) { url = 'http://' + url; }
286
287             G.data.server = url; G.data.stash('server'); 
288             G.data.session = { 'key' : G.auth.session.key, 'auth' : G.auth.session.authtime }; G.data.stash('session');
289             G.data.stash_retrieve();
290             try {
291                 var ios = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
292                 var cookieUri = ios.newURI("http://" + G.data.server_unadorned, null, null);
293                 var cookieUriSSL = ios.newURI("https://" + G.data.server_unadorned, null, null);
294                 var cookieSvc = Components.classes["@mozilla.org/cookieService;1"].getService(Components.interfaces.nsICookieService);
295
296                 cookieSvc.setCookieString(cookieUri, null, "ses="+G.data.session.key, null);
297                 cookieSvc.setCookieString(cookieUriSSL, null, "ses="+G.data.session.key, null);
298                 cookieSvc.setCookieString(cookieUri, null, "xul=1", null);
299                 cookieSvc.setCookieString(cookieUriSSL, null, "xul=1", null);
300
301             } catch(E) {
302                 alert(offlineStrings.getFormattedString(main.session_cookie.error, [E]));
303             }
304
305             grant_perms(url);
306
307             xulG = {
308                 'auth' : G.auth,
309                 'url' : url,
310                 'window' : G.window,
311                 'data' : G.data,
312                 'pref' : G.pref
313             };
314
315             if (G.data.ws_info && G.data.ws_info[G.auth.controller.view.server_prompt.value]) {
316                 JSAN.use('util.widgets');
317                 var deck = document.getElementById('progress_space');
318                 util.widgets.remove_children( deck );
319                 var iframe = document.createElement('iframe'); deck.appendChild(iframe);
320                 iframe.setAttribute( 'src', url + urls.XUL_LOGIN_DATA );
321                 iframe.contentWindow.xulG = xulG;
322                 G.data_xul = iframe.contentWindow;
323             } else {
324                 xulG.file = G.file;
325                 var deck = G.auth.controller.view.ws_deck;
326                 JSAN.use('util.widgets'); util.widgets.remove_children('ws_deck');
327                 var iframe = document.createElement('iframe'); deck.appendChild(iframe);
328                 iframe.setAttribute( 'src', url + urls.XUL_WORKSTATION_INFO );
329                 iframe.contentWindow.xulG = xulG;
330                 deck.selectedIndex = deck.childNodes.length - 1;
331             }
332         };
333
334         G.auth.on_standalone = function() {
335             try {
336                 G.window.open(urls.XUL_STANDALONE,'Offline','chrome,resizable');
337             } catch(E) {
338                 alert(E);
339             }
340         };
341
342         G.auth.on_standalone_export = function() {
343             try {
344                 JSAN.use('util.file'); var file = new util.file('pending_xacts');
345                 if (file._file.exists()) {
346                     var file2 = new util.file('');
347                     var f = file2.pick_file( { 'mode' : 'save', 'title' : offlineStrings.getString('main.transaction_export.title') } );
348                     if (f) {
349                         if (f.exists()) {
350                             var r = G.error.yns_alert(
351                                 offlineStrings.getFormattedString('main.transaction_export.prompt', [f.leafName]),
352                                 offlineStrings.getString('main.transaction_export.prompt.title'),
353                                 offlineStrings.getString('common.yes'),
354                                 offlineStrings.getString('common.no'),
355                                 null,
356                                 offlineStrings.getString('common.confirm')
357                             );
358                             if (r != 0) { file.close(); return; }
359                         }
360                         var e_file = new util.file(''); e_file._file = f;
361                         e_file.write_content( 'truncate', file.get_content() );
362                         e_file.close();
363                         var r = G.error.yns_alert(
364                             offlineStrings.getFormattedString('main.transaction_export.success.prompt', [f.leafName]),
365                             offlineStrings.getString('main.transaction_export.success.title'),
366                             offlineStrings.getString('common.yes'),
367                             offlineStrings.getString('common.no'),
368                             null,
369                             offlineStrings.getString('common.confirm')
370                         );
371                         if (r == 0) {
372                             var count = 0;
373                             var filename = 'pending_xacts_exported_' + new Date().getTime();
374                             var t_file = new util.file(filename);
375                             while (t_file._file.exists()) {
376                                 filename = 'pending_xacts_' + new Date().getTime() + '.exported';
377                                 t_file = new util.file(filename);
378                                 if (count++ > 100) {
379                                     throw(offlineStrings.getString('main.transaction_export.filename.error'));
380                                 }
381                             }
382                             file.close(); file = new util.file('pending_xacts'); // prevents a bug with .moveTo below
383                             file._file.moveTo(null,filename);
384                         } else {
385                             alert(offlineStrings.getString('main.transaction_export.duplicate.warning'));
386                         }
387                     } else {
388                         alert(offlineStrings.getString('main.transaction_export.no_filename.error'));
389                     }
390                 } else {
391                     alert(offlineStrings.getString('main.transaction_export.no_transactions.error'));
392                 }
393                 file.close();
394             } catch(E) {
395                 alert(E);
396             }
397         };
398
399         G.auth.on_standalone_import = function() {
400             try {
401                 JSAN.use('util.file'); var file = new util.file('pending_xacts');
402                 if (file._file.exists()) {
403                     alert(offlineStrings.getString('main.transaction_import.outstanding.error'));
404                 } else {
405                     var file2 = new util.file('');
406                     var f = file2.pick_file( { 'mode' : 'open', 'title' : offlineStrings.getString('main.transaction_import.title')} );
407                     if (f && f.exists()) {
408                         var i_file = new util.file(''); i_file._file = f;
409                         file.write_content( 'truncate', i_file.get_content() );
410                         i_file.close();
411                         var r = G.error.yns_alert(
412                             offlineStrings.getFormattedString('main.transaction_import.delete.prompt', [f.leafName]),
413                             offlineStrings.getString('main.transaction_import.success'),
414                             offlineStrings.getString('common.yes'),
415                             offlineStrings.getString('common.no'),
416                             null,
417                             offlineStrings.getString('common.confirm')
418                         );
419                         if (r == 0) {
420                             f.remove(false);
421                         }
422                     }
423                 }
424                 file.close();
425             } catch(E) {
426                 alert(E);
427             }
428         };
429
430         G.auth.on_debug = function(action) {
431             switch(action) {
432                 case 'js_console' :
433                     G.window.open(urls.XUL_DEBUG_CONSOLE,'testconsole','chrome,resizable');
434                 break;
435                 case 'clear_cache' :
436                     clear_the_cache();
437                     alert(offlineStrings.getString('main.on_debug.clear_cache'));
438                 break;
439                 default:
440                     alert(offlineStrings.getString('main.on_debug.debug'));
441                 break;
442             }
443         };
444
445         G.auth.init();
446         // XML_HTTP_SERVER will get reset to G.auth.controller.view.server_prompt.value
447
448         /////////////////////////////////////////////////////////////////////////////
449
450         var version = CLIENT_VERSION;
451         if (CLIENT_STAMP.length == 0) {
452             version = 'versionless debug build';
453             document.getElementById('debug_gb').hidden = false;
454         }
455
456         try {
457             if (G.pref && G.pref.getBoolPref('open-ils.debug_options')) {
458                 document.getElementById('debug_gb').hidden = false;
459             }
460         } catch(E) {
461         }
462
463         var appInfo = Components.classes["@mozilla.org/xre/app-info;1"] 
464             .getService(Components.interfaces.nsIXULAppInfo); 
465
466         if (appInfo.ID == "staff-client@open-ils.org")
467         {
468             try {
469                 if (G.pref && G.pref.getBoolPref('app.update.enabled')) {
470                     document.getElementById('check_upgrade_sep').hidden = false;
471                     var upgrademenu = document.getElementById('check_upgrade');
472                     upgrademenu.hidden = false;
473                     G.upgradeCheck = function () {
474                         var um = Components.classes["@mozilla.org/updates/update-manager;1"]
475                             .getService(Components.interfaces.nsIUpdateManager);
476                         var prompter = Components.classes["@mozilla.org/updates/update-prompt;1"]
477                             .createInstance(Components.interfaces.nsIUpdatePrompt);
478
479                         if (um.activeUpdate && um.activeUpdate.state == "pending")
480                             prompter.showUpdateDownloaded(um.activeUpdate);
481                         else
482                             prompter.checkForUpdates();
483                     }
484                     upgrademenu.addEventListener(
485                         'command',
486                         G.upgradeCheck,
487                         false
488                     );
489                 }
490             } catch(E) {
491             }
492         }
493
494         window.title = authStrings.getFormattedString('staff.auth.titlebar.label', version);
495         var x = document.getElementById('about_btn');
496         x.addEventListener(
497             'command',
498             function() {
499                 try { 
500                     G.window.open('about.html','about','chrome,resizable,width=800,height=600');
501                 } catch(E) { alert(E); }
502             }, 
503             false
504         );
505
506         var y = document.getElementById('new_window_btn');
507         y.addEventListener(
508             'command',
509             function() {
510                 if (G.data.session) {
511                     new_tabs(Array('new'), null, null);
512                 } else {
513                     alert ( offlineStrings.getString('main.new_window_btn.login_first_warning') );
514                 }
515             },
516             false
517         );
518
519         JSAN.use('util.mozilla');
520         var z = document.getElementById('locale_menupopup');
521         if (z) {
522             while (z.lastChild) z.removeChild(z.lastChild);
523             var locales = util.mozilla.chromeRegistry().getLocalesForPackage( String( location.href ).split(/\//)[2] );
524             var current_locale = util.mozilla.prefs().getCharPref('general.useragent.locale');
525             while (locales.hasMore()) {
526                 var locale = locales.getNext();
527                 var parts = locale.split(/-/);
528                 var label;
529                 try {
530                     label = locale + ' : ' + util.mozilla.languages().GetStringFromName(parts[0]);
531                     if (parts.length > 1) {
532                         try {
533                             label += ' (' + util.mozilla.regions().GetStringFromName(parts[1].toLowerCase()) + ')';
534                         } catch(E) {
535                             label += ' (' + parts[1] + ')';
536                         }
537                     }
538                 } catch(E) {
539                     label = locale;
540                 }
541                 var mi = document.createElement('menuitem');
542                 mi.setAttribute('label',label);
543                 mi.setAttribute('value',locale);
544                 if (locale == current_locale) {
545                     if (z.parentNode.tagName == 'menulist') {
546                         mi.setAttribute('selected','true');
547                         z.parentNode.setAttribute('label',label);
548                         z.parentNode.setAttribute('value',locale);
549                     }
550                 }
551                 z.appendChild( mi );
552             }
553         }
554         var xx = document.getElementById('apply_locale_btn');
555         xx.addEventListener(
556             'command',
557             function() {
558                 util.mozilla.change_locale(z.parentNode.value);
559             },
560             false
561         );
562
563         if ( found_ws_info_in_Achrome() && G.pref && G.pref.getBoolPref("open-ils.write_in_user_chrome_directory") ) {
564             //var hbox = x.parentNode; var b = document.createElement('button'); 
565             //b.setAttribute('label','Migrate legacy settings'); hbox.appendChild(b);
566             //b.addEventListener(
567             //    'command',
568             //    function() {
569             //        try {
570             //            handle_migration();
571             //        } catch(E) { alert(E); }
572             //    },
573             //    false
574             //);
575             if (window.confirm(offlineStrings.getString('main.settings.migrate'))) {
576                 setTimeout( function() { handle_migration(); }, 0 );
577             }
578         }
579
580         window.addEventListener(
581             'close',
582             function(ev) {
583
584                 G.data.stash_retrieve();
585                 if (typeof G.data.unsaved_data != 'undefined') {
586                     if (G.data.unsaved_data > 0) {
587                         var confirmation = window.confirm(offlineStrings.getString('menu.shutdown.unsaved_data_warning'));
588                         if (!confirmation) {
589                             ev.preventDefault();
590                             return false;
591                         }
592                     }
593                 }
594                 G.data.unsaved_data = 0;
595                 G.data.stash('unsaved_data');
596
597                 return true;
598
599             },
600             false
601         );
602
603
604     } catch(E) {
605         var error = offlineStrings.getFormattedString('common.exception', [E, '']);
606         try { G.error.sdump('D_ERROR',error); } catch(E) { dump(error); }
607         alert(error);
608     }
609     dump('exiting main_init()\n');
610 }
611
612 function found_ws_info_in_Achrome() {
613     JSAN.use('util.file');
614     var f = new util.file();
615     var f_in_chrome = f.get('ws_info','chrome');
616     var path = f_in_chrome.exists() ? f_in_chrome.path : false;
617     f.close();
618     return path;
619 }
620
621 function found_ws_info_in_Uchrome() {
622     JSAN.use('util.file');
623     var f = new util.file();
624     var f_in_uchrome = f.get('ws_info','uchrome');
625     var path = f_in_uchrome.exists() ? f_in_uchrome.path : false;
626     f.close();
627     return path;
628 }
629
630 function handle_migration() {
631     if ( found_ws_info_in_Uchrome() ) {
632         alert(offlineStrings.getFormattedString('main.settings.migrate.failed', [found_ws_info_in_Uchrome(), found_ws_info_in_Achrome()])
633         );
634     } else {
635         var dirService = Components.classes["@mozilla.org/file/directory_service;1"].getService( Components.interfaces.nsIProperties );
636         var f_new = dirService.get( "UChrm", Components.interfaces.nsIFile );
637         var f_old = dirService.get( "AChrom", Components.interfaces.nsIFile );
638         f_old.append(myPackageDir); f_old.append("content"); f_old.append("conf"); 
639         if (window.confirm(offlineStrings.getFormattedString("main.settings.migrate.confirm", [f_old.path, f_new.path]))) {
640             var files = f_old.directoryEntries;
641             while (files.hasMoreElements()) {
642                 var file = files.getNext();
643                 var file2 = file.QueryInterface( Components.interfaces.nsILocalFile );
644                 try {
645                     file2.moveTo( f_new, '' );
646                 } catch(E) {
647                     alert(offlineStrings.getFormattedString('main.settings.migrate.error', [file2.path, f_new.path]) + '\n');
648                 }
649             }
650             location.href = location.href; // huh?
651         }
652     }
653 }
654
655 dump('exiting main/main.js\n');