1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.948.2.9 2010/09/01 16:51:47 raeburn Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29: # Makes a table out of the previous attempts
30: # Inputs result_from_symbread, user, domain, course_id
31: # Reads in non-network-related .tab files
32:
33: # POD header:
34:
35: =pod
36:
37: =head1 NAME
38:
39: Apache::loncommon - pile of common routines
40:
41: =head1 SYNOPSIS
42:
43: Common routines for manipulating connections, student answers,
44: domains, common Javascript fragments, etc.
45:
46: =head1 OVERVIEW
47:
48: A collection of commonly used subroutines that don't have a natural
49: home anywhere else. This collection helps remove
50: redundancy from other modules and increase efficiency of memory usage.
51:
52: =cut
53:
54: # End of POD header
55: package Apache::loncommon;
56:
57: use strict;
58: use Apache::lonnet;
59: use GDBM_File;
60: use POSIX qw(strftime mktime);
61: use Apache::lonmenu();
62: use Apache::lonenc();
63: use Apache::lonlocal;
64: use Apache::lonnet();
65: use HTML::Entities;
66: use Apache::lonhtmlcommon();
67: use Apache::loncoursedata();
68: use Apache::lontexconvert();
69: use Apache::lonclonecourse();
70: use LONCAPA qw(:DEFAULT :match);
71: use DateTime::TimeZone;
72: use DateTime::Locale::Catalog;
73:
74: # ---------------------------------------------- Designs
75: use vars qw(%defaultdesign);
76:
77: my $readit;
78:
79:
80: ##
81: ## Global Variables
82: ##
83:
84:
85: # ----------------------------------------------- SSI with retries:
86: #
87:
88: =pod
89:
90: =head1 Server Side include with retries:
91:
92: =over 4
93:
94: =item * &ssi_with_retries(resource,retries form)
95:
96: Performs an ssi with some number of retries. Retries continue either
97: until the result is ok or until the retry count supplied by the
98: caller is exhausted.
99:
100: Inputs:
101:
102: =over 4
103:
104: resource - Identifies the resource to insert.
105:
106: retries - Count of the number of retries allowed.
107:
108: form - Hash that identifies the rendering options.
109:
110: =back
111:
112: Returns:
113:
114: =over 4
115:
116: content - The content of the response. If retries were exhausted this is empty.
117:
118: response - The response from the last attempt (which may or may not have been successful.
119:
120: =back
121:
122: =back
123:
124: =cut
125:
126: sub ssi_with_retries {
127: my ($resource, $retries, %form) = @_;
128:
129:
130: my $ok = 0; # True if we got a good response.
131: my $content;
132: my $response;
133:
134: # Try to get the ssi done. within the retries count:
135:
136: do {
137: ($content, $response) = &Apache::lonnet::ssi($resource, %form);
138: $ok = $response->is_success;
139: if (!$ok) {
140: &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
141: }
142: $retries--;
143: } while (!$ok && ($retries > 0));
144:
145: if (!$ok) {
146: $content = ''; # On error return an empty content.
147: }
148: return ($content, $response);
149:
150: }
151:
152:
153:
154: # ----------------------------------------------- Filetypes/Languages/Copyright
155: my %language;
156: my %supported_language;
157: my %cprtag;
158: my %scprtag;
159: my %fe; my %fd; my %fm;
160: my %category_extensions;
161:
162: # ---------------------------------------------- Thesaurus variables
163: #
164: # %Keywords:
165: # A hash used by &keyword to determine if a word is considered a keyword.
166: # $thesaurus_db_file
167: # Scalar containing the full path to the thesaurus database.
168:
169: my %Keywords;
170: my $thesaurus_db_file;
171:
172: #
173: # Initialize values from language.tab, copyright.tab, filetypes.tab,
174: # thesaurus.tab, and filecategories.tab.
175: #
176: BEGIN {
177: # Variable initialization
178: $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
179: #
180: unless ($readit) {
181: # ------------------------------------------------------------------- languages
182: {
183: my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
184: '/language.tab';
185: if ( open(my $fh,"<$langtabfile") ) {
186: while (my $line = <$fh>) {
187: next if ($line=~/^\#/);
188: chomp($line);
189: my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
190: $language{$key}=$val.' - '.$enc;
191: if ($sup) {
192: $supported_language{$key}=$sup;
193: }
194: }
195: close($fh);
196: }
197: }
198: # ------------------------------------------------------------------ copyrights
199: {
200: my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
201: '/copyright.tab';
202: if ( open (my $fh,"<$copyrightfile") ) {
203: while (my $line = <$fh>) {
204: next if ($line=~/^\#/);
205: chomp($line);
206: my ($key,$val)=(split(/\s+/,$line,2));
207: $cprtag{$key}=$val;
208: }
209: close($fh);
210: }
211: }
212: # ----------------------------------------------------------- source copyrights
213: {
214: my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
215: '/source_copyright.tab';
216: if ( open (my $fh,"<$sourcecopyrightfile") ) {
217: while (my $line = <$fh>) {
218: next if ($line =~ /^\#/);
219: chomp($line);
220: my ($key,$val)=(split(/\s+/,$line,2));
221: $scprtag{$key}=$val;
222: }
223: close($fh);
224: }
225: }
226:
227: # -------------------------------------------------------------- default domain designs
228: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
229: my $designfile = $designdir.'/default.tab';
230: if ( open (my $fh,"<$designfile") ) {
231: while (my $line = <$fh>) {
232: next if ($line =~ /^\#/);
233: chomp($line);
234: my ($key,$val)=(split(/\=/,$line));
235: if ($val) { $defaultdesign{$key}=$val; }
236: }
237: close($fh);
238: }
239:
240: # ------------------------------------------------------------- file categories
241: {
242: my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
243: '/filecategories.tab';
244: if ( open (my $fh,"<$categoryfile") ) {
245: while (my $line = <$fh>) {
246: next if ($line =~ /^\#/);
247: chomp($line);
248: my ($extension,$category)=(split(/\s+/,$line,2));
249: push @{$category_extensions{lc($category)}},$extension;
250: }
251: close($fh);
252: }
253:
254: }
255: # ------------------------------------------------------------------ file types
256: {
257: my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
258: '/filetypes.tab';
259: if ( open (my $fh,"<$typesfile") ) {
260: while (my $line = <$fh>) {
261: next if ($line =~ /^\#/);
262: chomp($line);
263: my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
264: if ($descr ne '') {
265: $fe{$ending}=lc($emb);
266: $fd{$ending}=$descr;
267: if ($mime ne 'unk') { $fm{$ending}=$mime; }
268: }
269: }
270: close($fh);
271: }
272: }
273: &Apache::lonnet::logthis(
274: "<span style='color:yellow;'>INFO: Read file types</span>");
275: $readit=1;
276: } # end of unless($readit)
277:
278: }
279:
280: ###############################################################
281: ## HTML and Javascript Helper Functions ##
282: ###############################################################
283:
284: =pod
285:
286: =head1 HTML and Javascript Functions
287:
288: =over 4
289:
290: =item * &browser_and_searcher_javascript()
291:
292: X<browsing, javascript>X<searching, javascript>Returns a string
293: containing javascript with two functions, C<openbrowser> and
294: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
295: tags.
296:
297: =item * &openbrowser(formname,elementname,only,omit) [javascript]
298:
299: inputs: formname, elementname, only, omit
300:
301: formname and elementname indicate the name of the html form and name of
302: the element that the results of the browsing selection are to be placed in.
303:
304: Specifying 'only' will restrict the browser to displaying only files
305: with the given extension. Can be a comma separated list.
306:
307: Specifying 'omit' will restrict the browser to NOT displaying files
308: with the given extension. Can be a comma separated list.
309:
310: =item * &opensearcher(formname,elementname) [javascript]
311:
312: Inputs: formname, elementname
313:
314: formname and elementname specify the name of the html form and the name
315: of the element the selection from the search results will be placed in.
316:
317: =cut
318:
319: sub browser_and_searcher_javascript {
320: my ($mode)=@_;
321: if (!defined($mode)) { $mode='edit'; }
322: my $resurl=&escape_single(&lastresurl());
323: return <<END;
324: // <!-- BEGIN LON-CAPA Internal
325: var editbrowser = null;
326: function openbrowser(formname,elementname,only,omit,titleelement) {
327: var url = '$resurl/?';
328: if (editbrowser == null) {
329: url += 'launch=1&';
330: }
331: url += 'catalogmode=interactive&';
332: url += 'mode=$mode&';
333: url += 'inhibitmenu=yes&';
334: url += 'form=' + formname + '&';
335: if (only != null) {
336: url += 'only=' + only + '&';
337: } else {
338: url += 'only=&';
339: }
340: if (omit != null) {
341: url += 'omit=' + omit + '&';
342: } else {
343: url += 'omit=&';
344: }
345: if (titleelement != null) {
346: url += 'titleelement=' + titleelement + '&';
347: } else {
348: url += 'titleelement=&';
349: }
350: url += 'element=' + elementname + '';
351: var title = 'Browser';
352: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
353: options += ',width=700,height=600';
354: editbrowser = open(url,title,options,'1');
355: editbrowser.focus();
356: }
357: var editsearcher;
358: function opensearcher(formname,elementname,titleelement) {
359: var url = '/adm/searchcat?';
360: if (editsearcher == null) {
361: url += 'launch=1&';
362: }
363: url += 'catalogmode=interactive&';
364: url += 'mode=$mode&';
365: url += 'form=' + formname + '&';
366: if (titleelement != null) {
367: url += 'titleelement=' + titleelement + '&';
368: } else {
369: url += 'titleelement=&';
370: }
371: url += 'element=' + elementname + '';
372: var title = 'Search';
373: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
374: options += ',width=700,height=600';
375: editsearcher = open(url,title,options,'1');
376: editsearcher.focus();
377: }
378: // END LON-CAPA Internal -->
379: END
380: }
381:
382: sub lastresurl {
383: if ($env{'environment.lastresurl'}) {
384: return $env{'environment.lastresurl'}
385: } else {
386: return '/res';
387: }
388: }
389:
390: sub storeresurl {
391: my $resurl=&Apache::lonnet::clutter(shift);
392: unless ($resurl=~/^\/res/) { return 0; }
393: $resurl=~s/\/$//;
394: &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
395: &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
396: return 1;
397: }
398:
399: sub studentbrowser_javascript {
400: unless (
401: (($env{'request.course.id'}) &&
402: (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
403: || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
404: '/'.$env{'request.course.sec'})
405: ))
406: || ($env{'request.role'}=~/^(au|dc|su)/)
407: ) { return ''; }
408: return (<<'ENDSTDBRW');
409: <script type="text/javascript" language="Javascript">
410: // <![CDATA[
411: var stdeditbrowser;
412: function openstdbrowser(formname,uname,udom,roleflag,ignorefilter,courseadvonly) {
413: var url = '/adm/pickstudent?';
414: var filter;
415: if (!ignorefilter) {
416: eval('filter=document.'+formname+'.'+uname+'.value;');
417: }
418: if (filter != null) {
419: if (filter != '') {
420: url += 'filter='+filter+'&';
421: }
422: }
423: url += 'form=' + formname + '&unameelement='+uname+
424: '&udomelement='+udom;
425: if (roleflag) { url+="&roles=1"; }
426: if (courseadvonly) { url+="&courseadvonly=1"; }
427: var title = 'Student_Browser';
428: var options = 'scrollbars=1,resizable=1,menubar=0';
429: options += ',width=700,height=600';
430: stdeditbrowser = open(url,title,options,'1');
431: stdeditbrowser.focus();
432: }
433: // ]]>
434: </script>
435: ENDSTDBRW
436: }
437:
438: sub selectstudent_link {
439: my ($form,$unameele,$udomele,$courseadvonly)=@_;
440: my $callargs = "'".$form."','".$unameele."','".$udomele."'";
441: if ($env{'request.course.id'}) {
442: if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
443: && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
444: '/'.$env{'request.course.sec'})) {
445: return '';
446: }
447: if ($courseadvonly) {
448: $callargs .= ",'',1,1";
449: }
450: return '<span class="LC_nobreak">'.
451: '<a href="javascript:openstdbrowser('.$callargs.');">'.
452: &mt('Select User').'</a></span>';
453: }
454: if ($env{'request.role'}=~/^(au|dc|su)/) {
455: $callargs .= ",1";
456: return '<span class="LC_nobreak">'.
457: '<a href="javascript:openstdbrowser('.$callargs.');">'.
458: &mt('Select User').'</a></span>';
459: }
460: return '';
461: }
462:
463: sub authorbrowser_javascript {
464: return <<"ENDAUTHORBRW";
465: <script type="text/javascript" language="JavaScript">
466: // <![CDATA[
467: var stdeditbrowser;
468:
469: function openauthorbrowser(formname,udom) {
470: var url = '/adm/pickauthor?';
471: url += 'form='+formname+'&roledom='+udom;
472: var title = 'Author_Browser';
473: var options = 'scrollbars=1,resizable=1,menubar=0';
474: options += ',width=700,height=600';
475: stdeditbrowser = open(url,title,options,'1');
476: stdeditbrowser.focus();
477: }
478:
479: // ]]>
480: </script>
481: ENDAUTHORBRW
482: }
483:
484: sub coursebrowser_javascript {
485: my ($domainfilter,$sec_element,$formname,$role_element,$crstype) = @_;
486: my $wintitle = 'Course_Browser';
487: if ($crstype eq 'Community') {
488: $wintitle = 'Community_Browser';
489: }
490: my $id_functions = &javascript_index_functions();
491: my $output = '
492: <script type="text/javascript" language="JavaScript">
493: // <![CDATA[
494: var stdeditbrowser;'."\n";
495:
496: $output .= <<"ENDSTDBRW";
497: function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
498: var url = '/adm/pickcourse?';
499: var formid = getFormIdByName(formname);
500: var domainfilter = getDomainFromSelectbox(formname,udom);
501: if (domainfilter != null) {
502: if (domainfilter != '') {
503: url += 'domainfilter='+domainfilter+'&';
504: }
505: }
506: url += 'form=' + formname + '&cnumelement='+uname+
507: '&cdomelement='+udom+
508: '&cnameelement='+desc;
509: if (extra_element !=null && extra_element != '') {
510: if (formname == 'rolechoice' || formname == 'studentform') {
511: url += '&roleelement='+extra_element;
512: if (domainfilter == null || domainfilter == '') {
513: url += '&domainfilter='+extra_element;
514: }
515: }
516: else {
517: if (formname == 'portform') {
518: url += '&setroles='+extra_element;
519: } else {
520: if (formname == 'rules') {
521: url += '&fixeddom='+extra_element;
522: }
523: }
524: }
525: }
526: if (type != null && type != '') {
527: url += '&type='+type;
528: }
529: if (type_elem != null && type_elem != '') {
530: url += '&typeelement='+type_elem;
531: }
532: if (formname == 'ccrs') {
533: var ownername = document.forms[formid].ccuname.value;
534: var ownerdom = document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
535: url += '&cloner='+ownername+':'+ownerdom;
536: }
537: if (multflag !=null && multflag != '') {
538: url += '&multiple='+multflag;
539: }
540: var title = '$wintitle';
541: var options = 'scrollbars=1,resizable=1,menubar=0';
542: options += ',width=700,height=600';
543: stdeditbrowser = open(url,title,options,'1');
544: stdeditbrowser.focus();
545: }
546: $id_functions
547: ENDSTDBRW
548: if (($sec_element ne '') || ($role_element ne '')) {
549: $output .= &setsec_javascript($sec_element,$formname,$role_element);
550: }
551: $output .= '
552: // ]]>
553: </script>';
554: return $output;
555: }
556:
557: sub javascript_index_functions {
558: return <<"ENDJS";
559:
560: function getFormIdByName(formname) {
561: for (var i=0;i<document.forms.length;i++) {
562: if (document.forms[i].name == formname) {
563: return i;
564: }
565: }
566: return -1;
567: }
568:
569: function getIndexByName(formid,item) {
570: for (var i=0;i<document.forms[formid].elements.length;i++) {
571: if (document.forms[formid].elements[i].name == item) {
572: return i;
573: }
574: }
575: return -1;
576: }
577:
578: function getDomainFromSelectbox(formname,udom) {
579: var userdom;
580: var formid = getFormIdByName(formname);
581: if (formid > -1) {
582: var domid = getIndexByName(formid,udom);
583: if (domid > -1) {
584: if (document.forms[formid].elements[domid].type == 'select-one') {
585: userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
586: }
587: if (document.forms[formid].elements[domid].type == 'hidden') {
588: userdom=document.forms[formid].elements[domid].value;
589: }
590: }
591: }
592: return userdom;
593: }
594:
595: ENDJS
596:
597: }
598:
599: sub userbrowser_javascript {
600: my $id_functions = &javascript_index_functions();
601: return <<"ENDUSERBRW";
602:
603: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
604: var url = '/adm/pickuser?';
605: var userdom = getDomainFromSelectbox(formname,udom);
606: if (userdom != null) {
607: if (userdom != '') {
608: url += 'srchdom='+userdom+'&';
609: }
610: }
611: url += 'form=' + formname + '&unameelement='+uname+
612: '&udomelement='+udom+
613: '&ulastelement='+ulast+
614: '&ufirstelement='+ufirst+
615: '&uemailelement='+uemail+
616: '&hideudomelement='+hideudom+
617: '&coursedom='+crsdom;
618: if ((caller != null) && (caller != undefined)) {
619: url += '&caller='+caller;
620: }
621: var title = 'User_Browser';
622: var options = 'scrollbars=1,resizable=1,menubar=0';
623: options += ',width=700,height=600';
624: var stdeditbrowser = open(url,title,options,'1');
625: stdeditbrowser.focus();
626: }
627:
628: function fix_domain (formname,udom,origdom,uname) {
629: var formid = getFormIdByName(formname);
630: if (formid > -1) {
631: var unameid = getIndexByName(formid,uname);
632: var domid = getIndexByName(formid,udom);
633: var hidedomid = getIndexByName(formid,origdom);
634: if (hidedomid > -1) {
635: var fixeddom = document.forms[formid].elements[hidedomid].value;
636: var unameval = document.forms[formid].elements[unameid].value;
637: if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
638: if (domid > -1) {
639: var slct = document.forms[formid].elements[domid];
640: if (slct.type == 'select-one') {
641: var i;
642: for (i=0;i<slct.length;i++) {
643: if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
644: }
645: }
646: if (slct.type == 'hidden') {
647: slct.value = fixeddom;
648: }
649: }
650: }
651: }
652: }
653: return;
654: }
655:
656: $id_functions
657: ENDUSERBRW
658: }
659:
660: sub setsec_javascript {
661: my ($sec_element,$formname,$role_element) = @_;
662: my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
663: $communityrolestr);
664: if ($role_element ne '') {
665: my @allroles = ('st','ta','ep','in','ad');
666: foreach my $crstype ('Course','Community') {
667: if ($crstype eq 'Community') {
668: foreach my $role (@allroles) {
669: push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
670: }
671: push(@communityrolenames,&Apache::lonnet::plaintext('co'));
672: } else {
673: foreach my $role (@allroles) {
674: push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
675: }
676: push(@courserolenames,&Apache::lonnet::plaintext('cc'));
677: }
678: }
679: $rolestr = '"'.join('","',@allroles).'"';
680: $courserolestr = '"'.join('","',@courserolenames).'"';
681: $communityrolestr = '"'.join('","',@communityrolenames).'"';
682: }
683: my $setsections = qq|
684: function setSect(sectionlist) {
685: var sectionsArray = new Array();
686: if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
687: sectionsArray = sectionlist.split(",");
688: }
689: var numSections = sectionsArray.length;
690: document.$formname.$sec_element.length = 0;
691: if (numSections == 0) {
692: document.$formname.$sec_element.multiple=false;
693: document.$formname.$sec_element.size=1;
694: document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
695: } else {
696: if (numSections == 1) {
697: document.$formname.$sec_element.multiple=false;
698: document.$formname.$sec_element.size=1;
699: document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
700: document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
701: document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
702: } else {
703: for (var i=0; i<numSections; i++) {
704: document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
705: }
706: document.$formname.$sec_element.multiple=true
707: if (numSections < 3) {
708: document.$formname.$sec_element.size=numSections;
709: } else {
710: document.$formname.$sec_element.size=3;
711: }
712: document.$formname.$sec_element.options[0].selected = false
713: }
714: }
715: }
716:
717: function setRole(crstype) {
718: |;
719: if ($role_element eq '') {
720: $setsections .= ' return;
721: }
722: ';
723: } else {
724: $setsections .= qq|
725: var elementLength = document.$formname.$role_element.length;
726: var allroles = Array($rolestr);
727: var courserolenames = Array($courserolestr);
728: var communityrolenames = Array($communityrolestr);
729: if (elementLength != undefined) {
730: if (document.$formname.$role_element.options[5].value == 'cc') {
731: if (crstype == 'Course') {
732: return;
733: } else {
734: allroles[5] = 'co';
735: for (var i=0; i<6; i++) {
736: document.$formname.$role_element.options[i].value = allroles[i];
737: document.$formname.$role_element.options[i].text = communityrolenames[i];
738: }
739: }
740: } else {
741: if (crstype == 'Community') {
742: return;
743: } else {
744: allroles[5] = 'cc';
745: for (var i=0; i<6; i++) {
746: document.$formname.$role_element.options[i].value = allroles[i];
747: document.$formname.$role_element.options[i].text = courserolenames[i];
748: }
749: }
750: }
751: }
752: return;
753: }
754: |;
755: }
756: return $setsections;
757: }
758:
759: sub selectcourse_link {
760: my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
761: $typeelement) = @_;
762: my $type = $selecttype;
763: my $linktext = &mt('Select Course');
764: if ($selecttype eq 'Community') {
765: $linktext = &mt('Select Community');
766: } elsif ($selecttype eq 'Course/Community') {
767: $linktext = &mt('Select Course/Community');
768: $type = '';
769: }
770: return '<span class="LC_nobreak">'
771: ."<a href='"
772: .'javascript:opencrsbrowser("'.$form.'","'.$unameele
773: .'","'.$udomele.'","'.$desc.'","'.$extra_element
774: .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
775: ."'>".$linktext.'</a>'
776: .'</span>';
777: }
778:
779: sub selectauthor_link {
780: my ($form,$udom)=@_;
781: return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
782: &mt('Select Author').'</a>';
783: }
784:
785: sub selectuser_link {
786: my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
787: $coursedom,$linktext,$caller) = @_;
788: return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
789: "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
790: ');">'.$linktext.'</a>';
791: }
792:
793: sub check_uncheck_jscript {
794: my $jscript = <<"ENDSCRT";
795: function checkAll(field) {
796: if (field.length > 0) {
797: for (i = 0; i < field.length; i++) {
798: field[i].checked = true ;
799: }
800: } else {
801: field.checked = true
802: }
803: }
804:
805: function uncheckAll(field) {
806: if (field.length > 0) {
807: for (i = 0; i < field.length; i++) {
808: field[i].checked = false ;
809: }
810: } else {
811: field.checked = false ;
812: }
813: }
814: ENDSCRT
815: return $jscript;
816: }
817:
818: sub select_timezone {
819: my ($name,$selected,$onchange,$includeempty)=@_;
820: my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
821: if ($includeempty) {
822: $output .= '<option value=""';
823: if (($selected eq '') || ($selected eq 'local')) {
824: $output .= ' selected="selected" ';
825: }
826: $output .= '> </option>';
827: }
828: my @timezones = DateTime::TimeZone->all_names;
829: foreach my $tzone (@timezones) {
830: $output.= '<option value="'.$tzone.'"';
831: if ($tzone eq $selected) {
832: $output.=' selected="selected"';
833: }
834: $output.=">$tzone</option>\n";
835: }
836: $output.="</select>";
837: return $output;
838: }
839:
840: sub select_datelocale {
841: my ($name,$selected,$onchange,$includeempty)=@_;
842: my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
843: if ($includeempty) {
844: $output .= '<option value=""';
845: if ($selected eq '') {
846: $output .= ' selected="selected" ';
847: }
848: $output .= '> </option>';
849: }
850: my (@possibles,%locale_names);
851: my @locales = DateTime::Locale::Catalog::Locales;
852: foreach my $locale (@locales) {
853: if (ref($locale) eq 'HASH') {
854: my $id = $locale->{'id'};
855: if ($id ne '') {
856: my $en_terr = $locale->{'en_territory'};
857: my $native_terr = $locale->{'native_territory'};
858: my @languages = &Apache::lonlocal::preferred_languages();
859: if (grep(/^en$/,@languages) || !@languages) {
860: if ($en_terr ne '') {
861: $locale_names{$id} = '('.$en_terr.')';
862: } elsif ($native_terr ne '') {
863: $locale_names{$id} = $native_terr;
864: }
865: } else {
866: if ($native_terr ne '') {
867: $locale_names{$id} = $native_terr.' ';
868: } elsif ($en_terr ne '') {
869: $locale_names{$id} = '('.$en_terr.')';
870: }
871: }
872: push (@possibles,$id);
873: }
874: }
875: }
876: foreach my $item (sort(@possibles)) {
877: $output.= '<option value="'.$item.'"';
878: if ($item eq $selected) {
879: $output.=' selected="selected"';
880: }
881: $output.=">$item";
882: if ($locale_names{$item} ne '') {
883: $output.=" $locale_names{$item}</option>\n";
884: }
885: $output.="</option>\n";
886: }
887: $output.="</select>";
888: return $output;
889: }
890:
891: sub select_language {
892: my ($name,$selected,$includeempty) = @_;
893: my %langchoices;
894: if ($includeempty) {
895: %langchoices = ('' => 'No language preference');
896: }
897: foreach my $id (&languageids()) {
898: my $code = &supportedlanguagecode($id);
899: if ($code) {
900: $langchoices{$code} = &plainlanguagedescription($id);
901: }
902: }
903: return &select_form($selected,$name,\%langchoices);
904: }
905:
906: =pod
907:
908: =item * &linked_select_forms(...)
909:
910: linked_select_forms returns a string containing a <script></script> block
911: and html for two <select> menus. The select menus will be linked in that
912: changing the value of the first menu will result in new values being placed
913: in the second menu. The values in the select menu will appear in alphabetical
914: order unless a defined order is provided.
915:
916: linked_select_forms takes the following ordered inputs:
917:
918: =over 4
919:
920: =item * $formname, the name of the <form> tag
921:
922: =item * $middletext, the text which appears between the <select> tags
923:
924: =item * $firstdefault, the default value for the first menu
925:
926: =item * $firstselectname, the name of the first <select> tag
927:
928: =item * $secondselectname, the name of the second <select> tag
929:
930: =item * $hashref, a reference to a hash containing the data for the menus.
931:
932: =item * $menuorder, the order of values in the first menu
933:
934: =back
935:
936: Below is an example of such a hash. Only the 'text', 'default', and
937: 'select2' keys must appear as stated. keys(%menu) are the possible
938: values for the first select menu. The text that coincides with the
939: first menu value is given in $menu{$choice1}->{'text'}. The values
940: and text for the second menu are given in the hash pointed to by
941: $menu{$choice1}->{'select2'}.
942:
943: my %menu = ( A1 => { text =>"Choice A1" ,
944: default => "B3",
945: select2 => {
946: B1 => "Choice B1",
947: B2 => "Choice B2",
948: B3 => "Choice B3",
949: B4 => "Choice B4"
950: },
951: order => ['B4','B3','B1','B2'],
952: },
953: A2 => { text =>"Choice A2" ,
954: default => "C2",
955: select2 => {
956: C1 => "Choice C1",
957: C2 => "Choice C2",
958: C3 => "Choice C3"
959: },
960: order => ['C2','C1','C3'],
961: },
962: A3 => { text =>"Choice A3" ,
963: default => "D6",
964: select2 => {
965: D1 => "Choice D1",
966: D2 => "Choice D2",
967: D3 => "Choice D3",
968: D4 => "Choice D4",
969: D5 => "Choice D5",
970: D6 => "Choice D6",
971: D7 => "Choice D7"
972: },
973: order => ['D4','D3','D2','D1','D7','D6','D5'],
974: }
975: );
976:
977: =cut
978:
979: sub linked_select_forms {
980: my ($formname,
981: $middletext,
982: $firstdefault,
983: $firstselectname,
984: $secondselectname,
985: $hashref,
986: $menuorder,
987: ) = @_;
988: my $second = "document.$formname.$secondselectname";
989: my $first = "document.$formname.$firstselectname";
990: # output the javascript to do the changing
991: my $result = '';
992: $result.='<script type="text/javascript" language="JavaScript">'."\n";
993: $result.="// <![CDATA[\n";
994: $result.="var select2data = new Object();\n";
995: $" = '","';
996: my $debug = '';
997: foreach my $s1 (sort(keys(%$hashref))) {
998: $result.="select2data.d_$s1 = new Object();\n";
999: $result.="select2data.d_$s1.def = new String('".
1000: $hashref->{$s1}->{'default'}."');\n";
1001: $result.="select2data.d_$s1.values = new Array(";
1002: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1003: if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
1004: @s2values = @{$hashref->{$s1}->{'order'}};
1005: }
1006: $result.="\"@s2values\");\n";
1007: $result.="select2data.d_$s1.texts = new Array(";
1008: my @s2texts;
1009: foreach my $value (@s2values) {
1010: push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
1011: }
1012: $result.="\"@s2texts\");\n";
1013: }
1014: $"=' ';
1015: $result.= <<"END";
1016:
1017: function select1_changed() {
1018: // Determine new choice
1019: var newvalue = "d_" + $first.value;
1020: // update select2
1021: var values = select2data[newvalue].values;
1022: var texts = select2data[newvalue].texts;
1023: var select2def = select2data[newvalue].def;
1024: var i;
1025: // out with the old
1026: for (i = 0; i < $second.options.length; i++) {
1027: $second.options[i] = null;
1028: }
1029: // in with the nuclear
1030: for (i=0;i<values.length; i++) {
1031: $second.options[i] = new Option(values[i]);
1032: $second.options[i].value = values[i];
1033: $second.options[i].text = texts[i];
1034: if (values[i] == select2def) {
1035: $second.options[i].selected = true;
1036: }
1037: }
1038: }
1039: // ]]>
1040: </script>
1041: END
1042: # output the initial values for the selection lists
1043: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
1044: my @order = sort(keys(%{$hashref}));
1045: if (ref($menuorder) eq 'ARRAY') {
1046: @order = @{$menuorder};
1047: }
1048: foreach my $value (@order) {
1049: $result.=" <option value=\"$value\" ";
1050: $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1051: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1052: }
1053: $result .= "</select>\n";
1054: my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
1055: $result .= $middletext;
1056: $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
1057: my $seconddefault = $hashref->{$firstdefault}->{'default'};
1058:
1059: my @secondorder = sort(keys(%select2));
1060: if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
1061: @secondorder = @{$hashref->{$firstdefault}->{'order'}};
1062: }
1063: foreach my $value (@secondorder) {
1064: $result.=" <option value=\"$value\" ";
1065: $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1066: $result.=">".&mt($select2{$value})."</option>\n";
1067: }
1068: $result .= "</select>\n";
1069: # return $debug;
1070: return $result;
1071: } # end of sub linked_select_forms {
1072:
1073: =pod
1074:
1075: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1076:
1077: Returns a string corresponding to an HTML link to the given help
1078: $topic, where $topic corresponds to the name of a .tex file in
1079: /home/httpd/html/adm/help/tex, with underscores replaced by
1080: spaces.
1081:
1082: $text will optionally be linked to the same topic, allowing you to
1083: link text in addition to the graphic. If you do not want to link
1084: text, but wish to specify one of the later parameters, pass an
1085: empty string.
1086:
1087: $stayOnPage is a value that will be interpreted as a boolean. If true,
1088: the link will not open a new window. If false, the link will open
1089: a new window using Javascript. (Default is false.)
1090:
1091: $width and $height are optional numerical parameters that will
1092: override the width and height of the popped up window, which may
1093: be useful for certain help topics with big pictures included.
1094:
1095: =cut
1096:
1097: sub help_open_topic {
1098: my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1099: $text = "" if (not defined $text);
1100: $stayOnPage = 0 if (not defined $stayOnPage);
1101: $width = 350 if (not defined $width);
1102: $height = 400 if (not defined $height);
1103: my $filename = $topic;
1104: $filename =~ s/ /_/g;
1105:
1106: my $template = "";
1107: my $link;
1108:
1109: $topic=~s/\W/\_/g;
1110:
1111: if (!$stayOnPage) {
1112: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1113: } else {
1114: $link = "/adm/help/${filename}.hlp";
1115: }
1116:
1117: # Add the text
1118: if ($text ne "") {
1119: $template.='<span class="LC_help_open_topic">'
1120: .'<a target="_top" href="'.$link.'">'
1121: .$text.'</a>';
1122: }
1123:
1124: # (Always) Add the graphic
1125: my $title = &mt('Online Help');
1126: my $helpicon=&lonhttpdurl("/adm/help/help.png");
1127: if ($imgid ne '') {
1128: $imgid = ' id="'.$imgid.'"';
1129: }
1130: $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
1131: .'<img src="'.$helpicon.'" border="0"'
1132: .' alt="'.&mt('Help: [_1]',$topic).'"'
1133: .' title="'.$title.'" style="vertical-align:middle;"'.$imgid
1134: .' /></a>';
1135: if ($text ne "") {
1136: $template.='</span>';
1137: }
1138: return $template;
1139:
1140: }
1141:
1142: # This is a quicky function for Latex cheatsheet editing, since it
1143: # appears in at least four places
1144: sub helpLatexCheatsheet {
1145: my ($topic,$text,$not_author) = @_;
1146: my $out;
1147: my $addOther = '';
1148: if ($topic) {
1149: $addOther = '<span>'.&Apache::loncommon::help_open_topic($topic,&mt($text),
1150: undef, undef, 600).
1151: '</span> ';
1152: }
1153: $out = '<span>' # Start cheatsheet
1154: .$addOther
1155: .'<span>'
1156: .&Apache::loncommon::help_open_topic('Greek_Symbols',&mt('Greek Symbols'),
1157: undef,undef,600)
1158: .'</span> <span>'
1159: .&Apache::loncommon::help_open_topic('Other_Symbols',&mt('Other Symbols'),
1160: undef,undef,600)
1161: .'</span>';
1162: unless ($not_author) {
1163: $out .= ' <span>'
1164: .&Apache::loncommon::help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),
1165: undef,undef,600)
1166: .'</span>';
1167: }
1168: $out .= '</span>'; # End cheatsheet
1169: return $out;
1170: }
1171:
1172: sub general_help {
1173: my $helptopic='Student_Intro';
1174: if ($env{'request.role'}=~/^(ca|au)/) {
1175: $helptopic='Authoring_Intro';
1176: } elsif ($env{'request.role'}=~/^(cc|co)/) {
1177: $helptopic='Course_Coordination_Intro';
1178: } elsif ($env{'request.role'}=~/^dc/) {
1179: $helptopic='Domain_Coordination_Intro';
1180: }
1181: return $helptopic;
1182: }
1183:
1184: sub update_help_link {
1185: my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
1186: my $origurl = $ENV{'REQUEST_URI'};
1187: $origurl=~s|^/~|/priv/|;
1188: my $timestamp = time;
1189: foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
1190: $$datum = &escape($$datum);
1191: }
1192:
1193: my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage";
1194: my $output .= <<"ENDOUTPUT";
1195: <script type="text/javascript">
1196: // <![CDATA[
1197: banner_link = '$banner_link';
1198: // ]]>
1199: </script>
1200: ENDOUTPUT
1201: return $output;
1202: }
1203:
1204: # now just updates the help link and generates a blue icon
1205: sub help_open_menu {
1206: my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text)
1207: = @_;
1208: $stayOnPage = 0 if (not defined $stayOnPage);
1209: # only use pop-up help (stayOnPage == 0)
1210: # if environment.remote is on (using remote control UI)
1211: if ($env{'environment.remote'} eq 'off' ) {
1212: $stayOnPage=1;
1213: }
1214: my $output;
1215: if ($component_help) {
1216: if (!$text) {
1217: $output=&help_open_topic($component_help,undef,$stayOnPage,
1218: $width,$height);
1219: } else {
1220: my $help_text;
1221: $help_text=&unescape($topic);
1222: $output='<table><tr><td>'.
1223: &help_open_topic($component_help,$help_text,$stayOnPage,
1224: $width,$height).'</td></tr></table>';
1225: }
1226: }
1227: my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
1228: return $output.$banner_link;
1229: }
1230:
1231: sub top_nav_help {
1232: my ($text) = @_;
1233: $text = &mt($text);
1234: my $stay_on_page =
1235: ($env{'environment.remote'} eq 'off' );
1236: my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1237: : "javascript:helpMenu('open')";
1238: my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1239:
1240: my $title = &mt('Get help');
1241:
1242: return <<"END";
1243: $banner_link
1244: <a href="$link" title="$title">$text</a>
1245: END
1246: }
1247:
1248: sub help_menu_js {
1249: my ($text) = @_;
1250:
1251: my $stayOnPage =
1252: ($env{'environment.remote'} eq 'off' );
1253:
1254: my $width = 620;
1255: my $height = 600;
1256: my $helptopic=&general_help();
1257: my $details_link = '/adm/help/'.$helptopic.'.hlp';
1258: my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1259: my $start_page =
1260: &Apache::loncommon::start_page('Help Menu', undef,
1261: {'frameset' => 1,
1262: 'js_ready' => 1,
1263: 'add_entries' => {
1264: 'border' => '0',
1265: 'rows' => "110,*",},});
1266: my $end_page =
1267: &Apache::loncommon::end_page({'frameset' => 1,
1268: 'js_ready' => 1,});
1269:
1270: my $template .= <<"ENDTEMPLATE";
1271: <script type="text/javascript">
1272: // <![CDATA[
1273: // <!-- BEGIN LON-CAPA Internal
1274: var banner_link = '';
1275: function helpMenu(target) {
1276: var caller = this;
1277: if (target == 'open') {
1278: var newWindow = null;
1279: try {
1280: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1281: }
1282: catch(error) {
1283: writeHelp(caller);
1284: return;
1285: }
1286: if (newWindow) {
1287: caller = newWindow;
1288: }
1289: }
1290: writeHelp(caller);
1291: return;
1292: }
1293: function writeHelp(caller) {
1294: caller.document.writeln('$start_page<frame name="bannerframe" src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
1295: caller.document.close()
1296: caller.focus()
1297: }
1298: // END LON-CAPA Internal -->
1299: // ]]>
1300: </script>
1301: ENDTEMPLATE
1302: return $template;
1303: }
1304:
1305: sub help_open_bug {
1306: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1307: unless ($env{'user.adv'}) { return ''; }
1308: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
1309: $text = "" if (not defined $text);
1310: $stayOnPage = 0 if (not defined $stayOnPage);
1311: if ($env{'environment.remote'} eq 'off' ) {
1312: $stayOnPage=1;
1313: }
1314: $width = 600 if (not defined $width);
1315: $height = 600 if (not defined $height);
1316:
1317: $topic=~s/\W+/\+/g;
1318: my $link='';
1319: my $template='';
1320: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
1321: &escape($ENV{'REQUEST_URI'}).'&component='.$topic;
1322: if (!$stayOnPage)
1323: {
1324: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1325: }
1326: else
1327: {
1328: $link = $url;
1329: }
1330: # Add the text
1331: if ($text ne "")
1332: {
1333: $template .=
1334: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1335: "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1336: }
1337:
1338: # Add the graphic
1339: my $title = &mt('Report a Bug');
1340: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1341: $template .= <<"ENDTEMPLATE";
1342: <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1343: ENDTEMPLATE
1344: if ($text ne '') { $template.='</td></tr></table>' };
1345: return $template;
1346:
1347: }
1348:
1349: sub help_open_faq {
1350: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1351: unless ($env{'user.adv'}) { return ''; }
1352: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
1353: $text = "" if (not defined $text);
1354: $stayOnPage = 0 if (not defined $stayOnPage);
1355: if ($env{'environment.remote'} eq 'off' ) {
1356: $stayOnPage=1;
1357: }
1358: $width = 350 if (not defined $width);
1359: $height = 400 if (not defined $height);
1360:
1361: $topic=~s/\W+/\+/g;
1362: my $link='';
1363: my $template='';
1364: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
1365: if (!$stayOnPage)
1366: {
1367: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1368: }
1369: else
1370: {
1371: $link = $url;
1372: }
1373:
1374: # Add the text
1375: if ($text ne "")
1376: {
1377: $template .=
1378: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1379: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1380: }
1381:
1382: # Add the graphic
1383: my $title = &mt('View the FAQ');
1384: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1385: $template .= <<"ENDTEMPLATE";
1386: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1387: ENDTEMPLATE
1388: if ($text ne '') { $template.='</td></tr></table>' };
1389: return $template;
1390:
1391: }
1392:
1393: ###############################################################
1394: ###############################################################
1395:
1396: =pod
1397:
1398: =item * &change_content_javascript():
1399:
1400: This and the next function allow you to create small sections of an
1401: otherwise static HTML page that you can update on the fly with
1402: Javascript, even in Netscape 4.
1403:
1404: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
1405: must be written to the HTML page once. It will prove the Javascript
1406: function "change(name, content)". Calling the change function with the
1407: name of the section
1408: you want to update, matching the name passed to C<changable_area>, and
1409: the new content you want to put in there, will put the content into
1410: that area.
1411:
1412: B<Note>: Netscape 4 only reserves enough space for the changable area
1413: to contain room for the original contents. You need to "make space"
1414: for whatever changes you wish to make, and be B<sure> to check your
1415: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
1416: it's adequate for updating a one-line status display, but little more.
1417: This script will set the space to 100% width, so you only need to
1418: worry about height in Netscape 4.
1419:
1420: Modern browsers are much less limiting, and if you can commit to the
1421: user not using Netscape 4, this feature may be used freely with
1422: pretty much any HTML.
1423:
1424: =cut
1425:
1426: sub change_content_javascript {
1427: # If we're on Netscape 4, we need to use Layer-based code
1428: if ($env{'browser.type'} eq 'netscape' &&
1429: $env{'browser.version'} =~ /^4\./) {
1430: return (<<NETSCAPE4);
1431: function change(name, content) {
1432: doc = document.layers[name+"___escape"].layers[0].document;
1433: doc.open();
1434: doc.write(content);
1435: doc.close();
1436: }
1437: NETSCAPE4
1438: } else {
1439: # Otherwise, we need to use semi-standards-compliant code
1440: # (technically, "innerHTML" isn't standard but the equivalent
1441: # is really scary, and every useful browser supports it
1442: return (<<DOMBASED);
1443: function change(name, content) {
1444: element = document.getElementById(name);
1445: element.innerHTML = content;
1446: }
1447: DOMBASED
1448: }
1449: }
1450:
1451: =pod
1452:
1453: =item * &changable_area($name,$origContent):
1454:
1455: This provides a "changable area" that can be modified on the fly via
1456: the Javascript code provided in C<change_content_javascript>. $name is
1457: the name you will use to reference the area later; do not repeat the
1458: same name on a given HTML page more then once. $origContent is what
1459: the area will originally contain, which can be left blank.
1460:
1461: =cut
1462:
1463: sub changable_area {
1464: my ($name, $origContent) = @_;
1465:
1466: if ($env{'browser.type'} eq 'netscape' &&
1467: $env{'browser.version'} =~ /^4\./) {
1468: # If this is netscape 4, we need to use the Layer tag
1469: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
1470: } else {
1471: return "<span id='$name'>$origContent</span>";
1472: }
1473: }
1474:
1475: =pod
1476:
1477: =item * &viewport_geometry_js
1478:
1479: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
1480:
1481: =cut
1482:
1483:
1484: sub viewport_geometry_js {
1485: return <<"GEOMETRY";
1486: var Geometry = {};
1487: function init_geometry() {
1488: if (Geometry.init) { return };
1489: Geometry.init=1;
1490: if (window.innerHeight) {
1491: Geometry.getViewportHeight = function() { return window.innerHeight; };
1492: Geometry.getViewportWidth = function() { return window.innerWidth; };
1493: Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
1494: Geometry.getVerticalScroll = function() { return window.pageYOffset; };
1495: }
1496: else if (document.documentElement && document.documentElement.clientHeight) {
1497: Geometry.getViewportHeight =
1498: function() { return document.documentElement.clientHeight; };
1499: Geometry.getViewportWidth =
1500: function() { return document.documentElement.clientWidth; };
1501:
1502: Geometry.getHorizontalScroll =
1503: function() { return document.documentElement.scrollLeft; };
1504: Geometry.getVerticalScroll =
1505: function() { return document.documentElement.scrollTop; };
1506: }
1507: else if (document.body.clientHeight) {
1508: Geometry.getViewportHeight =
1509: function() { return document.body.clientHeight; };
1510: Geometry.getViewportWidth =
1511: function() { return document.body.clientWidth; };
1512: Geometry.getHorizontalScroll =
1513: function() { return document.body.scrollLeft; };
1514: Geometry.getVerticalScroll =
1515: function() { return document.body.scrollTop; };
1516: }
1517: }
1518:
1519: GEOMETRY
1520: }
1521:
1522: =pod
1523:
1524: =item * &viewport_size_js()
1525:
1526: Provides a javascript function to set values of two form elements - width and height (elements are passed in as arguments to the javascript function) to the dimensions of the user's browser window.
1527:
1528: =cut
1529:
1530: sub viewport_size_js {
1531: my $geometry = &viewport_geometry_js();
1532: return <<"DIMS";
1533:
1534: $geometry
1535:
1536: function getViewportDims(width,height) {
1537: init_geometry();
1538: width.value = Geometry.getViewportWidth();
1539: height.value = Geometry.getViewportHeight();
1540: return;
1541: }
1542:
1543: DIMS
1544: }
1545:
1546: =pod
1547:
1548: =item * &resize_textarea_js()
1549:
1550: emits the needed javascript to resize a textarea to be as big as possible
1551:
1552: creates a function resize_textrea that takes two IDs first should be
1553: the id of the element to resize, second should be the id of a div that
1554: surrounds everything that comes after the textarea, this routine needs
1555: to be attached to the <body> for the onload and onresize events.
1556:
1557: =back
1558:
1559: =cut
1560:
1561: sub resize_textarea_js {
1562: my $geometry = &viewport_geometry_js();
1563: return <<"RESIZE";
1564: <script type="text/javascript">
1565: // <![CDATA[
1566: $geometry
1567:
1568: function getX(element) {
1569: var x = 0;
1570: while (element) {
1571: x += element.offsetLeft;
1572: element = element.offsetParent;
1573: }
1574: return x;
1575: }
1576: function getY(element) {
1577: var y = 0;
1578: while (element) {
1579: y += element.offsetTop;
1580: element = element.offsetParent;
1581: }
1582: return y;
1583: }
1584:
1585:
1586: function resize_textarea(textarea_id,bottom_id) {
1587: init_geometry();
1588: var textarea = document.getElementById(textarea_id);
1589: //alert(textarea);
1590:
1591: var textarea_top = getY(textarea);
1592: var textarea_height = textarea.offsetHeight;
1593: var bottom = document.getElementById(bottom_id);
1594: var bottom_top = getY(bottom);
1595: var bottom_height = bottom.offsetHeight;
1596: var window_height = Geometry.getViewportHeight();
1597: var fudge = 23;
1598: var new_height = window_height-fudge-textarea_top-bottom_height;
1599: if (new_height < 300) {
1600: new_height = 300;
1601: }
1602: textarea.style.height=new_height+'px';
1603: }
1604: // ]]>
1605: </script>
1606: RESIZE
1607:
1608: }
1609:
1610: =pod
1611:
1612: =head1 Excel and CSV file utility routines
1613:
1614: =over 4
1615:
1616: =cut
1617:
1618: ###############################################################
1619: ###############################################################
1620:
1621: =pod
1622:
1623: =item * &csv_translate($text)
1624:
1625: Translate $text to allow it to be output as a 'comma separated values'
1626: format.
1627:
1628: =cut
1629:
1630: ###############################################################
1631: ###############################################################
1632: sub csv_translate {
1633: my $text = shift;
1634: $text =~ s/\"/\"\"/g;
1635: $text =~ s/\n/ /g;
1636: return $text;
1637: }
1638:
1639: ###############################################################
1640: ###############################################################
1641:
1642: =pod
1643:
1644: =item * &define_excel_formats()
1645:
1646: Define some commonly used Excel cell formats.
1647:
1648: Currently supported formats:
1649:
1650: =over 4
1651:
1652: =item header
1653:
1654: =item bold
1655:
1656: =item h1
1657:
1658: =item h2
1659:
1660: =item h3
1661:
1662: =item h4
1663:
1664: =item i
1665:
1666: =item date
1667:
1668: =back
1669:
1670: Inputs: $workbook
1671:
1672: Returns: $format, a hash reference.
1673:
1674: =cut
1675:
1676: ###############################################################
1677: ###############################################################
1678: sub define_excel_formats {
1679: my ($workbook) = @_;
1680: my $format;
1681: $format->{'header'} = $workbook->add_format(bold => 1,
1682: bottom => 1,
1683: align => 'center');
1684: $format->{'bold'} = $workbook->add_format(bold=>1);
1685: $format->{'h1'} = $workbook->add_format(bold=>1, size=>18);
1686: $format->{'h2'} = $workbook->add_format(bold=>1, size=>16);
1687: $format->{'h3'} = $workbook->add_format(bold=>1, size=>14);
1688: $format->{'h4'} = $workbook->add_format(bold=>1, size=>12);
1689: $format->{'i'} = $workbook->add_format(italic=>1);
1690: $format->{'date'} = $workbook->add_format(num_format=>
1691: 'mm/dd/yyyy hh:mm:ss');
1692: return $format;
1693: }
1694:
1695: ###############################################################
1696: ###############################################################
1697:
1698: =pod
1699:
1700: =item * &create_workbook()
1701:
1702: Create an Excel worksheet. If it fails, output message on the
1703: request object and return undefs.
1704:
1705: Inputs: Apache request object
1706:
1707: Returns (undef) on failure,
1708: Excel worksheet object, scalar with filename, and formats
1709: from &Apache::loncommon::define_excel_formats on success
1710:
1711: =cut
1712:
1713: ###############################################################
1714: ###############################################################
1715: sub create_workbook {
1716: my ($r) = @_;
1717: #
1718: # Create the excel spreadsheet
1719: my $filename = '/prtspool/'.
1720: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1721: time.'_'.rand(1000000000).'.xls';
1722: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
1723: if (! defined($workbook)) {
1724: $r->log_error("Error creating excel spreadsheet $filename: $!");
1725: $r->print(
1726: '<p class="LC_error">'
1727: .&mt('Problems occurred in creating the new Excel file.')
1728: .' '.&mt('This error has been logged.')
1729: .' '.&mt('Please alert your LON-CAPA administrator.')
1730: .'</p>'
1731: );
1732: return (undef);
1733: }
1734: #
1735: $workbook->set_tempdir('/home/httpd/perl/tmp');
1736: #
1737: my $format = &Apache::loncommon::define_excel_formats($workbook);
1738: return ($workbook,$filename,$format);
1739: }
1740:
1741: ###############################################################
1742: ###############################################################
1743:
1744: =pod
1745:
1746: =item * &create_text_file()
1747:
1748: Create a file to write to and eventually make available to the user.
1749: If file creation fails, outputs an error message on the request object and
1750: return undefs.
1751:
1752: Inputs: Apache request object, and file suffix
1753:
1754: Returns (undef) on failure,
1755: Filehandle and filename on success.
1756:
1757: =cut
1758:
1759: ###############################################################
1760: ###############################################################
1761: sub create_text_file {
1762: my ($r,$suffix) = @_;
1763: if (! defined($suffix)) { $suffix = 'txt'; };
1764: my $fh;
1765: my $filename = '/prtspool/'.
1766: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1767: time.'_'.rand(1000000000).'.'.$suffix;
1768: $fh = Apache::File->new('>/home/httpd'.$filename);
1769: if (! defined($fh)) {
1770: $r->log_error("Couldn't open $filename for output $!");
1771: $r->print(
1772: '<p class="LC_error">'
1773: .&mt('Problems occurred in creating the output file.')
1774: .' '.&mt('This error has been logged.')
1775: .' '.&mt('Please alert your LON-CAPA administrator.')
1776: .'</p>'
1777: );
1778: }
1779: return ($fh,$filename)
1780: }
1781:
1782:
1783: =pod
1784:
1785: =back
1786:
1787: =cut
1788:
1789: ###############################################################
1790: ## Home server <option> list generating code ##
1791: ###############################################################
1792:
1793: # ------------------------------------------
1794:
1795: sub domain_select {
1796: my ($name,$value,$multiple)=@_;
1797: my %domains=map {
1798: $_ => $_.' '. &Apache::lonnet::domain($_,'description')
1799: } &Apache::lonnet::all_domains();
1800: if ($multiple) {
1801: $domains{''}=&mt('Any domain');
1802: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1803: return &multiple_select_form($name,$value,4,\%domains);
1804: } else {
1805: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1806: return &select_form($name,$value,\%domains);
1807: }
1808: }
1809:
1810: #-------------------------------------------
1811:
1812: =pod
1813:
1814: =head1 Routines for form select boxes
1815:
1816: =over 4
1817:
1818: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1819:
1820: Returns a string containing a <select> element int multiple mode
1821:
1822:
1823: Args:
1824: $name - name of the <select> element
1825: $value - scalar or array ref of values that should already be selected
1826: $size - number of rows long the select element is
1827: $hash - the elements should be 'option' => 'shown text'
1828: (shown text should already have been &mt())
1829: $order - (optional) array ref of the order to show the elements in
1830:
1831: =cut
1832:
1833: #-------------------------------------------
1834: sub multiple_select_form {
1835: my ($name,$value,$size,$hash,$order)=@_;
1836: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
1837: my $output='';
1838: if (! defined($size)) {
1839: $size = 4;
1840: if (scalar(keys(%$hash))<4) {
1841: $size = scalar(keys(%$hash));
1842: }
1843: }
1844: $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1845: my @order;
1846: if (ref($order) eq 'ARRAY') {
1847: @order = @{$order};
1848: } else {
1849: @order = sort(keys(%$hash));
1850: }
1851: if (exists($$hash{'select_form_order'})) {
1852: @order = @{$$hash{'select_form_order'}};
1853: }
1854:
1855: foreach my $key (@order) {
1856: $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1857: $output.='selected="selected" ' if ($selected{$key});
1858: $output.='>'.$hash->{$key}."</option>\n";
1859: }
1860: $output.="</select>\n";
1861: return $output;
1862: }
1863:
1864: #-------------------------------------------
1865:
1866: =pod
1867:
1868: =item * &select_form($defdom,$name,$hashref,$onchange)
1869:
1870: Returns a string containing a <select name='$name' size='1'> form to
1871: allow a user to select options from a ref to a hash containing:
1872: option_name => displayed text. An optional $onchange can include
1873: a javascript onchange item, e.g., onchange="this.form.submit();"
1874:
1875: See lonrights.pm for an example invocation and use.
1876:
1877: =cut
1878:
1879: #-------------------------------------------
1880: sub select_form {
1881: my ($def,$name,$hashref,$onchange) = @_;
1882: return unless (ref($hashref) eq 'HASH');
1883: if ($onchange) {
1884: $onchange = ' onchange="'.$onchange.'"';
1885: }
1886: my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
1887: my @keys;
1888: if (exists($hashref->{'select_form_order'})) {
1889: @keys=@{$hashref->{'select_form_order'}};
1890: } else {
1891: @keys=sort(keys(%{$hashref}));
1892: }
1893: foreach my $key (@keys) {
1894: $selectform.=
1895: '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
1896: ($key eq $def ? 'selected="selected" ' : '').
1897: ">".$hashref->{$key}."</option>\n";
1898: }
1899: $selectform.="</select>";
1900: return $selectform;
1901: }
1902:
1903: # For display filters
1904:
1905: sub display_filter {
1906: if (!$env{'form.show'}) { $env{'form.show'}=10; }
1907: if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1908: return '<span class="LC_nobreak"><label>'.&mt('Records [_1]',
1909: &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
1910: (&mt('all'),10,20,50,100,1000,10000))).
1911: '</label></span> <span class="LC_nobreak">'.
1912: &mt('Filter [_1]',
1913: &select_form($env{'form.displayfilter'},
1914: 'displayfilter',
1915: {'currentfolder' => 'Current folder/page',
1916: 'containing' => 'Containing phrase',
1917: 'none' => 'None'})).
1918: '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></span>';
1919: }
1920:
1921: sub gradeleveldescription {
1922: my $gradelevel=shift;
1923: my %gradelevels=(0 => 'Not specified',
1924: 1 => 'Grade 1',
1925: 2 => 'Grade 2',
1926: 3 => 'Grade 3',
1927: 4 => 'Grade 4',
1928: 5 => 'Grade 5',
1929: 6 => 'Grade 6',
1930: 7 => 'Grade 7',
1931: 8 => 'Grade 8',
1932: 9 => 'Grade 9',
1933: 10 => 'Grade 10',
1934: 11 => 'Grade 11',
1935: 12 => 'Grade 12',
1936: 13 => 'Grade 13',
1937: 14 => '100 Level',
1938: 15 => '200 Level',
1939: 16 => '300 Level',
1940: 17 => '400 Level',
1941: 18 => 'Graduate Level');
1942: return &mt($gradelevels{$gradelevel});
1943: }
1944:
1945: sub select_level_form {
1946: my ($deflevel,$name)=@_;
1947: unless ($deflevel) { $deflevel=0; }
1948: my $selectform = "<select name=\"$name\" size=\"1\">\n";
1949: for (my $i=0; $i<=18; $i++) {
1950: $selectform.="<option value=\"$i\" ".
1951: ($i==$deflevel ? 'selected="selected" ' : '').
1952: ">".&gradeleveldescription($i)."</option>\n";
1953: }
1954: $selectform.="</select>";
1955: return $selectform;
1956: }
1957:
1958: #-------------------------------------------
1959:
1960: =pod
1961:
1962: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms)
1963:
1964: Returns a string containing a <select name='$name' size='1'> form to
1965: allow a user to select the domain to preform an operation in.
1966: See loncreateuser.pm for an example invocation and use.
1967:
1968: If the $includeempty flag is set, it also includes an empty choice ("no domain
1969: selected");
1970:
1971: If the $showdomdesc flag is set, the domain name is followed by the domain description.
1972:
1973: The optional $onchange argument specifies what should occur if the domain selector is changed, e.g., 'this.form.submit()' if the form is to be automatically submitted.
1974:
1975: The optional $incdoms is a reference to an array of domains which will be the only available options.
1976:
1977: =cut
1978:
1979: #-------------------------------------------
1980: sub select_dom_form {
1981: my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms) = @_;
1982: if ($onchange) {
1983: $onchange = ' onchange="'.$onchange.'"';
1984: }
1985: my @domains;
1986: if (ref($incdoms) eq 'ARRAY') {
1987: @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
1988: } else {
1989: @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
1990: }
1991: if ($includeempty) { @domains=('',@domains); }
1992: my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
1993: foreach my $dom (@domains) {
1994: $selectdomain.="<option value=\"$dom\" ".
1995: ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
1996: if ($showdomdesc) {
1997: if ($dom ne '') {
1998: my $domdesc = &Apache::lonnet::domain($dom,'description');
1999: if ($domdesc ne '') {
2000: $selectdomain .= ' ('.$domdesc.')';
2001: }
2002: }
2003: }
2004: $selectdomain .= "</option>\n";
2005: }
2006: $selectdomain.="</select>";
2007: return $selectdomain;
2008: }
2009:
2010: #-------------------------------------------
2011:
2012: =pod
2013:
2014: =item * &home_server_form_item($domain,$name,$defaultflag)
2015:
2016: input: 4 arguments (two required, two optional) -
2017: $domain - domain of new user
2018: $name - name of form element
2019: $default - Value of 'default' causes a default item to be first
2020: option, and selected by default.
2021: $hide - Value of 'hide' causes hiding of the name of the server,
2022: if 1 server found, or default, if 0 found.
2023: output: returns 2 items:
2024: (a) form element which contains either:
2025: (i) <select name="$name">
2026: <option value="$hostid1">$hostid $servers{$hostid}</option>
2027: <option value="$hostid2">$hostid $servers{$hostid}</option>
2028: </select>
2029: form item if there are multiple library servers in $domain, or
2030: (ii) an <input type="hidden" name="$name" value="$hostid" /> form item
2031: if there is only one library server in $domain.
2032:
2033: (b) number of library servers found.
2034:
2035: See loncreateuser.pm for example of use.
2036:
2037: =cut
2038:
2039: #-------------------------------------------
2040: sub home_server_form_item {
2041: my ($domain,$name,$default,$hide) = @_;
2042: my %servers = &Apache::lonnet::get_servers($domain,'library');
2043: my $result;
2044: my $numlib = keys(%servers);
2045: if ($numlib > 1) {
2046: $result .= '<select name="'.$name.'" />'."\n";
2047: if ($default) {
2048: $result .= '<option value="default" selected="selected">'.&mt('default').
2049: '</option>'."\n";
2050: }
2051: foreach my $hostid (sort(keys(%servers))) {
2052: $result.= '<option value="'.$hostid.'">'.
2053: $hostid.' '.$servers{$hostid}."</option>\n";
2054: }
2055: $result .= '</select>'."\n";
2056: } elsif ($numlib == 1) {
2057: my $hostid;
2058: foreach my $item (keys(%servers)) {
2059: $hostid = $item;
2060: }
2061: $result .= '<input type="hidden" name="'.$name.'" value="'.
2062: $hostid.'" />';
2063: if (!$hide) {
2064: $result .= $hostid.' '.$servers{$hostid};
2065: }
2066: $result .= "\n";
2067: } elsif ($default) {
2068: $result .= '<input type="hidden" name="'.$name.
2069: '" value="default" />';
2070: if (!$hide) {
2071: $result .= &mt('default');
2072: }
2073: $result .= "\n";
2074: }
2075: return ($result,$numlib);
2076: }
2077:
2078: =pod
2079:
2080: =back
2081:
2082: =cut
2083:
2084: ###############################################################
2085: ## Decoding User Agent ##
2086: ###############################################################
2087:
2088: =pod
2089:
2090: =head1 Decoding the User Agent
2091:
2092: =over 4
2093:
2094: =item * &decode_user_agent()
2095:
2096: Inputs: $r
2097:
2098: Outputs:
2099:
2100: =over 4
2101:
2102: =item * $httpbrowser
2103:
2104: =item * $clientbrowser
2105:
2106: =item * $clientversion
2107:
2108: =item * $clientmathml
2109:
2110: =item * $clientunicode
2111:
2112: =item * $clientos
2113:
2114: =back
2115:
2116: =back
2117:
2118: =cut
2119:
2120: ###############################################################
2121: ###############################################################
2122: sub decode_user_agent {
2123: my ($r)=@_;
2124: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
2125: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
2126: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
2127: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
2128: my $clientbrowser='unknown';
2129: my $clientversion='0';
2130: my $clientmathml='';
2131: my $clientunicode='0';
2132: for (my $i=0;$i<=$#browsertype;$i++) {
2133: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
2134: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
2135: $clientbrowser=$bname;
2136: $httpbrowser=~/$vreg/i;
2137: $clientversion=$1;
2138: $clientmathml=($clientversion>=$minv);
2139: $clientunicode=($clientversion>=$univ);
2140: }
2141: }
2142: my $clientos='unknown';
2143: if (($httpbrowser=~/linux/i) ||
2144: ($httpbrowser=~/unix/i) ||
2145: ($httpbrowser=~/ux/i) ||
2146: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
2147: if (($httpbrowser=~/vax/i) ||
2148: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
2149: if ($httpbrowser=~/next/i) { $clientos='next'; }
2150: if (($httpbrowser=~/mac/i) ||
2151: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
2152: if ($httpbrowser=~/win/i) { $clientos='win'; }
2153: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
2154: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
2155: $clientunicode,$clientos,);
2156: }
2157:
2158: ###############################################################
2159: ## Authentication changing form generation subroutines ##
2160: ###############################################################
2161: ##
2162: ## All of the authform_xxxxxxx subroutines take their inputs in a
2163: ## hash, and have reasonable default values.
2164: ##
2165: ## formname = the name given in the <form> tag.
2166: #-------------------------------------------
2167:
2168: =pod
2169:
2170: =head1 Authentication Routines
2171:
2172: =over 4
2173:
2174: =item * &authform_xxxxxx()
2175:
2176: The authform_xxxxxx subroutines provide javascript and html forms which
2177: handle some of the conveniences required for authentication forms.
2178: This is not an optimal method, but it works.
2179:
2180: =over 4
2181:
2182: =item * authform_header
2183:
2184: =item * authform_authorwarning
2185:
2186: =item * authform_nochange
2187:
2188: =item * authform_kerberos
2189:
2190: =item * authform_internal
2191:
2192: =item * authform_filesystem
2193:
2194: =back
2195:
2196: See loncreateuser.pm for invocation and use examples.
2197:
2198: =cut
2199:
2200: #-------------------------------------------
2201: sub authform_header{
2202: my %in = (
2203: formname => 'cu',
2204: kerb_def_dom => '',
2205: @_,
2206: );
2207: $in{'formname'} = 'document.' . $in{'formname'};
2208: my $result='';
2209:
2210: #---------------------------------------------- Code for upper case translation
2211: my $Javascript_toUpperCase;
2212: unless ($in{kerb_def_dom}) {
2213: $Javascript_toUpperCase =<<"END";
2214: switch (choice) {
2215: case 'krb': currentform.elements[choicearg].value =
2216: currentform.elements[choicearg].value.toUpperCase();
2217: break;
2218: default:
2219: }
2220: END
2221: } else {
2222: $Javascript_toUpperCase = "";
2223: }
2224:
2225: my $radioval = "'nochange'";
2226: if (defined($in{'curr_authtype'})) {
2227: if ($in{'curr_authtype'} ne '') {
2228: $radioval = "'".$in{'curr_authtype'}."arg'";
2229: }
2230: }
2231: my $argfield = 'null';
2232: if (defined($in{'mode'})) {
2233: if ($in{'mode'} eq 'modifycourse') {
2234: if (defined($in{'curr_autharg'})) {
2235: if ($in{'curr_autharg'} ne '') {
2236: $argfield = "'$in{'curr_autharg'}'";
2237: }
2238: }
2239: }
2240: }
2241:
2242: $result.=<<"END";
2243: var current = new Object();
2244: current.radiovalue = $radioval;
2245: current.argfield = $argfield;
2246:
2247: function changed_radio(choice,currentform) {
2248: var choicearg = choice + 'arg';
2249: // If a radio button in changed, we need to change the argfield
2250: if (current.radiovalue != choice) {
2251: current.radiovalue = choice;
2252: if (current.argfield != null) {
2253: currentform.elements[current.argfield].value = '';
2254: }
2255: if (choice == 'nochange') {
2256: current.argfield = null;
2257: } else {
2258: current.argfield = choicearg;
2259: switch(choice) {
2260: case 'krb':
2261: currentform.elements[current.argfield].value =
2262: "$in{'kerb_def_dom'}";
2263: break;
2264: default:
2265: break;
2266: }
2267: }
2268: }
2269: return;
2270: }
2271:
2272: function changed_text(choice,currentform) {
2273: var choicearg = choice + 'arg';
2274: if (currentform.elements[choicearg].value !='') {
2275: $Javascript_toUpperCase
2276: // clear old field
2277: if ((current.argfield != choicearg) && (current.argfield != null)) {
2278: currentform.elements[current.argfield].value = '';
2279: }
2280: current.argfield = choicearg;
2281: }
2282: set_auth_radio_buttons(choice,currentform);
2283: return;
2284: }
2285:
2286: function set_auth_radio_buttons(newvalue,currentform) {
2287: var i=0;
2288: while (i < currentform.login.length) {
2289: if (currentform.login[i].value == newvalue) { break; }
2290: i++;
2291: }
2292: if (i == currentform.login.length) {
2293: return;
2294: }
2295: current.radiovalue = newvalue;
2296: currentform.login[i].checked = true;
2297: return;
2298: }
2299: END
2300: return $result;
2301: }
2302:
2303: sub authform_authorwarning{
2304: my $result='';
2305: $result='<i>'.
2306: &mt('As a general rule, only authors or co-authors should be '.
2307: 'filesystem authenticated '.
2308: '(which allows access to the server filesystem).')."</i>\n";
2309: return $result;
2310: }
2311:
2312: sub authform_nochange{
2313: my %in = (
2314: formname => 'document.cu',
2315: kerb_def_dom => 'MSU.EDU',
2316: @_,
2317: );
2318: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2319: my $result;
2320: if (keys(%can_assign) == 0) {
2321: $result = &mt('Under you current role you are not permitted to change login settings for this user');
2322: } else {
2323: $result = '<label>'.&mt('[_1] Do not change login data',
2324: '<input type="radio" name="login" value="nochange" '.
2325: 'checked="checked" onclick="'.
2326: "javascript:changed_radio('nochange',$in{'formname'});".'" />').
2327: '</label>';
2328: }
2329: return $result;
2330: }
2331:
2332: sub authform_kerberos {
2333: my %in = (
2334: formname => 'document.cu',
2335: kerb_def_dom => 'MSU.EDU',
2336: kerb_def_auth => 'krb4',
2337: @_,
2338: );
2339: my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
2340: $autharg,$jscall);
2341: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2342: if ($in{'kerb_def_auth'} eq 'krb5') {
2343: $check5 = ' checked="checked"';
2344: } else {
2345: $check4 = ' checked="checked"';
2346: }
2347: $krbarg = $in{'kerb_def_dom'};
2348: if (defined($in{'curr_authtype'})) {
2349: if ($in{'curr_authtype'} eq 'krb') {
2350: $krbcheck = ' checked="checked"';
2351: if (defined($in{'mode'})) {
2352: if ($in{'mode'} eq 'modifyuser') {
2353: $krbcheck = '';
2354: }
2355: }
2356: if (defined($in{'curr_kerb_ver'})) {
2357: if ($in{'curr_krb_ver'} eq '5') {
2358: $check5 = ' checked="checked"';
2359: $check4 = '';
2360: } else {
2361: $check4 = ' checked="checked"';
2362: $check5 = '';
2363: }
2364: }
2365: if (defined($in{'curr_autharg'})) {
2366: $krbarg = $in{'curr_autharg'};
2367: }
2368: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2369: if (defined($in{'curr_autharg'})) {
2370: $result =
2371: &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
2372: $in{'curr_autharg'},$krbver);
2373: } else {
2374: $result =
2375: &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
2376: }
2377: return $result;
2378: }
2379: }
2380: } else {
2381: if ($authnum == 1) {
2382: $authtype = '<input type="hidden" name="login" value="krb" />';
2383: }
2384: }
2385: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2386: return;
2387: } elsif ($authtype eq '') {
2388: if (defined($in{'mode'})) {
2389: if ($in{'mode'} eq 'modifycourse') {
2390: if ($authnum == 1) {
2391: $authtype = '<input type="hidden" name="login" value="krb" />';
2392: }
2393: }
2394: }
2395: }
2396: $jscall = "javascript:changed_radio('krb',$in{'formname'});";
2397: if ($authtype eq '') {
2398: $authtype = '<input type="radio" name="login" value="krb" '.
2399: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
2400: $krbcheck.' />';
2401: }
2402: if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
2403: ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
2404: $in{'curr_authtype'} eq 'krb5') ||
2405: (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
2406: $in{'curr_authtype'} eq 'krb4')) {
2407: $result .= &mt
2408: ('[_1] Kerberos authenticated with domain [_2] '.
2409: '[_3] Version 4 [_4] Version 5 [_5]',
2410: '<label>'.$authtype,
2411: '</label><input type="text" size="10" name="krbarg" '.
2412: 'value="'.$krbarg.'" '.
2413: 'onchange="'.$jscall.'" />',
2414: '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
2415: '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
2416: '</label>');
2417: } elsif ($can_assign{'krb4'}) {
2418: $result .= &mt
2419: ('[_1] Kerberos authenticated with domain [_2] '.
2420: '[_3] Version 4 [_4]',
2421: '<label>'.$authtype,
2422: '</label><input type="text" size="10" name="krbarg" '.
2423: 'value="'.$krbarg.'" '.
2424: 'onchange="'.$jscall.'" />',
2425: '<label><input type="hidden" name="krbver" value="4" />',
2426: '</label>');
2427: } elsif ($can_assign{'krb5'}) {
2428: $result .= &mt
2429: ('[_1] Kerberos authenticated with domain [_2] '.
2430: '[_3] Version 5 [_4]',
2431: '<label>'.$authtype,
2432: '</label><input type="text" size="10" name="krbarg" '.
2433: 'value="'.$krbarg.'" '.
2434: 'onchange="'.$jscall.'" />',
2435: '<label><input type="hidden" name="krbver" value="5" />',
2436: '</label>');
2437: }
2438: return $result;
2439: }
2440:
2441: sub authform_internal{
2442: my %in = (
2443: formname => 'document.cu',
2444: kerb_def_dom => 'MSU.EDU',
2445: @_,
2446: );
2447: my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
2448: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2449: if (defined($in{'curr_authtype'})) {
2450: if ($in{'curr_authtype'} eq 'int') {
2451: if ($can_assign{'int'}) {
2452: $intcheck = 'checked="checked" ';
2453: if (defined($in{'mode'})) {
2454: if ($in{'mode'} eq 'modifyuser') {
2455: $intcheck = '';
2456: }
2457: }
2458: if (defined($in{'curr_autharg'})) {
2459: $intarg = $in{'curr_autharg'};
2460: }
2461: } else {
2462: $result = &mt('Currently internally authenticated.');
2463: return $result;
2464: }
2465: }
2466: } else {
2467: if ($authnum == 1) {
2468: $authtype = '<input type="hidden" name="login" value="int" />';
2469: }
2470: }
2471: if (!$can_assign{'int'}) {
2472: return;
2473: } elsif ($authtype eq '') {
2474: if (defined($in{'mode'})) {
2475: if ($in{'mode'} eq 'modifycourse') {
2476: if ($authnum == 1) {
2477: $authtype = '<input type="hidden" name="login" value="int" />';
2478: }
2479: }
2480: }
2481: }
2482: $jscall = "javascript:changed_radio('int',$in{'formname'});";
2483: if ($authtype eq '') {
2484: $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
2485: ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
2486: }
2487: $autharg = '<input type="password" size="10" name="intarg" value="'.
2488: $intarg.'" onchange="'.$jscall.'" />';
2489: $result = &mt
2490: ('[_1] Internally authenticated (with initial password [_2])',
2491: '<label>'.$authtype,'</label>'.$autharg);
2492: $result.="<label><input type=\"checkbox\" name=\"visible\" onclick='if (this.checked) { this.form.intarg.type=\"text\" } else { this.form.intarg.type=\"password\" }' />".&mt('Visible input').'</label>';
2493: return $result;
2494: }
2495:
2496: sub authform_local{
2497: my %in = (
2498: formname => 'document.cu',
2499: kerb_def_dom => 'MSU.EDU',
2500: @_,
2501: );
2502: my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
2503: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2504: if (defined($in{'curr_authtype'})) {
2505: if ($in{'curr_authtype'} eq 'loc') {
2506: if ($can_assign{'loc'}) {
2507: $loccheck = 'checked="checked" ';
2508: if (defined($in{'mode'})) {
2509: if ($in{'mode'} eq 'modifyuser') {
2510: $loccheck = '';
2511: }
2512: }
2513: if (defined($in{'curr_autharg'})) {
2514: $locarg = $in{'curr_autharg'};
2515: }
2516: } else {
2517: $result = &mt('Currently using local (institutional) authentication.');
2518: return $result;
2519: }
2520: }
2521: } else {
2522: if ($authnum == 1) {
2523: $authtype = '<input type="hidden" name="login" value="loc" />';
2524: }
2525: }
2526: if (!$can_assign{'loc'}) {
2527: return;
2528: } elsif ($authtype eq '') {
2529: if (defined($in{'mode'})) {
2530: if ($in{'mode'} eq 'modifycourse') {
2531: if ($authnum == 1) {
2532: $authtype = '<input type="hidden" name="login" value="loc" />';
2533: }
2534: }
2535: }
2536: }
2537: $jscall = "javascript:changed_radio('loc',$in{'formname'});";
2538: if ($authtype eq '') {
2539: $authtype = '<input type="radio" name="login" value="loc" '.
2540: $loccheck.' onchange="'.$jscall.'" onclick="'.
2541: $jscall.'" />';
2542: }
2543: $autharg = '<input type="text" size="10" name="locarg" value="'.
2544: $locarg.'" onchange="'.$jscall.'" />';
2545: $result = &mt('[_1] Local Authentication with argument [_2]',
2546: '<label>'.$authtype,'</label>'.$autharg);
2547: return $result;
2548: }
2549:
2550: sub authform_filesystem{
2551: my %in = (
2552: formname => 'document.cu',
2553: kerb_def_dom => 'MSU.EDU',
2554: @_,
2555: );
2556: my ($fsyscheck,$result,$authtype,$autharg,$jscall);
2557: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2558: if (defined($in{'curr_authtype'})) {
2559: if ($in{'curr_authtype'} eq 'fsys') {
2560: if ($can_assign{'fsys'}) {
2561: $fsyscheck = 'checked="checked" ';
2562: if (defined($in{'mode'})) {
2563: if ($in{'mode'} eq 'modifyuser') {
2564: $fsyscheck = '';
2565: }
2566: }
2567: } else {
2568: $result = &mt('Currently Filesystem Authenticated.');
2569: return $result;
2570: }
2571: }
2572: } else {
2573: if ($authnum == 1) {
2574: $authtype = '<input type="hidden" name="login" value="fsys" />';
2575: }
2576: }
2577: if (!$can_assign{'fsys'}) {
2578: return;
2579: } elsif ($authtype eq '') {
2580: if (defined($in{'mode'})) {
2581: if ($in{'mode'} eq 'modifycourse') {
2582: if ($authnum == 1) {
2583: $authtype = '<input type="hidden" name="login" value="fsys" />';
2584: }
2585: }
2586: }
2587: }
2588: $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
2589: if ($authtype eq '') {
2590: $authtype = '<input type="radio" name="login" value="fsys" '.
2591: $fsyscheck.' onchange="'.$jscall.'" onclick="'.
2592: $jscall.'" />';
2593: }
2594: $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
2595: ' onchange="'.$jscall.'" />';
2596: $result = &mt
2597: ('[_1] Filesystem Authenticated (with initial password [_2])',
2598: '<label><input type="radio" name="login" value="fsys" '.
2599: $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
2600: '</label><input type="password" size="10" name="fsysarg" value="" '.
2601: 'onchange="'.$jscall.'" />');
2602: return $result;
2603: }
2604:
2605: sub get_assignable_auth {
2606: my ($dom) = @_;
2607: if ($dom eq '') {
2608: $dom = $env{'request.role.domain'};
2609: }
2610: my %can_assign = (
2611: krb4 => 1,
2612: krb5 => 1,
2613: int => 1,
2614: loc => 1,
2615: );
2616: my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
2617: if (ref($domconfig{'usercreation'}) eq 'HASH') {
2618: if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
2619: my $authhash = $domconfig{'usercreation'}{'authtypes'};
2620: my $context;
2621: if ($env{'request.role'} =~ /^au/) {
2622: $context = 'author';
2623: } elsif ($env{'request.role'} =~ /^dc/) {
2624: $context = 'domain';
2625: } elsif ($env{'request.course.id'}) {
2626: $context = 'course';
2627: }
2628: if ($context) {
2629: if (ref($authhash->{$context}) eq 'HASH') {
2630: %can_assign = %{$authhash->{$context}};
2631: }
2632: }
2633: }
2634: }
2635: my $authnum = 0;
2636: foreach my $key (keys(%can_assign)) {
2637: if ($can_assign{$key}) {
2638: $authnum ++;
2639: }
2640: }
2641: if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
2642: $authnum --;
2643: }
2644: return ($authnum,%can_assign);
2645: }
2646:
2647: ###############################################################
2648: ## Get Kerberos Defaults for Domain ##
2649: ###############################################################
2650: ##
2651: ## Returns default kerberos version and an associated argument
2652: ## as listed in file domain.tab. If not listed, provides
2653: ## appropriate default domain and kerberos version.
2654: ##
2655: #-------------------------------------------
2656:
2657: =pod
2658:
2659: =item * &get_kerberos_defaults()
2660:
2661: get_kerberos_defaults($target_domain) returns the default kerberos
2662: version and domain. If not found, it defaults to version 4 and the
2663: domain of the server.
2664:
2665: =over 4
2666:
2667: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
2668:
2669: =back
2670:
2671: =back
2672:
2673: =cut
2674:
2675: #-------------------------------------------
2676: sub get_kerberos_defaults {
2677: my $domain=shift;
2678: my ($krbdef,$krbdefdom);
2679: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
2680: if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
2681: $krbdef = $domdefaults{'auth_def'};
2682: $krbdefdom = $domdefaults{'auth_arg_def'};
2683: } else {
2684: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
2685: my $krbdefdom=$1;
2686: $krbdefdom=~tr/a-z/A-Z/;
2687: $krbdef = "krb4";
2688: }
2689: return ($krbdef,$krbdefdom);
2690: }
2691:
2692:
2693: ###############################################################
2694: ## Thesaurus Functions ##
2695: ###############################################################
2696:
2697: =pod
2698:
2699: =head1 Thesaurus Functions
2700:
2701: =over 4
2702:
2703: =item * &initialize_keywords()
2704:
2705: Initializes the package variable %Keywords if it is empty. Uses the
2706: package variable $thesaurus_db_file.
2707:
2708: =cut
2709:
2710: ###################################################
2711:
2712: sub initialize_keywords {
2713: return 1 if (scalar keys(%Keywords));
2714: # If we are here, %Keywords is empty, so fill it up
2715: # Make sure the file we need exists...
2716: if (! -e $thesaurus_db_file) {
2717: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
2718: " failed because it does not exist");
2719: return 0;
2720: }
2721: # Set up the hash as a database
2722: my %thesaurus_db;
2723: if (! tie(%thesaurus_db,'GDBM_File',
2724: $thesaurus_db_file,&GDBM_READER(),0640)){
2725: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
2726: $thesaurus_db_file);
2727: return 0;
2728: }
2729: # Get the average number of appearances of a word.
2730: my $avecount = $thesaurus_db{'average.count'};
2731: # Put keywords (those that appear > average) into %Keywords
2732: while (my ($word,$data)=each (%thesaurus_db)) {
2733: my ($count,undef) = split /:/,$data;
2734: $Keywords{$word}++ if ($count > $avecount);
2735: }
2736: untie %thesaurus_db;
2737: # Remove special values from %Keywords.
2738: foreach my $value ('total.count','average.count') {
2739: delete($Keywords{$value}) if (exists($Keywords{$value}));
2740: }
2741: return 1;
2742: }
2743:
2744: ###################################################
2745:
2746: =pod
2747:
2748: =item * &keyword($word)
2749:
2750: Returns true if $word is a keyword. A keyword is a word that appears more
2751: than the average number of times in the thesaurus database. Calls
2752: &initialize_keywords
2753:
2754: =cut
2755:
2756: ###################################################
2757:
2758: sub keyword {
2759: return if (!&initialize_keywords());
2760: my $word=lc(shift());
2761: $word=~s/\W//g;
2762: return exists($Keywords{$word});
2763: }
2764:
2765: ###############################################################
2766:
2767: =pod
2768:
2769: =item * &get_related_words()
2770:
2771: Look up a word in the thesaurus. Takes a scalar argument and returns
2772: an array of words. If the keyword is not in the thesaurus, an empty array
2773: will be returned. The order of the words returned is determined by the
2774: database which holds them.
2775:
2776: Uses global $thesaurus_db_file.
2777:
2778: =cut
2779:
2780: ###############################################################
2781: sub get_related_words {
2782: my $keyword = shift;
2783: my %thesaurus_db;
2784: if (! -e $thesaurus_db_file) {
2785: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
2786: "failed because the file does not exist");
2787: return ();
2788: }
2789: if (! tie(%thesaurus_db,'GDBM_File',
2790: $thesaurus_db_file,&GDBM_READER(),0640)){
2791: return ();
2792: }
2793: my @Words=();
2794: my $count=0;
2795: if (exists($thesaurus_db{$keyword})) {
2796: # The first element is the number of times
2797: # the word appears. We do not need it now.
2798: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
2799: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
2800: my $threshold=$mostfrequentcount/10;
2801: foreach my $possibleword (@RelatedWords) {
2802: my ($word,$wordcount)=split(/\,/,$possibleword);
2803: if ($wordcount>$threshold) {
2804: push(@Words,$word);
2805: $count++;
2806: if ($count>10) { last; }
2807: }
2808: }
2809: }
2810: untie %thesaurus_db;
2811: return @Words;
2812: }
2813:
2814: =pod
2815:
2816: =back
2817:
2818: =cut
2819:
2820: # -------------------------------------------------------------- Plaintext name
2821: =pod
2822:
2823: =head1 User Name Functions
2824:
2825: =over 4
2826:
2827: =item * &plainname($uname,$udom,$first)
2828:
2829: Takes a users logon name and returns it as a string in
2830: "first middle last generation" form
2831: if $first is set to 'lastname' then it returns it as
2832: 'lastname generation, firstname middlename' if their is a lastname
2833:
2834: =cut
2835:
2836:
2837: ###############################################################
2838: sub plainname {
2839: my ($uname,$udom,$first)=@_;
2840: return if (!defined($uname) || !defined($udom));
2841: my %names=&getnames($uname,$udom);
2842: my $name=&Apache::lonnet::format_name($names{'firstname'},
2843: $names{'middlename'},
2844: $names{'lastname'},
2845: $names{'generation'},$first);
2846: $name=~s/^\s+//;
2847: $name=~s/\s+$//;
2848: $name=~s/\s+/ /g;
2849: if ($name !~ /\S/) { $name=$uname.':'.$udom; }
2850: return $name;
2851: }
2852:
2853: # -------------------------------------------------------------------- Nickname
2854: =pod
2855:
2856: =item * &nickname($uname,$udom)
2857:
2858: Gets a users name and returns it as a string as
2859:
2860: ""nickname""
2861:
2862: if the user has a nickname or
2863:
2864: "first middle last generation"
2865:
2866: if the user does not
2867:
2868: =cut
2869:
2870: sub nickname {
2871: my ($uname,$udom)=@_;
2872: return if (!defined($uname) || !defined($udom));
2873: my %names=&getnames($uname,$udom);
2874: my $name=$names{'nickname'};
2875: if ($name) {
2876: $name='"'.$name.'"';
2877: } else {
2878: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
2879: $names{'lastname'}.' '.$names{'generation'};
2880: $name=~s/\s+$//;
2881: $name=~s/\s+/ /g;
2882: }
2883: return $name;
2884: }
2885:
2886: sub getnames {
2887: my ($uname,$udom)=@_;
2888: return if (!defined($uname) || !defined($udom));
2889: if ($udom eq 'public' && $uname eq 'public') {
2890: return ('lastname' => &mt('Public'));
2891: }
2892: my $id=$uname.':'.$udom;
2893: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
2894: if ($cached) {
2895: return %{$names};
2896: } else {
2897: my %loadnames=&Apache::lonnet::get('environment',
2898: ['firstname','middlename','lastname','generation','nickname'],
2899: $udom,$uname);
2900: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
2901: return %loadnames;
2902: }
2903: }
2904:
2905: # -------------------------------------------------------------------- getemails
2906:
2907: =pod
2908:
2909: =item * &getemails($uname,$udom)
2910:
2911: Gets a user's email information and returns it as a hash with keys:
2912: notification, critnotification, permanentemail
2913:
2914: For notification and critnotification, values are comma-separated lists
2915: of e-mail addresses; for permanentemail, value is a single e-mail address.
2916:
2917:
2918: =cut
2919:
2920:
2921: sub getemails {
2922: my ($uname,$udom)=@_;
2923: if ($udom eq 'public' && $uname eq 'public') {
2924: return;
2925: }
2926: if (!$udom) { $udom=$env{'user.domain'}; }
2927: if (!$uname) { $uname=$env{'user.name'}; }
2928: my $id=$uname.':'.$udom;
2929: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
2930: if ($cached) {
2931: return %{$names};
2932: } else {
2933: my %loadnames=&Apache::lonnet::get('environment',
2934: ['notification','critnotification',
2935: 'permanentemail'],
2936: $udom,$uname);
2937: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
2938: return %loadnames;
2939: }
2940: }
2941:
2942: sub flush_email_cache {
2943: my ($uname,$udom)=@_;
2944: if (!$udom) { $udom =$env{'user.domain'}; }
2945: if (!$uname) { $uname=$env{'user.name'}; }
2946: return if ($udom eq 'public' && $uname eq 'public');
2947: my $id=$uname.':'.$udom;
2948: &Apache::lonnet::devalidate_cache_new('emailscache',$id);
2949: }
2950:
2951: # -------------------------------------------------------------------- getlangs
2952:
2953: =pod
2954:
2955: =item * &getlangs($uname,$udom)
2956:
2957: Gets a user's language preference and returns it as a hash with key:
2958: language.
2959:
2960: =cut
2961:
2962:
2963: sub getlangs {
2964: my ($uname,$udom) = @_;
2965: if (!$udom) { $udom =$env{'user.domain'}; }
2966: if (!$uname) { $uname=$env{'user.name'}; }
2967: my $id=$uname.':'.$udom;
2968: my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
2969: if ($cached) {
2970: return %{$langs};
2971: } else {
2972: my %loadlangs=&Apache::lonnet::get('environment',['languages'],
2973: $udom,$uname);
2974: &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
2975: return %loadlangs;
2976: }
2977: }
2978:
2979: sub flush_langs_cache {
2980: my ($uname,$udom)=@_;
2981: if (!$udom) { $udom =$env{'user.domain'}; }
2982: if (!$uname) { $uname=$env{'user.name'}; }
2983: return if ($udom eq 'public' && $uname eq 'public');
2984: my $id=$uname.':'.$udom;
2985: &Apache::lonnet::devalidate_cache_new('userlangs',$id);
2986: }
2987:
2988: # ------------------------------------------------------------------ Screenname
2989:
2990: =pod
2991:
2992: =item * &screenname($uname,$udom)
2993:
2994: Gets a users screenname and returns it as a string
2995:
2996: =cut
2997:
2998: sub screenname {
2999: my ($uname,$udom)=@_;
3000: if ($uname eq $env{'user.name'} &&
3001: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
3002: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
3003: return $names{'screenname'};
3004: }
3005:
3006:
3007: # ------------------------------------------------------------- Confirm Wrapper
3008: =pod
3009:
3010: =item confirmwrapper
3011:
3012: Wrap messages about completion of operation in box
3013:
3014: =cut
3015:
3016: sub confirmwrapper {
3017: my ($message)=@_;
3018: if ($message) {
3019: return "\n".'<div class="LC_confirm_box">'."\n"
3020: .$message."\n"
3021: .'</div>'."\n";
3022: } else {
3023: return $message;
3024: }
3025: }
3026:
3027: # ------------------------------------------------------------- Message Wrapper
3028:
3029: sub messagewrapper {
3030: my ($link,$username,$domain,$subject,$text)=@_;
3031: return
3032: '<a href="/adm/email?compose=individual&'.
3033: 'recname='.$username.'&recdom='.$domain.
3034: '&subject='.&escape($subject).'&text='.&escape($text).'" '.
3035: 'title="'.&mt('Send message').'">'.$link.'</a>';
3036: }
3037:
3038: # --------------------------------------------------------------- Notes Wrapper
3039:
3040: sub noteswrapper {
3041: my ($link,$un,$do)=@_;
3042: return
3043: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
3044: }
3045:
3046: # ------------------------------------------------------------- Aboutme Wrapper
3047:
3048: sub aboutmewrapper {
3049: my ($link,$username,$domain,$target)=@_;
3050: if (!defined($username) && !defined($domain)) {
3051: return;
3052: }
3053: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme?forcestudent=1"'.
3054: ($target?' target="$target"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
3055: }
3056:
3057: # ------------------------------------------------------------ Syllabus Wrapper
3058:
3059: sub syllabuswrapper {
3060: my ($linktext,$coursedir,$domain)=@_;
3061: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
3062: }
3063:
3064: # -----------------------------------------------------------------------------
3065:
3066: sub track_student_link {
3067: my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
3068: my $link ="/adm/trackstudent?";
3069: my $title = 'View recent activity';
3070: if (defined($sname) && $sname !~ /^\s*$/ &&
3071: defined($sdom) && $sdom !~ /^\s*$/) {
3072: $link .= "selected_student=$sname:$sdom";
3073: $title .= ' of this student';
3074: }
3075: if (defined($target) && $target !~ /^\s*$/) {
3076: $target = qq{target="$target"};
3077: } else {
3078: $target = '';
3079: }
3080: if ($start) { $link.='&start='.$start; }
3081: if ($only_body) { $link .= '&only_body=1'; }
3082: $title = &mt($title);
3083: $linktext = &mt($linktext);
3084: return qq{<a href="$link" title="$title" $target>$linktext</a>}.
3085: &help_open_topic('View_recent_activity');
3086: }
3087:
3088: sub slot_reservations_link {
3089: my ($linktext,$sname,$sdom,$target) = @_;
3090: my $link ="/adm/slotrequest?command=showresv&origin=aboutme";
3091: my $title = 'View slot reservation history';
3092: if (defined($sname) && $sname !~ /^\s*$/ &&
3093: defined($sdom) && $sdom !~ /^\s*$/) {
3094: $link .= "&uname=$sname&udom=$sdom";
3095: $title .= ' of this student';
3096: }
3097: if (defined($target) && $target !~ /^\s*$/) {
3098: $target = qq{target="$target"};
3099: } else {
3100: $target = '';
3101: }
3102: $title = &mt($title);
3103: $linktext = &mt($linktext);
3104: return qq{<a href="$link" title="$title" $target>$linktext</a>};
3105: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
3106:
3107: }
3108:
3109: # ===================================================== Display a student photo
3110:
3111:
3112: sub student_image_tag {
3113: my ($domain,$user)=@_;
3114: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
3115: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
3116: return '<img src="'.$imgsrc.'" align="right" />';
3117: } else {
3118: return '';
3119: }
3120: }
3121:
3122: =pod
3123:
3124: =back
3125:
3126: =head1 Access .tab File Data
3127:
3128: =over 4
3129:
3130: =item * &languageids()
3131:
3132: returns list of all language ids
3133:
3134: =cut
3135:
3136: sub languageids {
3137: return sort(keys(%language));
3138: }
3139:
3140: =pod
3141:
3142: =item * &languagedescription()
3143:
3144: returns description of a specified language id
3145:
3146: =cut
3147:
3148: sub languagedescription {
3149: my $code=shift;
3150: return ($supported_language{$code}?'* ':'').
3151: $language{$code}.
3152: ($supported_language{$code}?' ('.&mt('interface available').')':'');
3153: }
3154:
3155: sub plainlanguagedescription {
3156: my $code=shift;
3157: return $language{$code};
3158: }
3159:
3160: sub supportedlanguagecode {
3161: my $code=shift;
3162: return $supported_language{$code};
3163: }
3164:
3165: =pod
3166:
3167: =item * ©rightids()
3168:
3169: returns list of all copyrights
3170:
3171: =cut
3172:
3173: sub copyrightids {
3174: return sort(keys(%cprtag));
3175: }
3176:
3177: =pod
3178:
3179: =item * ©rightdescription()
3180:
3181: returns description of a specified copyright id
3182:
3183: =cut
3184:
3185: sub copyrightdescription {
3186: return &mt($cprtag{shift(@_)});
3187: }
3188:
3189: =pod
3190:
3191: =item * &source_copyrightids()
3192:
3193: returns list of all source copyrights
3194:
3195: =cut
3196:
3197: sub source_copyrightids {
3198: return sort(keys(%scprtag));
3199: }
3200:
3201: =pod
3202:
3203: =item * &source_copyrightdescription()
3204:
3205: returns description of a specified source copyright id
3206:
3207: =cut
3208:
3209: sub source_copyrightdescription {
3210: return &mt($scprtag{shift(@_)});
3211: }
3212:
3213: =pod
3214:
3215: =item * &filecategories()
3216:
3217: returns list of all file categories
3218:
3219: =cut
3220:
3221: sub filecategories {
3222: return sort(keys(%category_extensions));
3223: }
3224:
3225: =pod
3226:
3227: =item * &filecategorytypes()
3228:
3229: returns list of file types belonging to a given file
3230: category
3231:
3232: =cut
3233:
3234: sub filecategorytypes {
3235: my ($cat) = @_;
3236: return @{$category_extensions{lc($cat)}};
3237: }
3238:
3239: =pod
3240:
3241: =item * &fileembstyle()
3242:
3243: returns embedding style for a specified file type
3244:
3245: =cut
3246:
3247: sub fileembstyle {
3248: return $fe{lc(shift(@_))};
3249: }
3250:
3251: sub filemimetype {
3252: return $fm{lc(shift(@_))};
3253: }
3254:
3255:
3256: sub filecategoryselect {
3257: my ($name,$value)=@_;
3258: return &select_form($value,$name,
3259: '' => &mt('Any category'),
3260: {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
3261: }
3262:
3263: =pod
3264:
3265: =item * &filedescription()
3266:
3267: returns description for a specified file type
3268:
3269: =cut
3270:
3271: sub filedescription {
3272: my $file_description = $fd{lc(shift())};
3273: $file_description =~ s:([\[\]]):~$1:g;
3274: return &mt($file_description);
3275: }
3276:
3277: =pod
3278:
3279: =item * &filedescriptionex()
3280:
3281: returns description for a specified file type with
3282: extra formatting
3283:
3284: =cut
3285:
3286: sub filedescriptionex {
3287: my $ex=shift;
3288: my $file_description = $fd{lc($ex)};
3289: $file_description =~ s:([\[\]]):~$1:g;
3290: return '.'.$ex.' '.&mt($file_description);
3291: }
3292:
3293: # End of .tab access
3294: =pod
3295:
3296: =back
3297:
3298: =cut
3299:
3300: # ------------------------------------------------------------------ File Types
3301: sub fileextensions {
3302: return sort(keys(%fe));
3303: }
3304:
3305: # ----------------------------------------------------------- Display Languages
3306: # returns a hash with all desired display languages
3307: #
3308:
3309: sub display_languages {
3310: my %languages=();
3311: foreach my $lang (&Apache::lonlocal::preferred_languages()) {
3312: $languages{$lang}=1;
3313: }
3314: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
3315: if ($env{'form.displaylanguage'}) {
3316: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
3317: $languages{$lang}=1;
3318: }
3319: }
3320: return %languages;
3321: }
3322:
3323: sub languages {
3324: my ($possible_langs) = @_;
3325: my @preferred_langs = &Apache::lonlocal::preferred_languages();
3326: if (!ref($possible_langs)) {
3327: if( wantarray ) {
3328: return @preferred_langs;
3329: } else {
3330: return $preferred_langs[0];
3331: }
3332: }
3333: my %possibilities = map { $_ => 1 } (@$possible_langs);
3334: my @preferred_possibilities;
3335: foreach my $preferred_lang (@preferred_langs) {
3336: if (exists($possibilities{$preferred_lang})) {
3337: push(@preferred_possibilities, $preferred_lang);
3338: }
3339: }
3340: if( wantarray ) {
3341: return @preferred_possibilities;
3342: }
3343: return $preferred_possibilities[0];
3344: }
3345:
3346: sub user_lang {
3347: my ($touname,$toudom,$fromcid) = @_;
3348: my @userlangs;
3349: if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
3350: @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
3351: $env{'course.'.$fromcid.'.languages'}));
3352: } else {
3353: my %langhash = &getlangs($touname,$toudom);
3354: if ($langhash{'languages'} ne '') {
3355: @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
3356: } else {
3357: my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
3358: if ($domdefs{'lang_def'} ne '') {
3359: @userlangs = ($domdefs{'lang_def'});
3360: }
3361: }
3362: }
3363: my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
3364: my $user_lh = Apache::localize->get_handle(@languages);
3365: return $user_lh;
3366: }
3367:
3368:
3369: ###############################################################
3370: ## Student Answer Attempts ##
3371: ###############################################################
3372:
3373: =pod
3374:
3375: =head1 Alternate Problem Views
3376:
3377: =over 4
3378:
3379: =item * &get_previous_attempt($symb, $username, $domain, $course,
3380: $getattempt, $regexp, $gradesub)
3381:
3382: Return string with previous attempt on problem. Arguments:
3383:
3384: =over 4
3385:
3386: =item * $symb: Problem, including path
3387:
3388: =item * $username: username of the desired student
3389:
3390: =item * $domain: domain of the desired student
3391:
3392: =item * $course: Course ID
3393:
3394: =item * $getattempt: Leave blank for all attempts, otherwise put
3395: something
3396:
3397: =item * $regexp: if string matches this regexp, the string will be
3398: sent to $gradesub
3399:
3400: =item * $gradesub: routine that processes the string if it matches $regexp
3401:
3402: =back
3403:
3404: The output string is a table containing all desired attempts, if any.
3405:
3406: =cut
3407:
3408: sub get_previous_attempt {
3409: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
3410: my $prevattempts='';
3411: no strict 'refs';
3412: if ($symb) {
3413: my (%returnhash)=
3414: &Apache::lonnet::restore($symb,$course,$domain,$username);
3415: if ($returnhash{'version'}) {
3416: my %lasthash=();
3417: my $version;
3418: for ($version=1;$version<=$returnhash{'version'};$version++) {
3419: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
3420: $lasthash{$key}=$returnhash{$version.':'.$key};
3421: }
3422: }
3423: $prevattempts=&start_data_table().&start_data_table_header_row();
3424: $prevattempts.='<th>'.&mt('History').'</th>';
3425: my (%typeparts,%lasthidden);
3426: my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
3427: foreach my $key (sort(keys(%lasthash))) {
3428: my ($ign,@parts) = split(/\./,$key);
3429: if ($#parts > 0) {
3430: my $data=$parts[-1];
3431: pop(@parts);
3432: if ($data eq 'type') {
3433: unless ($showsurv) {
3434: my $id = join(',',@parts);
3435: $typeparts{$ign.'.'.$id} = $lasthash{$key};
3436: if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
3437: $lasthidden{$ign.'.'.$id} = 1;
3438: }
3439: }
3440: delete($lasthash{$key});
3441: } else {
3442: $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.' </th>';
3443: }
3444: } else {
3445: if ($#parts == 0) {
3446: $prevattempts.='<th>'.$parts[0].'</th>';
3447: } else {
3448: $prevattempts.='<th>'.$ign.'</th>';
3449: }
3450: }
3451: }
3452: $prevattempts.=&end_data_table_header_row();
3453: if ($getattempt eq '') {
3454: for ($version=1;$version<=$returnhash{'version'};$version++) {
3455: my @hidden;
3456: if (%typeparts) {
3457: foreach my $id (keys(%typeparts)) {
3458: if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
3459: push(@hidden,$id);
3460: }
3461: }
3462: }
3463: $prevattempts.=&start_data_table_row().
3464: '<td>'.&mt('Transaction [_1]',$version).'</td>';
3465: if (@hidden) {
3466: foreach my $key (sort(keys(%lasthash))) {
3467: my $hide;
3468: foreach my $id (@hidden) {
3469: if ($key =~ /^\Q$id\E/) {
3470: $hide = 1;
3471: last;
3472: }
3473: }
3474: if ($hide) {
3475: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
3476: if (($data eq 'award') || ($data eq 'awarddetail')) {
3477: my $value = &format_previous_attempt_value($key,
3478: $returnhash{$version.':'.$key});
3479: $prevattempts.='<td>'.$value.' </td>';
3480: } else {
3481: $prevattempts.='<td> </td>';
3482: }
3483: } else {
3484: if ($key =~ /\./) {
3485: my $value = &format_previous_attempt_value($key,
3486: $returnhash{$version.':'.$key});
3487: $prevattempts.='<td>'.$value.' </td>';
3488: } else {
3489: $prevattempts.='<td> </td>';
3490: }
3491: }
3492: }
3493: } else {
3494: foreach my $key (sort(keys(%lasthash))) {
3495: my $value = &format_previous_attempt_value($key,
3496: $returnhash{$version.':'.$key});
3497: $prevattempts.='<td>'.$value.' </td>';
3498: }
3499: }
3500: $prevattempts.=&end_data_table_row();
3501: }
3502: }
3503: my @currhidden = keys(%lasthidden);
3504: $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
3505: foreach my $key (sort(keys(%lasthash))) {
3506: if (%typeparts) {
3507: my $hidden;
3508: foreach my $id (@currhidden) {
3509: if ($key =~ /^\Q$id\E/) {
3510: $hidden = 1;
3511: last;
3512: }
3513: }
3514: if ($hidden) {
3515: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
3516: if (($data eq 'award') || ($data eq 'awarddetail')) {
3517: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3518: if ($key =~/$regexp$/ && (defined &$gradesub)) {
3519: $value = &$gradesub($value);
3520: }
3521: $prevattempts.='<td>'.$value.' </td>';
3522: } else {
3523: $prevattempts.='<td> </td>';
3524: }
3525: } else {
3526: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3527: if ($key =~/$regexp$/ && (defined &$gradesub)) {
3528: $value = &$gradesub($value);
3529: }
3530: $prevattempts.='<td>'.$value.' </td>';
3531: }
3532: } else {
3533: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3534: if ($key =~/$regexp$/ && (defined &$gradesub)) {
3535: $value = &$gradesub($value);
3536: }
3537: $prevattempts.='<td>'.$value.' </td>';
3538: }
3539: }
3540: $prevattempts.= &end_data_table_row().&end_data_table();
3541: } else {
3542: $prevattempts=
3543: &start_data_table().&start_data_table_row().
3544: '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
3545: &end_data_table_row().&end_data_table();
3546: }
3547: } else {
3548: $prevattempts=
3549: &start_data_table().&start_data_table_row().
3550: '<td>'.&mt('No data.').'</td>'.
3551: &end_data_table_row().&end_data_table();
3552: }
3553: }
3554:
3555: sub format_previous_attempt_value {
3556: my ($key,$value) = @_;
3557: if ($key =~ /timestamp/) {
3558: $value = &Apache::lonlocal::locallocaltime($value);
3559: } elsif (ref($value) eq 'ARRAY') {
3560: $value = '('.join(', ', @{ $value }).')';
3561: } else {
3562: $value = &unescape($value);
3563: }
3564: return $value;
3565: }
3566:
3567:
3568: sub relative_to_absolute {
3569: my ($url,$output)=@_;
3570: my $parser=HTML::TokeParser->new(\$output);
3571: my $token;
3572: my $thisdir=$url;
3573: my @rlinks=();
3574: while ($token=$parser->get_token) {
3575: if ($token->[0] eq 'S') {
3576: if ($token->[1] eq 'a') {
3577: if ($token->[2]->{'href'}) {
3578: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
3579: }
3580: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
3581: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
3582: } elsif ($token->[1] eq 'base') {
3583: $thisdir=$token->[2]->{'href'};
3584: }
3585: }
3586: }
3587: $thisdir=~s-/[^/]*$--;
3588: foreach my $link (@rlinks) {
3589: unless (($link=~/^https?\:\/\//i) ||
3590: ($link=~/^\//) ||
3591: ($link=~/^javascript:/i) ||
3592: ($link=~/^mailto:/i) ||
3593: ($link=~/^\#/)) {
3594: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
3595: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
3596: }
3597: }
3598: # -------------------------------------------------- Deal with Applet codebases
3599: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
3600: return $output;
3601: }
3602:
3603: =pod
3604:
3605: =item * &get_student_view()
3606:
3607: show a snapshot of what student was looking at
3608:
3609: =cut
3610:
3611: sub get_student_view {
3612: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
3613: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
3614: my (%form);
3615: my @elements=('symb','courseid','domain','username');
3616: foreach my $element (@elements) {
3617: $form{'grade_'.$element}=eval '$'.$element #'
3618: }
3619: if (defined($moreenv)) {
3620: %form=(%form,%{$moreenv});
3621: }
3622: if (defined($target)) { $form{'grade_target'} = $target; }
3623: $feedurl=&Apache::lonnet::clutter($feedurl);
3624: my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
3625: $userview=~s/\<body[^\>]*\>//gi;
3626: $userview=~s/\<\/body\>//gi;
3627: $userview=~s/\<html\>//gi;
3628: $userview=~s/\<\/html\>//gi;
3629: $userview=~s/\<head\>//gi;
3630: $userview=~s/\<\/head\>//gi;
3631: $userview=~s/action\s*\=/would_be_action\=/gi;
3632: $userview=&relative_to_absolute($feedurl,$userview);
3633: if (wantarray) {
3634: return ($userview,$response);
3635: } else {
3636: return $userview;
3637: }
3638: }
3639:
3640: sub get_student_view_with_retries {
3641: my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
3642:
3643: my $ok = 0; # True if we got a good response.
3644: my $content;
3645: my $response;
3646:
3647: # Try to get the student_view done. within the retries count:
3648:
3649: do {
3650: ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
3651: $ok = $response->is_success;
3652: if (!$ok) {
3653: &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
3654: }
3655: $retries--;
3656: } while (!$ok && ($retries > 0));
3657:
3658: if (!$ok) {
3659: $content = ''; # On error return an empty content.
3660: }
3661: if (wantarray) {
3662: return ($content, $response);
3663: } else {
3664: return $content;
3665: }
3666: }
3667:
3668: =pod
3669:
3670: =item * &get_student_answers()
3671:
3672: show a snapshot of how student was answering problem
3673:
3674: =cut
3675:
3676: sub get_student_answers {
3677: my ($symb,$username,$domain,$courseid,%form) = @_;
3678: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
3679: my (%moreenv);
3680: my @elements=('symb','courseid','domain','username');
3681: foreach my $element (@elements) {
3682: $moreenv{'grade_'.$element}=eval '$'.$element #'
3683: }
3684: $moreenv{'grade_target'}='answer';
3685: %moreenv=(%form,%moreenv);
3686: $feedurl = &Apache::lonnet::clutter($feedurl);
3687: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
3688: return $userview;
3689: }
3690:
3691: =pod
3692:
3693: =item * &submlink()
3694:
3695: Inputs: $text $uname $udom $symb $target
3696:
3697: Returns: A link to grades.pm such as to see the SUBM view of a student
3698:
3699: =cut
3700:
3701: ###############################################
3702: sub submlink {
3703: my ($text,$uname,$udom,$symb,$target)=@_;
3704: if (!($uname && $udom)) {
3705: (my $cursymb, my $courseid,$udom,$uname)=
3706: &Apache::lonnet::whichuser($symb);
3707: if (!$symb) { $symb=$cursymb; }
3708: }
3709: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
3710: $symb=&escape($symb);
3711: if ($target) { $target=" target=\"$target\""; }
3712: return
3713: '<a href="/adm/grades?command=submission'.
3714: '&symb='.$symb.
3715: '&student='.$uname.
3716: '&userdom='.$udom.'"'.
3717: $target.'>'.$text.'</a>';
3718: }
3719: ##############################################
3720:
3721: =pod
3722:
3723: =item * &pgrdlink()
3724:
3725: Inputs: $text $uname $udom $symb $target
3726:
3727: Returns: A link to grades.pm such as to see the PGRD view of a student
3728:
3729: =cut
3730:
3731: ###############################################
3732: sub pgrdlink {
3733: my $link=&submlink(@_);
3734: $link=~s/(&command=submission)/$1&showgrading=yes/;
3735: return $link;
3736: }
3737: ##############################################
3738:
3739: =pod
3740:
3741: =item * &pprmlink()
3742:
3743: Inputs: $text $uname $udom $symb $target
3744:
3745: Returns: A link to parmset.pm such as to see the PPRM view of a
3746: student and a specific resource
3747:
3748: =cut
3749:
3750: ###############################################
3751: sub pprmlink {
3752: my ($text,$uname,$udom,$symb,$target)=@_;
3753: if (!($uname && $udom)) {
3754: (my $cursymb, my $courseid,$udom,$uname)=
3755: &Apache::lonnet::whichuser($symb);
3756: if (!$symb) { $symb=$cursymb; }
3757: }
3758: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
3759: $symb=&escape($symb);
3760: if ($target) { $target="target=\"$target\""; }
3761: return '<a href="/adm/parmset?command=set&'.
3762: 'symb='.$symb.'&uname='.$uname.
3763: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
3764: }
3765: ##############################################
3766:
3767: =pod
3768:
3769: =back
3770:
3771: =cut
3772:
3773: ###############################################
3774:
3775:
3776: sub timehash {
3777: my ($thistime) = @_;
3778: my $timezone = &Apache::lonlocal::gettimezone();
3779: my $dt = DateTime->from_epoch(epoch => $thistime)
3780: ->set_time_zone($timezone);
3781: my $wday = $dt->day_of_week();
3782: if ($wday == 7) { $wday = 0; }
3783: return ( 'second' => $dt->second(),
3784: 'minute' => $dt->minute(),
3785: 'hour' => $dt->hour(),
3786: 'day' => $dt->day_of_month(),
3787: 'month' => $dt->month(),
3788: 'year' => $dt->year(),
3789: 'weekday' => $wday,
3790: 'dayyear' => $dt->day_of_year(),
3791: 'dlsav' => $dt->is_dst() );
3792: }
3793:
3794: sub utc_string {
3795: my ($date)=@_;
3796: return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
3797: }
3798:
3799: sub maketime {
3800: my %th=@_;
3801: my ($epoch_time,$timezone,$dt);
3802: $timezone = &Apache::lonlocal::gettimezone();
3803: eval {
3804: $dt = DateTime->new( year => $th{'year'},
3805: month => $th{'month'},
3806: day => $th{'day'},
3807: hour => $th{'hour'},
3808: minute => $th{'minute'},
3809: second => $th{'second'},
3810: time_zone => $timezone,
3811: );
3812: };
3813: if (!$@) {
3814: $epoch_time = $dt->epoch;
3815: if ($epoch_time) {
3816: return $epoch_time;
3817: }
3818: }
3819: return POSIX::mktime(
3820: ($th{'seconds'},$th{'minutes'},$th{'hours'},
3821: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
3822: }
3823:
3824: #########################################
3825:
3826: sub findallcourses {
3827: my ($roles,$uname,$udom) = @_;
3828: my %roles;
3829: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
3830: my %courses;
3831: my $now=time;
3832: if (!defined($uname)) {
3833: $uname = $env{'user.name'};
3834: }
3835: if (!defined($udom)) {
3836: $udom = $env{'user.domain'};
3837: }
3838: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
3839: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
3840: if (!%roles) {
3841: %roles = (
3842: cc => 1,
3843: co => 1,
3844: in => 1,
3845: ep => 1,
3846: ta => 1,
3847: cr => 1,
3848: st => 1,
3849: );
3850: }
3851: foreach my $entry (keys(%roleshash)) {
3852: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
3853: if ($trole =~ /^cr/) {
3854: next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
3855: } else {
3856: next if (!exists($roles{$trole}));
3857: }
3858: if ($tend) {
3859: next if ($tend < $now);
3860: }
3861: if ($tstart) {
3862: next if ($tstart > $now);
3863: }
3864: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
3865: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
3866: if ($secpart eq '') {
3867: ($cnum,$role) = split(/_/,$cnumpart);
3868: $sec = 'none';
3869: $realsec = '';
3870: } else {
3871: $cnum = $cnumpart;
3872: ($sec,$role) = split(/_/,$secpart);
3873: $realsec = $sec;
3874: }
3875: $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
3876: }
3877: } else {
3878: foreach my $key (keys(%env)) {
3879: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
3880: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
3881: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
3882: next if ($role eq 'ca' || $role eq 'aa');
3883: next if (%roles && !exists($roles{$role}));
3884: my ($starttime,$endtime)=split(/\./,$env{$key});
3885: my $active=1;
3886: if ($starttime) {
3887: if ($now<$starttime) { $active=0; }
3888: }
3889: if ($endtime) {
3890: if ($now>$endtime) { $active=0; }
3891: }
3892: if ($active) {
3893: if ($sec eq '') {
3894: $sec = 'none';
3895: }
3896: $courses{$cdom.'_'.$cnum}{$sec} =
3897: $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
3898: }
3899: }
3900: }
3901: }
3902: return %courses;
3903: }
3904:
3905: ###############################################
3906:
3907: sub blockcheck {
3908: my ($setters,$activity,$uname,$udom) = @_;
3909:
3910: if (!defined($udom)) {
3911: $udom = $env{'user.domain'};
3912: }
3913: if (!defined($uname)) {
3914: $uname = $env{'user.name'};
3915: }
3916:
3917: # If uname and udom are for a course, check for blocks in the course.
3918:
3919: if (&Apache::lonnet::is_course($udom,$uname)) {
3920: my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
3921: my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
3922: return ($startblock,$endblock);
3923: }
3924:
3925: my $startblock = 0;
3926: my $endblock = 0;
3927: my %live_courses = &findallcourses(undef,$uname,$udom);
3928:
3929: # If uname is for a user, and activity is course-specific, i.e.,
3930: # boards, chat or groups, check for blocking in current course only.
3931:
3932: if (($activity eq 'boards' || $activity eq 'chat' ||
3933: $activity eq 'groups') && ($env{'request.course.id'})) {
3934: foreach my $key (keys(%live_courses)) {
3935: if ($key ne $env{'request.course.id'}) {
3936: delete($live_courses{$key});
3937: }
3938: }
3939: }
3940:
3941: my $otheruser = 0;
3942: my %own_courses;
3943: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
3944: # Resource belongs to user other than current user.
3945: $otheruser = 1;
3946: # Gather courses for current user
3947: %own_courses =
3948: &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
3949: }
3950:
3951: # Gather active course roles - course coordinator, instructor,
3952: # exam proctor, ta, student, or custom role.
3953:
3954: foreach my $course (keys(%live_courses)) {
3955: my ($cdom,$cnum);
3956: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
3957: $cdom = $env{'course.'.$course.'.domain'};
3958: $cnum = $env{'course.'.$course.'.num'};
3959: } else {
3960: ($cdom,$cnum) = split(/_/,$course);
3961: }
3962: my $no_ownblock = 0;
3963: my $no_userblock = 0;
3964: if ($otheruser && $activity ne 'com') {
3965: # Check if current user has 'evb' priv for this
3966: if (defined($own_courses{$course})) {
3967: foreach my $sec (keys(%{$own_courses{$course}})) {
3968: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
3969: if ($sec ne 'none') {
3970: $checkrole .= '/'.$sec;
3971: }
3972: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
3973: $no_ownblock = 1;
3974: last;
3975: }
3976: }
3977: }
3978: # if they have 'evb' priv and are currently not playing student
3979: next if (($no_ownblock) &&
3980: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
3981: }
3982: foreach my $sec (keys(%{$live_courses{$course}})) {
3983: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
3984: if ($sec ne 'none') {
3985: $checkrole .= '/'.$sec;
3986: }
3987: if ($otheruser) {
3988: # Resource belongs to user other than current user.
3989: # Assemble privs for that user, and check for 'evb' priv.
3990: my ($trole,$tdom,$tnum,$tsec);
3991: my $entry = $live_courses{$course}{$sec};
3992: if ($entry =~ /^cr/) {
3993: ($trole,$tdom,$tnum,$tsec) =
3994: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
3995: } else {
3996: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
3997: }
3998: my ($spec,$area,$trest,%allroles,%userroles);
3999: $area = '/'.$tdom.'/'.$tnum;
4000: $trest = $tnum;
4001: if ($tsec ne '') {
4002: $area .= '/'.$tsec;
4003: $trest .= '/'.$tsec;
4004: }
4005: $spec = $trole.'.'.$area;
4006: if ($trole =~ /^cr/) {
4007: &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
4008: $tdom,$spec,$trest,$area);
4009: } else {
4010: &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
4011: $tdom,$spec,$trest,$area);
4012: }
4013: my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
4014: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
4015: if ($1) {
4016: $no_userblock = 1;
4017: last;
4018: }
4019: }
4020: } else {
4021: # Resource belongs to current user
4022: # Check for 'evb' priv via lonnet::allowed().
4023: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
4024: $no_ownblock = 1;
4025: last;
4026: }
4027: }
4028: }
4029: # if they have the evb priv and are currently not playing student
4030: next if (($no_ownblock) &&
4031: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
4032: next if ($no_userblock);
4033:
4034: # Retrieve blocking times and identity of locker for course
4035: # of specified user, unless user has 'evb' privilege.
4036:
4037: my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
4038: if (($start != 0) &&
4039: (($startblock == 0) || ($startblock > $start))) {
4040: $startblock = $start;
4041: }
4042: if (($end != 0) &&
4043: (($endblock == 0) || ($endblock < $end))) {
4044: $endblock = $end;
4045: }
4046: }
4047: return ($startblock,$endblock);
4048: }
4049:
4050: sub get_blocks {
4051: my ($setters,$activity,$cdom,$cnum) = @_;
4052: my $startblock = 0;
4053: my $endblock = 0;
4054: my $course = $cdom.'_'.$cnum;
4055: $setters->{$course} = {};
4056: $setters->{$course}{'staff'} = [];
4057: $setters->{$course}{'times'} = [];
4058: my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
4059: foreach my $record (keys(%records)) {
4060: my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
4061: if ($start <= time && $end >= time) {
4062: my ($staff_name,$staff_dom,$title,$blocks) =
4063: &parse_block_record($records{$record});
4064: if ($blocks->{$activity} eq 'on') {
4065: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
4066: push(@{$$setters{$course}{'times'}}, [$start,$end]);
4067: if ( ($startblock == 0) || ($startblock > $start) ) {
4068: $startblock = $start;
4069: }
4070: if ( ($endblock == 0) || ($endblock < $end) ) {
4071: $endblock = $end;
4072: }
4073: }
4074: }
4075: }
4076: return ($startblock,$endblock);
4077: }
4078:
4079: sub parse_block_record {
4080: my ($record) = @_;
4081: my ($setuname,$setudom,$title,$blocks);
4082: if (ref($record) eq 'HASH') {
4083: ($setuname,$setudom) = split(/:/,$record->{'setter'});
4084: $title = &unescape($record->{'event'});
4085: $blocks = $record->{'blocks'};
4086: } else {
4087: my @data = split(/:/,$record,3);
4088: if (scalar(@data) eq 2) {
4089: $title = $data[1];
4090: ($setuname,$setudom) = split(/@/,$data[0]);
4091: } else {
4092: ($setuname,$setudom,$title) = @data;
4093: }
4094: $blocks = { 'com' => 'on' };
4095: }
4096: return ($setuname,$setudom,$title,$blocks);
4097: }
4098:
4099: sub blocking_status {
4100: my ($activity,$uname,$udom) = @_;
4101: my %setters;
4102:
4103: # check for active blocking
4104: my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
4105:
4106: my $blocked = $startblock && $endblock ? 1 : 0;
4107:
4108: # caller just wants to know whether a block is active
4109: if (!wantarray) { return $blocked; }
4110:
4111: # build a link to a popup window containing the details
4112: my $querystring = "?activity=$activity";
4113: # $uname and $udom decide whose portfolio the user is trying to look at
4114: $querystring .= "&udom=$udom" if $udom;
4115: $querystring .= "&uname=$uname" if $uname;
4116:
4117: my $output .= <<'END_MYBLOCK';
4118: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
4119: var options = "width=" + w + ",height=" + h + ",";
4120: options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
4121: options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
4122: var newWin = window.open(url, wdwName, options);
4123: newWin.focus();
4124: }
4125: END_MYBLOCK
4126:
4127: $output = Apache::lonhtmlcommon::scripttag($output);
4128:
4129: my $popupUrl = "/adm/blockingstatus/$querystring";
4130: my $text = mt('Communication Blocked');
4131:
4132: $output .= <<"END_BLOCK";
4133: <div class='LC_comblock'>
4134: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
4135: title='$text'>
4136: <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
4137: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
4138: title='$text'>$text</a>
4139: </div>
4140:
4141: END_BLOCK
4142:
4143: return ($blocked, $output);
4144: }
4145:
4146: ###############################################
4147:
4148: sub check_ip_acc {
4149: my ($acc)=@_;
4150: &Apache::lonxml::debug("acc is $acc");
4151: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
4152: return 1;
4153: }
4154: my $allowed=0;
4155: my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
4156:
4157: my $name;
4158: foreach my $pattern (split(',',$acc)) {
4159: $pattern =~ s/^\s*//;
4160: $pattern =~ s/\s*$//;
4161: if ($pattern =~ /\*$/) {
4162: #35.8.*
4163: $pattern=~s/\*//;
4164: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
4165: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
4166: #35.8.3.[34-56]
4167: my $low=$2;
4168: my $high=$3;
4169: $pattern=$1;
4170: if ($ip =~ /^\Q$pattern\E/) {
4171: my $last=(split(/\./,$ip))[3];
4172: if ($last <=$high && $last >=$low) { $allowed=1; }
4173: }
4174: } elsif ($pattern =~ /^\*/) {
4175: #*.msu.edu
4176: $pattern=~s/\*//;
4177: if (!defined($name)) {
4178: use Socket;
4179: my $netaddr=inet_aton($ip);
4180: ($name)=gethostbyaddr($netaddr,AF_INET);
4181: }
4182: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
4183: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
4184: #127.0.0.1
4185: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
4186: } else {
4187: #some.name.com
4188: if (!defined($name)) {
4189: use Socket;
4190: my $netaddr=inet_aton($ip);
4191: ($name)=gethostbyaddr($netaddr,AF_INET);
4192: }
4193: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
4194: }
4195: if ($allowed) { last; }
4196: }
4197: return $allowed;
4198: }
4199:
4200: ###############################################
4201:
4202: =pod
4203:
4204: =head1 Domain Template Functions
4205:
4206: =over 4
4207:
4208: =item * &determinedomain()
4209:
4210: Inputs: $domain (usually will be undef)
4211:
4212: Returns: Determines which domain should be used for designs
4213:
4214: =cut
4215:
4216: ###############################################
4217: sub determinedomain {
4218: my $domain=shift;
4219: if (! $domain) {
4220: # Determine domain if we have not been given one
4221: $domain = &Apache::lonnet::default_login_domain();
4222: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
4223: if ($env{'request.role.domain'}) {
4224: $domain=$env{'request.role.domain'};
4225: }
4226: }
4227: return $domain;
4228: }
4229: ###############################################
4230:
4231: sub devalidate_domconfig_cache {
4232: my ($udom)=@_;
4233: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
4234: }
4235:
4236: # ---------------------- Get domain configuration for a domain
4237: sub get_domainconf {
4238: my ($udom) = @_;
4239: my $cachetime=1800;
4240: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
4241: if (defined($cached)) { return %{$result}; }
4242:
4243: my %domconfig = &Apache::lonnet::get_dom('configuration',
4244: ['login','rolecolors','autoenroll'],$udom);
4245: my (%designhash,%legacy);
4246: if (keys(%domconfig) > 0) {
4247: if (ref($domconfig{'login'}) eq 'HASH') {
4248: if (keys(%{$domconfig{'login'}})) {
4249: foreach my $key (keys(%{$domconfig{'login'}})) {
4250: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
4251: if ($key eq 'loginvia') {
4252: if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
4253: my @ids = &Apache::lonnet::current_machine_ids();
4254: foreach my $hostname (@ids) {
4255: if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
4256: if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
4257: my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
4258: $designhash{$udom.'.login.loginvia'} = $server;
4259: if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
4260:
4261: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
4262: } else {
4263: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
4264: }
4265: if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
4266: $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
4267: }
4268: }
4269: }
4270: }
4271: }
4272: } else {
4273: foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
4274: $designhash{$udom.'.login.'.$key.'_'.$img} =
4275: $domconfig{'login'}{$key}{$img};
4276: }
4277: }
4278: } else {
4279: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
4280: }
4281: }
4282: } else {
4283: $legacy{'login'} = 1;
4284: }
4285: } else {
4286: $legacy{'login'} = 1;
4287: }
4288: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
4289: if (keys(%{$domconfig{'rolecolors'}})) {
4290: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
4291: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
4292: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
4293: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
4294: }
4295: }
4296: }
4297: } else {
4298: $legacy{'rolecolors'} = 1;
4299: }
4300: } else {
4301: $legacy{'rolecolors'} = 1;
4302: }
4303: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
4304: if ($domconfig{'autoenroll'}{'co-owners'}) {
4305: $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
4306: }
4307: }
4308: if (keys(%legacy) > 0) {
4309: my %legacyhash = &get_legacy_domconf($udom);
4310: foreach my $item (keys(%legacyhash)) {
4311: if ($item =~ /^\Q$udom\E\.login/) {
4312: if ($legacy{'login'}) {
4313: $designhash{$item} = $legacyhash{$item};
4314: }
4315: } else {
4316: if ($legacy{'rolecolors'}) {
4317: $designhash{$item} = $legacyhash{$item};
4318: }
4319: }
4320: }
4321: }
4322: } else {
4323: %designhash = &get_legacy_domconf($udom);
4324: }
4325: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
4326: $cachetime);
4327: return %designhash;
4328: }
4329:
4330: sub get_legacy_domconf {
4331: my ($udom) = @_;
4332: my %legacyhash;
4333: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
4334: my $designfile = $designdir.'/'.$udom.'.tab';
4335: if (-e $designfile) {
4336: if ( open (my $fh,"<$designfile") ) {
4337: while (my $line = <$fh>) {
4338: next if ($line =~ /^\#/);
4339: chomp($line);
4340: my ($key,$val)=(split(/\=/,$line));
4341: if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
4342: }
4343: close($fh);
4344: }
4345: }
4346: if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
4347: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
4348: }
4349: return %legacyhash;
4350: }
4351:
4352: =pod
4353:
4354: =item * &domainlogo()
4355:
4356: Inputs: $domain (usually will be undef)
4357:
4358: Returns: A link to a domain logo, if the domain logo exists.
4359: If the domain logo does not exist, a description of the domain.
4360:
4361: =cut
4362:
4363: ###############################################
4364: sub domainlogo {
4365: my $domain = &determinedomain(shift);
4366: my %designhash = &get_domainconf($domain);
4367: # See if there is a logo
4368: if ($designhash{$domain.'.login.domlogo'} ne '') {
4369: my $imgsrc = $designhash{$domain.'.login.domlogo'};
4370: if ($imgsrc =~ m{^/(adm|res)/}) {
4371: if ($imgsrc =~ m{^/res/}) {
4372: my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
4373: &Apache::lonnet::repcopy($local_name);
4374: }
4375: $imgsrc = &lonhttpdurl($imgsrc);
4376: }
4377: return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
4378: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
4379: return &Apache::lonnet::domain($domain,'description');
4380: } else {
4381: return '';
4382: }
4383: }
4384: ##############################################
4385:
4386: =pod
4387:
4388: =item * &designparm()
4389:
4390: Inputs: $which parameter; $domain (usually will be undef)
4391:
4392: Returns: value of designparamter $which
4393:
4394: =cut
4395:
4396:
4397: ##############################################
4398: sub designparm {
4399: my ($which,$domain)=@_;
4400: if (exists($env{'environment.color.'.$which})) {
4401: return $env{'environment.color.'.$which};
4402: }
4403: $domain=&determinedomain($domain);
4404: my %domdesign = &get_domainconf($domain);
4405: my $output;
4406: if ($domdesign{$domain.'.'.$which} ne '') {
4407: $output = $domdesign{$domain.'.'.$which};
4408: } else {
4409: $output = $defaultdesign{$which};
4410: }
4411: if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
4412: ($which =~ /login\.(img|logo|domlogo|login)/)) {
4413: if ($output =~ m{^/(adm|res)/}) {
4414: if ($output =~ m{^/res/}) {
4415: my $local_name = &Apache::lonnet::filelocation('',$output);
4416: &Apache::lonnet::repcopy($local_name);
4417: }
4418: $output = &lonhttpdurl($output);
4419: }
4420: }
4421: return $output;
4422: }
4423:
4424: ##############################################
4425: =pod
4426:
4427: =item * &authorspace()
4428:
4429: Inputs: ./.
4430:
4431: Returns: Path to the Construction Space of the current user's
4432: accessed author space
4433: The author space will be that of the current user
4434: when accessing the own author space
4435: and that of the co-author/assistent co-author
4436: when accessing the co-author's/assistent co-author's
4437: space
4438:
4439: =cut
4440:
4441: sub authorspace {
4442: my $caname = '';
4443: if ($env{'request.role'} =~ /^ca|^aa/) {
4444: (undef,$caname) =
4445: ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
4446: } else {
4447: $caname = $env{'user.name'};
4448: }
4449: return '/priv/'.$caname.'/';
4450: }
4451:
4452: ##############################################
4453: =pod
4454:
4455: =item * &head_subbox()
4456:
4457: Inputs: $content (contains HTML code with page functions, etc.)
4458:
4459: Returns: HTML div with $content
4460: To be included in page header
4461:
4462: =cut
4463:
4464: sub head_subbox {
4465: my ($content)=@_;
4466: my $output =
4467: '<div id="LC_head_subbox">'
4468: .$content
4469: .'</div>'
4470: }
4471:
4472: ##############################################
4473: =pod
4474:
4475: =item * &CSTR_pageheader()
4476:
4477: Inputs: ./.
4478:
4479: Returns: HTML div with CSTR path and recent box
4480: To be included on Construction Space pages
4481:
4482: =cut
4483:
4484: sub CSTR_pageheader {
4485: # this is for resources; directories have customtitle, and crumbs
4486: # and select recent are created in lonpubdir.pm
4487: my ($uname,$thisdisfn)=
4488: ($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
4489: my $formaction='/priv/'.$uname.'/'.$thisdisfn;
4490: $formaction=~s/\/+/\//g;
4491:
4492: my $parentpath = '';
4493: my $lastitem = '';
4494: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
4495: $parentpath = $1;
4496: $lastitem = $2;
4497: } else {
4498: $lastitem = $thisdisfn;
4499: }
4500:
4501: my $output =
4502: '<div>'
4503: .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
4504: .'<b>'.&mt('Construction Space:').'</b> '
4505: .'<form name="dirs" method="post" action="'.$formaction
4506: .'" target="_top">' #FIXME lonpubdir: target="_parent"
4507: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv',undef,undef);
4508:
4509: if ($lastitem) {
4510: $output .=
4511: '<span class="LC_filename">'
4512: .$lastitem
4513: .'</span>';
4514: }
4515: $output .=
4516: '<br />'
4517: #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
4518: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
4519: .'</form>'
4520: .&Apache::lonmenu::constspaceform()
4521: .'</div>';
4522:
4523: return $output;
4524: }
4525:
4526: ###############################################
4527: ###############################################
4528:
4529: =pod
4530:
4531: =back
4532:
4533: =head1 HTML Helpers
4534:
4535: =over 4
4536:
4537: =item * &bodytag()
4538:
4539: Returns a uniform header for LON-CAPA web pages.
4540:
4541: Inputs:
4542:
4543: =over 4
4544:
4545: =item * $title, A title to be displayed on the page.
4546:
4547: =item * $function, the current role (can be undef).
4548:
4549: =item * $addentries, extra parameters for the <body> tag.
4550:
4551: =item * $bodyonly, if defined, only return the <body> tag.
4552:
4553: =item * $domain, if defined, force a given domain.
4554:
4555: =item * $forcereg, if page should register as content page (relevant for
4556: text interface only)
4557:
4558: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
4559: navigational links
4560:
4561: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
4562:
4563: =item * $no_inline_link, if true and in remote mode, don't show the
4564: 'Switch To Inline Menu' link
4565:
4566: =item * $args, optional argument valid values are
4567: no_auto_mt_title -> prevents &mt()ing the title arg
4568: inherit_jsmath -> when creating popup window in a page,
4569: should it have jsmath forced on by the
4570: current page
4571:
4572: =back
4573:
4574: Returns: A uniform header for LON-CAPA web pages.
4575: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
4576: If $bodyonly is undef or zero, an html string containing a <body> tag and
4577: other decorations will be returned.
4578:
4579: =cut
4580:
4581: sub bodytag {
4582: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
4583: $no_nav_bar,$bgcolor,$no_inline_link,$args)=@_;
4584:
4585: my $public;
4586: if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
4587: || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
4588: $public = 1;
4589: }
4590: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
4591:
4592: $function = &get_users_function() if (!$function);
4593: my $img = &designparm($function.'.img',$domain);
4594: my $font = &designparm($function.'.font',$domain);
4595: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
4596:
4597: my %design = ( 'style' => 'margin-top: 0',
4598: 'bgcolor' => $pgbg,
4599: 'text' => $font,
4600: 'alink' => &designparm($function.'.alink',$domain),
4601: 'vlink' => &designparm($function.'.vlink',$domain),
4602: 'link' => &designparm($function.'.link',$domain),);
4603: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
4604:
4605: # role and realm
4606: my ($role,$realm) = split(/\./,$env{'request.role'},2);
4607: if ($role eq 'ca') {
4608: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
4609: $realm = &plainname($rname,$rdom);
4610: }
4611: # realm
4612: if ($env{'request.course.id'}) {
4613: if ($env{'request.role'} !~ /^cr/) {
4614: $role = &Apache::lonnet::plaintext($role,&course_type());
4615: }
4616: if ($env{'request.course.sec'}) {
4617: $role .= (' 'x2).'- '.&mt('section:').' '.$env{'request.course.sec'};
4618: }
4619: $realm = $env{'course.'.$env{'request.course.id'}.'.description'};
4620: } else {
4621: $role = &Apache::lonnet::plaintext($role);
4622: }
4623:
4624: if (!$realm) { $realm=' '; }
4625: # Set messages
4626: my $messages=&domainlogo($domain);
4627:
4628: my $extra_body_attr = &make_attr_string($forcereg,\%design);
4629:
4630: # construct main body tag
4631: my $bodytag = "<body $extra_body_attr>".
4632: &Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
4633:
4634: if ($bodyonly) {
4635: return $bodytag;
4636: }
4637:
4638: my $name = &plainname($env{'user.name'},$env{'user.domain'});
4639: if ($public) {
4640: undef($role);
4641: } else {
4642: $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
4643: }
4644:
4645: my $titleinfo = '<h1>'.$title.'</h1>';
4646: #
4647: # Extra info if you are the DC
4648: my $dc_info = '';
4649: if ($env{'user.adv'} && exists($env{'user.role.dc./'.
4650: $env{'course.'.$env{'request.course.id'}.
4651: '.domain'}.'/'})) {
4652: my $cid = $env{'request.course.id'};
4653: $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
4654: $dc_info =~ s/\s+$//;
4655: }
4656:
4657: $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
4658: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
4659:
4660: if ($env{'environment.remote'} eq 'off') {
4661: # No Remote
4662: if ($no_nav_bar || $env{'form.inhibitmenu'} eq 'yes') {
4663: return $bodytag;
4664: }
4665:
4666: if ($env{'request.state'} eq 'construct') { $forcereg=1; }
4667:
4668: # if ($env{'request.state'} eq 'construct') {
4669: # $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
4670: # }
4671:
4672:
4673:
4674: if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
4675: if ($dc_info) {
4676: $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
4677: }
4678: $bodytag .= qq|<div id="LC_nav_bar">$name $role<br />
4679: <em>$realm</em> $dc_info</div>|;
4680: return $bodytag;
4681: }
4682:
4683: unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
4684: $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>|;
4685: }
4686:
4687: $bodytag .= Apache::lonhtmlcommon::scripttag(
4688: Apache::lonmenu::utilityfunctions(), 'start');
4689:
4690: $bodytag .= Apache::lonmenu::primary_menu();
4691:
4692: if ($dc_info) {
4693: $dc_info = &dc_courseid_toggle($dc_info);
4694: }
4695: $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
4696:
4697: #don't show menus for public users
4698: if (!$public){
4699: $bodytag .= Apache::lonmenu::secondary_menu();
4700: $bodytag .= Apache::lonmenu::serverform();
4701: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
4702: if ($env{'request.state'} eq 'construct') {
4703: $bodytag .= &Apache::lonmenu::innerregister($forcereg,'',
4704: $args->{'bread_crumbs'});
4705: } elsif ($forcereg) {
4706: $bodytag .= &Apache::lonmenu::innerregister($forcereg);
4707: }
4708: }else{
4709: # this is to seperate menu from content when there's no secondary
4710: # menu. Especially needed for public accessible ressources.
4711: $bodytag .= '<hr style="clear:both" />';
4712: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
4713: }
4714:
4715: return $bodytag;
4716: }
4717:
4718: #
4719: # Top frame rendering, Remote is up
4720: #
4721:
4722: my $imgsrc = $img;
4723: if ($img =~ /^\/adm/) {
4724: $imgsrc = &lonhttpdurl($img);
4725: }
4726: my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
4727:
4728: # Explicit link to get inline menu
4729: my $menu= ($no_inline_link?''
4730: :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
4731:
4732: if ($dc_info) {
4733: $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
4734: }
4735:
4736: $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
4737: <ol class="LC_primary_menu LC_right">
4738: <li>$menu</li>
4739: </ol><div id="LC_realm"> $realm $dc_info</div>| unless $env{'form.inhibitmenu'};
4740: return(<<ENDBODY);
4741: $bodytag
4742: <table id="LC_title_bar" class="LC_with_remote">
4743: <tr><td>$upperleft</td>
4744: <td>$messages </td>
4745: </tr>
4746: <tr><td>$titleinfo $dc_info $menu</td>
4747: </tr>
4748: </table>
4749: ENDBODY
4750: }
4751:
4752: sub dc_courseid_toggle {
4753: my ($dc_info) = @_;
4754: return ' <span id="dccidtext" class="LC_cusr_subheading">'.
4755: '<a href="javascript:showCourseID();">'.
4756: &mt('(More ...)').'</a></span>'.
4757: '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
4758: }
4759:
4760: sub make_attr_string {
4761: my ($register,$attr_ref) = @_;
4762:
4763: if ($attr_ref && !ref($attr_ref)) {
4764: die("addentries Must be a hash ref ".
4765: join(':',caller(1))." ".
4766: join(':',caller(0))." ");
4767: }
4768:
4769: if ($register) {
4770: my ($on_load,$on_unload);
4771: foreach my $key (keys(%{$attr_ref})) {
4772: if (lc($key) eq 'onload') {
4773: $on_load.=$attr_ref->{$key}.';';
4774: delete($attr_ref->{$key});
4775:
4776: } elsif (lc($key) eq 'onunload') {
4777: $on_unload.=$attr_ref->{$key}.';';
4778: delete($attr_ref->{$key});
4779: }
4780: }
4781: $attr_ref->{'onload'} =
4782: &Apache::lonmenu::loadevents(). $on_load;
4783: $attr_ref->{'onunload'}=
4784: &Apache::lonmenu::unloadevents().$on_unload;
4785: }
4786:
4787: # Accessibility font enhance
4788: if ($env{'browser.fontenhance'} eq 'on') {
4789: my $style;
4790: foreach my $key (keys(%{$attr_ref})) {
4791: if (lc($key) eq 'style') {
4792: $style.=$attr_ref->{$key}.';';
4793: delete($attr_ref->{$key});
4794: }
4795: }
4796: $attr_ref->{'style'}=$style.'; font-size: x-large;';
4797: }
4798:
4799: my $attr_string;
4800: foreach my $attr (keys(%$attr_ref)) {
4801: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
4802: }
4803: return $attr_string;
4804: }
4805:
4806:
4807: ###############################################
4808: ###############################################
4809:
4810: =pod
4811:
4812: =item * &endbodytag()
4813:
4814: Returns a uniform footer for LON-CAPA web pages.
4815:
4816: Inputs: 1 - optional reference to an args hash
4817: If in the hash, key for noredirectlink has a value which evaluates to true,
4818: a 'Continue' link is not displayed if the page contains an
4819: internal redirect in the <head></head> section,
4820: i.e., $env{'internal.head.redirect'} exists
4821:
4822: =cut
4823:
4824: sub endbodytag {
4825: my ($args) = @_;
4826: my $endbodytag='</body>';
4827: $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
4828: if ( exists( $env{'internal.head.redirect'} ) ) {
4829: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
4830: $endbodytag=
4831: "<br /><a href=\"$env{'internal.head.redirect'}\">".
4832: &mt('Continue').'</a>'.
4833: $endbodytag;
4834: }
4835: }
4836: return $endbodytag;
4837: }
4838:
4839: =pod
4840:
4841: =item * &standard_css()
4842:
4843: Returns a style sheet
4844:
4845: Inputs: (all optional)
4846: domain -> force to color decorate a page for a specific
4847: domain
4848: function -> force usage of a specific rolish color scheme
4849: bgcolor -> override the default page bgcolor
4850:
4851: =cut
4852:
4853: sub standard_css {
4854: my ($function,$domain,$bgcolor) = @_;
4855: $function = &get_users_function() if (!$function);
4856: my $img = &designparm($function.'.img', $domain);
4857: my $tabbg = &designparm($function.'.tabbg', $domain);
4858: my $font = &designparm($function.'.font', $domain);
4859: my $fontmenu = &designparm($function.'.fontmenu', $domain);
4860: #second colour for later usage
4861: my $sidebg = &designparm($function.'.sidebg',$domain);
4862: my $pgbg_or_bgcolor =
4863: $bgcolor ||
4864: &designparm($function.'.pgbg', $domain);
4865: my $pgbg = &designparm($function.'.pgbg', $domain);
4866: my $alink = &designparm($function.'.alink', $domain);
4867: my $vlink = &designparm($function.'.vlink', $domain);
4868: my $link = &designparm($function.'.link', $domain);
4869:
4870: my $sans = 'Verdana,Arial,Helvetica,sans-serif';
4871: my $mono = 'monospace';
4872: my $data_table_head = $sidebg;
4873: my $data_table_light = '#FAFAFA';
4874: my $data_table_dark = '#F0F0F0';
4875: my $data_table_darker = '#CCCCCC';
4876: my $data_table_highlight = '#FFFF00';
4877: my $mail_new = '#FFBB77';
4878: my $mail_new_hover = '#DD9955';
4879: my $mail_read = '#BBBB77';
4880: my $mail_read_hover = '#999944';
4881: my $mail_replied = '#AAAA88';
4882: my $mail_replied_hover = '#888855';
4883: my $mail_other = '#99BBBB';
4884: my $mail_other_hover = '#669999';
4885: my $table_header = '#DDDDDD';
4886: my $feedback_link_bg = '#BBBBBB';
4887: my $lg_border_color = '#C8C8C8';
4888: my $button_hover = '#BF2317';
4889:
4890: my $border = ($env{'browser.type'} eq 'explorer' ||
4891: $env{'browser.type'} eq 'safari' ) ? '0 2px 0 2px'
4892: : '0 3px 0 4px';
4893:
4894: return <<END;
4895:
4896: /* needed for iframe to allow 100% height in FF */
4897: body, html {
4898: margin: 0;
4899: padding: 0 0.5%;
4900: height: 99%; /* to avoid scrollbars */
4901: }
4902:
4903: body {
4904: font-family: $sans;
4905: line-height:130%;
4906: font-size:0.83em;
4907: color:$font;
4908: }
4909:
4910: a:focus,
4911: a:focus img {
4912: color: red;
4913: background: yellow;
4914: }
4915:
4916: form, .inline {
4917: display: inline;
4918: }
4919:
4920: .LC_right {
4921: text-align:right;
4922: }
4923:
4924: .LC_middle {
4925: vertical-align:middle;
4926: }
4927:
4928: .LC_400Box {
4929: width:400px;
4930: }
4931:
4932: .LC_iframecontainer {
4933: width: 98%;
4934: margin: 0;
4935: position: fixed;
4936: top: 8.5em;
4937: bottom: 0;
4938: }
4939:
4940: .LC_iframecontainer iframe{
4941: border: none;
4942: width: 100%;
4943: height: 100%;
4944: }
4945:
4946: .LC_filename {
4947: font-family: $mono;
4948: white-space:pre;
4949: font-size: 120%;
4950: }
4951:
4952: .LC_fileicon {
4953: border: none;
4954: height: 1.3em;
4955: vertical-align: text-bottom;
4956: margin-right: 0.3em;
4957: text-decoration:none;
4958: }
4959:
4960: .LC_error {
4961: color: red;
4962: font-size: larger;
4963: }
4964:
4965: .LC_warning,
4966: .LC_diff_removed {
4967: color: red;
4968: }
4969:
4970: .LC_info,
4971: .LC_success,
4972: .LC_diff_added {
4973: color: green;
4974: }
4975:
4976: div.LC_confirm_box {
4977: background-color: #FAFAFA;
4978: border: 1px solid $lg_border_color;
4979: margin-right: 0;
4980: padding: 5px;
4981: }
4982:
4983: div.LC_confirm_box .LC_error img,
4984: div.LC_confirm_box .LC_success img {
4985: vertical-align: middle;
4986: }
4987:
4988: .LC_icon {
4989: border: none;
4990: vertical-align: middle;
4991: }
4992:
4993: .LC_docs_spacer {
4994: width: 25px;
4995: height: 1px;
4996: border: none;
4997: }
4998:
4999: .LC_internal_info {
5000: color: #999999;
5001: }
5002:
5003: .LC_discussion {
5004: background: $tabbg;
5005: border: 1px solid black;
5006: margin: 2px;
5007: }
5008:
5009: .LC_disc_action_links_bar {
5010: background: $tabbg;
5011: border: none;
5012: margin: 4px;
5013: }
5014:
5015: .LC_disc_action_left {
5016: text-align: left;
5017: }
5018:
5019: .LC_disc_action_right {
5020: text-align: right;
5021: }
5022:
5023: .LC_disc_new_item {
5024: background: white;
5025: border: 2px solid red;
5026: margin: 2px;
5027: }
5028:
5029: .LC_disc_old_item {
5030: background: white;
5031: border: 1px solid black;
5032: margin: 2px;
5033: }
5034:
5035: table.LC_pastsubmission {
5036: border: 1px solid black;
5037: margin: 2px;
5038: }
5039:
5040: table#LC_menubuttons {
5041: width: 100%;
5042: background: $pgbg;
5043: border: 2px;
5044: border-collapse: separate;
5045: padding: 0;
5046: }
5047:
5048: table#LC_title_bar a {
5049: color: $fontmenu;
5050: }
5051:
5052: table#LC_title_bar {
5053: clear: both;
5054: display: none;
5055: }
5056:
5057: table#LC_title_bar,
5058: table.LC_breadcrumbs, /* obsolete? */
5059: table#LC_title_bar.LC_with_remote {
5060: width: 100%;
5061: border-color: $pgbg;
5062: border-style: solid;
5063: border-width: $border;
5064: background: $pgbg;
5065: color: $fontmenu;
5066: border-collapse: collapse;
5067: padding: 0;
5068: margin: 0;
5069: }
5070:
5071: ul.LC_breadcrumb_tools_outerlist {
5072: margin: 0;
5073: padding: 0;
5074: position: relative;
5075: list-style: none;
5076: }
5077: ul.LC_breadcrumb_tools_outerlist li {
5078: display: inline;
5079: }
5080:
5081: .LC_breadcrumb_tools_navigation {
5082: padding: 0;
5083: margin: 0;
5084: float: left;
5085: }
5086: .LC_breadcrumb_tools_tools {
5087: padding: 0;
5088: margin: 0;
5089: float: right;
5090: }
5091:
5092: table#LC_title_bar td {
5093: background: $tabbg;
5094: }
5095:
5096: table#LC_menubuttons img {
5097: border: none;
5098: }
5099:
5100: .LC_breadcrumbs_component {
5101: float: right;
5102: margin: 0 1em;
5103: }
5104: .LC_breadcrumbs_component img {
5105: vertical-align: middle;
5106: }
5107:
5108: td.LC_table_cell_checkbox {
5109: text-align: center;
5110: }
5111:
5112: .LC_fontsize_small {
5113: font-size: 70%;
5114: }
5115:
5116: #LC_breadcrumbs {
5117: clear:both;
5118: background: $sidebg;
5119: border-bottom: 1px solid $lg_border_color;
5120: line-height: 2.5em;
5121: overflow: hidden;
5122: margin: 0;
5123: padding: 0;
5124: }
5125:
5126: /* Preliminary fix to hide breadcrumbs inside remote control window */
5127: #LC_remote #LC_breadcrumbs {
5128: display:none;
5129: }
5130:
5131: #LC_head_subbox {
5132: clear:both;
5133: background: #F8F8F8; /* $sidebg; */
5134: border: 1px solid $sidebg;
5135: margin: 0 0 10px 0;
5136: padding: 3px;
5137: }
5138:
5139: .LC_fontsize_medium {
5140: font-size: 85%;
5141: }
5142:
5143: .LC_fontsize_large {
5144: font-size: 120%;
5145: }
5146:
5147: .LC_menubuttons_inline_text {
5148: color: $font;
5149: font-size: 90%;
5150: padding-left:3px;
5151: }
5152:
5153: .LC_menubuttons_inline_text img{
5154: vertical-align: middle;
5155: }
5156:
5157: li.LC_menubuttons_inline_text img,a {
5158: cursor:pointer;
5159: }
5160:
5161: .LC_menubuttons_link {
5162: text-decoration: none;
5163: }
5164:
5165: .LC_menubuttons_category {
5166: color: $font;
5167: background: $pgbg;
5168: font-size: larger;
5169: font-weight: bold;
5170: }
5171:
5172: td.LC_menubuttons_text {
5173: color: $font;
5174: }
5175:
5176: .LC_current_location {
5177: background: $tabbg;
5178: }
5179:
5180: table.LC_data_table {
5181: border: 1px solid #000000;
5182: border-collapse: separate;
5183: border-spacing: 1px;
5184: background: $pgbg;
5185: }
5186:
5187: .LC_data_table_dense {
5188: font-size: small;
5189: }
5190:
5191: table.LC_nested_outer {
5192: border: 1px solid #000000;
5193: border-collapse: collapse;
5194: border-spacing: 0;
5195: width: 100%;
5196: }
5197:
5198: table.LC_innerpickbox,
5199: table.LC_nested {
5200: border: none;
5201: border-collapse: collapse;
5202: border-spacing: 0;
5203: width: 100%;
5204: }
5205:
5206: .ui-accordion,
5207: .ui-accordion table.LC_data_table,
5208: .ui-accordion table.LC_nested_outer{
5209: border: 0px;
5210: border-spacing: 0px;
5211: margin: 3px;
5212: }
5213:
5214: table.LC_data_table tr th,
5215: table.LC_calendar tr th,
5216: table.LC_prior_tries tr th,
5217: table.LC_innerpickbox tr th {
5218: font-weight: bold;
5219: background-color: $data_table_head;
5220: color:$fontmenu;
5221: font-size:90%;
5222: }
5223:
5224: table.LC_innerpickbox tr th,
5225: table.LC_innerpickbox tr td {
5226: vertical-align: top;
5227: }
5228:
5229: table.LC_data_table tr.LC_info_row > td {
5230: background-color: #CCCCCC;
5231: font-weight: bold;
5232: text-align: left;
5233: }
5234:
5235: table.LC_data_table tr.LC_odd_row > td {
5236: background-color: $data_table_light;
5237: padding: 2px;
5238: vertical-align: top;
5239: }
5240:
5241: table.LC_pick_box tr > td.LC_odd_row {
5242: background-color: $data_table_light;
5243: vertical-align: top;
5244: }
5245:
5246: table.LC_data_table tr.LC_even_row > td {
5247: background-color: $data_table_dark;
5248: padding: 2px;
5249: vertical-align: top;
5250: }
5251:
5252: table.LC_pick_box tr > td.LC_even_row {
5253: background-color: $data_table_dark;
5254: vertical-align: top;
5255: }
5256:
5257: table.LC_data_table tr.LC_data_table_highlight td {
5258: background-color: $data_table_darker;
5259: }
5260:
5261: table.LC_data_table tr td.LC_leftcol_header {
5262: background-color: $data_table_head;
5263: font-weight: bold;
5264: }
5265:
5266: table.LC_data_table tr.LC_empty_row td,
5267: table.LC_nested tr.LC_empty_row td {
5268: font-weight: bold;
5269: font-style: italic;
5270: text-align: center;
5271: padding: 8px;
5272: }
5273:
5274: table.LC_data_table tr.LC_empty_row td {
5275: background-color: $sidebg;
5276: }
5277:
5278: table.LC_nested tr.LC_empty_row td {
5279: background-color: #FFFFFF;
5280: }
5281:
5282: table.LC_caption {
5283: }
5284:
5285: table.LC_nested tr.LC_empty_row td {
5286: padding: 4ex
5287: }
5288:
5289: table.LC_nested_outer tr th {
5290: font-weight: bold;
5291: color:$fontmenu;
5292: background-color: $data_table_head;
5293: font-size: small;
5294: border-bottom: 1px solid #000000;
5295: }
5296:
5297: table.LC_nested_outer tr td.LC_subheader {
5298: background-color: $data_table_head;
5299: font-weight: bold;
5300: font-size: small;
5301: border-bottom: 1px solid #000000;
5302: text-align: right;
5303: }
5304:
5305: table.LC_nested tr.LC_info_row td {
5306: background-color: #CCCCCC;
5307: font-weight: bold;
5308: font-size: small;
5309: text-align: center;
5310: }
5311:
5312: table.LC_nested tr.LC_info_row td.LC_left_item,
5313: table.LC_nested_outer tr th.LC_left_item {
5314: text-align: left;
5315: }
5316:
5317: table.LC_nested td {
5318: background-color: #FFFFFF;
5319: font-size: small;
5320: }
5321:
5322: table.LC_nested_outer tr th.LC_right_item,
5323: table.LC_nested tr.LC_info_row td.LC_right_item,
5324: table.LC_nested tr.LC_odd_row td.LC_right_item,
5325: table.LC_nested tr td.LC_right_item {
5326: text-align: right;
5327: }
5328:
5329: .ui-accordion table.LC_nested tr.LC_odd_row td.LC_left_item,
5330: .ui-accordion table.LC_nested tr.LC_even_row td.LC_left_item {
5331: text-align: right;
5332: width: 40%;
5333: padding-right:10px;
5334: vertical-align: top;
5335: padding: 5px;
5336: }
5337:
5338: .ui-accordion table.LC_nested tr.LC_odd_row td.LC_right_item,
5339: .ui-accordion table.LC_nested tr.LC_even_row td.LC_right_item {
5340: text-align: left;
5341: width: 60%;
5342: padding: 2px 4px;
5343: }
5344:
5345: table.LC_nested tr.LC_odd_row td {
5346: background-color: #EEEEEE;
5347: }
5348:
5349: table.LC_createuser {
5350: }
5351:
5352: table.LC_createuser tr.LC_section_row td {
5353: font-size: small;
5354: }
5355:
5356: table.LC_createuser tr.LC_info_row td {
5357: background-color: #CCCCCC;
5358: font-weight: bold;
5359: text-align: center;
5360: }
5361:
5362: table.LC_calendar {
5363: border: 1px solid #000000;
5364: border-collapse: collapse;
5365: width: 98%;
5366: }
5367:
5368: table.LC_calendar_pickdate {
5369: font-size: xx-small;
5370: }
5371:
5372: table.LC_calendar tr td {
5373: border: 1px solid #000000;
5374: vertical-align: top;
5375: width: 14%;
5376: }
5377:
5378: table.LC_calendar tr td.LC_calendar_day_empty {
5379: background-color: $data_table_dark;
5380: }
5381:
5382: table.LC_calendar tr td.LC_calendar_day_current {
5383: background-color: $data_table_highlight;
5384: }
5385:
5386: table.LC_data_table tr td.LC_mail_new {
5387: background-color: $mail_new;
5388: }
5389:
5390: table.LC_data_table tr.LC_mail_new:hover {
5391: background-color: $mail_new_hover;
5392: }
5393:
5394: table.LC_data_table tr td.LC_mail_read {
5395: background-color: $mail_read;
5396: }
5397:
5398: /*
5399: table.LC_data_table tr.LC_mail_read:hover {
5400: background-color: $mail_read_hover;
5401: }
5402: */
5403:
5404: table.LC_data_table tr td.LC_mail_replied {
5405: background-color: $mail_replied;
5406: }
5407:
5408: /*
5409: table.LC_data_table tr.LC_mail_replied:hover {
5410: background-color: $mail_replied_hover;
5411: }
5412: */
5413:
5414: table.LC_data_table tr td.LC_mail_other {
5415: background-color: $mail_other;
5416: }
5417:
5418: /*
5419: table.LC_data_table tr.LC_mail_other:hover {
5420: background-color: $mail_other_hover;
5421: }
5422: */
5423:
5424: table.LC_data_table tr > td.LC_browser_file,
5425: table.LC_data_table tr > td.LC_browser_file_published {
5426: background: #AAEE77;
5427: }
5428:
5429: table.LC_data_table tr > td.LC_browser_file_locked,
5430: table.LC_data_table tr > td.LC_browser_file_unpublished {
5431: background: #FFAA99;
5432: }
5433:
5434: table.LC_data_table tr > td.LC_browser_file_obsolete {
5435: background: #888888;
5436: }
5437:
5438: table.LC_data_table tr > td.LC_browser_file_modified,
5439: table.LC_data_table tr > td.LC_browser_file_metamodified {
5440: background: #F8F866;
5441: }
5442:
5443: table.LC_data_table tr.LC_browser_folder > td {
5444: background: #E0E8FF;
5445: }
5446:
5447: table.LC_data_table tr > td.LC_roles_is {
5448: /* background: #77FF77; */
5449: }
5450:
5451: table.LC_data_table tr > td.LC_roles_future {
5452: border-right: 8px solid #FFFF77;
5453: }
5454:
5455: table.LC_data_table tr > td.LC_roles_will {
5456: border-right: 8px solid #FFAA77;
5457: }
5458:
5459: table.LC_data_table tr > td.LC_roles_expired {
5460: border-right: 8px solid #FF7777;
5461: }
5462:
5463: table.LC_data_table tr > td.LC_roles_will_not {
5464: border-right: 8px solid #AAFF77;
5465: }
5466:
5467: table.LC_data_table tr > td.LC_roles_selected {
5468: border-right: 8px solid #11CC55;
5469: }
5470:
5471: span.LC_current_location {
5472: font-size:larger;
5473: background: $pgbg;
5474: }
5475:
5476: span.LC_parm_menu_item {
5477: font-size: larger;
5478: }
5479:
5480: span.LC_parm_scope_all {
5481: color: red;
5482: }
5483:
5484: span.LC_parm_scope_folder {
5485: color: green;
5486: }
5487:
5488: span.LC_parm_scope_resource {
5489: color: orange;
5490: }
5491:
5492: span.LC_parm_part {
5493: color: blue;
5494: }
5495:
5496: span.LC_parm_folder,
5497: span.LC_parm_symb {
5498: font-size: x-small;
5499: font-family: $mono;
5500: color: #AAAAAA;
5501: }
5502:
5503: ul.LC_parm_parmlist li {
5504: display: inline-block;
5505: padding: 0.3em 0.8em;
5506: vertical-align: top;
5507: width: 150px;
5508: border-top:1px solid $lg_border_color;
5509: }
5510:
5511: td.LC_parm_overview_level_menu,
5512: td.LC_parm_overview_map_menu,
5513: td.LC_parm_overview_parm_selectors,
5514: td.LC_parm_overview_restrictions {
5515: border: 1px solid black;
5516: border-collapse: collapse;
5517: }
5518:
5519: table.LC_parm_overview_restrictions td {
5520: border-width: 1px 4px 1px 4px;
5521: border-style: solid;
5522: border-color: $pgbg;
5523: text-align: center;
5524: }
5525:
5526: table.LC_parm_overview_restrictions th {
5527: background: $tabbg;
5528: border-width: 1px 4px 1px 4px;
5529: border-style: solid;
5530: border-color: $pgbg;
5531: }
5532:
5533: table#LC_helpmenu {
5534: border: none;
5535: height: 55px;
5536: border-spacing: 0;
5537: }
5538:
5539: table#LC_helpmenu fieldset legend {
5540: font-size: larger;
5541: }
5542:
5543: table#LC_helpmenu_links {
5544: width: 100%;
5545: border: 1px solid black;
5546: background: $pgbg;
5547: padding: 0;
5548: border-spacing: 1px;
5549: }
5550:
5551: table#LC_helpmenu_links tr td {
5552: padding: 1px;
5553: background: $tabbg;
5554: text-align: center;
5555: font-weight: bold;
5556: }
5557:
5558: table#LC_helpmenu_links a:link,
5559: table#LC_helpmenu_links a:visited,
5560: table#LC_helpmenu_links a:active {
5561: text-decoration: none;
5562: color: $font;
5563: }
5564:
5565: table#LC_helpmenu_links a:hover {
5566: text-decoration: underline;
5567: color: $vlink;
5568: }
5569:
5570: .LC_chrt_popup_exists {
5571: border: 1px solid #339933;
5572: margin: -1px;
5573: }
5574:
5575: .LC_chrt_popup_up {
5576: border: 1px solid yellow;
5577: margin: -1px;
5578: }
5579:
5580: .LC_chrt_popup {
5581: border: 1px solid #8888FF;
5582: background: #CCCCFF;
5583: }
5584:
5585: table.LC_pick_box {
5586: border-collapse: separate;
5587: background: white;
5588: border: 1px solid black;
5589: border-spacing: 1px;
5590: }
5591:
5592: table.LC_pick_box td.LC_pick_box_title {
5593: background: $sidebg;
5594: font-weight: bold;
5595: text-align: left;
5596: vertical-align: top;
5597: width: 184px;
5598: padding: 8px;
5599: }
5600:
5601: table.LC_pick_box td.LC_pick_box_value {
5602: text-align: left;
5603: padding: 8px;
5604: }
5605:
5606: table.LC_pick_box td.LC_pick_box_select {
5607: text-align: left;
5608: padding: 8px;
5609: }
5610:
5611: table.LC_pick_box td.LC_pick_box_separator {
5612: padding: 0;
5613: height: 1px;
5614: background: black;
5615: }
5616:
5617: table.LC_pick_box td.LC_pick_box_submit {
5618: text-align: right;
5619: }
5620:
5621: table.LC_pick_box td.LC_evenrow_value {
5622: text-align: left;
5623: padding: 8px;
5624: background-color: $data_table_light;
5625: }
5626:
5627: table.LC_pick_box td.LC_oddrow_value {
5628: text-align: left;
5629: padding: 8px;
5630: background-color: $data_table_light;
5631: }
5632:
5633: span.LC_helpform_receipt_cat {
5634: font-weight: bold;
5635: }
5636:
5637: table.LC_group_priv_box {
5638: background: white;
5639: border: 1px solid black;
5640: border-spacing: 1px;
5641: }
5642:
5643: table.LC_group_priv_box td.LC_pick_box_title {
5644: background: $tabbg;
5645: font-weight: bold;
5646: text-align: right;
5647: width: 184px;
5648: }
5649:
5650: table.LC_group_priv_box td.LC_groups_fixed {
5651: background: $data_table_light;
5652: text-align: center;
5653: }
5654:
5655: table.LC_group_priv_box td.LC_groups_optional {
5656: background: $data_table_dark;
5657: text-align: center;
5658: }
5659:
5660: table.LC_group_priv_box td.LC_groups_functionality {
5661: background: $data_table_darker;
5662: text-align: center;
5663: font-weight: bold;
5664: }
5665:
5666: table.LC_group_priv td {
5667: text-align: left;
5668: padding: 0;
5669: }
5670:
5671: table.LC_notify_front_page {
5672: background: white;
5673: border: 1px solid black;
5674: padding: 8px;
5675: }
5676:
5677: table.LC_notify_front_page td {
5678: padding: 8px;
5679: }
5680:
5681: .LC_navbuttons {
5682: margin: 2ex 0ex 2ex 0ex;
5683: }
5684:
5685: .LC_topic_bar {
5686: font-weight: bold;
5687: background: $tabbg;
5688: margin: 1em 0em 1em 2em;
5689: padding: 3px;
5690: font-size: 1.2em;
5691: }
5692:
5693: .LC_topic_bar span {
5694: left: 0.5em;
5695: position: absolute;
5696: vertical-align: middle;
5697: font-size: 1.2em;
5698: }
5699:
5700: table.LC_course_group_status {
5701: margin: 20px;
5702: }
5703:
5704: table.LC_status_selector td {
5705: vertical-align: top;
5706: text-align: center;
5707: padding: 4px;
5708: }
5709:
5710: div.LC_feedback_link {
5711: clear: both;
5712: background: $sidebg;
5713: width: 100%;
5714: padding-bottom: 10px;
5715: border: 1px $tabbg solid;
5716: height: 22px;
5717: line-height: 22px;
5718: padding-top: 5px;
5719: }
5720:
5721: div.LC_feedback_link img {
5722: height: 22px;
5723: vertical-align:middle;
5724: }
5725:
5726: div.LC_feedback_link a {
5727: text-decoration: none;
5728: }
5729:
5730: div.LC_comblock {
5731: display:inline;
5732: color:$font;
5733: font-size:90%;
5734: }
5735:
5736: div.LC_feedback_link div.LC_comblock {
5737: padding-left:5px;
5738: }
5739:
5740: div.LC_feedback_link div.LC_comblock a {
5741: color:$font;
5742: }
5743:
5744: span.LC_feedback_link {
5745: /* background: $feedback_link_bg; */
5746: font-size: larger;
5747: }
5748:
5749: span.LC_message_link {
5750: /* background: $feedback_link_bg; */
5751: font-size: larger;
5752: position: absolute;
5753: right: 1em;
5754: }
5755:
5756: table.LC_prior_tries {
5757: border: 1px solid #000000;
5758: border-collapse: separate;
5759: border-spacing: 1px;
5760: }
5761:
5762: table.LC_prior_tries td {
5763: padding: 2px;
5764: }
5765:
5766: .LC_answer_correct {
5767: background: lightgreen;
5768: color: darkgreen;
5769: padding: 6px;
5770: }
5771:
5772: .LC_answer_charged_try {
5773: background: #FFAAAA;
5774: color: darkred;
5775: padding: 6px;
5776: }
5777:
5778: .LC_answer_not_charged_try,
5779: .LC_answer_no_grade,
5780: .LC_answer_late {
5781: background: lightyellow;
5782: color: black;
5783: padding: 6px;
5784: }
5785:
5786: .LC_answer_previous {
5787: background: lightblue;
5788: color: darkblue;
5789: padding: 6px;
5790: }
5791:
5792: .LC_answer_no_message {
5793: background: #FFFFFF;
5794: color: black;
5795: padding: 6px;
5796: }
5797:
5798: .LC_answer_unknown {
5799: background: orange;
5800: color: black;
5801: padding: 6px;
5802: }
5803:
5804: span.LC_prior_numerical,
5805: span.LC_prior_string,
5806: span.LC_prior_custom,
5807: span.LC_prior_reaction,
5808: span.LC_prior_math {
5809: font-family: $mono;
5810: white-space: pre;
5811: }
5812:
5813: span.LC_prior_string {
5814: font-family: $mono;
5815: white-space: pre;
5816: }
5817:
5818: table.LC_prior_option {
5819: width: 100%;
5820: border-collapse: collapse;
5821: }
5822:
5823: table.LC_prior_rank,
5824: table.LC_prior_match {
5825: border-collapse: collapse;
5826: }
5827:
5828: table.LC_prior_option tr td,
5829: table.LC_prior_rank tr td,
5830: table.LC_prior_match tr td {
5831: border: 1px solid #000000;
5832: }
5833:
5834: .LC_nobreak {
5835: white-space: nowrap;
5836: }
5837:
5838: span.LC_cusr_emph {
5839: font-style: italic;
5840: }
5841:
5842: span.LC_cusr_subheading {
5843: font-weight: normal;
5844: font-size: 85%;
5845: }
5846:
5847: div.LC_docs_entry_move {
5848: border: 1px solid #BBBBBB;
5849: background: #DDDDDD;
5850: width: 22px;
5851: padding: 1px;
5852: margin: 0;
5853: }
5854:
5855: table.LC_data_table tr > td.LC_docs_entry_commands,
5856: table.LC_data_table tr > td.LC_docs_entry_parameter {
5857: background: #DDDDDD;
5858: font-size: x-small;
5859: }
5860:
5861: .LC_docs_entry_parameter {
5862: white-space: nowrap;
5863: }
5864:
5865: .LC_docs_copy {
5866: color: #000099;
5867: }
5868:
5869: .LC_docs_cut {
5870: color: #550044;
5871: }
5872:
5873: .LC_docs_rename {
5874: color: #009900;
5875: }
5876:
5877: .LC_docs_remove {
5878: color: #990000;
5879: }
5880:
5881: .LC_docs_reinit_warn,
5882: .LC_docs_ext_edit {
5883: font-size: x-small;
5884: }
5885:
5886: table.LC_docs_adddocs td,
5887: table.LC_docs_adddocs th {
5888: border: 1px solid #BBBBBB;
5889: padding: 4px;
5890: background: #DDDDDD;
5891: }
5892:
5893: table.LC_sty_begin {
5894: background: #BBFFBB;
5895: }
5896:
5897: table.LC_sty_end {
5898: background: #FFBBBB;
5899: }
5900:
5901: table.LC_double_column {
5902: border-width: 0;
5903: border-collapse: collapse;
5904: width: 100%;
5905: padding: 2px;
5906: }
5907:
5908: table.LC_double_column tr td.LC_left_col {
5909: top: 2px;
5910: left: 2px;
5911: width: 47%;
5912: vertical-align: top;
5913: }
5914:
5915: table.LC_double_column tr td.LC_right_col {
5916: top: 2px;
5917: right: 2px;
5918: width: 47%;
5919: vertical-align: top;
5920: }
5921:
5922: div.LC_left_float {
5923: float: left;
5924: padding-right: 5%;
5925: padding-bottom: 4px;
5926: }
5927:
5928: div.LC_clear_float_header {
5929: padding-bottom: 2px;
5930: }
5931:
5932: div.LC_clear_float_footer {
5933: padding-top: 10px;
5934: clear: both;
5935: }
5936:
5937: div.LC_grade_show_user {
5938: /* border-left: 5px solid $sidebg; */
5939: border-top: 5px solid #000000;
5940: margin: 50px 0 0 0;
5941: padding: 15px 0 5px 10px;
5942: }
5943:
5944: div.LC_grade_show_user_odd_row {
5945: /* border-left: 5px solid #000000; */
5946: }
5947:
5948: div.LC_grade_show_user div.LC_Box {
5949: margin-right: 50px;
5950: }
5951:
5952: div.LC_grade_submissions,
5953: div.LC_grade_message_center,
5954: div.LC_grade_info_links {
5955: margin: 5px;
5956: width: 99%;
5957: background: #FFFFFF;
5958: }
5959:
5960: div.LC_grade_submissions_header,
5961: div.LC_grade_message_center_header {
5962: font-weight: bold;
5963: font-size: large;
5964: }
5965:
5966: div.LC_grade_submissions_body,
5967: div.LC_grade_message_center_body {
5968: border: 1px solid black;
5969: width: 99%;
5970: background: #FFFFFF;
5971: }
5972:
5973: table.LC_scantron_action {
5974: width: 100%;
5975: }
5976:
5977: table.LC_scantron_action tr th {
5978: font-weight:bold;
5979: font-style:normal;
5980: }
5981:
5982: .LC_edit_problem_header,
5983: div.LC_edit_problem_footer {
5984: font-weight: normal;
5985: font-size: medium;
5986: margin: 2px;
5987: }
5988:
5989: div.LC_edit_problem_header,
5990: div.LC_edit_problem_header div,
5991: div.LC_edit_problem_footer,
5992: div.LC_edit_problem_footer div,
5993: div.LC_edit_problem_editxml_header,
5994: div.LC_edit_problem_editxml_header div {
5995: margin-top: 5px;
5996: }
5997:
5998: div.LC_edit_problem_header_title {
5999: font-weight: bold;
6000: font-size: larger;
6001: background: $tabbg;
6002: padding: 3px;
6003: }
6004:
6005: table.LC_edit_problem_header_title {
6006: width: 100%;
6007: background: $tabbg;
6008: }
6009:
6010: div.LC_edit_problem_discards {
6011: float: left;
6012: padding-bottom: 5px;
6013: }
6014:
6015: div.LC_edit_problem_saves {
6016: float: right;
6017: padding-bottom: 5px;
6018: }
6019:
6020: img.stift {
6021: border-width: 0;
6022: vertical-align: middle;
6023: }
6024:
6025: table td.LC_mainmenu_col_fieldset {
6026: vertical-align: top;
6027: }
6028:
6029: div.LC_createcourse {
6030: margin: 10px 10px 10px 10px;
6031: }
6032:
6033: .LC_dccid {
6034: margin: 0.2em 0 0 0;
6035: padding: 0;
6036: font-size: 90%;
6037: display:none;
6038: }
6039:
6040: a:hover,
6041: ol.LC_primary_menu a:hover,
6042: ol#LC_MenuBreadcrumbs a:hover,
6043: ol#LC_PathBreadcrumbs a:hover,
6044: ul#LC_secondary_menu a:hover,
6045: .LC_FormSectionClearButton input:hover
6046: ul.LC_TabContent li:hover a {
6047: color:$button_hover;
6048: text-decoration:none;
6049: }
6050:
6051: h1 {
6052: padding: 0;
6053: line-height:130%;
6054: }
6055:
6056: h2,
6057: h3,
6058: h4,
6059: h5,
6060: h6 {
6061: margin: 5px 0 5px 0;
6062: padding: 0;
6063: line-height:130%;
6064: }
6065:
6066: .LC_hcell {
6067: padding:3px 15px 3px 15px;
6068: margin: 0;
6069: background-color:$tabbg;
6070: color:$fontmenu;
6071: border-bottom:solid 1px $lg_border_color;
6072: }
6073:
6074: .LC_Box > .LC_hcell {
6075: margin: 0 -10px 10px -10px;
6076: }
6077:
6078: .LC_noBorder {
6079: border: 0;
6080: }
6081:
6082: .LC_FormSectionClearButton input {
6083: background-color:transparent;
6084: border: none;
6085: cursor:pointer;
6086: text-decoration:underline;
6087: }
6088:
6089: .LC_help_open_topic {
6090: color: #FFFFFF;
6091: background-color: #EEEEFF;
6092: margin: 1px;
6093: padding: 4px;
6094: border: 1px solid #000033;
6095: white-space: nowrap;
6096: /* vertical-align: middle; */
6097: }
6098:
6099: dl,
6100: ul,
6101: div,
6102: fieldset {
6103: margin: 10px 10px 10px 0;
6104: /* overflow: hidden; */
6105: }
6106:
6107: fieldset > legend {
6108: font-weight: bold;
6109: padding: 0 5px 0 5px;
6110: }
6111:
6112: #LC_nav_bar {
6113: float: left;
6114: margin: 0 0 2px 0;
6115: }
6116:
6117: #LC_realm {
6118: margin: 0.2em 0 0 0;
6119: padding: 0;
6120: font-weight: bold;
6121: text-align: center;
6122: }
6123:
6124: #LC_nav_bar em {
6125: font-weight: bold;
6126: font-style: normal;
6127: }
6128:
6129: /* Preliminary fix to hide nav_bar inside bookmarks window */
6130: #LC_bookmarks #LC_nav_bar {
6131: display:none;
6132: }
6133:
6134: ol.LC_primary_menu {
6135: float: right;
6136: margin: 0;
6137: }
6138:
6139: span.LC_new_message{
6140: font-weight:bold;
6141: color: darkred;
6142: }
6143:
6144: ol#LC_PathBreadcrumbs {
6145: margin: 0;
6146: }
6147:
6148: ol.LC_primary_menu li {
6149: display: inline;
6150: padding: 5px 5px 0 10px;
6151: vertical-align: top;
6152: }
6153:
6154: ol.LC_primary_menu li img {
6155: vertical-align: bottom;
6156: height: 1.1em;
6157: }
6158:
6159: ol.LC_primary_menu a {
6160: color: RGB(80, 80, 80);
6161: text-decoration: none;
6162: }
6163:
6164: ol.LC_docs_parameters {
6165: margin-left: 0;
6166: padding: 0;
6167: list-style: none;
6168: }
6169:
6170: ol.LC_docs_parameters li {
6171: margin: 0;
6172: padding-right: 20px;
6173: display: inline;
6174: }
6175:
6176: ol.LC_docs_parameters li:before {
6177: content: "\\002022 \\0020";
6178: }
6179:
6180: li.LC_docs_parameters_title {
6181: font-weight: bold;
6182: }
6183:
6184: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
6185: content: "";
6186: }
6187:
6188: ul#LC_secondary_menu {
6189: clear: both;
6190: color: $fontmenu;
6191: background: $tabbg;
6192: list-style: none;
6193: padding: 0;
6194: margin: 0;
6195: width: 100%;
6196: }
6197:
6198: ul#LC_secondary_menu li {
6199: font-weight: bold;
6200: line-height: 1.8em;
6201: padding: 0 0.8em;
6202: border-right: 1px solid black;
6203: display: inline;
6204: vertical-align: middle;
6205: }
6206:
6207: ul.LC_TabContent {
6208: display:block;
6209: background: $sidebg;
6210: border-bottom: solid 1px $lg_border_color;
6211: list-style:none;
6212: margin: 0 -10px;
6213: padding: 0;
6214: }
6215:
6216: ul.LC_TabContent li,
6217: ul.LC_TabContentBigger li {
6218: float:left;
6219: }
6220:
6221: ul#LC_secondary_menu li a {
6222: color: $fontmenu;
6223: text-decoration: none;
6224: }
6225:
6226: ul.LC_TabContent {
6227: min-height:20px;
6228: }
6229:
6230: ul.LC_TabContent li {
6231: vertical-align:middle;
6232: padding: 0 16px 0 10px;
6233: background-color:$tabbg;
6234: border-bottom:solid 1px $lg_border_color;
6235: border-right: solid 1px $font;
6236: }
6237:
6238: ul.LC_TabContent .right {
6239: float:right;
6240: }
6241:
6242: ul.LC_TabContent li a,
6243: ul.LC_TabContent li {
6244: color:rgb(47,47,47);
6245: text-decoration:none;
6246: font-size:95%;
6247: font-weight:bold;
6248: min-height:20px;
6249: }
6250:
6251: ul.LC_TabContent li a:hover,
6252: ul.LC_TabContent li a:focus {
6253: color: $button_hover;
6254: background:none;
6255: outline:none;
6256: }
6257:
6258: ul.LC_TabContent li:hover {
6259: color: $button_hover;
6260: cursor:pointer;
6261: }
6262:
6263: ul.LC_TabContent li.active {
6264: color: $font;
6265: background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
6266: border-bottom:solid 1px #FFFFFF;
6267: cursor: default;
6268: }
6269:
6270: ul.LC_TabContent li.active a {
6271: color:$font;
6272: background:#FFFFFF;
6273: outline: none;
6274: }
6275: #maincoursedoc {
6276: clear:both;
6277: }
6278:
6279: ul.LC_TabContentBigger {
6280: display:block;
6281: list-style:none;
6282: padding: 0;
6283: }
6284:
6285: ul.LC_TabContentBigger li {
6286: vertical-align:bottom;
6287: height: 30px;
6288: font-size:110%;
6289: font-weight:bold;
6290: color: #737373;
6291: }
6292:
6293: ul.LC_TabContentBigger li.active {
6294: position: relative;
6295: top: 1px;
6296: }
6297:
6298: ul.LC_TabContentBigger li a {
6299: background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
6300: height: 30px;
6301: line-height: 30px;
6302: text-align: center;
6303: display: block;
6304: text-decoration: none;
6305: outline: none;
6306: }
6307:
6308: ul.LC_TabContentBigger li.active a {
6309: background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
6310: color:$font;
6311: }
6312:
6313: ul.LC_TabContentBigger li b {
6314: background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
6315: display: block;
6316: float: left;
6317: padding: 0 30px;
6318: border-bottom: 1px solid $lg_border_color;
6319: }
6320:
6321: ul.LC_TabContentBigger li:hover b {
6322: color:$button_hover;
6323: }
6324:
6325: ul.LC_TabContentBigger li.active b {
6326: background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
6327: color:$font;
6328: border: 0;
6329: cursor:default;
6330: }
6331:
6332: ul.LC_CourseBreadcrumbs {
6333: background: $sidebg;
6334: line-height: 32px;
6335: padding-left: 10px;
6336: margin: 0 0 10px 0;
6337: list-style-position: inside;
6338:
6339: }
6340:
6341: ol#LC_MenuBreadcrumbs,
6342: ol#LC_PathBreadcrumbs {
6343: padding-left: 10px;
6344: margin: 0;
6345: height: 2.5em; /* equal to #LC_breadcrumbs line-height */
6346: }
6347:
6348: ol#LC_MenuBreadcrumbs li,
6349: ol#LC_PathBreadcrumbs li,
6350: ul.LC_CourseBreadcrumbs li {
6351: display: inline;
6352: white-space: normal;
6353: }
6354:
6355: ol#LC_MenuBreadcrumbs li a,
6356: ul.LC_CourseBreadcrumbs li a {
6357: text-decoration: none;
6358: font-size:90%;
6359: }
6360:
6361: ol#LC_MenuBreadcrumbs h1 {
6362: display: inline;
6363: font-size: 90%;
6364: line-height: 2.5em;
6365: margin: 0;
6366: padding: 0;
6367: }
6368:
6369: ol#LC_PathBreadcrumbs li a {
6370: text-decoration:none;
6371: font-size:100%;
6372: font-weight:bold;
6373: }
6374:
6375: .LC_Box {
6376: border: solid 1px $lg_border_color;
6377: padding: 0 10px 10px 10px;
6378: }
6379:
6380: .LC_AboutMe_Image {
6381: float:left;
6382: margin-right:10px;
6383: }
6384:
6385: .LC_Clear_AboutMe_Image {
6386: clear:left;
6387: }
6388:
6389: dl.LC_ListStyleClean dt {
6390: padding-right: 5px;
6391: display: table-header-group;
6392: }
6393:
6394: dl.LC_ListStyleClean dd {
6395: display: table-row;
6396: }
6397:
6398: .LC_ListStyleClean,
6399: .LC_ListStyleSimple,
6400: .LC_ListStyleNormal,
6401: .LC_ListStyleSpecial {
6402: /* display:block; */
6403: list-style-position: inside;
6404: list-style-type: none;
6405: overflow: hidden;
6406: padding: 0;
6407: }
6408:
6409: .LC_ListStyleSimple li,
6410: .LC_ListStyleSimple dd,
6411: .LC_ListStyleNormal li,
6412: .LC_ListStyleNormal dd,
6413: .LC_ListStyleSpecial li,
6414: .LC_ListStyleSpecial dd {
6415: margin: 0;
6416: padding: 5px 5px 5px 10px;
6417: clear: both;
6418: }
6419:
6420: .LC_ListStyleClean li,
6421: .LC_ListStyleClean dd {
6422: padding-top: 0;
6423: padding-bottom: 0;
6424: }
6425:
6426: .LC_ListStyleSimple dd,
6427: .LC_ListStyleSimple li {
6428: border-bottom: solid 1px $lg_border_color;
6429: }
6430:
6431: .LC_ListStyleSpecial li,
6432: .LC_ListStyleSpecial dd {
6433: list-style-type: none;
6434: background-color: RGB(220, 220, 220);
6435: margin-bottom: 4px;
6436: }
6437:
6438: table.LC_SimpleTable {
6439: margin:5px;
6440: border:solid 1px $lg_border_color;
6441: }
6442:
6443: table.LC_SimpleTable tr {
6444: padding: 0;
6445: border:solid 1px $lg_border_color;
6446: }
6447:
6448: table.LC_SimpleTable thead {
6449: background:rgb(220,220,220);
6450: }
6451:
6452: div.LC_columnSection {
6453: display: block;
6454: clear: both;
6455: overflow: hidden;
6456: margin: 0;
6457: }
6458:
6459: div.LC_columnSection>* {
6460: float: left;
6461: margin: 10px 20px 10px 0;
6462: overflow:hidden;
6463: }
6464:
6465: table em {
6466: font-weight: bold;
6467: font-style: normal;
6468: }
6469:
6470: table.LC_tableBrowseRes,
6471: table.LC_tableOfContent {
6472: border:none;
6473: border-spacing: 1px;
6474: padding: 3px;
6475: background-color: #FFFFFF;
6476: font-size: 90%;
6477: }
6478:
6479: table.LC_tableOfContent {
6480: border-collapse: collapse;
6481: }
6482:
6483: table.LC_tableBrowseRes a,
6484: table.LC_tableOfContent a {
6485: background-color: transparent;
6486: text-decoration: none;
6487: }
6488:
6489: table.LC_tableOfContent img {
6490: border: none;
6491: height: 1.3em;
6492: vertical-align: text-bottom;
6493: margin-right: 0.3em;
6494: }
6495:
6496: a#LC_content_toolbar_firsthomework {
6497: background-image:url(/res/adm/pages/open-first-problem.gif);
6498: }
6499:
6500: a#LC_content_toolbar_launchnav {
6501: background-image:url(/res/adm/pages/start-navigation.gif);
6502: }
6503:
6504: a#LC_content_toolbar_closenav {
6505: background-image:url(/res/adm/pages/close-navigation.gif);
6506: }
6507:
6508: a#LC_content_toolbar_everything {
6509: background-image:url(/res/adm/pages/show-all.gif);
6510: }
6511:
6512: a#LC_content_toolbar_uncompleted {
6513: background-image:url(/res/adm/pages/show-incomplete-problems.gif);
6514: }
6515:
6516: #LC_content_toolbar_clearbubbles {
6517: background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
6518: }
6519:
6520: a#LC_content_toolbar_changefolder {
6521: background : url(/res/adm/pages/close-all-folders.gif) top center ;
6522: }
6523:
6524: a#LC_content_toolbar_changefolder_toggled {
6525: background-image:url(/res/adm/pages/open-all-folders.gif);
6526: }
6527:
6528: ul#LC_toolbar li a:hover {
6529: background-position: bottom center;
6530: }
6531:
6532: ul#LC_toolbar {
6533: padding: 0;
6534: margin: 2px;
6535: list-style:none;
6536: position:relative;
6537: background-color:white;
6538: }
6539:
6540: ul#LC_toolbar li {
6541: border:1px solid white;
6542: padding: 0;
6543: margin: 0;
6544: float: left;
6545: display:inline;
6546: vertical-align:middle;
6547: }
6548:
6549:
6550: a.LC_toolbarItem {
6551: display:block;
6552: padding: 0;
6553: margin: 0;
6554: height: 32px;
6555: width: 32px;
6556: color:white;
6557: border: none;
6558: background-repeat:no-repeat;
6559: background-color:transparent;
6560: }
6561:
6562: ul.LC_funclist {
6563: margin: 0;
6564: padding: 0.5em 1em 0.5em 0;
6565: }
6566:
6567: ul.LC_funclist > li:first-child {
6568: font-weight:bold;
6569: margin-left:0.8em;
6570: }
6571:
6572: ul.LC_funclist + ul.LC_funclist {
6573: /*
6574: left border as a seperator if we have more than
6575: one list
6576: */
6577: border-left: 1px solid $sidebg;
6578: /*
6579: this hides the left border behind the border of the
6580: outer box if element is wrapped to the next 'line'
6581: */
6582: margin-left: -1px;
6583: }
6584:
6585: ul.LC_funclist li {
6586: display: inline;
6587: white-space: nowrap;
6588: margin: 0 0 0 25px;
6589: line-height: 150%;
6590: }
6591:
6592: .ui-accordion .LC_advanced_toggle {
6593: float: right;
6594: font-size: 90%;
6595: padding: 0px 4px
6596: }
6597:
6598: END
6599: }
6600:
6601: =pod
6602:
6603: =item * &headtag()
6604:
6605: Returns a uniform footer for LON-CAPA web pages.
6606:
6607: Inputs: $title - optional title for the head
6608: $head_extra - optional extra HTML to put inside the <head>
6609: $args - optional arguments
6610: force_register - if is true call registerurl so the remote is
6611: informed
6612: redirect -> array ref of
6613: 1- seconds before redirect occurs
6614: 2- url to redirect to
6615: 3- whether the side effect should occur
6616: (side effect of setting
6617: $env{'internal.head.redirect'} to the url
6618: redirected too)
6619: domain -> force to color decorate a page for a specific
6620: domain
6621: function -> force usage of a specific rolish color scheme
6622: bgcolor -> override the default page bgcolor
6623: no_auto_mt_title
6624: -> prevent &mt()ing the title arg
6625:
6626: =cut
6627:
6628: sub headtag {
6629: my ($title,$head_extra,$args) = @_;
6630:
6631: my $function = $args->{'function'} || &get_users_function();
6632: my $domain = $args->{'domain'} || &determinedomain();
6633: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
6634: my $url = join(':',$env{'user.name'},$env{'user.domain'},
6635: $Apache::lonnet::perlvar{'lonVersion'},
6636: #time(),
6637: $env{'environment.color.timestamp'},
6638: $function,$domain,$bgcolor);
6639:
6640: $url = '/adm/css/'.&escape($url).'.css';
6641:
6642: my $result =
6643: '<head>'.
6644: &font_settings();
6645:
6646: if (!$args->{'frameset'}) {
6647: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
6648: }
6649: if ($args->{'force_register'}) {
6650: $result .= &Apache::lonmenu::registerurl(1);
6651: }
6652: if (!$args->{'no_nav_bar'}
6653: && !$args->{'only_body'}
6654: && !$args->{'frameset'}) {
6655: $result .= &help_menu_js();
6656: }
6657:
6658: if (ref($args->{'redirect'})) {
6659: my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
6660: $url = &Apache::lonenc::check_encrypt($url);
6661: if (!$inhibit_continue) {
6662: $env{'internal.head.redirect'} = $url;
6663: }
6664: $result.=<<ADDMETA
6665: <meta http-equiv="pragma" content="no-cache" />
6666: <meta http-equiv="Refresh" content="$time; url=$url" />
6667: ADDMETA
6668: }
6669: if (!defined($title)) {
6670: $title = 'The LearningOnline Network with CAPA';
6671: }
6672: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
6673: $result .= '<title> LON-CAPA '.$title.'</title>'
6674: .'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
6675: .$head_extra;
6676: return $result;
6677: }
6678:
6679: =pod
6680:
6681: =item * &font_settings()
6682:
6683: Returns neccessary <meta> to set the proper encoding
6684:
6685: Inputs: none
6686:
6687: =cut
6688:
6689: sub font_settings {
6690: my $headerstring='';
6691: if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
6692: $headerstring.=
6693: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
6694: }
6695: return $headerstring;
6696: }
6697:
6698: =pod
6699:
6700: =item * &xml_begin()
6701:
6702: Returns the needed doctype and <html>
6703:
6704: Inputs: none
6705:
6706: =cut
6707:
6708: sub xml_begin {
6709: my $output='';
6710:
6711: if ($env{'browser.mathml'}) {
6712: $output='<?xml version="1.0"?>'
6713: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
6714: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
6715:
6716: # .'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" [<!ENTITY mathns "http://www.w3.org/1998/Math/MathML">] >'
6717: .'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">'
6718: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
6719: .'xmlns="http://www.w3.org/1999/xhtml">';
6720: } else {
6721: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
6722: .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
6723: }
6724: return $output;
6725: }
6726:
6727: =pod
6728:
6729: =item * &endheadtag()
6730:
6731: Returns a uniform </head> for LON-CAPA web pages.
6732:
6733: Inputs: none
6734:
6735: =cut
6736:
6737: sub endheadtag {
6738: return '</head>';
6739: }
6740:
6741: =pod
6742:
6743: =item * &head()
6744:
6745: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
6746:
6747: Inputs:
6748:
6749: =over 4
6750:
6751: $title - optional title for the page
6752:
6753: $head_extra - optional extra HTML to put inside the <head>
6754:
6755: =back
6756:
6757: =cut
6758:
6759: sub head {
6760: my ($title,$head_extra,$args) = @_;
6761: return &headtag($title,$head_extra,$args).&endheadtag();
6762: }
6763:
6764: =pod
6765:
6766: =item * &start_page()
6767:
6768: Returns a complete <html> .. <body> section for LON-CAPA web pages.
6769:
6770: Inputs:
6771:
6772: =over 4
6773:
6774: $title - optional title for the page
6775:
6776: $head_extra - optional extra HTML to incude inside the <head>
6777:
6778: $args - additional optional args supported are:
6779:
6780: =over 8
6781:
6782: only_body -> is true will set &bodytag() onlybodytag
6783: arg on
6784: no_nav_bar -> is true will set &bodytag() no_nav_bar arg on
6785: add_entries -> additional attributes to add to the <body>
6786: domain -> force to color decorate a page for a
6787: specific domain
6788: function -> force usage of a specific rolish color
6789: scheme
6790: redirect -> see &headtag()
6791: bgcolor -> override the default page bg color
6792: js_ready -> return a string ready for being used in
6793: a javascript writeln
6794: html_encode -> return a string ready for being used in
6795: a html attribute
6796: force_register -> if is true will turn on the &bodytag()
6797: $forcereg arg
6798: frameset -> if true will start with a <frameset>
6799: rather than <body>
6800: skip_phases -> hash ref of
6801: head -> skip the <html><head> generation
6802: body -> skip all <body> generation
6803: no_inline_link -> if true and in remote mode, don't show the
6804: 'Switch To Inline Menu' link
6805: no_auto_mt_title -> prevent &mt()ing the title arg
6806: inherit_jsmath -> when creating popup window in a page,
6807: should it have jsmath forced on by the
6808: current page
6809: bread_crumbs -> Array containing breadcrumbs
6810: bread_crumbs_components -> if exists show it as headline else show only the breadcrumbs
6811:
6812: =back
6813:
6814: =back
6815:
6816: =cut
6817:
6818: sub start_page {
6819: my ($title,$head_extra,$args) = @_;
6820: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
6821: my %head_args;
6822: foreach my $arg ('redirect','force_register','domain','function',
6823: 'bgcolor','frameset','no_nav_bar','only_body',
6824: 'no_auto_mt_title') {
6825: if (defined($args->{$arg})) {
6826: $head_args{$arg} = $args->{$arg};
6827: }
6828: }
6829:
6830: $env{'internal.start_page'}++;
6831: my $result;
6832: if (! exists($args->{'skip_phases'}{'head'}) ) {
6833: $result.=
6834: &xml_begin().
6835: &headtag($title,$head_extra,\%head_args).&endheadtag();
6836: }
6837:
6838: if (! exists($args->{'skip_phases'}{'body'}) ) {
6839: if ($args->{'frameset'}) {
6840: my $attr_string = &make_attr_string($args->{'force_register'},
6841: $args->{'add_entries'});
6842: $result .= "\n<frameset $attr_string>\n";
6843: } else {
6844: $result .=
6845: &bodytag($title,
6846: $args->{'function'}, $args->{'add_entries'},
6847: $args->{'only_body'}, $args->{'domain'},
6848: $args->{'force_register'}, $args->{'no_nav_bar'},
6849: $args->{'bgcolor'}, $args->{'no_inline_link'},
6850: $args);
6851: }
6852: }
6853:
6854: if ($args->{'js_ready'}) {
6855: $result = &js_ready($result);
6856: }
6857: if ($args->{'html_encode'}) {
6858: $result = &html_encode($result);
6859: }
6860:
6861: # Preparation for new and consistent functionlist at top of screen
6862: # if ($args->{'functionlist'}) {
6863: # $result .= &build_functionlist();
6864: #}
6865:
6866: # Don't add anything more if only_body wanted
6867: return $result if $args->{'only_body'};
6868:
6869: #Breadcrumbs for Construction Space provided by &bodytag.
6870: if (($env{'environment.remote'} eq 'off') && ($env{'request.state'} eq 'construct')) {
6871: return $result;
6872: }
6873:
6874: #Breadcrumbs
6875: if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
6876: &Apache::lonhtmlcommon::clear_breadcrumbs();
6877: #if any br links exists, add them to the breadcrumbs
6878: if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {
6879: foreach my $crumb (@{$args->{'bread_crumbs'}}){
6880: &Apache::lonhtmlcommon::add_breadcrumb($crumb);
6881: }
6882: }
6883:
6884: #if bread_crumbs_component exists show it as headline else show only the breadcrumbs
6885: if(exists($args->{'bread_crumbs_component'})){
6886: $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
6887: }else{
6888: $result .= &Apache::lonhtmlcommon::breadcrumbs();
6889: }
6890: }
6891: return $result;
6892: }
6893:
6894:
6895: =pod
6896:
6897: =item * &head()
6898:
6899: Returns a complete </body></html> section for LON-CAPA web pages.
6900:
6901: Inputs: $args - additional optional args supported are:
6902: js_ready -> return a string ready for being used in
6903: a javascript writeln
6904: html_encode -> return a string ready for being used in
6905: a html attribute
6906: frameset -> if true will start with a <frameset>
6907: rather than <body>
6908: dicsussion -> if true will get discussion from
6909: lonxml::xmlend
6910: (you can pass the target and parser arguments
6911: through optional 'target' and 'parser' args
6912: to this routine)
6913:
6914: =cut
6915:
6916: sub end_page {
6917: my ($args) = @_;
6918: $env{'internal.end_page'}++;
6919: my $result;
6920: if ($args->{'discussion'}) {
6921: my ($target,$parser);
6922: if (ref($args->{'discussion'})) {
6923: ($target,$parser) =($args->{'discussion'}{'target'},
6924: $args->{'discussion'}{'parser'});
6925: }
6926: $result .= &Apache::lonxml::xmlend($target,$parser);
6927: }
6928:
6929: if ($args->{'frameset'}) {
6930: $result .= '</frameset>';
6931: } else {
6932: $result .= &endbodytag($args);
6933: }
6934: $result .= "\n</html>";
6935:
6936: if ($args->{'js_ready'}) {
6937: $result = &js_ready($result);
6938: }
6939:
6940: if ($args->{'html_encode'}) {
6941: $result = &html_encode($result);
6942: }
6943:
6944: return $result;
6945: }
6946:
6947: sub html_encode {
6948: my ($result) = @_;
6949:
6950: $result = &HTML::Entities::encode($result,'<>&"');
6951:
6952: return $result;
6953: }
6954: sub js_ready {
6955: my ($result) = @_;
6956:
6957: $result =~ s/[\n\r]/ /xmsg;
6958: $result =~ s/\\/\\\\/xmsg;
6959: $result =~ s/'/\\'/xmsg;
6960: $result =~ s{</}{<\\/}xmsg;
6961:
6962: return $result;
6963: }
6964:
6965: sub validate_page {
6966: if ( exists($env{'internal.start_page'})
6967: && $env{'internal.start_page'} > 1) {
6968: &Apache::lonnet::logthis('start_page called multiple times '.
6969: $env{'internal.start_page'}.' '.
6970: $ENV{'request.filename'});
6971: }
6972: if ( exists($env{'internal.end_page'})
6973: && $env{'internal.end_page'} > 1) {
6974: &Apache::lonnet::logthis('end_page called multiple times '.
6975: $env{'internal.end_page'}.' '.
6976: $env{'request.filename'});
6977: }
6978: if ( exists($env{'internal.start_page'})
6979: && ! exists($env{'internal.end_page'})) {
6980: &Apache::lonnet::logthis('start_page called without end_page '.
6981: $env{'request.filename'});
6982: }
6983: if ( ! exists($env{'internal.start_page'})
6984: && exists($env{'internal.end_page'})) {
6985: &Apache::lonnet::logthis('end_page called without start_page'.
6986: $env{'request.filename'});
6987: }
6988: }
6989:
6990: sub simple_error_page {
6991: my ($r,$title,$msg) = @_;
6992: my $page =
6993: &Apache::loncommon::start_page($title).
6994: &mt($msg).
6995: &Apache::loncommon::end_page();
6996: if (ref($r)) {
6997: $r->print($page);
6998: return;
6999: }
7000: return $page;
7001: }
7002:
7003: {
7004: my @row_count;
7005:
7006: sub start_data_table_count {
7007: unshift(@row_count, 0);
7008: return;
7009: }
7010:
7011: sub end_data_table_count {
7012: shift(@row_count);
7013: return;
7014: }
7015:
7016: sub start_data_table {
7017: my ($add_class) = @_;
7018: my $css_class = (join(' ','LC_data_table',$add_class));
7019: &start_data_table_count();
7020: return '<table class="'.$css_class.'">'."\n";
7021: }
7022:
7023: sub end_data_table {
7024: &end_data_table_count();
7025: return '</table>'."\n";;
7026: }
7027:
7028: sub start_data_table_row {
7029: my ($add_class) = @_;
7030: $row_count[0]++;
7031: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
7032: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
7033: return '<tr class="'.$css_class.'">'."\n";;
7034: }
7035:
7036: sub continue_data_table_row {
7037: my ($add_class) = @_;
7038: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
7039: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');;
7040: return '<tr class="'.$css_class.'">'."\n";;
7041: }
7042:
7043: sub end_data_table_row {
7044: return '</tr>'."\n";;
7045: }
7046:
7047: sub start_data_table_empty_row {
7048: # $row_count[0]++;
7049: return '<tr class="LC_empty_row" >'."\n";;
7050: }
7051:
7052: sub end_data_table_empty_row {
7053: return '</tr>'."\n";;
7054: }
7055:
7056: sub start_data_table_header_row {
7057: return '<tr class="LC_header_row">'."\n";;
7058: }
7059:
7060: sub end_data_table_header_row {
7061: return '</tr>'."\n";;
7062: }
7063:
7064: sub data_table_caption {
7065: my $caption = shift;
7066: return "<caption class=\"LC_caption\">$caption</caption>";
7067: }
7068: }
7069:
7070: =pod
7071:
7072: =item * &inhibit_menu_check($arg)
7073:
7074: Checks for a inhibitmenu state and generates output to preserve it
7075:
7076: Inputs: $arg - can be any of
7077: - undef - in which case the return value is a string
7078: to add into arguments list of a uri
7079: - 'input' - in which case the return value is a HTML
7080: <form> <input> field of type hidden to
7081: preserve the value
7082: - a url - in which case the return value is the url with
7083: the neccesary cgi args added to preserve the
7084: inhibitmenu state
7085: - a ref to a url - no return value, but the string is
7086: updated to include the neccessary cgi
7087: args to preserve the inhibitmenu state
7088:
7089: =cut
7090:
7091: sub inhibit_menu_check {
7092: my ($arg) = @_;
7093: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
7094: if ($arg eq 'input') {
7095: if ($env{'form.inhibitmenu'}) {
7096: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
7097: } else {
7098: return
7099: }
7100: }
7101: if ($env{'form.inhibitmenu'}) {
7102: if (ref($arg)) {
7103: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
7104: } elsif ($arg eq '') {
7105: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
7106: } else {
7107: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
7108: }
7109: }
7110: if (!ref($arg)) {
7111: return $arg;
7112: }
7113: }
7114:
7115: ###############################################
7116:
7117: =pod
7118:
7119: =back
7120:
7121: =head1 User Information Routines
7122:
7123: =over 4
7124:
7125: =item * &get_users_function()
7126:
7127: Used by &bodytag to determine the current users primary role.
7128: Returns either 'student','coordinator','admin', or 'author'.
7129:
7130: =cut
7131:
7132: ###############################################
7133: sub get_users_function {
7134: my $function = 'norole';
7135: if ($env{'request.role'}=~/^(st)/) {
7136: $function='student';
7137: }
7138: if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
7139: $function='coordinator';
7140: }
7141: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
7142: $function='admin';
7143: }
7144: if (($env{'request.role'}=~/^(au|ca|aa)/) ||
7145: ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
7146: $function='author';
7147: }
7148: return $function;
7149: }
7150:
7151: ###############################################
7152:
7153: =pod
7154:
7155: =item * &show_course()
7156:
7157: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
7158: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
7159:
7160: Inputs:
7161: None
7162:
7163: Outputs:
7164: Scalar: 1 if 'Course' to be used, 0 otherwise.
7165:
7166: =cut
7167:
7168: ###############################################
7169: sub show_course {
7170: my $course = !$env{'user.adv'};
7171: if (!$env{'user.adv'}) {
7172: foreach my $env (keys(%env)) {
7173: next if ($env !~ m/^user\.priv\./);
7174: if ($env !~ m/^user\.priv\.(?:st|cm)/) {
7175: $course = 0;
7176: last;
7177: }
7178: }
7179: }
7180: return $course;
7181: }
7182:
7183: ###############################################
7184:
7185: =pod
7186:
7187: =item * &check_user_status()
7188:
7189: Determines current status of supplied role for a
7190: specific user. Roles can be active, previous or future.
7191:
7192: Inputs:
7193: user's domain, user's username, course's domain,
7194: course's number, optional section ID.
7195:
7196: Outputs:
7197: role status: active, previous or future.
7198:
7199: =cut
7200:
7201: sub check_user_status {
7202: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
7203: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
7204: my @uroles = keys %userinfo;
7205: my $srchstr;
7206: my $active_chk = 'none';
7207: my $now = time;
7208: if (@uroles > 0) {
7209: if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
7210: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
7211: } else {
7212: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
7213: }
7214: if (grep/^\Q$srchstr\E$/,@uroles) {
7215: my $role_end = 0;
7216: my $role_start = 0;
7217: $active_chk = 'active';
7218: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
7219: $role_end = $1;
7220: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
7221: $role_start = $1;
7222: }
7223: }
7224: if ($role_start > 0) {
7225: if ($now < $role_start) {
7226: $active_chk = 'future';
7227: }
7228: }
7229: if ($role_end > 0) {
7230: if ($now > $role_end) {
7231: $active_chk = 'previous';
7232: }
7233: }
7234: }
7235: }
7236: return $active_chk;
7237: }
7238:
7239: ###############################################
7240:
7241: =pod
7242:
7243: =item * &get_sections()
7244:
7245: Determines all the sections for a course including
7246: sections with students and sections containing other roles.
7247: Incoming parameters:
7248:
7249: 1. domain
7250: 2. course number
7251: 3. reference to array containing roles for which sections should
7252: be gathered (optional).
7253: 4. reference to array containing status types for which sections
7254: should be gathered (optional).
7255:
7256: If the third argument is undefined, sections are gathered for any role.
7257: If the fourth argument is undefined, sections are gathered for any status.
7258: Permissible values are 'active' or 'future' or 'previous'.
7259:
7260: Returns section hash (keys are section IDs, values are
7261: number of users in each section), subject to the
7262: optional roles filter, optional status filter
7263:
7264: =cut
7265:
7266: ###############################################
7267: sub get_sections {
7268: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
7269: if (!defined($cdom) || !defined($cnum)) {
7270: my $cid = $env{'request.course.id'};
7271:
7272: return if (!defined($cid));
7273:
7274: $cdom = $env{'course.'.$cid.'.domain'};
7275: $cnum = $env{'course.'.$cid.'.num'};
7276: }
7277:
7278: my %sectioncount;
7279: my $now = time;
7280:
7281: if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
7282: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
7283: my $sec_index = &Apache::loncoursedata::CL_SECTION();
7284: my $status_index = &Apache::loncoursedata::CL_STATUS();
7285: my $start_index = &Apache::loncoursedata::CL_START();
7286: my $end_index = &Apache::loncoursedata::CL_END();
7287: my $status;
7288: while (my ($student,$data) = each(%$classlist)) {
7289: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
7290: $data->[$status_index],
7291: $data->[$start_index],
7292: $data->[$end_index]);
7293: if ($stu_status eq 'Active') {
7294: $status = 'active';
7295: } elsif ($end < $now) {
7296: $status = 'previous';
7297: } elsif ($start > $now) {
7298: $status = 'future';
7299: }
7300: if ($section ne '-1' && $section !~ /^\s*$/) {
7301: if ((!defined($possible_status)) || (($status ne '') &&
7302: (grep/^\Q$status\E$/,@{$possible_status}))) {
7303: $sectioncount{$section}++;
7304: }
7305: }
7306: }
7307: }
7308: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
7309: foreach my $user (sort(keys(%courseroles))) {
7310: if ($user !~ /^(\w{2})/) { next; }
7311: my ($role) = ($user =~ /^(\w{2})/);
7312: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
7313: my ($section,$status);
7314: if ($role eq 'cr' &&
7315: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
7316: $section=$1;
7317: }
7318: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
7319: if (!defined($section) || $section eq '-1') { next; }
7320: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
7321: if ($end == -1 && $start == -1) {
7322: next; #deleted role
7323: }
7324: if (!defined($possible_status)) {
7325: $sectioncount{$section}++;
7326: } else {
7327: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
7328: $status = 'active';
7329: } elsif ($end < $now) {
7330: $status = 'future';
7331: } elsif ($start > $now) {
7332: $status = 'previous';
7333: }
7334: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
7335: $sectioncount{$section}++;
7336: }
7337: }
7338: }
7339: return %sectioncount;
7340: }
7341:
7342: ###############################################
7343:
7344: =pod
7345:
7346: =item * &get_course_users()
7347:
7348: Retrieves usernames:domains for users in the specified course
7349: with specific role(s), and access status.
7350:
7351: Incoming parameters:
7352: 1. course domain
7353: 2. course number
7354: 3. access status: users must have - either active,
7355: previous, future, or all.
7356: 4. reference to array of permissible roles
7357: 5. reference to array of section restrictions (optional)
7358: 6. reference to results object (hash of hashes).
7359: 7. reference to optional userdata hash
7360: 8. reference to optional statushash
7361: 9. flag if privileged users (except those set to unhide in
7362: course settings) should be excluded
7363: Keys of top level results hash are roles.
7364: Keys of inner hashes are username:domain, with
7365: values set to access type.
7366: Optional userdata hash returns an array with arguments in the
7367: same order as loncoursedata::get_classlist() for student data.
7368:
7369: Optional statushash returns
7370:
7371: Entries for end, start, section and status are blank because
7372: of the possibility of multiple values for non-student roles.
7373:
7374: =cut
7375:
7376: ###############################################
7377:
7378: sub get_course_users {
7379: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
7380: my %idx = ();
7381: my %seclists;
7382:
7383: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
7384: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
7385: $idx{end} = &Apache::loncoursedata::CL_END();
7386: $idx{start} = &Apache::loncoursedata::CL_START();
7387: $idx{id} = &Apache::loncoursedata::CL_ID();
7388: $idx{section} = &Apache::loncoursedata::CL_SECTION();
7389: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
7390: $idx{status} = &Apache::loncoursedata::CL_STATUS();
7391:
7392: if (grep(/^st$/,@{$roles})) {
7393: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
7394: my $now = time;
7395: foreach my $student (keys(%{$classlist})) {
7396: my $match = 0;
7397: my $secmatch = 0;
7398: my $section = $$classlist{$student}[$idx{section}];
7399: my $status = $$classlist{$student}[$idx{status}];
7400: if ($section eq '') {
7401: $section = 'none';
7402: }
7403: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
7404: if (grep(/^all$/,@{$sections})) {
7405: $secmatch = 1;
7406: } elsif ($$classlist{$student}[$idx{section}] eq '') {
7407: if (grep(/^none$/,@{$sections})) {
7408: $secmatch = 1;
7409: }
7410: } else {
7411: if (grep(/^\Q$section\E$/,@{$sections})) {
7412: $secmatch = 1;
7413: }
7414: }
7415: if (!$secmatch) {
7416: next;
7417: }
7418: }
7419: if (defined($$types{'active'})) {
7420: if ($$classlist{$student}[$idx{status}] eq 'Active') {
7421: push(@{$$users{st}{$student}},'active');
7422: $match = 1;
7423: }
7424: }
7425: if (defined($$types{'previous'})) {
7426: if ($$classlist{$student}[$idx{status}] eq 'Expired') {
7427: push(@{$$users{st}{$student}},'previous');
7428: $match = 1;
7429: }
7430: }
7431: if (defined($$types{'future'})) {
7432: if ($$classlist{$student}[$idx{status}] eq 'Future') {
7433: push(@{$$users{st}{$student}},'future');
7434: $match = 1;
7435: }
7436: }
7437: if ($match) {
7438: push(@{$seclists{$student}},$section);
7439: if (ref($userdata) eq 'HASH') {
7440: $$userdata{$student} = $$classlist{$student};
7441: }
7442: if (ref($statushash) eq 'HASH') {
7443: $statushash->{$student}{'st'}{$section} = $status;
7444: }
7445: }
7446: }
7447: }
7448: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
7449: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
7450: my $now = time;
7451: my %displaystatus = ( previous => 'Expired',
7452: active => 'Active',
7453: future => 'Future',
7454: );
7455: my %nothide;
7456: if ($hidepriv) {
7457: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
7458: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
7459: if ($user !~ /:/) {
7460: $nothide{join(':',split(/[\@]/,$user))}=1;
7461: } else {
7462: $nothide{$user} = 1;
7463: }
7464: }
7465: }
7466: foreach my $person (sort(keys(%coursepersonnel))) {
7467: my $match = 0;
7468: my $secmatch = 0;
7469: my $status;
7470: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
7471: $user =~ s/:$//;
7472: my ($end,$start) = split(/:/,$coursepersonnel{$person});
7473: if ($end == -1 || $start == -1) {
7474: next;
7475: }
7476: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
7477: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
7478: my ($uname,$udom) = split(/:/,$user);
7479: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
7480: if (grep(/^all$/,@{$sections})) {
7481: $secmatch = 1;
7482: } elsif ($usec eq '') {
7483: if (grep(/^none$/,@{$sections})) {
7484: $secmatch = 1;
7485: }
7486: } else {
7487: if (grep(/^\Q$usec\E$/,@{$sections})) {
7488: $secmatch = 1;
7489: }
7490: }
7491: if (!$secmatch) {
7492: next;
7493: }
7494: }
7495: if ($usec eq '') {
7496: $usec = 'none';
7497: }
7498: if ($uname ne '' && $udom ne '') {
7499: if ($hidepriv) {
7500: if ((&Apache::lonnet::privileged($uname,$udom)) &&
7501: (!$nothide{$uname.':'.$udom})) {
7502: next;
7503: }
7504: }
7505: if ($end > 0 && $end < $now) {
7506: $status = 'previous';
7507: } elsif ($start > $now) {
7508: $status = 'future';
7509: } else {
7510: $status = 'active';
7511: }
7512: foreach my $type (keys(%{$types})) {
7513: if ($status eq $type) {
7514: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
7515: push(@{$$users{$role}{$user}},$type);
7516: }
7517: $match = 1;
7518: }
7519: }
7520: if (($match) && (ref($userdata) eq 'HASH')) {
7521: if (!exists($$userdata{$uname.':'.$udom})) {
7522: &get_user_info($udom,$uname,\%idx,$userdata);
7523: }
7524: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
7525: push(@{$seclists{$uname.':'.$udom}},$usec);
7526: }
7527: if (ref($statushash) eq 'HASH') {
7528: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
7529: }
7530: }
7531: }
7532: }
7533: }
7534: if (grep(/^ow$/,@{$roles})) {
7535: if ((defined($cdom)) && (defined($cnum))) {
7536: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
7537: if ( defined($csettings{'internal.courseowner'}) ) {
7538: my $owner = $csettings{'internal.courseowner'};
7539: next if ($owner eq '');
7540: my ($ownername,$ownerdom);
7541: if ($owner =~ /^([^:]+):([^:]+)$/) {
7542: $ownername = $1;
7543: $ownerdom = $2;
7544: } else {
7545: $ownername = $owner;
7546: $ownerdom = $cdom;
7547: $owner = $ownername.':'.$ownerdom;
7548: }
7549: @{$$users{'ow'}{$owner}} = 'any';
7550: if (defined($userdata) &&
7551: !exists($$userdata{$owner})) {
7552: &get_user_info($ownerdom,$ownername,\%idx,$userdata);
7553: if (!grep(/^none$/,@{$seclists{$owner}})) {
7554: push(@{$seclists{$owner}},'none');
7555: }
7556: if (ref($statushash) eq 'HASH') {
7557: $statushash->{$owner}{'ow'}{'none'} = 'Any';
7558: }
7559: }
7560: }
7561: }
7562: }
7563: foreach my $user (keys(%seclists)) {
7564: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
7565: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
7566: }
7567: }
7568: return;
7569: }
7570:
7571: sub get_user_info {
7572: my ($udom,$uname,$idx,$userdata) = @_;
7573: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
7574: &plainname($uname,$udom,'lastname');
7575: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
7576: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
7577: my %idhash = &Apache::lonnet::idrget($udom,($uname));
7578: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname};
7579: return;
7580: }
7581:
7582: ###############################################
7583:
7584: =pod
7585:
7586: =item * &get_user_quota()
7587:
7588: Retrieves quota assigned for storage of portfolio files for a user
7589:
7590: Incoming parameters:
7591: 1. user's username
7592: 2. user's domain
7593:
7594: Returns:
7595: 1. Disk quota (in Mb) assigned to student.
7596: 2. (Optional) Type of setting: custom or default
7597: (individually assigned or default for user's
7598: institutional status).
7599: 3. (Optional) - User's institutional status (e.g., faculty, staff
7600: or student - types as defined in localenroll::inst_usertypes
7601: for user's domain, which determines default quota for user.
7602: 4. (Optional) - Default quota which would apply to the user.
7603:
7604: If a value has been stored in the user's environment,
7605: it will return that, otherwise it returns the maximal default
7606: defined for the user's instituional status(es) in the domain.
7607:
7608: =cut
7609:
7610: ###############################################
7611:
7612:
7613: sub get_user_quota {
7614: my ($uname,$udom) = @_;
7615: my ($quota,$quotatype,$settingstatus,$defquota);
7616: if (!defined($udom)) {
7617: $udom = $env{'user.domain'};
7618: }
7619: if (!defined($uname)) {
7620: $uname = $env{'user.name'};
7621: }
7622: if (($udom eq '' || $uname eq '') ||
7623: ($udom eq 'public') && ($uname eq 'public')) {
7624: $quota = 0;
7625: $quotatype = 'default';
7626: $defquota = 0;
7627: } else {
7628: my $inststatus;
7629: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
7630: $quota = $env{'environment.portfolioquota'};
7631: $inststatus = $env{'environment.inststatus'};
7632: } else {
7633: my %userenv =
7634: &Apache::lonnet::get('environment',['portfolioquota',
7635: 'inststatus'],$udom,$uname);
7636: my ($tmp) = keys(%userenv);
7637: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
7638: $quota = $userenv{'portfolioquota'};
7639: $inststatus = $userenv{'inststatus'};
7640: } else {
7641: undef(%userenv);
7642: }
7643: }
7644: ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
7645: if ($quota eq '') {
7646: $quota = $defquota;
7647: $quotatype = 'default';
7648: } else {
7649: $quotatype = 'custom';
7650: }
7651: }
7652: if (wantarray) {
7653: return ($quota,$quotatype,$settingstatus,$defquota);
7654: } else {
7655: return $quota;
7656: }
7657: }
7658:
7659: ###############################################
7660:
7661: =pod
7662:
7663: =item * &default_quota()
7664:
7665: Retrieves default quota assigned for storage of user portfolio files,
7666: given an (optional) user's institutional status.
7667:
7668: Incoming parameters:
7669: 1. domain
7670: 2. (Optional) institutional status(es). This is a : separated list of
7671: status types (e.g., faculty, staff, student etc.)
7672: which apply to the user for whom the default is being retrieved.
7673: If the institutional status string in undefined, the domain
7674: default quota will be returned.
7675:
7676: Returns:
7677: 1. Default disk quota (in Mb) for user portfolios in the domain.
7678: 2. (Optional) institutional type which determined the value of the
7679: default quota.
7680:
7681: If a value has been stored in the domain's configuration db,
7682: it will return that, otherwise it returns 20 (for backwards
7683: compatibility with domains which have not set up a configuration
7684: db file; the original statically defined portfolio quota was 20 Mb).
7685:
7686: If the user's status includes multiple types (e.g., staff and student),
7687: the largest default quota which applies to the user determines the
7688: default quota returned.
7689:
7690: =back
7691:
7692: =cut
7693:
7694: ###############################################
7695:
7696:
7697: sub default_quota {
7698: my ($udom,$inststatus) = @_;
7699: my ($defquota,$settingstatus);
7700: my %quotahash = &Apache::lonnet::get_dom('configuration',
7701: ['quotas'],$udom);
7702: if (ref($quotahash{'quotas'}) eq 'HASH') {
7703: if ($inststatus ne '') {
7704: my @statuses = map { &unescape($_); } split(/:/,$inststatus);
7705: foreach my $item (@statuses) {
7706: if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
7707: if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
7708: if ($defquota eq '') {
7709: $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
7710: $settingstatus = $item;
7711: } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
7712: $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
7713: $settingstatus = $item;
7714: }
7715: }
7716: } else {
7717: if ($quotahash{'quotas'}{$item} ne '') {
7718: if ($defquota eq '') {
7719: $defquota = $quotahash{'quotas'}{$item};
7720: $settingstatus = $item;
7721: } elsif ($quotahash{'quotas'}{$item} > $defquota) {
7722: $defquota = $quotahash{'quotas'}{$item};
7723: $settingstatus = $item;
7724: }
7725: }
7726: }
7727: }
7728: }
7729: if ($defquota eq '') {
7730: if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
7731: $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
7732: } else {
7733: $defquota = $quotahash{'quotas'}{'default'};
7734: }
7735: $settingstatus = 'default';
7736: }
7737: } else {
7738: $settingstatus = 'default';
7739: $defquota = 20;
7740: }
7741: if (wantarray) {
7742: return ($defquota,$settingstatus);
7743: } else {
7744: return $defquota;
7745: }
7746: }
7747:
7748: sub get_secgrprole_info {
7749: my ($cdom,$cnum,$needroles,$type) = @_;
7750: my %sections_count = &get_sections($cdom,$cnum);
7751: my @sections = (sort {$a <=> $b} keys(%sections_count));
7752: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
7753: my @groups = sort(keys(%curr_groups));
7754: my $allroles = [];
7755: my $rolehash;
7756: my $accesshash = {
7757: active => 'Currently has access',
7758: future => 'Will have future access',
7759: previous => 'Previously had access',
7760: };
7761: if ($needroles) {
7762: $rolehash = {'all' => 'all'};
7763: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
7764: if (&Apache::lonnet::error(%user_roles)) {
7765: undef(%user_roles);
7766: }
7767: foreach my $item (keys(%user_roles)) {
7768: my ($role)=split(/\:/,$item,2);
7769: if ($role eq 'cr') { next; }
7770: if ($role =~ /^cr/) {
7771: $$rolehash{$role} = (split('/',$role))[3];
7772: } else {
7773: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
7774: }
7775: }
7776: foreach my $key (sort(keys(%{$rolehash}))) {
7777: push(@{$allroles},$key);
7778: }
7779: push (@{$allroles},'st');
7780: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
7781: }
7782: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
7783: }
7784:
7785: sub user_picker {
7786: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
7787: my $currdom = $dom;
7788: my %curr_selected = (
7789: srchin => 'dom',
7790: srchby => 'lastname',
7791: );
7792: my $srchterm;
7793: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
7794: if ($srch->{'srchby'} ne '') {
7795: $curr_selected{'srchby'} = $srch->{'srchby'};
7796: }
7797: if ($srch->{'srchin'} ne '') {
7798: $curr_selected{'srchin'} = $srch->{'srchin'};
7799: }
7800: if ($srch->{'srchtype'} ne '') {
7801: $curr_selected{'srchtype'} = $srch->{'srchtype'};
7802: }
7803: if ($srch->{'srchdomain'} ne '') {
7804: $currdom = $srch->{'srchdomain'};
7805: }
7806: $srchterm = $srch->{'srchterm'};
7807: }
7808: my %lt=&Apache::lonlocal::texthash(
7809: 'usr' => 'Search criteria',
7810: 'doma' => 'Domain/institution to search',
7811: 'uname' => 'username',
7812: 'lastname' => 'last name',
7813: 'lastfirst' => 'last name, first name',
7814: 'crs' => 'in this course',
7815: 'dom' => 'in selected LON-CAPA domain',
7816: 'alc' => 'all LON-CAPA',
7817: 'instd' => 'in institutional directory for selected domain',
7818: 'exact' => 'is',
7819: 'contains' => 'contains',
7820: 'begins' => 'begins with',
7821: 'youm' => "You must include some text to search for.",
7822: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
7823: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
7824: 'yomc' => "You must choose a domain when using an institutional directory search.",
7825: 'ymcd' => "You must choose a domain when using a domain search.",
7826: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.",
7827: 'whse' => "When searching by last,first you must include at least one character in the first name.",
7828: 'thfo' => "The following need to be corrected before the search can be run:",
7829: );
7830: my $domform = &select_dom_form($currdom,'srchdomain',1,1);
7831: my $srchinsel = ' <select name="srchin">';
7832:
7833: my @srchins = ('crs','dom','alc','instd');
7834:
7835: foreach my $option (@srchins) {
7836: # FIXME 'alc' option unavailable until
7837: # loncreateuser::print_user_query_page()
7838: # has been completed.
7839: next if ($option eq 'alc');
7840: next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));
7841: next if ($option eq 'crs' && !$env{'request.course.id'});
7842: if ($curr_selected{'srchin'} eq $option) {
7843: $srchinsel .= '
7844: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
7845: } else {
7846: $srchinsel .= '
7847: <option value="'.$option.'">'.$lt{$option}.'</option>';
7848: }
7849: }
7850: $srchinsel .= "\n </select>\n";
7851:
7852: my $srchbysel = ' <select name="srchby">';
7853: foreach my $option ('lastname','lastfirst','uname') {
7854: if ($curr_selected{'srchby'} eq $option) {
7855: $srchbysel .= '
7856: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
7857: } else {
7858: $srchbysel .= '
7859: <option value="'.$option.'">'.$lt{$option}.'</option>';
7860: }
7861: }
7862: $srchbysel .= "\n </select>\n";
7863:
7864: my $srchtypesel = ' <select name="srchtype">';
7865: foreach my $option ('begins','contains','exact') {
7866: if ($curr_selected{'srchtype'} eq $option) {
7867: $srchtypesel .= '
7868: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
7869: } else {
7870: $srchtypesel .= '
7871: <option value="'.$option.'">'.$lt{$option}.'</option>';
7872: }
7873: }
7874: $srchtypesel .= "\n </select>\n";
7875:
7876: my ($newuserscript,$new_user_create);
7877:
7878: if ($forcenewuser) {
7879: if (ref($srch) eq 'HASH') {
7880: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
7881: if ($cancreate) {
7882: $new_user_create = '<p> <input type="submit" name="forcenew" value="'.&HTML::Entities::encode(&mt('Make new user "[_1]"',$srchterm),'<>&"').'" onclick="javascript:setSearch(\'1\','.$caller.');" /> </p>';
7883: } else {
7884: my $helplink = 'javascript:helpMenu('."'display'".')';
7885: my %usertypetext = (
7886: official => 'institutional',
7887: unofficial => 'non-institutional',
7888: );
7889: $new_user_create = '<p class="LC_warning">'
7890: .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
7891: .' '
7892: .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
7893: ,'<a href="'.$helplink.'">','</a>')
7894: .'</p><br />';
7895: }
7896: }
7897: }
7898:
7899: $newuserscript = <<"ENDSCRIPT";
7900:
7901: function setSearch(createnew,callingForm) {
7902: if (createnew == 1) {
7903: for (var i=0; i<callingForm.srchby.length; i++) {
7904: if (callingForm.srchby.options[i].value == 'uname') {
7905: callingForm.srchby.selectedIndex = i;
7906: }
7907: }
7908: for (var i=0; i<callingForm.srchin.length; i++) {
7909: if ( callingForm.srchin.options[i].value == 'dom') {
7910: callingForm.srchin.selectedIndex = i;
7911: }
7912: }
7913: for (var i=0; i<callingForm.srchtype.length; i++) {
7914: if (callingForm.srchtype.options[i].value == 'exact') {
7915: callingForm.srchtype.selectedIndex = i;
7916: }
7917: }
7918: for (var i=0; i<callingForm.srchdomain.length; i++) {
7919: if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
7920: callingForm.srchdomain.selectedIndex = i;
7921: }
7922: }
7923: }
7924: }
7925: ENDSCRIPT
7926:
7927: }
7928:
7929: my $output = <<"END_BLOCK";
7930: <script type="text/javascript">
7931: // <![CDATA[
7932: function validateEntry(callingForm) {
7933:
7934: var checkok = 1;
7935: var srchin;
7936: for (var i=0; i<callingForm.srchin.length; i++) {
7937: if ( callingForm.srchin[i].checked ) {
7938: srchin = callingForm.srchin[i].value;
7939: }
7940: }
7941:
7942: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
7943: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
7944: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
7945: var srchterm = callingForm.srchterm.value;
7946: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
7947: var msg = "";
7948:
7949: if (srchterm == "") {
7950: checkok = 0;
7951: msg += "$lt{'youm'}\\n";
7952: }
7953:
7954: if (srchtype== 'begins') {
7955: if (srchterm.length < 2) {
7956: checkok = 0;
7957: msg += "$lt{'thte'}\\n";
7958: }
7959: }
7960:
7961: if (srchtype== 'contains') {
7962: if (srchterm.length < 3) {
7963: checkok = 0;
7964: msg += "$lt{'thet'}\\n";
7965: }
7966: }
7967: if (srchin == 'instd') {
7968: if (srchdomain == '') {
7969: checkok = 0;
7970: msg += "$lt{'yomc'}\\n";
7971: }
7972: }
7973: if (srchin == 'dom') {
7974: if (srchdomain == '') {
7975: checkok = 0;
7976: msg += "$lt{'ymcd'}\\n";
7977: }
7978: }
7979: if (srchby == 'lastfirst') {
7980: if (srchterm.indexOf(",") == -1) {
7981: checkok = 0;
7982: msg += "$lt{'whus'}\\n";
7983: }
7984: if (srchterm.indexOf(",") == srchterm.length -1) {
7985: checkok = 0;
7986: msg += "$lt{'whse'}\\n";
7987: }
7988: }
7989: if (checkok == 0) {
7990: alert("$lt{'thfo'}\\n"+msg);
7991: return;
7992: }
7993: if (checkok == 1) {
7994: callingForm.submit();
7995: }
7996: }
7997:
7998: $newuserscript
7999:
8000: // ]]>
8001: </script>
8002:
8003: $new_user_create
8004:
8005: END_BLOCK
8006:
8007: $output .= &Apache::lonhtmlcommon::start_pick_box().
8008: &Apache::lonhtmlcommon::row_title($lt{'doma'}).
8009: $domform.
8010: &Apache::lonhtmlcommon::row_closure().
8011: &Apache::lonhtmlcommon::row_title($lt{'usr'}).
8012: $srchbysel.
8013: $srchtypesel.
8014: '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
8015: $srchinsel.
8016: &Apache::lonhtmlcommon::row_closure(1).
8017: &Apache::lonhtmlcommon::end_pick_box().
8018: '<br />';
8019: return $output;
8020: }
8021:
8022: sub user_rule_check {
8023: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
8024: my $response;
8025: if (ref($usershash) eq 'HASH') {
8026: foreach my $user (keys(%{$usershash})) {
8027: my ($uname,$udom) = split(/:/,$user);
8028: next if ($udom eq '' || $uname eq '');
8029: my ($id,$newuser);
8030: if (ref($usershash->{$user}) eq 'HASH') {
8031: $newuser = $usershash->{$user}->{'newuser'};
8032: $id = $usershash->{$user}->{'id'};
8033: }
8034: my $inst_response;
8035: if (ref($checks) eq 'HASH') {
8036: if (defined($checks->{'username'})) {
8037: ($inst_response,%{$inst_results->{$user}}) =
8038: &Apache::lonnet::get_instuser($udom,$uname);
8039: } elsif (defined($checks->{'id'})) {
8040: ($inst_response,%{$inst_results->{$user}}) =
8041: &Apache::lonnet::get_instuser($udom,undef,$id);
8042: }
8043: } else {
8044: ($inst_response,%{$inst_results->{$user}}) =
8045: &Apache::lonnet::get_instuser($udom,$uname);
8046: return;
8047: }
8048: if (!$got_rules->{$udom}) {
8049: my %domconfig = &Apache::lonnet::get_dom('configuration',
8050: ['usercreation'],$udom);
8051: if (ref($domconfig{'usercreation'}) eq 'HASH') {
8052: foreach my $item ('username','id') {
8053: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
8054: $$curr_rules{$udom}{$item} =
8055: $domconfig{'usercreation'}{$item.'_rule'};
8056: }
8057: }
8058: }
8059: $got_rules->{$udom} = 1;
8060: }
8061: foreach my $item (keys(%{$checks})) {
8062: if (ref($$curr_rules{$udom}) eq 'HASH') {
8063: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
8064: if (@{$$curr_rules{$udom}{$item}} > 0) {
8065: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
8066: foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
8067: if ($rule_check{$rule}) {
8068: $$rulematch{$user}{$item} = $rule;
8069: if ($inst_response eq 'ok') {
8070: if (ref($inst_results) eq 'HASH') {
8071: if (ref($inst_results->{$user}) eq 'HASH') {
8072: if (keys(%{$inst_results->{$user}}) == 0) {
8073: $$alerts{$item}{$udom}{$uname} = 1;
8074: }
8075: }
8076: }
8077: }
8078: last;
8079: }
8080: }
8081: }
8082: }
8083: }
8084: }
8085: }
8086: }
8087: return;
8088: }
8089:
8090: sub user_rule_formats {
8091: my ($domain,$domdesc,$curr_rules,$check) = @_;
8092: my %text = (
8093: 'username' => 'Usernames',
8094: 'id' => 'IDs',
8095: );
8096: my $output;
8097: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
8098: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
8099: if (@{$ruleorder} > 0) {
8100: $output = '<br />'.&mt("$text{$check} with the following format(s) may <span class=\"LC_cusr_emph\">only</span> be used for verified users at [_1]:",$domdesc).' <ul>';
8101: foreach my $rule (@{$ruleorder}) {
8102: if (ref($curr_rules) eq 'ARRAY') {
8103: if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
8104: if (ref($rules->{$rule}) eq 'HASH') {
8105: $output .= '<li>'.$rules->{$rule}{'name'}.': '.
8106: $rules->{$rule}{'desc'}.'</li>';
8107: }
8108: }
8109: }
8110: }
8111: $output .= '</ul>';
8112: }
8113: }
8114: return $output;
8115: }
8116:
8117: sub instrule_disallow_msg {
8118: my ($checkitem,$domdesc,$count,$mode) = @_;
8119: my $response;
8120: my %text = (
8121: item => 'username',
8122: items => 'usernames',
8123: match => 'matches',
8124: do => 'does',
8125: action => 'a username',
8126: one => 'one',
8127: );
8128: if ($count > 1) {
8129: $text{'item'} = 'usernames';
8130: $text{'match'} ='match';
8131: $text{'do'} = 'do';
8132: $text{'action'} = 'usernames',
8133: $text{'one'} = 'ones';
8134: }
8135: if ($checkitem eq 'id') {
8136: $text{'items'} = 'IDs';
8137: $text{'item'} = 'ID';
8138: $text{'action'} = 'an ID';
8139: if ($count > 1) {
8140: $text{'item'} = 'IDs';
8141: $text{'action'} = 'IDs';
8142: }
8143: }
8144: $response = &mt("The $text{'item'} you chose $text{'match'} the format of $text{'items'} defined for [_1], but the $text{'item'} $text{'do'} not exist in the institutional directory.",'<span class="LC_cusr_emph">'.$domdesc.'</span>').'<br />';
8145: if ($mode eq 'upload') {
8146: if ($checkitem eq 'username') {
8147: $response .= &mt("You will need to modify your upload file so it will include $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
8148: } elsif ($checkitem eq 'id') {
8149: $response .= &mt("Either upload a file which includes $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or when associating fields with data columns, omit an association for the Student/Employee ID field.");
8150: }
8151: } elsif ($mode eq 'selfcreate') {
8152: if ($checkitem eq 'id') {
8153: $response .= &mt("You must either choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or leave the ID field blank.");
8154: }
8155: } else {
8156: if ($checkitem eq 'username') {
8157: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
8158: } elsif ($checkitem eq 'id') {
8159: $response .= &mt("You must either choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or leave the ID field blank.");
8160: }
8161: }
8162: return $response;
8163: }
8164:
8165: sub personal_data_fieldtitles {
8166: my %fieldtitles = &Apache::lonlocal::texthash (
8167: id => 'Student/Employee ID',
8168: permanentemail => 'E-mail address',
8169: lastname => 'Last Name',
8170: firstname => 'First Name',
8171: middlename => 'Middle Name',
8172: generation => 'Generation',
8173: gen => 'Generation',
8174: inststatus => 'Affiliation',
8175: );
8176: return %fieldtitles;
8177: }
8178:
8179: sub sorted_inst_types {
8180: my ($dom) = @_;
8181: my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
8182: my $othertitle = &mt('All users');
8183: if ($env{'request.course.id'}) {
8184: $othertitle = &mt('Any users');
8185: }
8186: my @types;
8187: if (ref($order) eq 'ARRAY') {
8188: @types = @{$order};
8189: }
8190: if (@types == 0) {
8191: if (ref($usertypes) eq 'HASH') {
8192: @types = sort(keys(%{$usertypes}));
8193: }
8194: }
8195: if (keys(%{$usertypes}) > 0) {
8196: $othertitle = &mt('Other users');
8197: }
8198: return ($othertitle,$usertypes,\@types);
8199: }
8200:
8201: sub get_institutional_codes {
8202: my ($settings,$allcourses,$LC_code) = @_;
8203: # Get complete list of course sections to update
8204: my @currsections = ();
8205: my @currxlists = ();
8206: my $coursecode = $$settings{'internal.coursecode'};
8207:
8208: if ($$settings{'internal.sectionnums'} ne '') {
8209: @currsections = split(/,/,$$settings{'internal.sectionnums'});
8210: }
8211:
8212: if ($$settings{'internal.crosslistings'} ne '') {
8213: @currxlists = split(/,/,$$settings{'internal.crosslistings'});
8214: }
8215:
8216: if (@currxlists > 0) {
8217: foreach (@currxlists) {
8218: if (m/^([^:]+):(\w*)$/) {
8219: unless (grep/^$1$/,@{$allcourses}) {
8220: push @{$allcourses},$1;
8221: $$LC_code{$1} = $2;
8222: }
8223: }
8224: }
8225: }
8226:
8227: if (@currsections > 0) {
8228: foreach (@currsections) {
8229: if (m/^(\w+):(\w*)$/) {
8230: my $sec = $coursecode.$1;
8231: my $lc_sec = $2;
8232: unless (grep/^$sec$/,@{$allcourses}) {
8233: push @{$allcourses},$sec;
8234: $$LC_code{$sec} = $lc_sec;
8235: }
8236: }
8237: }
8238: }
8239: return;
8240: }
8241:
8242: sub get_standard_codeitems {
8243: return ('Year','Semester','Department','Number','Section');
8244: }
8245:
8246: =pod
8247:
8248: =head1 Slot Helpers
8249:
8250: =over 4
8251:
8252: =item * sorted_slots()
8253:
8254: Sorts an array of slot names in order of slot start time (earliest first).
8255:
8256: Inputs:
8257:
8258: =over 4
8259:
8260: slotsarr - Reference to array of unsorted slot names.
8261:
8262: slots - Reference to hash of hash, where outer hash keys are slot names.
8263:
8264: =back
8265:
8266: Returns:
8267:
8268: =over 4
8269:
8270: sorted - An array of slot names sorted by the start time of the slot.
8271:
8272: =back
8273:
8274: =back
8275:
8276: =cut
8277:
8278:
8279: sub sorted_slots {
8280: my ($slotsarr,$slots) = @_;
8281: my @sorted;
8282: if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
8283: @sorted =
8284: sort {
8285: if (ref($slots->{$a}) && ref($slots->{$b})) {
8286: return $slots->{$a}{'starttime'} <=> $slots->{$b}{'starttime'}
8287: }
8288: if (ref($slots->{$a})) { return -1;}
8289: if (ref($slots->{$b})) { return 1;}
8290: return 0;
8291: } @{$slotsarr};
8292: }
8293: return @sorted;
8294: }
8295:
8296:
8297: =pod
8298:
8299: =head1 HTTP Helpers
8300:
8301: =over 4
8302:
8303: =item * &get_unprocessed_cgi($query,$possible_names)
8304:
8305: Modify the %env hash to contain unprocessed CGI form parameters held in
8306: $query. The parameters listed in $possible_names (an array reference),
8307: will be set in $env{'form.name'} if they do not already exist.
8308:
8309: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
8310: $possible_names is an ref to an array of form element names. As an example:
8311: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
8312: will result in $env{'form.uname'} and $env{'form.udom'} being set.
8313:
8314: =cut
8315:
8316: sub get_unprocessed_cgi {
8317: my ($query,$possible_names)= @_;
8318: # $Apache::lonxml::debug=1;
8319: foreach my $pair (split(/&/,$query)) {
8320: my ($name, $value) = split(/=/,$pair);
8321: $name = &unescape($name);
8322: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
8323: $value =~ tr/+/ /;
8324: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
8325: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
8326: }
8327: }
8328: }
8329:
8330: =pod
8331:
8332: =item * &cacheheader()
8333:
8334: returns cache-controlling header code
8335:
8336: =cut
8337:
8338: sub cacheheader {
8339: unless ($env{'request.method'} eq 'GET') { return ''; }
8340: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
8341: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
8342: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
8343: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
8344: return $output;
8345: }
8346:
8347: =pod
8348:
8349: =item * &no_cache($r)
8350:
8351: specifies header code to not have cache
8352:
8353: =cut
8354:
8355: sub no_cache {
8356: my ($r) = @_;
8357: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
8358: $env{'request.method'} ne 'GET') { return ''; }
8359: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
8360: $r->no_cache(1);
8361: $r->header_out("Expires" => $date);
8362: $r->header_out("Pragma" => "no-cache");
8363: }
8364:
8365: sub content_type {
8366: my ($r,$type,$charset) = @_;
8367: if ($r) {
8368: # Note that printout.pl calls this with undef for $r.
8369: &no_cache($r);
8370: }
8371: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
8372: unless ($charset) {
8373: $charset=&Apache::lonlocal::current_encoding;
8374: }
8375: if ($charset) { $type.='; charset='.$charset; }
8376: if ($r) {
8377: $r->content_type($type);
8378: } else {
8379: print("Content-type: $type\n\n");
8380: }
8381: }
8382:
8383: =pod
8384:
8385: =item * &add_to_env($name,$value)
8386:
8387: adds $name to the %env hash with value
8388: $value, if $name already exists, the entry is converted to an array
8389: reference and $value is added to the array.
8390:
8391: =cut
8392:
8393: sub add_to_env {
8394: my ($name,$value)=@_;
8395: if (defined($env{$name})) {
8396: if (ref($env{$name})) {
8397: #already have multiple values
8398: push(@{ $env{$name} },$value);
8399: } else {
8400: #first time seeing multiple values, convert hash entry to an arrayref
8401: my $first=$env{$name};
8402: undef($env{$name});
8403: push(@{ $env{$name} },$first,$value);
8404: }
8405: } else {
8406: $env{$name}=$value;
8407: }
8408: }
8409:
8410: =pod
8411:
8412: =item * &get_env_multiple($name)
8413:
8414: gets $name from the %env hash, it seemlessly handles the cases where multiple
8415: values may be defined and end up as an array ref.
8416:
8417: returns an array of values
8418:
8419: =cut
8420:
8421: sub get_env_multiple {
8422: my ($name) = @_;
8423: my @values;
8424: if (defined($env{$name})) {
8425: # exists is it an array
8426: if (ref($env{$name})) {
8427: @values=@{ $env{$name} };
8428: } else {
8429: $values[0]=$env{$name};
8430: }
8431: }
8432: return(@values);
8433: }
8434:
8435: sub ask_for_embedded_content {
8436: my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
8437: my $upload_output = '
8438: <form name="upload_embedded" action="'.$actionurl.'"
8439: method="post" enctype="multipart/form-data">';
8440: $upload_output .= $state;
8441: $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
8442:
8443: my $num = 0;
8444: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
8445: $upload_output .= &start_data_table_row().
8446: '<td>'.$embed_file.'</td><td>';
8447: if ($args->{'ignore_remote_references'}
8448: && $embed_file =~ m{^\w+://}) {
8449: $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
8450: } elsif ($args->{'error_on_invalid_names'}
8451: && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
8452:
8453: $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
8454:
8455: } else {
8456: $upload_output .='
8457: <input name="embedded_item_'.$num.'" type="file" value="" />
8458: <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
8459: my $attrib = join(':',@{$$allfiles{$embed_file}});
8460: $upload_output .=
8461: "\n\t\t".
8462: '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
8463: $attrib.'" />';
8464: if (exists($$codebase{$embed_file})) {
8465: $upload_output .=
8466: "\n\t\t".
8467: '<input name="codebase_'.$num.'" type="hidden" value="'.
8468: &escape($$codebase{$embed_file}).'" />';
8469: }
8470: }
8471: $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
8472: $num++;
8473: }
8474: $upload_output .= &Apache::loncommon::end_data_table().'<br />
8475: <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
8476: <input type ="submit" value="'.&mt('Upload Listed Files').'" />
8477: '.&mt('(only files for which a location has been provided will be uploaded)').'
8478: </form>';
8479: return $upload_output;
8480: }
8481:
8482: sub upload_embedded {
8483: my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
8484: $current_disk_usage) = @_;
8485: my $output;
8486: for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
8487: next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
8488: my $orig_uploaded_filename =
8489: $env{'form.embedded_item_'.$i.'.filename'};
8490:
8491: $env{'form.embedded_orig_'.$i} =
8492: &unescape($env{'form.embedded_orig_'.$i});
8493: my ($path,$fname) =
8494: ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
8495: # no path, whole string is fname
8496: if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
8497:
8498: $path = $env{'form.currentpath'}.$path;
8499: $fname = &Apache::lonnet::clean_filename($fname);
8500: # See if there is anything left
8501: next if ($fname eq '');
8502:
8503: # Check if file already exists as a file or directory.
8504: my ($state,$msg);
8505: if ($context eq 'portfolio') {
8506: my $port_path = $dirpath;
8507: if ($group ne '') {
8508: $port_path = "groups/$group/$port_path";
8509: }
8510: ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
8511: $dir_root,$port_path,$disk_quota,
8512: $current_disk_usage,$uname,$udom);
8513: if ($state eq 'will_exceed_quota'
8514: || $state eq 'file_locked'
8515: || $state eq 'file_exists' ) {
8516: $output .= $msg;
8517: next;
8518: }
8519: } elsif (($context eq 'author') || ($context eq 'testbank')) {
8520: ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
8521: if ($state eq 'exists') {
8522: $output .= $msg;
8523: next;
8524: }
8525: }
8526: # Check if extension is valid
8527: if (($fname =~ /\.(\w+)$/) &&
8528: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
8529: $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
8530: next;
8531: } elsif (($fname =~ /\.(\w+)$/) &&
8532: (!defined(&Apache::loncommon::fileembstyle($1)))) {
8533: $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
8534: next;
8535: } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
8536: $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
8537: next;
8538: }
8539:
8540: $env{'form.embedded_item_'.$i.'.filename'}=$fname;
8541: if ($context eq 'portfolio') {
8542: my $result=
8543: &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
8544: $dirpath.$path);
8545: if ($result !~ m|^/uploaded/|) {
8546: $output .= '<span class="LC_error">'
8547: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
8548: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
8549: .'</span><br />';
8550: next;
8551: } else {
8552: $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
8553: $path.$fname.'</span>').'</p>';
8554: }
8555: } else {
8556: # Save the file
8557: my $target = $env{'form.embedded_item_'.$i};
8558: my $fullpath = $dir_root.$dirpath.'/'.$path;
8559: my $dest = $fullpath.$fname;
8560: my $url = $url_root.$dirpath.'/'.$path.$fname;
8561: my @parts=split(/\//,$fullpath);
8562: my $count;
8563: my $filepath = $dir_root;
8564: for ($count=4;$count<=$#parts;$count++) {
8565: $filepath .= "/$parts[$count]";
8566: if ((-e $filepath)!=1) {
8567: mkdir($filepath,0770);
8568: }
8569: }
8570: my $fh;
8571: if (!open($fh,'>'.$dest)) {
8572: &Apache::lonnet::logthis('Failed to create '.$dest);
8573: $output .= '<span class="LC_error">'.
8574: &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
8575: '</span><br />';
8576: } else {
8577: if (!print $fh $env{'form.embedded_item_'.$i}) {
8578: &Apache::lonnet::logthis('Failed to write to '.$dest);
8579: $output .= '<span class="LC_error">'.
8580: &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
8581: '</span><br />';
8582: } else {
8583: if ($context eq 'testbank') {
8584: $output .= &mt('Embedded file uploaded successfully:').
8585: ' <a href="'.$url.'">'.
8586: $orig_uploaded_filename.'</a><br />';
8587: } else {
8588: $output .= '<span class=\"LC_fontsize_large\">'.
8589: &mt('View embedded file: [_1]','<a href="'.$url.'">'.
8590: $orig_uploaded_filename.'</a>').'</span><br />';
8591: }
8592: }
8593: close($fh);
8594: }
8595: }
8596: }
8597: return $output;
8598: }
8599:
8600: sub check_for_existing {
8601: my ($path,$fname,$element) = @_;
8602: my ($state,$msg);
8603: if (-d $path.'/'.$fname) {
8604: $state = 'exists';
8605: $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
8606: } elsif (-e $path.'/'.$fname) {
8607: $state = 'exists';
8608: $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
8609: }
8610: if ($state eq 'exists') {
8611: $msg = '<span class="LC_error">'.$msg.'</span><br />';
8612: }
8613: return ($state,$msg);
8614: }
8615:
8616: sub check_for_upload {
8617: my ($path,$fname,$group,$element,$portfolio_root,$port_path,
8618: $disk_quota,$current_disk_usage,$uname,$udom) = @_;
8619: my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
8620: my $getpropath = 1;
8621: my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
8622: $getpropath);
8623: my $found_file = 0;
8624: my $locked_file = 0;
8625: foreach my $line (@dir_list) {
8626: my ($file_name)=split(/\&/,$line,2);
8627: if ($file_name eq $fname){
8628: $file_name = $path.$file_name;
8629: if ($group ne '') {
8630: $file_name = $group.$file_name;
8631: }
8632: $found_file = 1;
8633: if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
8634: $locked_file = 1;
8635: }
8636: }
8637: }
8638: if (($current_disk_usage + $filesize) > $disk_quota){
8639: my $msg = '<span class="LC_error">'.
8640: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
8641: '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
8642: return ('will_exceed_quota',$msg);
8643: } elsif ($found_file) {
8644: if ($locked_file) {
8645: my $msg = '<span class="LC_error">';
8646: $msg .= &mt('Unable to upload [_1]. A locked file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>','<span class="LC_filename">'.$port_path.$env{'form.currentpath'}.'</span>');
8647: $msg .= '</span><br />';
8648: $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
8649: return ('file_locked',$msg);
8650: } else {
8651: my $msg = '<span class="LC_error">';
8652: $msg .= &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
8653: $msg .= '</span>';
8654: $msg .= '<br />';
8655: $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
8656: return ('file_exists',$msg);
8657: }
8658: }
8659: }
8660:
8661:
8662: =pod
8663:
8664: =back
8665:
8666: =head1 CSV Upload/Handling functions
8667:
8668: =over 4
8669:
8670: =item * &upfile_store($r)
8671:
8672: Store uploaded file, $r should be the HTTP Request object,
8673: needs $env{'form.upfile'}
8674: returns $datatoken to be put into hidden field
8675:
8676: =cut
8677:
8678: sub upfile_store {
8679: my $r=shift;
8680: $env{'form.upfile'}=~s/\r/\n/gs;
8681: $env{'form.upfile'}=~s/\f/\n/gs;
8682: $env{'form.upfile'}=~s/\n+/\n/gs;
8683: $env{'form.upfile'}=~s/\n+$//gs;
8684:
8685: my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
8686: '_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
8687: {
8688: my $datafile = $r->dir_config('lonDaemons').
8689: '/tmp/'.$datatoken.'.tmp';
8690: if ( open(my $fh,">$datafile") ) {
8691: print $fh $env{'form.upfile'};
8692: close($fh);
8693: }
8694: }
8695: return $datatoken;
8696: }
8697:
8698: =pod
8699:
8700: =item * &load_tmp_file($r)
8701:
8702: Load uploaded file from tmp, $r should be the HTTP Request object,
8703: needs $env{'form.datatoken'},
8704: sets $env{'form.upfile'} to the contents of the file
8705:
8706: =cut
8707:
8708: sub load_tmp_file {
8709: my $r=shift;
8710: my @studentdata=();
8711: {
8712: my $studentfile = $r->dir_config('lonDaemons').
8713: '/tmp/'.$env{'form.datatoken'}.'.tmp';
8714: if ( open(my $fh,"<$studentfile") ) {
8715: @studentdata=<$fh>;
8716: close($fh);
8717: }
8718: }
8719: $env{'form.upfile'}=join('',@studentdata);
8720: }
8721:
8722: =pod
8723:
8724: =item * &upfile_record_sep()
8725:
8726: Separate uploaded file into records
8727: returns array of records,
8728: needs $env{'form.upfile'} and $env{'form.upfiletype'}
8729:
8730: =cut
8731:
8732: sub upfile_record_sep {
8733: if ($env{'form.upfiletype'} eq 'xml') {
8734: } else {
8735: my @records;
8736: foreach my $line (split(/\n/,$env{'form.upfile'})) {
8737: if ($line=~/^\s*$/) { next; }
8738: push(@records,$line);
8739: }
8740: return @records;
8741: }
8742: }
8743:
8744: =pod
8745:
8746: =item * &record_sep($record)
8747:
8748: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
8749:
8750: =cut
8751:
8752: sub takeleft {
8753: my $index=shift;
8754: return substr('0000'.$index,-4,4);
8755: }
8756:
8757: sub record_sep {
8758: my $record=shift;
8759: my %components=();
8760: if ($env{'form.upfiletype'} eq 'xml') {
8761: } elsif ($env{'form.upfiletype'} eq 'space') {
8762: my $i=0;
8763: foreach my $field (split(/\s+/,$record)) {
8764: $field=~s/^(\"|\')//;
8765: $field=~s/(\"|\')$//;
8766: $components{&takeleft($i)}=$field;
8767: $i++;
8768: }
8769: } elsif ($env{'form.upfiletype'} eq 'tab') {
8770: my $i=0;
8771: foreach my $field (split(/\t/,$record)) {
8772: $field=~s/^(\"|\')//;
8773: $field=~s/(\"|\')$//;
8774: $components{&takeleft($i)}=$field;
8775: $i++;
8776: }
8777: } else {
8778: my $separator=',';
8779: if ($env{'form.upfiletype'} eq 'semisv') {
8780: $separator=';';
8781: }
8782: my $i=0;
8783: # the character we are looking for to indicate the end of a quote or a record
8784: my $looking_for=$separator;
8785: # do not add the characters to the fields
8786: my $ignore=0;
8787: # we just encountered a separator (or the beginning of the record)
8788: my $just_found_separator=1;
8789: # store the field we are working on here
8790: my $field='';
8791: # work our way through all characters in record
8792: foreach my $character ($record=~/(.)/g) {
8793: if ($character eq $looking_for) {
8794: if ($character ne $separator) {
8795: # Found the end of a quote, again looking for separator
8796: $looking_for=$separator;
8797: $ignore=1;
8798: } else {
8799: # Found a separator, store away what we got
8800: $components{&takeleft($i)}=$field;
8801: $i++;
8802: $just_found_separator=1;
8803: $ignore=0;
8804: $field='';
8805: }
8806: next;
8807: }
8808: # single or double quotation marks after a separator indicate beginning of a quote
8809: # we are now looking for the end of the quote and need to ignore separators
8810: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) {
8811: $looking_for=$character;
8812: next;
8813: }
8814: # ignore would be true after we reached the end of a quote
8815: if ($ignore) { next; }
8816: if (($just_found_separator) && ($character=~/\s/)) { next; }
8817: $field.=$character;
8818: $just_found_separator=0;
8819: }
8820: # catch the very last entry, since we never encountered the separator
8821: $components{&takeleft($i)}=$field;
8822: }
8823: return %components;
8824: }
8825:
8826: ######################################################
8827: ######################################################
8828:
8829: =pod
8830:
8831: =item * &upfile_select_html()
8832:
8833: Return HTML code to select a file from the users machine and specify
8834: the file type.
8835:
8836: =cut
8837:
8838: ######################################################
8839: ######################################################
8840: sub upfile_select_html {
8841: my %Types = (
8842: csv => &mt('CSV (comma separated values, spreadsheet)'),
8843: semisv => &mt('Semicolon separated values'),
8844: space => &mt('Space separated'),
8845: tab => &mt('Tabulator separated'),
8846: # xml => &mt('HTML/XML'),
8847: );
8848: my $Str = '<input type="file" name="upfile" size="50" />'.
8849: '<br />'.&mt('Type').': <select name="upfiletype">';
8850: foreach my $type (sort(keys(%Types))) {
8851: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
8852: }
8853: $Str .= "</select>\n";
8854: return $Str;
8855: }
8856:
8857: sub get_samples {
8858: my ($records,$toget) = @_;
8859: my @samples=({});
8860: my $got=0;
8861: foreach my $rec (@$records) {
8862: my %temp = &record_sep($rec);
8863: if (! grep(/\S/, values(%temp))) { next; }
8864: if (%temp) {
8865: $samples[$got]=\%temp;
8866: $got++;
8867: if ($got == $toget) { last; }
8868: }
8869: }
8870: return \@samples;
8871: }
8872:
8873: ######################################################
8874: ######################################################
8875:
8876: =pod
8877:
8878: =item * &csv_print_samples($r,$records)
8879:
8880: Prints a table of sample values from each column uploaded $r is an
8881: Apache Request ref, $records is an arrayref from
8882: &Apache::loncommon::upfile_record_sep
8883:
8884: =cut
8885:
8886: ######################################################
8887: ######################################################
8888: sub csv_print_samples {
8889: my ($r,$records) = @_;
8890: my $samples = &get_samples($records,5);
8891:
8892: $r->print(&mt('Samples').'<br />'.&start_data_table().
8893: &start_data_table_header_row());
8894: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
8895: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
8896: $r->print(&end_data_table_header_row());
8897: foreach my $hash (@$samples) {
8898: $r->print(&start_data_table_row());
8899: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
8900: $r->print('<td>');
8901: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
8902: $r->print('</td>');
8903: }
8904: $r->print(&end_data_table_row());
8905: }
8906: $r->print(&end_data_table().'<br />'."\n");
8907: }
8908:
8909: ######################################################
8910: ######################################################
8911:
8912: =pod
8913:
8914: =item * &csv_print_select_table($r,$records,$d)
8915:
8916: Prints a table to create associations between values and table columns.
8917:
8918: $r is an Apache Request ref,
8919: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
8920: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
8921:
8922: =cut
8923:
8924: ######################################################
8925: ######################################################
8926: sub csv_print_select_table {
8927: my ($r,$records,$d) = @_;
8928: my $i=0;
8929: my $samples = &get_samples($records,1);
8930: $r->print(&mt('Associate columns with student attributes.')."\n".
8931: &start_data_table().&start_data_table_header_row().
8932: '<th>'.&mt('Attribute').'</th>'.
8933: '<th>'.&mt('Column').'</th>'.
8934: &end_data_table_header_row()."\n");
8935: foreach my $array_ref (@$d) {
8936: my ($value,$display,$defaultcol)=@{ $array_ref };
8937: $r->print(&start_data_table_row().'<td>'.$display.'</td>');
8938:
8939: $r->print('<td><select name="f'.$i.'"'.
8940: ' onchange="javascript:flip(this.form,'.$i.');">');
8941: $r->print('<option value="none"></option>');
8942: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
8943: $r->print('<option value="'.$sample.'"'.
8944: ($sample eq $defaultcol ? ' selected="selected" ' : '').
8945: '>'.&mt('Column [_1]',($sample+1)).'</option>');
8946: }
8947: $r->print('</select></td>'.&end_data_table_row()."\n");
8948: $i++;
8949: }
8950: $r->print(&end_data_table());
8951: $i--;
8952: return $i;
8953: }
8954:
8955: ######################################################
8956: ######################################################
8957:
8958: =pod
8959:
8960: =item * &csv_samples_select_table($r,$records,$d)
8961:
8962: Prints a table of sample values from the upload and can make associate samples to internal names.
8963:
8964: $r is an Apache Request ref,
8965: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
8966: $d is an array of 2 element arrays (internal name, displayed name)
8967:
8968: =cut
8969:
8970: ######################################################
8971: ######################################################
8972: sub csv_samples_select_table {
8973: my ($r,$records,$d) = @_;
8974: my $i=0;
8975: #
8976: my $max_samples = 5;
8977: my $samples = &get_samples($records,$max_samples);
8978: $r->print(&start_data_table().
8979: &start_data_table_header_row().'<th>'.
8980: &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
8981: &end_data_table_header_row());
8982:
8983: foreach my $key (sort(keys(%{ $samples->[0] }))) {
8984: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
8985: ' onchange="javascript:flip(this.form,'.$i.');">');
8986: foreach my $option (@$d) {
8987: my ($value,$display,$defaultcol)=@{ $option };
8988: $r->print('<option value="'.$value.'"'.
8989: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
8990: $display.'</option>');
8991: }
8992: $r->print('</select></td><td>');
8993: foreach my $line (0..($max_samples-1)) {
8994: if (defined($samples->[$line]{$key})) {
8995: $r->print($samples->[$line]{$key}."<br />\n");
8996: }
8997: }
8998: $r->print('</td>'.&end_data_table_row());
8999: $i++;
9000: }
9001: $r->print(&end_data_table());
9002: $i--;
9003: return($i);
9004: }
9005:
9006: ######################################################
9007: ######################################################
9008:
9009: =pod
9010:
9011: =item * &clean_excel_name($name)
9012:
9013: Returns a replacement for $name which does not contain any illegal characters.
9014:
9015: =cut
9016:
9017: ######################################################
9018: ######################################################
9019: sub clean_excel_name {
9020: my ($name) = @_;
9021: $name =~ s/[:\*\?\/\\]//g;
9022: if (length($name) > 31) {
9023: $name = substr($name,0,31);
9024: }
9025: return $name;
9026: }
9027:
9028: =pod
9029:
9030: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
9031:
9032: Returns either 1 or undef
9033:
9034: 1 if the part is to be hidden, undef if it is to be shown
9035:
9036: Arguments are:
9037:
9038: $id the id of the part to be checked
9039: $symb, optional the symb of the resource to check
9040: $udom, optional the domain of the user to check for
9041: $uname, optional the username of the user to check for
9042:
9043: =cut
9044:
9045: sub check_if_partid_hidden {
9046: my ($id,$symb,$udom,$uname) = @_;
9047: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
9048: $symb,$udom,$uname);
9049: my $truth=1;
9050: #if the string starts with !, then the list is the list to show not hide
9051: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
9052: my @hiddenlist=split(/,/,$hiddenparts);
9053: foreach my $checkid (@hiddenlist) {
9054: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
9055: }
9056: return !$truth;
9057: }
9058:
9059:
9060: ############################################################
9061: ############################################################
9062:
9063: =pod
9064:
9065: =back
9066:
9067: =head1 cgi-bin script and graphing routines
9068:
9069: =over 4
9070:
9071: =item * &get_cgi_id()
9072:
9073: Inputs: none
9074:
9075: Returns an id which can be used to pass environment variables
9076: to various cgi-bin scripts. These environment variables will
9077: be removed from the users environment after a given time by
9078: the routine &Apache::lonnet::transfer_profile_to_env.
9079:
9080: =cut
9081:
9082: ############################################################
9083: ############################################################
9084: my $uniq=0;
9085: sub get_cgi_id {
9086: $uniq=($uniq+1)%100000;
9087: return (time.'_'.$$.'_'.$uniq);
9088: }
9089:
9090: ############################################################
9091: ############################################################
9092:
9093: =pod
9094:
9095: =item * &DrawBarGraph()
9096:
9097: Facilitates the plotting of data in a (stacked) bar graph.
9098: Puts plot definition data into the users environment in order for
9099: graph.png to plot it. Returns an <img> tag for the plot.
9100: The bars on the plot are labeled '1','2',...,'n'.
9101:
9102: Inputs:
9103:
9104: =over 4
9105:
9106: =item $Title: string, the title of the plot
9107:
9108: =item $xlabel: string, text describing the X-axis of the plot
9109:
9110: =item $ylabel: string, text describing the Y-axis of the plot
9111:
9112: =item $Max: scalar, the maximum Y value to use in the plot
9113: If $Max is < any data point, the graph will not be rendered.
9114:
9115: =item $colors: array ref holding the colors to be used for the data sets when
9116: they are plotted. If undefined, default values will be used.
9117:
9118: =item $labels: array ref holding the labels to use on the x-axis for the bars.
9119:
9120: =item @Values: An array of array references. Each array reference holds data
9121: to be plotted in a stacked bar chart.
9122:
9123: =item If the final element of @Values is a hash reference the key/value
9124: pairs will be added to the graph definition.
9125:
9126: =back
9127:
9128: Returns:
9129:
9130: An <img> tag which references graph.png and the appropriate identifying
9131: information for the plot.
9132:
9133: =cut
9134:
9135: ############################################################
9136: ############################################################
9137: sub DrawBarGraph {
9138: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
9139: #
9140: if (! defined($colors)) {
9141: $colors = ['#33ff00',
9142: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
9143: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
9144: ];
9145: }
9146: my $extra_settings = {};
9147: if (ref($Values[-1]) eq 'HASH') {
9148: $extra_settings = pop(@Values);
9149: }
9150: #
9151: my $identifier = &get_cgi_id();
9152: my $id = 'cgi.'.$identifier;
9153: if (! @Values || ref($Values[0]) ne 'ARRAY') {
9154: return '';
9155: }
9156: #
9157: my @Labels;
9158: if (defined($labels)) {
9159: @Labels = @$labels;
9160: } else {
9161: for (my $i=0;$i<@{$Values[0]};$i++) {
9162: push (@Labels,$i+1);
9163: }
9164: }
9165: #
9166: my $NumBars = scalar(@{$Values[0]});
9167: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
9168: my %ValuesHash;
9169: my $NumSets=1;
9170: foreach my $array (@Values) {
9171: next if (! ref($array));
9172: $ValuesHash{$id.'.data.'.$NumSets++} =
9173: join(',',@$array);
9174: }
9175: #
9176: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
9177: if ($NumBars < 3) {
9178: $width = 120+$NumBars*32;
9179: $xskip = 1;
9180: $bar_width = 30;
9181: } elsif ($NumBars < 5) {
9182: $width = 120+$NumBars*20;
9183: $xskip = 1;
9184: $bar_width = 20;
9185: } elsif ($NumBars < 10) {
9186: $width = 120+$NumBars*15;
9187: $xskip = 1;
9188: $bar_width = 15;
9189: } elsif ($NumBars <= 25) {
9190: $width = 120+$NumBars*11;
9191: $xskip = 5;
9192: $bar_width = 8;
9193: } elsif ($NumBars <= 50) {
9194: $width = 120+$NumBars*8;
9195: $xskip = 5;
9196: $bar_width = 4;
9197: } else {
9198: $width = 120+$NumBars*8;
9199: $xskip = 5;
9200: $bar_width = 4;
9201: }
9202: #
9203: $Max = 1 if ($Max < 1);
9204: if ( int($Max) < $Max ) {
9205: $Max++;
9206: $Max = int($Max);
9207: }
9208: $Title = '' if (! defined($Title));
9209: $xlabel = '' if (! defined($xlabel));
9210: $ylabel = '' if (! defined($ylabel));
9211: $ValuesHash{$id.'.title'} = &escape($Title);
9212: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
9213: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
9214: $ValuesHash{$id.'.y_max_value'} = $Max;
9215: $ValuesHash{$id.'.NumBars'} = $NumBars;
9216: $ValuesHash{$id.'.NumSets'} = $NumSets;
9217: $ValuesHash{$id.'.PlotType'} = 'bar';
9218: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
9219: $ValuesHash{$id.'.height'} = $height;
9220: $ValuesHash{$id.'.width'} = $width;
9221: $ValuesHash{$id.'.xskip'} = $xskip;
9222: $ValuesHash{$id.'.bar_width'} = $bar_width;
9223: $ValuesHash{$id.'.labels'} = join(',',@Labels);
9224: #
9225: # Deal with other parameters
9226: while (my ($key,$value) = each(%$extra_settings)) {
9227: $ValuesHash{$id.'.'.$key} = $value;
9228: }
9229: #
9230: &Apache::lonnet::appenv(\%ValuesHash);
9231: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
9232: }
9233:
9234: ############################################################
9235: ############################################################
9236:
9237: =pod
9238:
9239: =item * &DrawXYGraph()
9240:
9241: Facilitates the plotting of data in an XY graph.
9242: Puts plot definition data into the users environment in order for
9243: graph.png to plot it. Returns an <img> tag for the plot.
9244:
9245: Inputs:
9246:
9247: =over 4
9248:
9249: =item $Title: string, the title of the plot
9250:
9251: =item $xlabel: string, text describing the X-axis of the plot
9252:
9253: =item $ylabel: string, text describing the Y-axis of the plot
9254:
9255: =item $Max: scalar, the maximum Y value to use in the plot
9256: If $Max is < any data point, the graph will not be rendered.
9257:
9258: =item $colors: Array ref containing the hex color codes for the data to be
9259: plotted in. If undefined, default values will be used.
9260:
9261: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
9262:
9263: =item $Ydata: Array ref containing Array refs.
9264: Each of the contained arrays will be plotted as a separate curve.
9265:
9266: =item %Values: hash indicating or overriding any default values which are
9267: passed to graph.png.
9268: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
9269:
9270: =back
9271:
9272: Returns:
9273:
9274: An <img> tag which references graph.png and the appropriate identifying
9275: information for the plot.
9276:
9277: =cut
9278:
9279: ############################################################
9280: ############################################################
9281: sub DrawXYGraph {
9282: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
9283: #
9284: # Create the identifier for the graph
9285: my $identifier = &get_cgi_id();
9286: my $id = 'cgi.'.$identifier;
9287: #
9288: $Title = '' if (! defined($Title));
9289: $xlabel = '' if (! defined($xlabel));
9290: $ylabel = '' if (! defined($ylabel));
9291: my %ValuesHash =
9292: (
9293: $id.'.title' => &escape($Title),
9294: $id.'.xlabel' => &escape($xlabel),
9295: $id.'.ylabel' => &escape($ylabel),
9296: $id.'.y_max_value'=> $Max,
9297: $id.'.labels' => join(',',@$Xlabels),
9298: $id.'.PlotType' => 'XY',
9299: );
9300: #
9301: if (defined($colors) && ref($colors) eq 'ARRAY') {
9302: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
9303: }
9304: #
9305: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
9306: return '';
9307: }
9308: my $NumSets=1;
9309: foreach my $array (@{$Ydata}){
9310: next if (! ref($array));
9311: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
9312: }
9313: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
9314: #
9315: # Deal with other parameters
9316: while (my ($key,$value) = each(%Values)) {
9317: $ValuesHash{$id.'.'.$key} = $value;
9318: }
9319: #
9320: &Apache::lonnet::appenv(\%ValuesHash);
9321: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
9322: }
9323:
9324: ############################################################
9325: ############################################################
9326:
9327: =pod
9328:
9329: =item * &DrawXYYGraph()
9330:
9331: Facilitates the plotting of data in an XY graph with two Y axes.
9332: Puts plot definition data into the users environment in order for
9333: graph.png to plot it. Returns an <img> tag for the plot.
9334:
9335: Inputs:
9336:
9337: =over 4
9338:
9339: =item $Title: string, the title of the plot
9340:
9341: =item $xlabel: string, text describing the X-axis of the plot
9342:
9343: =item $ylabel: string, text describing the Y-axis of the plot
9344:
9345: =item $colors: Array ref containing the hex color codes for the data to be
9346: plotted in. If undefined, default values will be used.
9347:
9348: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
9349:
9350: =item $Ydata1: The first data set
9351:
9352: =item $Min1: The minimum value of the left Y-axis
9353:
9354: =item $Max1: The maximum value of the left Y-axis
9355:
9356: =item $Ydata2: The second data set
9357:
9358: =item $Min2: The minimum value of the right Y-axis
9359:
9360: =item $Max2: The maximum value of the left Y-axis
9361:
9362: =item %Values: hash indicating or overriding any default values which are
9363: passed to graph.png.
9364: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
9365:
9366: =back
9367:
9368: Returns:
9369:
9370: An <img> tag which references graph.png and the appropriate identifying
9371: information for the plot.
9372:
9373: =cut
9374:
9375: ############################################################
9376: ############################################################
9377: sub DrawXYYGraph {
9378: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
9379: $Ydata2,$Min2,$Max2,%Values)=@_;
9380: #
9381: # Create the identifier for the graph
9382: my $identifier = &get_cgi_id();
9383: my $id = 'cgi.'.$identifier;
9384: #
9385: $Title = '' if (! defined($Title));
9386: $xlabel = '' if (! defined($xlabel));
9387: $ylabel = '' if (! defined($ylabel));
9388: my %ValuesHash =
9389: (
9390: $id.'.title' => &escape($Title),
9391: $id.'.xlabel' => &escape($xlabel),
9392: $id.'.ylabel' => &escape($ylabel),
9393: $id.'.labels' => join(',',@$Xlabels),
9394: $id.'.PlotType' => 'XY',
9395: $id.'.NumSets' => 2,
9396: $id.'.two_axes' => 1,
9397: $id.'.y1_max_value' => $Max1,
9398: $id.'.y1_min_value' => $Min1,
9399: $id.'.y2_max_value' => $Max2,
9400: $id.'.y2_min_value' => $Min2,
9401: );
9402: #
9403: if (defined($colors) && ref($colors) eq 'ARRAY') {
9404: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
9405: }
9406: #
9407: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
9408: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
9409: return '';
9410: }
9411: my $NumSets=1;
9412: foreach my $array ($Ydata1,$Ydata2){
9413: next if (! ref($array));
9414: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
9415: }
9416: #
9417: # Deal with other parameters
9418: while (my ($key,$value) = each(%Values)) {
9419: $ValuesHash{$id.'.'.$key} = $value;
9420: }
9421: #
9422: &Apache::lonnet::appenv(\%ValuesHash);
9423: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
9424: }
9425:
9426: ############################################################
9427: ############################################################
9428:
9429: =pod
9430:
9431: =back
9432:
9433: =head1 Statistics helper routines?
9434:
9435: Bad place for them but what the hell.
9436:
9437: =over 4
9438:
9439: =item * &chartlink()
9440:
9441: Returns a link to the chart for a specific student.
9442:
9443: Inputs:
9444:
9445: =over 4
9446:
9447: =item $linktext: The text of the link
9448:
9449: =item $sname: The students username
9450:
9451: =item $sdomain: The students domain
9452:
9453: =back
9454:
9455: =back
9456:
9457: =cut
9458:
9459: ############################################################
9460: ############################################################
9461: sub chartlink {
9462: my ($linktext, $sname, $sdomain) = @_;
9463: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
9464: '&SelectedStudent='.&escape($sname.':'.$sdomain).
9465: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
9466: '">'.$linktext.'</a>';
9467: }
9468:
9469: #######################################################
9470: #######################################################
9471:
9472: =pod
9473:
9474: =head1 Course Environment Routines
9475:
9476: =over 4
9477:
9478: =item * &restore_course_settings()
9479:
9480: =item * &store_course_settings()
9481:
9482: Restores/Store indicated form parameters from the course environment.
9483: Will not overwrite existing values of the form parameters.
9484:
9485: Inputs:
9486: a scalar describing the data (e.g. 'chart', 'problem_analysis')
9487:
9488: a hash ref describing the data to be stored. For example:
9489:
9490: %Save_Parameters = ('Status' => 'scalar',
9491: 'chartoutputmode' => 'scalar',
9492: 'chartoutputdata' => 'scalar',
9493: 'Section' => 'array',
9494: 'Group' => 'array',
9495: 'StudentData' => 'array',
9496: 'Maps' => 'array');
9497:
9498: Returns: both routines return nothing
9499:
9500: =back
9501:
9502: =cut
9503:
9504: #######################################################
9505: #######################################################
9506: sub store_course_settings {
9507: return &store_settings($env{'request.course.id'},@_);
9508: }
9509:
9510: sub store_settings {
9511: # save to the environment
9512: # appenv the same items, just to be safe
9513: my $udom = $env{'user.domain'};
9514: my $uname = $env{'user.name'};
9515: my ($context,$prefix,$Settings) = @_;
9516: my %SaveHash;
9517: my %AppHash;
9518: while (my ($setting,$type) = each(%$Settings)) {
9519: my $basename = join('.','internal',$context,$prefix,$setting);
9520: my $envname = 'environment.'.$basename;
9521: if (exists($env{'form.'.$setting})) {
9522: # Save this value away
9523: if ($type eq 'scalar' &&
9524: (! exists($env{$envname}) ||
9525: $env{$envname} ne $env{'form.'.$setting})) {
9526: $SaveHash{$basename} = $env{'form.'.$setting};
9527: $AppHash{$envname} = $env{'form.'.$setting};
9528: } elsif ($type eq 'array') {
9529: my $stored_form;
9530: if (ref($env{'form.'.$setting})) {
9531: $stored_form = join(',',
9532: map {
9533: &escape($_);
9534: } sort(@{$env{'form.'.$setting}}));
9535: } else {
9536: $stored_form =
9537: &escape($env{'form.'.$setting});
9538: }
9539: # Determine if the array contents are the same.
9540: if ($stored_form ne $env{$envname}) {
9541: $SaveHash{$basename} = $stored_form;
9542: $AppHash{$envname} = $stored_form;
9543: }
9544: }
9545: }
9546: }
9547: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
9548: $udom,$uname);
9549: if ($put_result !~ /^(ok|delayed)/) {
9550: &Apache::lonnet::logthis('unable to save form parameters, '.
9551: 'got error:'.$put_result);
9552: }
9553: # Make sure these settings stick around in this session, too
9554: &Apache::lonnet::appenv(\%AppHash);
9555: return;
9556: }
9557:
9558: sub restore_course_settings {
9559: return &restore_settings($env{'request.course.id'},@_);
9560: }
9561:
9562: sub restore_settings {
9563: my ($context,$prefix,$Settings) = @_;
9564: while (my ($setting,$type) = each(%$Settings)) {
9565: next if (exists($env{'form.'.$setting}));
9566: my $envname = 'environment.internal.'.$context.'.'.$prefix.
9567: '.'.$setting;
9568: if (exists($env{$envname})) {
9569: if ($type eq 'scalar') {
9570: $env{'form.'.$setting} = $env{$envname};
9571: } elsif ($type eq 'array') {
9572: $env{'form.'.$setting} = [
9573: map {
9574: &unescape($_);
9575: } split(',',$env{$envname})
9576: ];
9577: }
9578: }
9579: }
9580: }
9581:
9582: #######################################################
9583: #######################################################
9584:
9585: =pod
9586:
9587: =head1 Domain E-mail Routines
9588:
9589: =over 4
9590:
9591: =item * &build_recipient_list()
9592:
9593: Build recipient lists for five types of e-mail:
9594: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
9595: (d) Help requests, (e) Course requests needing approval, generated by
9596: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
9597: loncoursequeueadmin.pm respectively.
9598:
9599: Inputs:
9600: defmail (scalar - email address of default recipient),
9601: mailing type (scalar - errormail, packagesmail, or helpdeskmail),
9602: defdom (domain for which to retrieve configuration settings),
9603: origmail (scalar - email address of recipient from loncapa.conf,
9604: i.e., predates configuration by DC via domainprefs.pm
9605:
9606: Returns: comma separated list of addresses to which to send e-mail.
9607:
9608: =back
9609:
9610: =cut
9611:
9612: ############################################################
9613: ############################################################
9614: sub build_recipient_list {
9615: my ($defmail,$mailing,$defdom,$origmail) = @_;
9616: my @recipients;
9617: my $otheremails;
9618: my %domconfig =
9619: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
9620: if (ref($domconfig{'contacts'}) eq 'HASH') {
9621: if (exists($domconfig{'contacts'}{$mailing})) {
9622: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
9623: my @contacts = ('adminemail','supportemail');
9624: foreach my $item (@contacts) {
9625: if ($domconfig{'contacts'}{$mailing}{$item}) {
9626: my $addr = $domconfig{'contacts'}{$item};
9627: if (!grep(/^\Q$addr\E$/,@recipients)) {
9628: push(@recipients,$addr);
9629: }
9630: }
9631: $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
9632: }
9633: }
9634: } elsif ($origmail ne '') {
9635: push(@recipients,$origmail);
9636: }
9637: } elsif ($origmail ne '') {
9638: push(@recipients,$origmail);
9639: }
9640: if (defined($defmail)) {
9641: if ($defmail ne '') {
9642: push(@recipients,$defmail);
9643: }
9644: }
9645: if ($otheremails) {
9646: my @others;
9647: if ($otheremails =~ /,/) {
9648: @others = split(/,/,$otheremails);
9649: } else {
9650: push(@others,$otheremails);
9651: }
9652: foreach my $addr (@others) {
9653: if (!grep(/^\Q$addr\E$/,@recipients)) {
9654: push(@recipients,$addr);
9655: }
9656: }
9657: }
9658: my $recipientlist = join(',',@recipients);
9659: return $recipientlist;
9660: }
9661:
9662: ############################################################
9663: ############################################################
9664:
9665: =pod
9666:
9667: =head1 Course Catalog Routines
9668:
9669: =over 4
9670:
9671: =item * &gather_categories()
9672:
9673: Converts category definitions - keys of categories hash stored in
9674: coursecategories in configuration.db on the primary library server in a
9675: domain - to an array. Also generates javascript and idx hash used to
9676: generate Domain Coordinator interface for editing Course Categories.
9677:
9678: Inputs:
9679:
9680: categories (reference to hash of category definitions).
9681:
9682: cats (reference to array of arrays/hashes which encapsulates hierarchy of
9683: categories and subcategories).
9684:
9685: idx (reference to hash of counters used in Domain Coordinator interface for
9686: editing Course Categories).
9687:
9688: jsarray (reference to array of categories used to create Javascript arrays for
9689: Domain Coordinator interface for editing Course Categories).
9690:
9691: Returns: nothing
9692:
9693: Side effects: populates cats, idx and jsarray.
9694:
9695: =cut
9696:
9697: sub gather_categories {
9698: my ($categories,$cats,$idx,$jsarray) = @_;
9699: my %counters;
9700: my $num = 0;
9701: foreach my $item (keys(%{$categories})) {
9702: my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
9703: if ($container eq '' && $depth == 0) {
9704: $cats->[$depth][$categories->{$item}] = $cat;
9705: } else {
9706: $cats->[$depth]{$container}[$categories->{$item}] = $cat;
9707: }
9708: my ($escitem,$tail) = split(/:/,$item,2);
9709: if ($counters{$tail} eq '') {
9710: $counters{$tail} = $num;
9711: $num ++;
9712: }
9713: if (ref($idx) eq 'HASH') {
9714: $idx->{$item} = $counters{$tail};
9715: }
9716: if (ref($jsarray) eq 'ARRAY') {
9717: push(@{$jsarray->[$counters{$tail}]},$item);
9718: }
9719: }
9720: return;
9721: }
9722:
9723: =pod
9724:
9725: =item * &extract_categories()
9726:
9727: Used to generate breadcrumb trails for course categories.
9728:
9729: Inputs:
9730:
9731: categories (reference to hash of category definitions).
9732:
9733: cats (reference to array of arrays/hashes which encapsulates hierarchy of
9734: categories and subcategories).
9735:
9736: trails (reference to array of breacrumb trails for each category).
9737:
9738: allitems (reference to hash - key is category key
9739: (format: escaped(name):escaped(parent category):depth in hierarchy).
9740:
9741: idx (reference to hash of counters used in Domain Coordinator interface for
9742: editing Course Categories).
9743:
9744: jsarray (reference to array of categories used to create Javascript arrays for
9745: Domain Coordinator interface for editing Course Categories).
9746:
9747: subcats (reference to hash of arrays containing all subcategories within each
9748: category, -recursive)
9749:
9750: Returns: nothing
9751:
9752: Side effects: populates trails and allitems hash references.
9753:
9754: =cut
9755:
9756: sub extract_categories {
9757: my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
9758: if (ref($categories) eq 'HASH') {
9759: &gather_categories($categories,$cats,$idx,$jsarray);
9760: if (ref($cats->[0]) eq 'ARRAY') {
9761: for (my $i=0; $i<@{$cats->[0]}; $i++) {
9762: my $name = $cats->[0][$i];
9763: my $item = &escape($name).'::0';
9764: my $trailstr;
9765: if ($name eq 'instcode') {
9766: $trailstr = &mt('Official courses (with institutional codes)');
9767: } elsif ($name eq 'communities') {
9768: $trailstr = &mt('Communities');
9769: } else {
9770: $trailstr = $name;
9771: }
9772: if ($allitems->{$item} eq '') {
9773: push(@{$trails},$trailstr);
9774: $allitems->{$item} = scalar(@{$trails})-1;
9775: }
9776: my @parents = ($name);
9777: if (ref($cats->[1]{$name}) eq 'ARRAY') {
9778: for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
9779: my $category = $cats->[1]{$name}[$j];
9780: if (ref($subcats) eq 'HASH') {
9781: push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
9782: }
9783: &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
9784: }
9785: } else {
9786: if (ref($subcats) eq 'HASH') {
9787: $subcats->{$item} = [];
9788: }
9789: }
9790: }
9791: }
9792: }
9793: return;
9794: }
9795:
9796: =pod
9797:
9798: =item *&recurse_categories()
9799:
9800: Recursively used to generate breadcrumb trails for course categories.
9801:
9802: Inputs:
9803:
9804: cats (reference to array of arrays/hashes which encapsulates hierarchy of
9805: categories and subcategories).
9806:
9807: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
9808:
9809: category (current course category, for which breadcrumb trail is being generated).
9810:
9811: trails (reference to array of breadcrumb trails for each category).
9812:
9813: allitems (reference to hash - key is category key
9814: (format: escaped(name):escaped(parent category):depth in hierarchy).
9815:
9816: parents (array containing containers directories for current category,
9817: back to top level).
9818:
9819: Returns: nothing
9820:
9821: Side effects: populates trails and allitems hash references
9822:
9823: =cut
9824:
9825: sub recurse_categories {
9826: my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
9827: my $shallower = $depth - 1;
9828: if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
9829: for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
9830: my $name = $cats->[$depth]{$category}[$k];
9831: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
9832: my $trailstr = join(' -> ',(@{$parents},$category));
9833: if ($allitems->{$item} eq '') {
9834: push(@{$trails},$trailstr);
9835: $allitems->{$item} = scalar(@{$trails})-1;
9836: }
9837: my $deeper = $depth+1;
9838: push(@{$parents},$category);
9839: if (ref($subcats) eq 'HASH') {
9840: my $subcat = &escape($name).':'.$category.':'.$depth;
9841: for (my $j=@{$parents}; $j>=0; $j--) {
9842: my $higher;
9843: if ($j > 0) {
9844: $higher = &escape($parents->[$j]).':'.
9845: &escape($parents->[$j-1]).':'.$j;
9846: } else {
9847: $higher = &escape($parents->[$j]).'::'.$j;
9848: }
9849: push(@{$subcats->{$higher}},$subcat);
9850: }
9851: }
9852: &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
9853: $subcats);
9854: pop(@{$parents});
9855: }
9856: } else {
9857: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
9858: my $trailstr = join(' -> ',(@{$parents},$category));
9859: if ($allitems->{$item} eq '') {
9860: push(@{$trails},$trailstr);
9861: $allitems->{$item} = scalar(@{$trails})-1;
9862: }
9863: }
9864: return;
9865: }
9866:
9867: =pod
9868:
9869: =item *&assign_categories_table()
9870:
9871: Create a datatable for display of hierarchical categories in a domain,
9872: with checkboxes to allow a course to be categorized.
9873:
9874: Inputs:
9875:
9876: cathash - reference to hash of categories defined for the domain (from
9877: configuration.db)
9878:
9879: currcat - scalar with an & separated list of categories assigned to a course.
9880:
9881: type - scalar contains course type (Course or Community).
9882:
9883: Returns: $output (markup to be displayed)
9884:
9885: =cut
9886:
9887: sub assign_categories_table {
9888: my ($cathash,$currcat,$type) = @_;
9889: my $output;
9890: if (ref($cathash) eq 'HASH') {
9891: my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
9892: &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
9893: $maxdepth = scalar(@cats);
9894: if (@cats > 0) {
9895: my $itemcount = 0;
9896: if (ref($cats[0]) eq 'ARRAY') {
9897: my @currcategories;
9898: if ($currcat ne '') {
9899: @currcategories = split('&',$currcat);
9900: }
9901: my $table;
9902: for (my $i=0; $i<@{$cats[0]}; $i++) {
9903: my $parent = $cats[0][$i];
9904: next if ($parent eq 'instcode');
9905: if ($type eq 'Community') {
9906: next unless ($parent eq 'communities');
9907: } else {
9908: next if ($parent eq 'communities');
9909: }
9910: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
9911: my $item = &escape($parent).'::0';
9912: my $checked = '';
9913: if (@currcategories > 0) {
9914: if (grep(/^\Q$item\E$/,@currcategories)) {
9915: $checked = ' checked="checked"';
9916: }
9917: }
9918: my $parent_title = $parent;
9919: if ($parent eq 'communities') {
9920: $parent_title = &mt('Communities');
9921: }
9922: $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
9923: '<input type="checkbox" name="usecategory" value="'.
9924: $item.'"'.$checked.' />'.$parent_title.'</span>'.
9925: '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
9926: my $depth = 1;
9927: push(@path,$parent);
9928: $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
9929: pop(@path);
9930: $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
9931: $itemcount ++;
9932: }
9933: if ($itemcount) {
9934: $output = &Apache::loncommon::start_data_table().
9935: $table.
9936: &Apache::loncommon::end_data_table();
9937: }
9938: }
9939: }
9940: }
9941: return $output;
9942: }
9943:
9944: =pod
9945:
9946: =item *&assign_category_rows()
9947:
9948: Create a datatable row for display of nested categories in a domain,
9949: with checkboxes to allow a course to be categorized,called recursively.
9950:
9951: Inputs:
9952:
9953: itemcount - track row number for alternating colors
9954:
9955: cats - reference to array of arrays/hashes which encapsulates hierarchy of
9956: categories and subcategories.
9957:
9958: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
9959:
9960: parent - parent of current category item
9961:
9962: path - Array containing all categories back up through the hierarchy from the
9963: current category to the top level.
9964:
9965: currcategories - reference to array of current categories assigned to the course
9966:
9967: Returns: $output (markup to be displayed).
9968:
9969: =cut
9970:
9971: sub assign_category_rows {
9972: my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
9973: my ($text,$name,$item,$chgstr);
9974: if (ref($cats) eq 'ARRAY') {
9975: my $maxdepth = scalar(@{$cats});
9976: if (ref($cats->[$depth]) eq 'HASH') {
9977: if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
9978: my $numchildren = @{$cats->[$depth]{$parent}};
9979: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
9980: $text .= '<td><table class="LC_datatable">';
9981: for (my $j=0; $j<$numchildren; $j++) {
9982: $name = $cats->[$depth]{$parent}[$j];
9983: $item = &escape($name).':'.&escape($parent).':'.$depth;
9984: my $deeper = $depth+1;
9985: my $checked = '';
9986: if (ref($currcategories) eq 'ARRAY') {
9987: if (@{$currcategories} > 0) {
9988: if (grep(/^\Q$item\E$/,@{$currcategories})) {
9989: $checked = ' checked="checked"';
9990: }
9991: }
9992: }
9993: $text .= '<tr><td><span class="LC_nobreak"><label>'.
9994: '<input type="checkbox" name="usecategory" value="'.
9995: $item.'"'.$checked.' />'.$name.'</label></span>'.
9996: '<input type="hidden" name="catname" value="'.$name.'" />'.
9997: '</td><td>';
9998: if (ref($path) eq 'ARRAY') {
9999: push(@{$path},$name);
10000: $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
10001: pop(@{$path});
10002: }
10003: $text .= '</td></tr>';
10004: }
10005: $text .= '</table></td>';
10006: }
10007: }
10008: }
10009: return $text;
10010: }
10011:
10012: ############################################################
10013: ############################################################
10014:
10015:
10016: sub commit_customrole {
10017: my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
10018: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
10019: ($start?', '.&mt('starting').' '.localtime($start):'').
10020: ($end?', ending '.localtime($end):'').': <b>'.
10021: &Apache::lonnet::assigncustomrole(
10022: $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
10023: '</b><br />';
10024: return $output;
10025: }
10026:
10027: sub commit_standardrole {
10028: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
10029: my ($output,$logmsg,$linefeed);
10030: if ($context eq 'auto') {
10031: $linefeed = "\n";
10032: } else {
10033: $linefeed = "<br />\n";
10034: }
10035: if ($three eq 'st') {
10036: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
10037: $one,$two,$sec,$context);
10038: if (($result =~ /^error/) || ($result eq 'not_in_class') ||
10039: ($result eq 'unknown_course') || ($result eq 'refused')) {
10040: $output = $logmsg.' '.&mt('Error: ').$result."\n";
10041: } else {
10042: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
10043: ($start?', '.&mt('starting').' '.localtime($start):'').
10044: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
10045: if ($context eq 'auto') {
10046: $output .= $result.$linefeed.&mt('Add to classlist').': ok';
10047: } else {
10048: $output .= '<b>'.$result.'</b>'.$linefeed.
10049: &mt('Add to classlist').': <b>ok</b>';
10050: }
10051: $output .= $linefeed;
10052: }
10053: } else {
10054: $output = &mt('Assigning').' '.$three.' in '.$url.
10055: ($start?', '.&mt('starting').' '.localtime($start):'').
10056: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
10057: my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
10058: if ($context eq 'auto') {
10059: $output .= $result.$linefeed;
10060: } else {
10061: $output .= '<b>'.$result.'</b>'.$linefeed;
10062: }
10063: }
10064: return $output;
10065: }
10066:
10067: sub commit_studentrole {
10068: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
10069: my ($result,$linefeed,$oldsecurl,$newsecurl);
10070: if ($context eq 'auto') {
10071: $linefeed = "\n";
10072: } else {
10073: $linefeed = '<br />'."\n";
10074: }
10075: if (defined($one) && defined($two)) {
10076: my $cid=$one.'_'.$two;
10077: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
10078: my $secchange = 0;
10079: my $expire_role_result;
10080: my $modify_section_result;
10081: if ($oldsec ne '-1') {
10082: if ($oldsec ne $sec) {
10083: $secchange = 1;
10084: my $now = time;
10085: my $uurl='/'.$cid;
10086: $uurl=~s/\_/\//g;
10087: if ($oldsec) {
10088: $uurl.='/'.$oldsec;
10089: }
10090: $oldsecurl = $uurl;
10091: $expire_role_result =
10092: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
10093: if ($env{'request.course.sec'} ne '') {
10094: if ($expire_role_result eq 'refused') {
10095: my @roles = ('st');
10096: my @statuses = ('previous');
10097: my @roledoms = ($one);
10098: my $withsec = 1;
10099: my %roleshash =
10100: &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
10101: \@statuses,\@roles,\@roledoms,$withsec);
10102: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
10103: my ($oldstart,$oldend) =
10104: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
10105: if ($oldend > 0 && $oldend <= $now) {
10106: $expire_role_result = 'ok';
10107: }
10108: }
10109: }
10110: }
10111: $result = $expire_role_result;
10112: }
10113: }
10114: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
10115: $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
10116: if ($modify_section_result =~ /^ok/) {
10117: if ($secchange == 1) {
10118: if ($sec eq '') {
10119: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
10120: } else {
10121: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
10122: }
10123: } elsif ($oldsec eq '-1') {
10124: if ($sec eq '') {
10125: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
10126: } else {
10127: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
10128: }
10129: } else {
10130: if ($sec eq '') {
10131: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
10132: } else {
10133: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
10134: }
10135: }
10136: } else {
10137: if ($secchange) {
10138: $$logmsg .= &mt('Error when attempting section change for [_1] from old section "[_2]" to new section: "[_3]" in course [_4] -error:',$uname,$oldsec,$sec,$cid).' '.$modify_section_result.$linefeed;
10139: } else {
10140: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
10141: }
10142: }
10143: $result = $modify_section_result;
10144: } elsif ($secchange == 1) {
10145: if ($oldsec eq '') {
10146: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
10147: } else {
10148: $$logmsg .= &mt('Error when attempting to expire existing role for [_1] in section [_2] in course [_3] -error: ',$uname,$oldsec,$cid).' '.$expire_role_result.$linefeed;
10149: }
10150: if ($expire_role_result eq 'refused') {
10151: my $newsecurl = '/'.$cid;
10152: $newsecurl =~ s/\_/\//g;
10153: if ($sec ne '') {
10154: $newsecurl.='/'.$sec;
10155: }
10156: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
10157: if ($sec eq '') {
10158: $$logmsg .= &mt('Although your current role has privileges to add students to section "[_1]", you do not have privileges to modify existing enrollments unaffiliated with any section.',$sec).$linefeed;
10159: } else {
10160: $$logmsg .= &mt('Although your current role has privileges to add students to section "[_1]", you do not have privileges to modify existing enrollments in other sections.',$sec).$linefeed;
10161: }
10162: }
10163: }
10164: }
10165: } else {
10166: $$logmsg .= &mt('Incomplete course id defined.').$linefeed.&mt('Addition of user [_1] from domain [_2] to course [_3], section [_4] not completed.',$uname,$udom,$one.'_'.$two,$sec).$linefeed;
10167: $result = "error: incomplete course id\n";
10168: }
10169: return $result;
10170: }
10171:
10172: ############################################################
10173: ############################################################
10174:
10175: sub check_clone {
10176: my ($args,$linefeed) = @_;
10177: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
10178: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
10179: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
10180: my $clonemsg;
10181: my $can_clone = 0;
10182: my $lctype = lc($args->{'crstype'});
10183: if ($lctype ne 'community') {
10184: $lctype = 'course';
10185: }
10186: if ($clonehome eq 'no_host') {
10187: if ($args->{'crstype'} eq 'Community') {
10188: $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
10189: } else {
10190: $clonemsg = &mt('No new course created.').$linefeed.&mt('A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
10191: }
10192: } else {
10193: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
10194: if ($args->{'crstype'} eq 'Community') {
10195: if ($clonedesc{'type'} ne 'Community') {
10196: $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
10197: return ($can_clone, $clonemsg, $cloneid, $clonehome);
10198: }
10199: }
10200: if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
10201: (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
10202: $can_clone = 1;
10203: } else {
10204: my %clonehash = &Apache::lonnet::get('environment',['cloners'],
10205: $args->{'clonedomain'},$args->{'clonecourse'});
10206: my @cloners = split(/,/,$clonehash{'cloners'});
10207: if (grep(/^\*$/,@cloners)) {
10208: $can_clone = 1;
10209: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
10210: $can_clone = 1;
10211: } else {
10212: my $ccrole = 'cc';
10213: if ($args->{'crstype'} eq 'Community') {
10214: $ccrole = 'co';
10215: }
10216: my %roleshash =
10217: &Apache::lonnet::get_my_roles($args->{'ccuname'},
10218: $args->{'ccdomain'},
10219: 'userroles',['active'],[$ccrole],
10220: [$args->{'clonedomain'}]);
10221: if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
10222: $can_clone = 1;
10223: } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
10224: $can_clone = 1;
10225: } else {
10226: if ($args->{'crstype'} eq 'Community') {
10227: $clonemsg = &mt('No new community created.').$linefeed.&mt('The new community could not be cloned from the existing community because the new community owner ([_1]) does not have cloning rights in the existing community ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
10228: } else {
10229: $clonemsg = &mt('No new course created.').$linefeed.&mt('The new course could not be cloned from the existing course because the new course owner ([_1]) does not have cloning rights in the existing course ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
10230: }
10231: }
10232: }
10233: }
10234: }
10235: return ($can_clone, $clonemsg, $cloneid, $clonehome);
10236: }
10237:
10238: sub construct_course {
10239: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
10240: my $outcome;
10241: my $linefeed = '<br />'."\n";
10242: if ($context eq 'auto') {
10243: $linefeed = "\n";
10244: }
10245:
10246: #
10247: # Are we cloning?
10248: #
10249: my ($can_clone, $clonemsg, $cloneid, $clonehome);
10250: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
10251: ($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
10252: if ($context ne 'auto') {
10253: if ($clonemsg ne '') {
10254: $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
10255: }
10256: }
10257: $outcome .= $clonemsg.$linefeed;
10258:
10259: if (!$can_clone) {
10260: return (0,$outcome);
10261: }
10262: }
10263:
10264: #
10265: # Open course
10266: #
10267: my $crstype = lc($args->{'crstype'});
10268: my %cenv=();
10269: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
10270: $args->{'cdescr'},
10271: $args->{'curl'},
10272: $args->{'course_home'},
10273: $args->{'nonstandard'},
10274: $args->{'crscode'},
10275: $args->{'ccuname'}.':'.
10276: $args->{'ccdomain'},
10277: $args->{'crstype'},
10278: $cnum,$context,$category);
10279:
10280: # Note: The testing routines depend on this being output; see
10281: # Utils::Course. This needs to at least be output as a comment
10282: # if anyone ever decides to not show this, and Utils::Course::new
10283: # will need to be suitably modified.
10284: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
10285: if ($$courseid =~ /^error:/) {
10286: return (0,$outcome);
10287: }
10288:
10289: #
10290: # Check if created correctly
10291: #
10292: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
10293: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
10294: if ($crsuhome eq 'no_host') {
10295: $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
10296: return (0,$outcome);
10297: }
10298: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
10299:
10300: #
10301: # Do the cloning
10302: #
10303: if ($can_clone && $cloneid) {
10304: $clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
10305: if ($context ne 'auto') {
10306: $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
10307: }
10308: $outcome .= $clonemsg.$linefeed;
10309: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
10310: # Copy all files
10311: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
10312: # Restore URL
10313: $cenv{'url'}=$oldcenv{'url'};
10314: # Restore title
10315: $cenv{'description'}=$oldcenv{'description'};
10316: # Restore creation date, creator and creation context.
10317: $cenv{'internal.created'}=$oldcenv{'internal.created'};
10318: $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
10319: $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
10320: # Mark as cloned
10321: $cenv{'clonedfrom'}=$cloneid;
10322: # Need to clone grading mode
10323: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
10324: $cenv{'grading'}=$newenv{'grading'};
10325: # Do not clone these environment entries
10326: &Apache::lonnet::del('environment',
10327: ['default_enrollment_start_date',
10328: 'default_enrollment_end_date',
10329: 'question.email',
10330: 'policy.email',
10331: 'comment.email',
10332: 'pch.users.denied',
10333: 'plc.users.denied',
10334: 'hidefromcat',
10335: 'categories'],
10336: $$crsudom,$$crsunum);
10337: }
10338:
10339: #
10340: # Set environment (will override cloned, if existing)
10341: #
10342: my @sections = ();
10343: my @xlists = ();
10344: if ($args->{'crstype'}) {
10345: $cenv{'type'}=$args->{'crstype'};
10346: }
10347: if ($args->{'crsid'}) {
10348: $cenv{'courseid'}=$args->{'crsid'};
10349: }
10350: if ($args->{'crscode'}) {
10351: $cenv{'internal.coursecode'}=$args->{'crscode'};
10352: }
10353: if ($args->{'crsquota'} ne '') {
10354: $cenv{'internal.coursequota'}=$args->{'crsquota'};
10355: } else {
10356: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
10357: }
10358: if ($args->{'ccuname'}) {
10359: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
10360: ':'.$args->{'ccdomain'};
10361: } else {
10362: $cenv{'internal.courseowner'} = $args->{'curruser'};
10363: }
10364: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
10365: if ($args->{'crssections'}) {
10366: $cenv{'internal.sectionnums'} = '';
10367: if ($args->{'crssections'} =~ m/,/) {
10368: @sections = split/,/,$args->{'crssections'};
10369: } else {
10370: $sections[0] = $args->{'crssections'};
10371: }
10372: if (@sections > 0) {
10373: foreach my $item (@sections) {
10374: my ($sec,$gp) = split/:/,$item;
10375: my $class = $args->{'crscode'}.$sec;
10376: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
10377: $cenv{'internal.sectionnums'} .= $item.',';
10378: unless ($addcheck eq 'ok') {
10379: push @badclasses, $class;
10380: }
10381: }
10382: $cenv{'internal.sectionnums'} =~ s/,$//;
10383: }
10384: }
10385: # do not hide course coordinator from staff listing,
10386: # even if privileged
10387: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10388: # add crosslistings
10389: if ($args->{'crsxlist'}) {
10390: $cenv{'internal.crosslistings'}='';
10391: if ($args->{'crsxlist'} =~ m/,/) {
10392: @xlists = split/,/,$args->{'crsxlist'};
10393: } else {
10394: $xlists[0] = $args->{'crsxlist'};
10395: }
10396: if (@xlists > 0) {
10397: foreach my $item (@xlists) {
10398: my ($xl,$gp) = split/:/,$item;
10399: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
10400: $cenv{'internal.crosslistings'} .= $item.',';
10401: unless ($addcheck eq 'ok') {
10402: push @badclasses, $xl;
10403: }
10404: }
10405: $cenv{'internal.crosslistings'} =~ s/,$//;
10406: }
10407: }
10408: if ($args->{'autoadds'}) {
10409: $cenv{'internal.autoadds'}=$args->{'autoadds'};
10410: }
10411: if ($args->{'autodrops'}) {
10412: $cenv{'internal.autodrops'}=$args->{'autodrops'};
10413: }
10414: # check for notification of enrollment changes
10415: my @notified = ();
10416: if ($args->{'notify_owner'}) {
10417: if ($args->{'ccuname'} ne '') {
10418: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
10419: }
10420: }
10421: if ($args->{'notify_dc'}) {
10422: if ($uname ne '') {
10423: push(@notified,$uname.':'.$udom);
10424: }
10425: }
10426: if (@notified > 0) {
10427: my $notifylist;
10428: if (@notified > 1) {
10429: $notifylist = join(',',@notified);
10430: } else {
10431: $notifylist = $notified[0];
10432: }
10433: $cenv{'internal.notifylist'} = $notifylist;
10434: }
10435: if (@badclasses > 0) {
10436: my %lt=&Apache::lonlocal::texthash(
10437: 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course. However, if automated course roster updates are enabled for this class, these particular sections/crosslistings will not contribute towards enrollment, because the user identified as the course owner for this LON-CAPA course',
10438: 'dnhr' => 'does not have rights to access enrollment in these classes',
10439: 'adby' => 'as determined by the policies of your institution on access to official classlists'
10440: );
10441: my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
10442: ' ('.$lt{'adby'}.')';
10443: if ($context eq 'auto') {
10444: $outcome .= $badclass_msg.$linefeed;
10445: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
10446: foreach my $item (@badclasses) {
10447: if ($context eq 'auto') {
10448: $outcome .= " - $item\n";
10449: } else {
10450: $outcome .= "<li>$item</li>\n";
10451: }
10452: }
10453: if ($context eq 'auto') {
10454: $outcome .= $linefeed;
10455: } else {
10456: $outcome .= "</ul><br /><br /></div>\n";
10457: }
10458: }
10459: }
10460: if ($args->{'no_end_date'}) {
10461: $args->{'endaccess'} = 0;
10462: }
10463: $cenv{'internal.autostart'}=$args->{'enrollstart'};
10464: $cenv{'internal.autoend'}=$args->{'enrollend'};
10465: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
10466: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
10467: if ($args->{'showphotos'}) {
10468: $cenv{'internal.showphotos'}=$args->{'showphotos'};
10469: }
10470: $cenv{'internal.authtype'} = $args->{'authtype'};
10471: $cenv{'internal.autharg'} = $args->{'autharg'};
10472: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
10473: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
10474: my $krb_msg = &mt('As you did not include the default Kerberos domain to be used for authentication in this class, the institutional data used by the automated enrollment process must include the Kerberos domain for each new student');
10475: if ($context eq 'auto') {
10476: $outcome .= $krb_msg;
10477: } else {
10478: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
10479: }
10480: $outcome .= $linefeed;
10481: }
10482: }
10483: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
10484: if ($args->{'setpolicy'}) {
10485: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10486: }
10487: if ($args->{'setcontent'}) {
10488: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10489: }
10490: }
10491: if ($args->{'reshome'}) {
10492: $cenv{'reshome'}=$args->{'reshome'}.'/';
10493: $cenv{'reshome'}=~s/\/+$/\//;
10494: }
10495: #
10496: # course has keyed access
10497: #
10498: if ($args->{'setkeys'}) {
10499: $cenv{'keyaccess'}='yes';
10500: }
10501: # if specified, key authority is not course, but user
10502: # only active if keyaccess is yes
10503: if ($args->{'keyauth'}) {
10504: my ($user,$domain) = split(':',$args->{'keyauth'});
10505: $user = &LONCAPA::clean_username($user);
10506: $domain = &LONCAPA::clean_username($domain);
10507: if ($user ne '' && $domain ne '') {
10508: $cenv{'keyauth'}=$user.':'.$domain;
10509: }
10510: }
10511:
10512: if ($args->{'disresdis'}) {
10513: $cenv{'pch.roles.denied'}='st';
10514: }
10515: if ($args->{'disablechat'}) {
10516: $cenv{'plc.roles.denied'}='st';
10517: }
10518:
10519: # Record we've not yet viewed the Course Initialization Helper for this
10520: # course
10521: $cenv{'course.helper.not.run'} = 1;
10522: #
10523: # Use new Randomseed
10524: #
10525: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
10526: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
10527: #
10528: # The encryption code and receipt prefix for this course
10529: #
10530: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
10531: $cenv{'internal.encpref'}=100+int(9*rand(99));
10532: #
10533: # By default, use standard grading
10534: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
10535:
10536: $outcome .= $linefeed.&mt('Setting environment').': '.
10537: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
10538: #
10539: # Open all assignments
10540: #
10541: if ($args->{'openall'}) {
10542: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
10543: my %storecontent = ($storeunder => time,
10544: $storeunder.'.type' => 'date_start');
10545:
10546: $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
10547: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
10548: }
10549: #
10550: # Set first page
10551: #
10552: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
10553: || ($cloneid)) {
10554: use LONCAPA::map;
10555: $outcome .= &mt('Setting first resource').': ';
10556:
10557: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
10558: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
10559:
10560: $outcome .= ($fatal?$errtext:'read ok').' - ';
10561: my $title; my $url;
10562: if ($args->{'firstres'} eq 'syl') {
10563: $title=&mt('Syllabus');
10564: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
10565: } else {
10566: $title=&mt('Table of Contents');
10567: $url='/adm/navmaps';
10568: }
10569:
10570: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
10571: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
10572:
10573: if ($errtext) { $fatal=2; }
10574: $outcome .= ($fatal?$errtext:'write ok').$linefeed;
10575: }
10576:
10577: return (1,$outcome);
10578: }
10579:
10580: ############################################################
10581: ############################################################
10582:
10583: sub course_type {
10584: my ($cid) = @_;
10585: if (!defined($cid)) {
10586: $cid = $env{'request.course.id'};
10587: }
10588: if (defined($env{'course.'.$cid.'.type'})) {
10589: return $env{'course.'.$cid.'.type'};
10590: } else {
10591: return 'Course';
10592: }
10593: }
10594:
10595: sub group_term {
10596: my $crstype = &course_type();
10597: my %names = (
10598: 'Course' => 'group',
10599: 'Community' => 'group',
10600: );
10601: return $names{$crstype};
10602: }
10603:
10604: sub course_types {
10605: my @types = ('official','unofficial','community');
10606: my %typename = (
10607: official => 'Official course',
10608: unofficial => 'Unofficial course',
10609: community => 'Community',
10610: );
10611: return (\@types,\%typename);
10612: }
10613:
10614: sub icon {
10615: my ($file)=@_;
10616: my $curfext = lc((split(/\./,$file))[-1]);
10617: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
10618: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
10619: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
10620: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
10621: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
10622: $curfext.".gif") {
10623: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
10624: $curfext.".gif";
10625: }
10626: }
10627: return &lonhttpdurl($iconname);
10628: }
10629:
10630: sub lonhttpdurl {
10631: #
10632: # Had been used for "small fry" static images on separate port 8080.
10633: # Modify here if lightweight http functionality desired again.
10634: # Currently eliminated due to increasing firewall issues.
10635: #
10636: my ($url)=@_;
10637: return $url;
10638: }
10639:
10640: sub connection_aborted {
10641: my ($r)=@_;
10642: $r->print(" ");$r->rflush();
10643: my $c = $r->connection;
10644: return $c->aborted();
10645: }
10646:
10647: # Escapes strings that may have embedded 's that will be put into
10648: # strings as 'strings'.
10649: sub escape_single {
10650: my ($input) = @_;
10651: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
10652: $input =~ s/\'/\\\'/g; # Esacpe the 's....
10653: return $input;
10654: }
10655:
10656: # Same as escape_single, but escape's "'s This
10657: # can be used for "strings"
10658: sub escape_double {
10659: my ($input) = @_;
10660: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
10661: $input =~ s/\"/\\\"/g; # Esacpe the "s....
10662: return $input;
10663: }
10664:
10665: # Escapes the last element of a full URL.
10666: sub escape_url {
10667: my ($url) = @_;
10668: my @urlslices = split(/\//, $url,-1);
10669: my $lastitem = &escape(pop(@urlslices));
10670: return join('/',@urlslices).'/'.$lastitem;
10671: }
10672:
10673: sub compare_arrays {
10674: my ($arrayref1,$arrayref2) = @_;
10675: my (@difference,%count);
10676: @difference = ();
10677: %count = ();
10678: if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
10679: foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
10680: foreach my $element (keys(%count)) {
10681: if ($count{$element} == 1) {
10682: push(@difference,$element);
10683: }
10684: }
10685: }
10686: return @difference;
10687: }
10688:
10689: # -------------------------------------------------------- Initialize user login
10690: sub init_user_environment {
10691: my ($r, $username, $domain, $authhost, $form, $args) = @_;
10692: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
10693:
10694: my $public=($username eq 'public' && $domain eq 'public');
10695:
10696: # See if old ID present, if so, remove
10697:
10698: my ($filename,$cookie,$userroles);
10699: my $now=time;
10700:
10701: if ($public) {
10702: my $max_public=100;
10703: my $oldest;
10704: my $oldest_time=0;
10705: for(my $next=1;$next<=$max_public;$next++) {
10706: if (-e $lonids."/publicuser_$next.id") {
10707: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
10708: if ($mtime<$oldest_time || !$oldest_time) {
10709: $oldest_time=$mtime;
10710: $oldest=$next;
10711: }
10712: } else {
10713: $cookie="publicuser_$next";
10714: last;
10715: }
10716: }
10717: if (!$cookie) { $cookie="publicuser_$oldest"; }
10718: } else {
10719: # if this isn't a robot, kill any existing non-robot sessions
10720: if (!$args->{'robot'}) {
10721: opendir(DIR,$lonids);
10722: while ($filename=readdir(DIR)) {
10723: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
10724: unlink($lonids.'/'.$filename);
10725: }
10726: }
10727: closedir(DIR);
10728: }
10729: # Give them a new cookie
10730: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
10731: : $now.$$.int(rand(10000)));
10732: $cookie="$username\_$id\_$domain\_$authhost";
10733:
10734: # Initialize roles
10735:
10736: $userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
10737: }
10738: # ------------------------------------ Check browser type and MathML capability
10739:
10740: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
10741: $clientunicode,$clientos) = &decode_user_agent($r);
10742:
10743: # ------------------------------------------------------------- Get environment
10744:
10745: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
10746: my ($tmp) = keys(%userenv);
10747: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10748: # default remote control to off
10749: if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
10750: } else {
10751: undef(%userenv);
10752: }
10753: if (($userenv{'interface'}) && (!$form->{'interface'})) {
10754: $form->{'interface'}=$userenv{'interface'};
10755: }
10756: $env{'environment.remote'}=$userenv{'remote'};
10757: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
10758:
10759: # --------------- Do not trust query string to be put directly into environment
10760: foreach my $option ('interface','localpath','localres') {
10761: $form->{$option}=~s/[\n\r\=]//gs;
10762: }
10763: # --------------------------------------------------------- Write first profile
10764:
10765: {
10766: my %initial_env =
10767: ("user.name" => $username,
10768: "user.domain" => $domain,
10769: "user.home" => $authhost,
10770: "browser.type" => $clientbrowser,
10771: "browser.version" => $clientversion,
10772: "browser.mathml" => $clientmathml,
10773: "browser.unicode" => $clientunicode,
10774: "browser.os" => $clientos,
10775: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
10776: "request.course.fn" => '',
10777: "request.course.uri" => '',
10778: "request.course.sec" => '',
10779: "request.role" => 'cm',
10780: "request.role.adv" => $env{'user.adv'},
10781: "request.host" => $ENV{'REMOTE_ADDR'},);
10782:
10783: if ($form->{'localpath'}) {
10784: $initial_env{"browser.localpath"} = $form->{'localpath'};
10785: $initial_env{"browser.localres"} = $form->{'localres'};
10786: }
10787:
10788: if ($public) {
10789: $initial_env{"environment.remote"} = "off";
10790: }
10791: if ($form->{'interface'}) {
10792: $form->{'interface'}=~s/\W//gs;
10793: $initial_env{"browser.interface"} = $form->{'interface'};
10794: $env{'browser.interface'}=$form->{'interface'};
10795: }
10796:
10797: foreach my $tool ('aboutme','blog','portfolio') {
10798: $userenv{'availabletools.'.$tool} =
10799: &Apache::lonnet::usertools_access($username,$domain,$tool,'reload');
10800: }
10801:
10802: foreach my $crstype ('official','unofficial','community') {
10803: $userenv{'canrequest.'.$crstype} =
10804: &Apache::lonnet::usertools_access($username,$domain,$crstype,
10805: 'reload','requestcourses');
10806: }
10807:
10808: $env{'user.environment'} = "$lonids/$cookie.id";
10809:
10810: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
10811: &GDBM_WRCREAT(),0640)) {
10812: &_add_to_env(\%disk_env,\%initial_env);
10813: &_add_to_env(\%disk_env,\%userenv,'environment.');
10814: &_add_to_env(\%disk_env,$userroles);
10815: if (ref($args->{'extra_env'})) {
10816: &_add_to_env(\%disk_env,$args->{'extra_env'});
10817: }
10818: untie(%disk_env);
10819: } else {
10820: &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
10821: 'Could not create environment storage in lonauth: '.$!.'</span>');
10822: return 'error: '.$!;
10823: }
10824: }
10825: $env{'request.role'}='cm';
10826: $env{'request.role.adv'}=$env{'user.adv'};
10827: $env{'browser.type'}=$clientbrowser;
10828:
10829: return $cookie;
10830:
10831: }
10832:
10833: sub _add_to_env {
10834: my ($idf,$env_data,$prefix) = @_;
10835: if (ref($env_data) eq 'HASH') {
10836: while (my ($key,$value) = each(%$env_data)) {
10837: $idf->{$prefix.$key} = $value;
10838: $env{$prefix.$key} = $value;
10839: }
10840: }
10841: }
10842:
10843: # --- Get the symbolic name of a problem and the url
10844: sub get_symb {
10845: my ($request,$silent) = @_;
10846: (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10847: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
10848: if ($symb eq '') {
10849: if (!$silent) {
10850: $request->print("Unable to handle ambiguous references:$url:.");
10851: return ();
10852: }
10853: }
10854: &Apache::lonenc::check_decrypt(\$symb);
10855: return ($symb);
10856: }
10857:
10858: # --------------------------------------------------------------Get annotation
10859:
10860: sub get_annotation {
10861: my ($symb,$enc) = @_;
10862:
10863: my $key = $symb;
10864: if (!$enc) {
10865: $key =
10866: &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
10867: }
10868: my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
10869: return $annotation{$key};
10870: }
10871:
10872: sub clean_symb {
10873: my ($symb,$delete_enc) = @_;
10874:
10875: &Apache::lonenc::check_decrypt(\$symb);
10876: my $enc = $env{'request.enc'};
10877: if ($delete_enc) {
10878: delete($env{'request.enc'});
10879: }
10880:
10881: return ($symb,$enc);
10882: }
10883:
10884: =pod
10885:
10886: =back
10887:
10888: =cut
10889:
10890: 1;
10891: __END__;
10892:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>