1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.650 2008/03/28 14:52:52 www 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 HTML::Entities;
65: use Apache::lonhtmlcommon();
66: use Apache::loncoursedata();
67: use Apache::lontexconvert();
68: use Apache::lonclonecourse();
69: use LONCAPA qw(:DEFAULT :match);
70:
71: # ---------------------------------------------- Designs
72: use vars qw(%defaultdesign);
73:
74: my $readit;
75:
76:
77: ##
78: ## Global Variables
79: ##
80:
81:
82: # ----------------------------------------------- SSI with retries:
83: #
84:
85: =pod
86:
87: =head1 Server Side include with retries:
88:
89: =over 4
90:
91: =item * &ssi_with_retries(resource,retries form)
92:
93: Performs an ssi with some number of retries. Retries continue either
94: until the result is ok or until the retry count supplied by the
95: caller is exhausted.
96:
97: Inputs:
98:
99: =over 4
100:
101: resource - Identifies the resource to insert.
102:
103: retries - Count of the number of retries allowed.
104:
105: form - Hash that identifies the rendering options.
106:
107: =back
108:
109: Returns:
110:
111: =over 4
112:
113: content - The content of the response. If retries were exhausted this is empty.
114:
115: response - The response from the last attempt (which may or may not have been successful.
116:
117: =back
118:
119: =back
120:
121: =cut
122:
123: sub ssi_with_retries {
124: my ($resource, $retries, %form) = @_;
125:
126:
127: my $ok = 0; # True if we got a good response.
128: my $content;
129: my $response;
130:
131: # Try to get the ssi done. within the retries count:
132:
133: do {
134: ($content, $response) = &Apache::lonnet::ssi($resource, %form);
135: $ok = $response->is_success;
136: if (!$ok) {
137: &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
138: }
139: $retries--;
140: } while (!$ok && ($retries > 0));
141:
142: if (!$ok) {
143: $content = ''; # On error return an empty content.
144: }
145: return ($content, $response);
146:
147: }
148:
149:
150:
151: # ----------------------------------------------- Filetypes/Languages/Copyright
152: my %language;
153: my %supported_language;
154: my %cprtag;
155: my %scprtag;
156: my %fe; my %fd; my %fm;
157: my %category_extensions;
158:
159: # ---------------------------------------------- Thesaurus variables
160: #
161: # %Keywords:
162: # A hash used by &keyword to determine if a word is considered a keyword.
163: # $thesaurus_db_file
164: # Scalar containing the full path to the thesaurus database.
165:
166: my %Keywords;
167: my $thesaurus_db_file;
168:
169: #
170: # Initialize values from language.tab, copyright.tab, filetypes.tab,
171: # thesaurus.tab, and filecategories.tab.
172: #
173: BEGIN {
174: # Variable initialization
175: $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
176: #
177: unless ($readit) {
178: # ------------------------------------------------------------------- languages
179: {
180: my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
181: '/language.tab';
182: if ( open(my $fh,"<$langtabfile") ) {
183: while (my $line = <$fh>) {
184: next if ($line=~/^\#/);
185: chomp($line);
186: my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
187: $language{$key}=$val.' - '.$enc;
188: if ($sup) {
189: $supported_language{$key}=$sup;
190: }
191: }
192: close($fh);
193: }
194: }
195: # ------------------------------------------------------------------ copyrights
196: {
197: my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
198: '/copyright.tab';
199: if ( open (my $fh,"<$copyrightfile") ) {
200: while (my $line = <$fh>) {
201: next if ($line=~/^\#/);
202: chomp($line);
203: my ($key,$val)=(split(/\s+/,$line,2));
204: $cprtag{$key}=$val;
205: }
206: close($fh);
207: }
208: }
209: # ----------------------------------------------------------- source copyrights
210: {
211: my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
212: '/source_copyright.tab';
213: if ( open (my $fh,"<$sourcecopyrightfile") ) {
214: while (my $line = <$fh>) {
215: next if ($line =~ /^\#/);
216: chomp($line);
217: my ($key,$val)=(split(/\s+/,$line,2));
218: $scprtag{$key}=$val;
219: }
220: close($fh);
221: }
222: }
223:
224: # -------------------------------------------------------------- default domain designs
225: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
226: my $designfile = $designdir.'/default.tab';
227: if ( open (my $fh,"<$designfile") ) {
228: while (my $line = <$fh>) {
229: next if ($line =~ /^\#/);
230: chomp($line);
231: my ($key,$val)=(split(/\=/,$line));
232: if ($val) { $defaultdesign{$key}=$val; }
233: }
234: close($fh);
235: }
236:
237: # ------------------------------------------------------------- file categories
238: {
239: my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
240: '/filecategories.tab';
241: if ( open (my $fh,"<$categoryfile") ) {
242: while (my $line = <$fh>) {
243: next if ($line =~ /^\#/);
244: chomp($line);
245: my ($extension,$category)=(split(/\s+/,$line,2));
246: push @{$category_extensions{lc($category)}},$extension;
247: }
248: close($fh);
249: }
250:
251: }
252: # ------------------------------------------------------------------ file types
253: {
254: my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
255: '/filetypes.tab';
256: if ( open (my $fh,"<$typesfile") ) {
257: while (my $line = <$fh>) {
258: next if ($line =~ /^\#/);
259: chomp($line);
260: my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
261: if ($descr ne '') {
262: $fe{$ending}=lc($emb);
263: $fd{$ending}=$descr;
264: if ($mime ne 'unk') { $fm{$ending}=$mime; }
265: }
266: }
267: close($fh);
268: }
269: }
270: &Apache::lonnet::logthis(
271: "<font color=yellow>INFO: Read file types</font>");
272: $readit=1;
273: } # end of unless($readit)
274:
275: }
276:
277: ###############################################################
278: ## HTML and Javascript Helper Functions ##
279: ###############################################################
280:
281: =pod
282:
283: =head1 HTML and Javascript Functions
284:
285: =over 4
286:
287: =item * &browser_and_searcher_javascript()
288:
289: X<browsing, javascript>X<searching, javascript>Returns a string
290: containing javascript with two functions, C<openbrowser> and
291: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
292: tags.
293:
294: =item * &openbrowser(formname,elementname,only,omit) [javascript]
295:
296: inputs: formname, elementname, only, omit
297:
298: formname and elementname indicate the name of the html form and name of
299: the element that the results of the browsing selection are to be placed in.
300:
301: Specifying 'only' will restrict the browser to displaying only files
302: with the given extension. Can be a comma separated list.
303:
304: Specifying 'omit' will restrict the browser to NOT displaying files
305: with the given extension. Can be a comma separated list.
306:
307: =item * &opensearcher(formname,elementname) [javascript]
308:
309: Inputs: formname, elementname
310:
311: formname and elementname specify the name of the html form and the name
312: of the element the selection from the search results will be placed in.
313:
314: =cut
315:
316: sub browser_and_searcher_javascript {
317: my ($mode)=@_;
318: if (!defined($mode)) { $mode='edit'; }
319: my $resurl=&escape_single(&lastresurl());
320: return <<END;
321: // <!-- BEGIN LON-CAPA Internal
322: var editbrowser = null;
323: function openbrowser(formname,elementname,only,omit,titleelement) {
324: var url = '$resurl/?';
325: if (editbrowser == null) {
326: url += 'launch=1&';
327: }
328: url += 'catalogmode=interactive&';
329: url += 'mode=$mode&';
330: url += 'inhibitmenu=yes&';
331: url += 'form=' + formname + '&';
332: if (only != null) {
333: url += 'only=' + only + '&';
334: } else {
335: url += 'only=&';
336: }
337: if (omit != null) {
338: url += 'omit=' + omit + '&';
339: } else {
340: url += 'omit=&';
341: }
342: if (titleelement != null) {
343: url += 'titleelement=' + titleelement + '&';
344: } else {
345: url += 'titleelement=&';
346: }
347: url += 'element=' + elementname + '';
348: var title = 'Browser';
349: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
350: options += ',width=700,height=600';
351: editbrowser = open(url,title,options,'1');
352: editbrowser.focus();
353: }
354: var editsearcher;
355: function opensearcher(formname,elementname,titleelement) {
356: var url = '/adm/searchcat?';
357: if (editsearcher == null) {
358: url += 'launch=1&';
359: }
360: url += 'catalogmode=interactive&';
361: url += 'mode=$mode&';
362: url += 'form=' + formname + '&';
363: if (titleelement != null) {
364: url += 'titleelement=' + titleelement + '&';
365: } else {
366: url += 'titleelement=&';
367: }
368: url += 'element=' + elementname + '';
369: var title = 'Search';
370: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
371: options += ',width=700,height=600';
372: editsearcher = open(url,title,options,'1');
373: editsearcher.focus();
374: }
375: // END LON-CAPA Internal -->
376: END
377: }
378:
379: sub lastresurl {
380: if ($env{'environment.lastresurl'}) {
381: return $env{'environment.lastresurl'}
382: } else {
383: return '/res';
384: }
385: }
386:
387: sub storeresurl {
388: my $resurl=&Apache::lonnet::clutter(shift);
389: unless ($resurl=~/^\/res/) { return 0; }
390: $resurl=~s/\/$//;
391: &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
392: &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
393: return 1;
394: }
395:
396: sub studentbrowser_javascript {
397: unless (
398: (($env{'request.course.id'}) &&
399: (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
400: || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
401: '/'.$env{'request.course.sec'})
402: ))
403: || ($env{'request.role'}=~/^(au|dc|su)/)
404: ) { return ''; }
405: return (<<'ENDSTDBRW');
406: <script type="text/javascript" language="Javascript" >
407: var stdeditbrowser;
408: function openstdbrowser(formname,uname,udom,roleflag,ignorefilter) {
409: var url = '/adm/pickstudent?';
410: var filter;
411: if (!ignorefilter) {
412: eval('filter=document.'+formname+'.'+uname+'.value;');
413: }
414: if (filter != null) {
415: if (filter != '') {
416: url += 'filter='+filter+'&';
417: }
418: }
419: url += 'form=' + formname + '&unameelement='+uname+
420: '&udomelement='+udom;
421: if (roleflag) { url+="&roles=1"; }
422: var title = 'Student_Browser';
423: var options = 'scrollbars=1,resizable=1,menubar=0';
424: options += ',width=700,height=600';
425: stdeditbrowser = open(url,title,options,'1');
426: stdeditbrowser.focus();
427: }
428: </script>
429: ENDSTDBRW
430: }
431:
432: sub selectstudent_link {
433: my ($form,$unameele,$udomele)=@_;
434: if ($env{'request.course.id'}) {
435: if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
436: && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
437: '/'.$env{'request.course.sec'})) {
438: return '';
439: }
440: return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
441: '","'.$udomele.'");'."'>".&mt('Select User')."</a>";
442: }
443: if ($env{'request.role'}=~/^(au|dc|su)/) {
444: return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
445: '","'.$udomele.'",1);'."'>".&mt('Select User')."</a>";
446: }
447: return '';
448: }
449:
450: sub coursebrowser_javascript {
451: my ($domainfilter,$sec_element,$formname)=@_;
452: my $crs_or_grp_alert = &mt('Please select the type of LON-CAPA entity - Course or Group - for which you wish to add/modify a user role');
453: my $output = '
454: <script type="text/javascript">
455: var stdeditbrowser;'."\n";
456: $output .= <<"ENDSTDBRW";
457: function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,crstype) {
458: var url = '/adm/pickcourse?';
459: var domainfilter = '';
460: var formid = getFormIdByName(formname);
461: if (formid > -1) {
462: var domid = getIndexByName(formid,udom);
463: if (domid > -1) {
464: if (document.forms[formid].elements[domid].type == 'select-one') {
465: domainfilter=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
466: }
467: if (document.forms[formid].elements[domid].type == 'hidden') {
468: domainfilter=document.forms[formid].elements[domid].value;
469: }
470: }
471: }
472: if (domainfilter != null) {
473: if (domainfilter != '') {
474: url += 'domainfilter='+domainfilter+'&';
475: }
476: }
477: url += 'form=' + formname + '&cnumelement='+uname+
478: '&cdomelement='+udom+
479: '&cnameelement='+desc;
480: if (extra_element !=null && extra_element != '') {
481: if (formname == 'rolechoice' || formname == 'studentform') {
482: url += '&roleelement='+extra_element;
483: if (domainfilter == null || domainfilter == '') {
484: url += '&domainfilter='+extra_element;
485: }
486: }
487: else {
488: if (formname == 'portform') {
489: url += '&setroles='+extra_element;
490: }
491: }
492: }
493: if (multflag !=null && multflag != '') {
494: url += '&multiple='+multflag;
495: }
496: if (crstype == 'Course/Group') {
497: if (formname == 'cu') {
498: crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value;
499: if (crstype == "") {
500: alert("$crs_or_grp_alert");
501: return;
502: }
503: }
504: }
505: if (crstype !=null && crstype != '') {
506: url += '&type='+crstype;
507: }
508: var title = 'Course_Browser';
509: var options = 'scrollbars=1,resizable=1,menubar=0';
510: options += ',width=700,height=600';
511: stdeditbrowser = open(url,title,options,'1');
512: stdeditbrowser.focus();
513: }
514:
515: function getFormIdByName(formname) {
516: for (var i=0;i<document.forms.length;i++) {
517: if (document.forms[i].name == formname) {
518: return i;
519: }
520: }
521: return -1;
522: }
523:
524: function getIndexByName(formid,item) {
525: for (var i=0;i<document.forms[formid].elements.length;i++) {
526: if (document.forms[formid].elements[i].name == item) {
527: return i;
528: }
529: }
530: return -1;
531: }
532: ENDSTDBRW
533: if ($sec_element ne '') {
534: $output .= &setsec_javascript($sec_element,$formname);
535: }
536: $output .= '
537: </script>';
538: return $output;
539: }
540:
541: sub setsec_javascript {
542: my ($sec_element,$formname) = @_;
543: my $setsections = qq|
544: function setSect(sectionlist) {
545: var sectionsArray = new Array();
546: if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
547: sectionsArray = sectionlist.split(",");
548: }
549: var numSections = sectionsArray.length;
550: document.$formname.$sec_element.length = 0;
551: if (numSections == 0) {
552: document.$formname.$sec_element.multiple=false;
553: document.$formname.$sec_element.size=1;
554: document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
555: } else {
556: if (numSections == 1) {
557: document.$formname.$sec_element.multiple=false;
558: document.$formname.$sec_element.size=1;
559: document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
560: document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
561: document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
562: } else {
563: for (var i=0; i<numSections; i++) {
564: document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
565: }
566: document.$formname.$sec_element.multiple=true
567: if (numSections < 3) {
568: document.$formname.$sec_element.size=numSections;
569: } else {
570: document.$formname.$sec_element.size=3;
571: }
572: document.$formname.$sec_element.options[0].selected = false
573: }
574: }
575: }
576: |;
577: return $setsections;
578: }
579:
580:
581: sub selectcourse_link {
582: my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
583: return "<a href='".'javascript:opencrsbrowser("'.$form.'","'.$unameele.
584: '","'.$udomele.'","'.$desc.'","'.$extra_element.'","'.$multflag.'","'.$selecttype.'");'."'>".&mt('Select Course')."</a>";
585: }
586:
587: sub check_uncheck_jscript {
588: my $jscript = <<"ENDSCRT";
589: function checkAll(field) {
590: if (field.length > 0) {
591: for (i = 0; i < field.length; i++) {
592: field[i].checked = true ;
593: }
594: } else {
595: field.checked = true
596: }
597: }
598:
599: function uncheckAll(field) {
600: if (field.length > 0) {
601: for (i = 0; i < field.length; i++) {
602: field[i].checked = false ;
603: }
604: } else {
605: field.checked = false ;
606: }
607: }
608: ENDSCRT
609: return $jscript;
610: }
611:
612:
613: =pod
614:
615: =item * &linked_select_forms(...)
616:
617: linked_select_forms returns a string containing a <script></script> block
618: and html for two <select> menus. The select menus will be linked in that
619: changing the value of the first menu will result in new values being placed
620: in the second menu. The values in the select menu will appear in alphabetical
621: order unless a defined order is provided.
622:
623: linked_select_forms takes the following ordered inputs:
624:
625: =over 4
626:
627: =item * $formname, the name of the <form> tag
628:
629: =item * $middletext, the text which appears between the <select> tags
630:
631: =item * $firstdefault, the default value for the first menu
632:
633: =item * $firstselectname, the name of the first <select> tag
634:
635: =item * $secondselectname, the name of the second <select> tag
636:
637: =item * $hashref, a reference to a hash containing the data for the menus.
638:
639: =item * $menuorder, the order of values in the first menu
640:
641: =back
642:
643: Below is an example of such a hash. Only the 'text', 'default', and
644: 'select2' keys must appear as stated. keys(%menu) are the possible
645: values for the first select menu. The text that coincides with the
646: first menu value is given in $menu{$choice1}->{'text'}. The values
647: and text for the second menu are given in the hash pointed to by
648: $menu{$choice1}->{'select2'}.
649:
650: my %menu = ( A1 => { text =>"Choice A1" ,
651: default => "B3",
652: select2 => {
653: B1 => "Choice B1",
654: B2 => "Choice B2",
655: B3 => "Choice B3",
656: B4 => "Choice B4"
657: },
658: order => ['B4','B3','B1','B2'],
659: },
660: A2 => { text =>"Choice A2" ,
661: default => "C2",
662: select2 => {
663: C1 => "Choice C1",
664: C2 => "Choice C2",
665: C3 => "Choice C3"
666: },
667: order => ['C2','C1','C3'],
668: },
669: A3 => { text =>"Choice A3" ,
670: default => "D6",
671: select2 => {
672: D1 => "Choice D1",
673: D2 => "Choice D2",
674: D3 => "Choice D3",
675: D4 => "Choice D4",
676: D5 => "Choice D5",
677: D6 => "Choice D6",
678: D7 => "Choice D7"
679: },
680: order => ['D4','D3','D2','D1','D7','D6','D5'],
681: }
682: );
683:
684: =cut
685:
686: sub linked_select_forms {
687: my ($formname,
688: $middletext,
689: $firstdefault,
690: $firstselectname,
691: $secondselectname,
692: $hashref,
693: $menuorder,
694: ) = @_;
695: my $second = "document.$formname.$secondselectname";
696: my $first = "document.$formname.$firstselectname";
697: # output the javascript to do the changing
698: my $result = '';
699: $result.="<script type=\"text/javascript\">\n";
700: $result.="var select2data = new Object();\n";
701: $" = '","';
702: my $debug = '';
703: foreach my $s1 (sort(keys(%$hashref))) {
704: $result.="select2data.d_$s1 = new Object();\n";
705: $result.="select2data.d_$s1.def = new String('".
706: $hashref->{$s1}->{'default'}."');\n";
707: $result.="select2data.d_$s1.values = new Array(";
708: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
709: if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
710: @s2values = @{$hashref->{$s1}->{'order'}};
711: }
712: $result.="\"@s2values\");\n";
713: $result.="select2data.d_$s1.texts = new Array(";
714: my @s2texts;
715: foreach my $value (@s2values) {
716: push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
717: }
718: $result.="\"@s2texts\");\n";
719: }
720: $"=' ';
721: $result.= <<"END";
722:
723: function select1_changed() {
724: // Determine new choice
725: var newvalue = "d_" + $first.value;
726: // update select2
727: var values = select2data[newvalue].values;
728: var texts = select2data[newvalue].texts;
729: var select2def = select2data[newvalue].def;
730: var i;
731: // out with the old
732: for (i = 0; i < $second.options.length; i++) {
733: $second.options[i] = null;
734: }
735: // in with the nuclear
736: for (i=0;i<values.length; i++) {
737: $second.options[i] = new Option(values[i]);
738: $second.options[i].value = values[i];
739: $second.options[i].text = texts[i];
740: if (values[i] == select2def) {
741: $second.options[i].selected = true;
742: }
743: }
744: }
745: </script>
746: END
747: # output the initial values for the selection lists
748: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
749: my @order = sort(keys(%{$hashref}));
750: if (ref($menuorder) eq 'ARRAY') {
751: @order = @{$menuorder};
752: }
753: foreach my $value (@order) {
754: $result.=" <option value=\"$value\" ";
755: $result.=" selected=\"selected\" " if ($value eq $firstdefault);
756: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
757: }
758: $result .= "</select>\n";
759: my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
760: $result .= $middletext;
761: $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
762: my $seconddefault = $hashref->{$firstdefault}->{'default'};
763:
764: my @secondorder = sort(keys(%select2));
765: if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
766: @secondorder = @{$hashref->{$firstdefault}->{'order'}};
767: }
768: foreach my $value (@secondorder) {
769: $result.=" <option value=\"$value\" ";
770: $result.=" selected=\"selected\" " if ($value eq $seconddefault);
771: $result.=">".&mt($select2{$value})."</option>\n";
772: }
773: $result .= "</select>\n";
774: # return $debug;
775: return $result;
776: } # end of sub linked_select_forms {
777:
778: =pod
779:
780: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height)
781:
782: Returns a string corresponding to an HTML link to the given help
783: $topic, where $topic corresponds to the name of a .tex file in
784: /home/httpd/html/adm/help/tex, with underscores replaced by
785: spaces.
786:
787: $text will optionally be linked to the same topic, allowing you to
788: link text in addition to the graphic. If you do not want to link
789: text, but wish to specify one of the later parameters, pass an
790: empty string.
791:
792: $stayOnPage is a value that will be interpreted as a boolean. If true,
793: the link will not open a new window. If false, the link will open
794: a new window using Javascript. (Default is false.)
795:
796: $width and $height are optional numerical parameters that will
797: override the width and height of the popped up window, which may
798: be useful for certain help topics with big pictures included.
799:
800: =cut
801:
802: sub help_open_topic {
803: my ($topic, $text, $stayOnPage, $width, $height) = @_;
804: $text = "" if (not defined $text);
805: $stayOnPage = 0 if (not defined $stayOnPage);
806: if ($env{'browser.interface'} eq 'textual') {
807: $stayOnPage=1;
808: }
809: $width = 350 if (not defined $width);
810: $height = 400 if (not defined $height);
811: my $filename = $topic;
812: $filename =~ s/ /_/g;
813:
814: my $template = "";
815: my $link;
816:
817: $topic=~s/\W/\_/g;
818:
819: if (!$stayOnPage) {
820: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
821: } else {
822: $link = "/adm/help/${filename}.hlp";
823: }
824:
825: # Add the text
826: if ($text ne "") {
827: $template .=
828: "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
829: "<td bgcolor='#5555FF'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
830: }
831:
832: # Add the graphic
833: my $title = &mt('Online Help');
834: my $helpicon=&lonhttpdurl("/res/adm/pages/help.png");
835: $template .= <<"ENDTEMPLATE";
836: <a target="_top" href="$link" title="$title"><img src="$helpicon" border="0" alt="(Help: $topic)" /></a>
837: ENDTEMPLATE
838: if ($text ne '') { $template.='</td></tr></table>' };
839: return $template;
840:
841: }
842:
843: # This is a quicky function for Latex cheatsheet editing, since it
844: # appears in at least four places
845: sub helpLatexCheatsheet {
846: my $other = shift;
847: my $addOther = '';
848: if ($other) {
849: $addOther = Apache::loncommon::help_open_topic($other, shift,
850: undef, undef, 600) .
851: '</td><td>';
852: }
853: return '<table><tr><td>'.
854: $addOther .
855: &Apache::loncommon::help_open_topic("Greek_Symbols",&mt('Greek Symbols'),
856: undef,undef,600)
857: .'</td><td>'.
858: &Apache::loncommon::help_open_topic("Other_Symbols",&mt('Other Symbols'),
859: undef,undef,600)
860: .'</td></tr></table>';
861: }
862:
863: sub general_help {
864: my $helptopic='Student_Intro';
865: if ($env{'request.role'}=~/^(ca|au)/) {
866: $helptopic='Authoring_Intro';
867: } elsif ($env{'request.role'}=~/^cc/) {
868: $helptopic='Course_Coordination_Intro';
869: }
870: return $helptopic;
871: }
872:
873: sub update_help_link {
874: my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
875: my $origurl = $ENV{'REQUEST_URI'};
876: $origurl=~s|^/~|/priv/|;
877: my $timestamp = time;
878: foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
879: $$datum = &escape($$datum);
880: }
881:
882: my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage";
883: my $output .= <<"ENDOUTPUT";
884: <script type="text/javascript">
885: banner_link = '$banner_link';
886: </script>
887: ENDOUTPUT
888: return $output;
889: }
890:
891: # now just updates the help link and generates a blue icon
892: sub help_open_menu {
893: my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text)
894: = @_;
895: $stayOnPage = 0 if (not defined $stayOnPage);
896: # only use pop-up help (stayOnPage == 0)
897: # if environment.remote is on (using remote control UI)
898: if ($env{'browser.interface'} eq 'textual' ||
899: $env{'environment.remote'} eq 'off' ) {
900: $stayOnPage=1;
901: }
902: my $output;
903: if ($component_help) {
904: if (!$text) {
905: $output=&help_open_topic($component_help,undef,$stayOnPage,
906: $width,$height);
907: } else {
908: my $help_text;
909: $help_text=&unescape($topic);
910: $output='<table><tr><td>'.
911: &help_open_topic($component_help,$help_text,$stayOnPage,
912: $width,$height).'</td></tr></table>';
913: }
914: }
915: my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
916: return $output.$banner_link;
917: }
918:
919: sub top_nav_help {
920: my ($text) = @_;
921: $text = &mt($text);
922: my $stay_on_page =
923: ($env{'browser.interface'} eq 'textual' ||
924: $env{'environment.remote'} eq 'off' );
925: my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
926: : "javascript:helpMenu('open')";
927: my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
928:
929: my $title = &mt('Get help');
930:
931: return <<"END";
932: $banner_link
933: <a href="$link" title="$title">$text</a>
934: END
935: }
936:
937: sub help_menu_js {
938: my ($text) = @_;
939:
940: my $stayOnPage =
941: ($env{'browser.interface'} eq 'textual' ||
942: $env{'environment.remote'} eq 'off' );
943:
944: my $width = 620;
945: my $height = 600;
946: my $helptopic=&general_help();
947: my $details_link = '/adm/help/'.$helptopic.'.hlp';
948: my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
949: my $start_page =
950: &Apache::loncommon::start_page('Help Menu', undef,
951: {'frameset' => 1,
952: 'js_ready' => 1,
953: 'add_entries' => {
954: 'border' => '0',
955: 'rows' => "110,*",},});
956: my $end_page =
957: &Apache::loncommon::end_page({'frameset' => 1,
958: 'js_ready' => 1,});
959:
960: my $template .= <<"ENDTEMPLATE";
961: <script type="text/javascript">
962: // <!-- BEGIN LON-CAPA Internal
963: // <![CDATA[
964: var banner_link = '';
965: function helpMenu(target) {
966: var caller = this;
967: if (target == 'open') {
968: var newWindow = null;
969: try {
970: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
971: }
972: catch(error) {
973: writeHelp(caller);
974: return;
975: }
976: if (newWindow) {
977: caller = newWindow;
978: }
979: }
980: writeHelp(caller);
981: return;
982: }
983: function writeHelp(caller) {
984: caller.document.writeln('$start_page<frame name="bannerframe" src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
985: caller.document.close()
986: caller.focus()
987: }
988: // ]]>
989: // END LON-CAPA Internal -->
990: </script>
991: ENDTEMPLATE
992: return $template;
993: }
994:
995: sub help_open_bug {
996: my ($topic, $text, $stayOnPage, $width, $height) = @_;
997: unless ($env{'user.adv'}) { return ''; }
998: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
999: $text = "" if (not defined $text);
1000: $stayOnPage = 0 if (not defined $stayOnPage);
1001: if ($env{'browser.interface'} eq 'textual' ||
1002: $env{'environment.remote'} eq 'off' ) {
1003: $stayOnPage=1;
1004: }
1005: $width = 600 if (not defined $width);
1006: $height = 600 if (not defined $height);
1007:
1008: $topic=~s/\W+/\+/g;
1009: my $link='';
1010: my $template='';
1011: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
1012: &escape($ENV{'REQUEST_URI'}).'&component='.$topic;
1013: if (!$stayOnPage)
1014: {
1015: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1016: }
1017: else
1018: {
1019: $link = $url;
1020: }
1021: # Add the text
1022: if ($text ne "")
1023: {
1024: $template .=
1025: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1026: "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
1027: }
1028:
1029: # Add the graphic
1030: my $title = &mt('Report a Bug');
1031: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1032: $template .= <<"ENDTEMPLATE";
1033: <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1034: ENDTEMPLATE
1035: if ($text ne '') { $template.='</td></tr></table>' };
1036: return $template;
1037:
1038: }
1039:
1040: sub help_open_faq {
1041: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1042: unless ($env{'user.adv'}) { return ''; }
1043: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
1044: $text = "" if (not defined $text);
1045: $stayOnPage = 0 if (not defined $stayOnPage);
1046: if ($env{'browser.interface'} eq 'textual' ||
1047: $env{'environment.remote'} eq 'off' ) {
1048: $stayOnPage=1;
1049: }
1050: $width = 350 if (not defined $width);
1051: $height = 400 if (not defined $height);
1052:
1053: $topic=~s/\W+/\+/g;
1054: my $link='';
1055: my $template='';
1056: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
1057: if (!$stayOnPage)
1058: {
1059: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1060: }
1061: else
1062: {
1063: $link = $url;
1064: }
1065:
1066: # Add the text
1067: if ($text ne "")
1068: {
1069: $template .=
1070: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1071: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
1072: }
1073:
1074: # Add the graphic
1075: my $title = &mt('View the FAQ');
1076: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1077: $template .= <<"ENDTEMPLATE";
1078: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1079: ENDTEMPLATE
1080: if ($text ne '') { $template.='</td></tr></table>' };
1081: return $template;
1082:
1083: }
1084:
1085: ###############################################################
1086: ###############################################################
1087:
1088: =pod
1089:
1090: =item * &change_content_javascript():
1091:
1092: This and the next function allow you to create small sections of an
1093: otherwise static HTML page that you can update on the fly with
1094: Javascript, even in Netscape 4.
1095:
1096: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
1097: must be written to the HTML page once. It will prove the Javascript
1098: function "change(name, content)". Calling the change function with the
1099: name of the section
1100: you want to update, matching the name passed to C<changable_area>, and
1101: the new content you want to put in there, will put the content into
1102: that area.
1103:
1104: B<Note>: Netscape 4 only reserves enough space for the changable area
1105: to contain room for the original contents. You need to "make space"
1106: for whatever changes you wish to make, and be B<sure> to check your
1107: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
1108: it's adequate for updating a one-line status display, but little more.
1109: This script will set the space to 100% width, so you only need to
1110: worry about height in Netscape 4.
1111:
1112: Modern browsers are much less limiting, and if you can commit to the
1113: user not using Netscape 4, this feature may be used freely with
1114: pretty much any HTML.
1115:
1116: =cut
1117:
1118: sub change_content_javascript {
1119: # If we're on Netscape 4, we need to use Layer-based code
1120: if ($env{'browser.type'} eq 'netscape' &&
1121: $env{'browser.version'} =~ /^4\./) {
1122: return (<<NETSCAPE4);
1123: function change(name, content) {
1124: doc = document.layers[name+"___escape"].layers[0].document;
1125: doc.open();
1126: doc.write(content);
1127: doc.close();
1128: }
1129: NETSCAPE4
1130: } else {
1131: # Otherwise, we need to use semi-standards-compliant code
1132: # (technically, "innerHTML" isn't standard but the equivalent
1133: # is really scary, and every useful browser supports it
1134: return (<<DOMBASED);
1135: function change(name, content) {
1136: element = document.getElementById(name);
1137: element.innerHTML = content;
1138: }
1139: DOMBASED
1140: }
1141: }
1142:
1143: =pod
1144:
1145: =item * &changable_area($name,$origContent):
1146:
1147: This provides a "changable area" that can be modified on the fly via
1148: the Javascript code provided in C<change_content_javascript>. $name is
1149: the name you will use to reference the area later; do not repeat the
1150: same name on a given HTML page more then once. $origContent is what
1151: the area will originally contain, which can be left blank.
1152:
1153: =cut
1154:
1155: sub changable_area {
1156: my ($name, $origContent) = @_;
1157:
1158: if ($env{'browser.type'} eq 'netscape' &&
1159: $env{'browser.version'} =~ /^4\./) {
1160: # If this is netscape 4, we need to use the Layer tag
1161: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
1162: } else {
1163: return "<span id='$name'>$origContent</span>";
1164: }
1165: }
1166:
1167: =pod
1168:
1169: =item * &viewport_geometry_js
1170:
1171: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
1172:
1173: =cut
1174:
1175:
1176: sub viewport_geometry_js {
1177: return <<"GEOMETRY";
1178: var Geometry = {};
1179: function init_geometry() {
1180: if (Geometry.init) { return };
1181: Geometry.init=1;
1182: if (window.innerHeight) {
1183: Geometry.getViewportHeight = function() { return window.innerHeight; };
1184: Geometry.getViewportWidth = function() { return window.innerWidth; };
1185: Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
1186: Geometry.getVerticalScroll = function() { return window.pageYOffset; };
1187: }
1188: else if (document.documentElement && document.documentElement.clientHeight) {
1189: Geometry.getViewportHeight =
1190: function() { return document.documentElement.clientHeight; };
1191: Geometry.getViewportWidth =
1192: function() { return document.documentElement.clientWidth; };
1193:
1194: Geometry.getHorizontalScroll =
1195: function() { return document.documentElement.scrollLeft; };
1196: Geometry.getVerticalScroll =
1197: function() { return document.documentElement.scrollTop; };
1198: }
1199: else if (document.body.clientHeight) {
1200: Geometry.getViewportHeight =
1201: function() { return document.body.clientHeight; };
1202: Geometry.getViewportWidth =
1203: function() { return document.body.clientWidth; };
1204: Geometry.getHorizontalScroll =
1205: function() { return document.body.scrollLeft; };
1206: Geometry.getVerticalScroll =
1207: function() { return document.body.scrollTop; };
1208: }
1209: }
1210:
1211: GEOMETRY
1212: }
1213:
1214: =pod
1215:
1216: =item * &viewport_size_js()
1217:
1218: 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.
1219:
1220: =cut
1221:
1222: sub viewport_size_js {
1223: my $geometry = &viewport_geometry_js();
1224: return <<"DIMS";
1225:
1226: $geometry
1227:
1228: function getViewportDims(width,height) {
1229: init_geometry();
1230: width.value = Geometry.getViewportWidth();
1231: height.value = Geometry.getViewportHeight();
1232: return;
1233: }
1234:
1235: DIMS
1236: }
1237:
1238: =pod
1239:
1240: =item * &resize_textarea_js()
1241:
1242: emits the needed javascript to resize a textarea to be as big as possible
1243:
1244: creates a function resize_textrea that takes two IDs first should be
1245: the id of the element to resize, second should be the id of a div that
1246: surrounds everything that comes after the textarea, this routine needs
1247: to be attached to the <body> for the onload and onresize events.
1248:
1249: =back
1250:
1251: =cut
1252:
1253: sub resize_textarea_js {
1254: my $geometry = &viewport_geometry_js();
1255: return <<"RESIZE";
1256: <script type="text/javascript">
1257: $geometry
1258:
1259: function getX(element) {
1260: var x = 0;
1261: while (element) {
1262: x += element.offsetLeft;
1263: element = element.offsetParent;
1264: }
1265: return x;
1266: }
1267: function getY(element) {
1268: var y = 0;
1269: while (element) {
1270: y += element.offsetTop;
1271: element = element.offsetParent;
1272: }
1273: return y;
1274: }
1275:
1276:
1277: function resize_textarea(textarea_id,bottom_id) {
1278: init_geometry();
1279: var textarea = document.getElementById(textarea_id);
1280: //alert(textarea);
1281:
1282: var textarea_top = getY(textarea);
1283: var textarea_height = textarea.offsetHeight;
1284: var bottom = document.getElementById(bottom_id);
1285: var bottom_top = getY(bottom);
1286: var bottom_height = bottom.offsetHeight;
1287: var window_height = Geometry.getViewportHeight();
1288: var fudge = 23;
1289: var new_height = window_height-fudge-textarea_top-bottom_height;
1290: if (new_height < 300) {
1291: new_height = 300;
1292: }
1293: textarea.style.height=new_height+'px';
1294: }
1295: </script>
1296: RESIZE
1297:
1298: }
1299:
1300: =pod
1301:
1302: =head1 Excel and CSV file utility routines
1303:
1304: =over 4
1305:
1306: =cut
1307:
1308: ###############################################################
1309: ###############################################################
1310:
1311: =pod
1312:
1313: =item * &csv_translate($text)
1314:
1315: Translate $text to allow it to be output as a 'comma separated values'
1316: format.
1317:
1318: =cut
1319:
1320: ###############################################################
1321: ###############################################################
1322: sub csv_translate {
1323: my $text = shift;
1324: $text =~ s/\"/\"\"/g;
1325: $text =~ s/\n/ /g;
1326: return $text;
1327: }
1328:
1329: ###############################################################
1330: ###############################################################
1331:
1332: =pod
1333:
1334: =item * &define_excel_formats()
1335:
1336: Define some commonly used Excel cell formats.
1337:
1338: Currently supported formats:
1339:
1340: =over 4
1341:
1342: =item header
1343:
1344: =item bold
1345:
1346: =item h1
1347:
1348: =item h2
1349:
1350: =item h3
1351:
1352: =item h4
1353:
1354: =item i
1355:
1356: =item date
1357:
1358: =back
1359:
1360: Inputs: $workbook
1361:
1362: Returns: $format, a hash reference.
1363:
1364: =cut
1365:
1366: ###############################################################
1367: ###############################################################
1368: sub define_excel_formats {
1369: my ($workbook) = @_;
1370: my $format;
1371: $format->{'header'} = $workbook->add_format(bold => 1,
1372: bottom => 1,
1373: align => 'center');
1374: $format->{'bold'} = $workbook->add_format(bold=>1);
1375: $format->{'h1'} = $workbook->add_format(bold=>1, size=>18);
1376: $format->{'h2'} = $workbook->add_format(bold=>1, size=>16);
1377: $format->{'h3'} = $workbook->add_format(bold=>1, size=>14);
1378: $format->{'h4'} = $workbook->add_format(bold=>1, size=>12);
1379: $format->{'i'} = $workbook->add_format(italic=>1);
1380: $format->{'date'} = $workbook->add_format(num_format=>
1381: 'mm/dd/yyyy hh:mm:ss');
1382: return $format;
1383: }
1384:
1385: ###############################################################
1386: ###############################################################
1387:
1388: =pod
1389:
1390: =item * &create_workbook()
1391:
1392: Create an Excel worksheet. If it fails, output message on the
1393: request object and return undefs.
1394:
1395: Inputs: Apache request object
1396:
1397: Returns (undef) on failure,
1398: Excel worksheet object, scalar with filename, and formats
1399: from &Apache::loncommon::define_excel_formats on success
1400:
1401: =cut
1402:
1403: ###############################################################
1404: ###############################################################
1405: sub create_workbook {
1406: my ($r) = @_;
1407: #
1408: # Create the excel spreadsheet
1409: my $filename = '/prtspool/'.
1410: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1411: time.'_'.rand(1000000000).'.xls';
1412: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
1413: if (! defined($workbook)) {
1414: $r->log_error("Error creating excel spreadsheet $filename: $!");
1415: $r->print('<p>'.&mt("Unable to create new Excel file. ".
1416: "This error has been logged. ".
1417: "Please alert your LON-CAPA administrator").
1418: '</p>');
1419: return (undef);
1420: }
1421: #
1422: $workbook->set_tempdir('/home/httpd/perl/tmp');
1423: #
1424: my $format = &Apache::loncommon::define_excel_formats($workbook);
1425: return ($workbook,$filename,$format);
1426: }
1427:
1428: ###############################################################
1429: ###############################################################
1430:
1431: =pod
1432:
1433: =item * &create_text_file()
1434:
1435: Create a file to write to and eventually make available to the user.
1436: If file creation fails, outputs an error message on the request object and
1437: return undefs.
1438:
1439: Inputs: Apache request object, and file suffix
1440:
1441: Returns (undef) on failure,
1442: Filehandle and filename on success.
1443:
1444: =cut
1445:
1446: ###############################################################
1447: ###############################################################
1448: sub create_text_file {
1449: my ($r,$suffix) = @_;
1450: if (! defined($suffix)) { $suffix = 'txt'; };
1451: my $fh;
1452: my $filename = '/prtspool/'.
1453: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1454: time.'_'.rand(1000000000).'.'.$suffix;
1455: $fh = Apache::File->new('>/home/httpd'.$filename);
1456: if (! defined($fh)) {
1457: $r->log_error("Couldn't open $filename for output $!");
1458: $r->print("Problems occured in creating the output file. ".
1459: "This error has been logged. ".
1460: "Please alert your LON-CAPA administrator.");
1461: }
1462: return ($fh,$filename)
1463: }
1464:
1465:
1466: =pod
1467:
1468: =back
1469:
1470: =cut
1471:
1472: ###############################################################
1473: ## Home server <option> list generating code ##
1474: ###############################################################
1475:
1476: # ------------------------------------------
1477:
1478: sub domain_select {
1479: my ($name,$value,$multiple)=@_;
1480: my %domains=map {
1481: $_ => $_.' '. &Apache::lonnet::domain($_,'description')
1482: } &Apache::lonnet::all_domains();
1483: if ($multiple) {
1484: $domains{''}=&mt('Any domain');
1485: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1486: return &multiple_select_form($name,$value,4,\%domains);
1487: } else {
1488: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1489: return &select_form($name,$value,%domains);
1490: }
1491: }
1492:
1493: #-------------------------------------------
1494:
1495: =pod
1496:
1497: =head1 Routines for form select boxes
1498:
1499: =over 4
1500:
1501: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1502:
1503: Returns a string containing a <select> element int multiple mode
1504:
1505:
1506: Args:
1507: $name - name of the <select> element
1508: $value - scalar or array ref of values that should already be selected
1509: $size - number of rows long the select element is
1510: $hash - the elements should be 'option' => 'shown text'
1511: (shown text should already have been &mt())
1512: $order - (optional) array ref of the order to show the elements in
1513:
1514: =cut
1515:
1516: #-------------------------------------------
1517: sub multiple_select_form {
1518: my ($name,$value,$size,$hash,$order)=@_;
1519: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
1520: my $output='';
1521: if (! defined($size)) {
1522: $size = 4;
1523: if (scalar(keys(%$hash))<4) {
1524: $size = scalar(keys(%$hash));
1525: }
1526: }
1527: $output.="\n<select name='$name' size='$size' multiple='1'>";
1528: my @order;
1529: if (ref($order) eq 'ARRAY') {
1530: @order = @{$order};
1531: } else {
1532: @order = sort(keys(%$hash));
1533: }
1534: if (exists($$hash{'select_form_order'})) {
1535: @order = @{$$hash{'select_form_order'}};
1536: }
1537:
1538: foreach my $key (@order) {
1539: $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1540: $output.='selected="selected" ' if ($selected{$key});
1541: $output.='>'.$hash->{$key}."</option>\n";
1542: }
1543: $output.="</select>\n";
1544: return $output;
1545: }
1546:
1547: #-------------------------------------------
1548:
1549: =pod
1550:
1551: =item * &select_form($defdom,$name,%hash)
1552:
1553: Returns a string containing a <select name='$name' size='1'> form to
1554: allow a user to select options from a hash option_name => displayed text.
1555: See lonrights.pm for an example invocation and use.
1556:
1557: =cut
1558:
1559: #-------------------------------------------
1560: sub select_form {
1561: my ($def,$name,%hash) = @_;
1562: my $selectform = "<select name=\"$name\" size=\"1\">\n";
1563: my @keys;
1564: if (exists($hash{'select_form_order'})) {
1565: @keys=@{$hash{'select_form_order'}};
1566: } else {
1567: @keys=sort(keys(%hash));
1568: }
1569: foreach my $key (@keys) {
1570: $selectform.=
1571: '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
1572: ($key eq $def ? 'selected="selected" ' : '').
1573: ">".&mt($hash{$key})."</option>\n";
1574: }
1575: $selectform.="</select>";
1576: return $selectform;
1577: }
1578:
1579: # For display filters
1580:
1581: sub display_filter {
1582: if (!$env{'form.show'}) { $env{'form.show'}=10; }
1583: if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1584: return '<nobr><label>'.&mt('Records [_1]',
1585: &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
1586: (&mt('all'),10,20,50,100,1000,10000))).
1587: '</label></nobr> <nobr>'.
1588: &mt('Filter [_1]',
1589: &select_form($env{'form.displayfilter'},
1590: 'displayfilter',
1591: ('currentfolder' => 'Current folder/page',
1592: 'containing' => 'Containing phrase',
1593: 'none' => 'None'))).
1594: '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></nobr>';
1595: }
1596:
1597: sub gradeleveldescription {
1598: my $gradelevel=shift;
1599: my %gradelevels=(0 => 'Not specified',
1600: 1 => 'Grade 1',
1601: 2 => 'Grade 2',
1602: 3 => 'Grade 3',
1603: 4 => 'Grade 4',
1604: 5 => 'Grade 5',
1605: 6 => 'Grade 6',
1606: 7 => 'Grade 7',
1607: 8 => 'Grade 8',
1608: 9 => 'Grade 9',
1609: 10 => 'Grade 10',
1610: 11 => 'Grade 11',
1611: 12 => 'Grade 12',
1612: 13 => 'Grade 13',
1613: 14 => '100 Level',
1614: 15 => '200 Level',
1615: 16 => '300 Level',
1616: 17 => '400 Level',
1617: 18 => 'Graduate Level');
1618: return &mt($gradelevels{$gradelevel});
1619: }
1620:
1621: sub select_level_form {
1622: my ($deflevel,$name)=@_;
1623: unless ($deflevel) { $deflevel=0; }
1624: my $selectform = "<select name=\"$name\" size=\"1\">\n";
1625: for (my $i=0; $i<=18; $i++) {
1626: $selectform.="<option value=\"$i\" ".
1627: ($i==$deflevel ? 'selected="selected" ' : '').
1628: ">".&gradeleveldescription($i)."</option>\n";
1629: }
1630: $selectform.="</select>";
1631: return $selectform;
1632: }
1633:
1634: #-------------------------------------------
1635:
1636: =pod
1637:
1638: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc)
1639:
1640: Returns a string containing a <select name='$name' size='1'> form to
1641: allow a user to select the domain to preform an operation in.
1642: See loncreateuser.pm for an example invocation and use.
1643:
1644: If the $includeempty flag is set, it also includes an empty choice ("no domain
1645: selected");
1646:
1647: If the $showdomdesc flag is set, the domain name is followed by the domain description.
1648:
1649: =cut
1650:
1651: #-------------------------------------------
1652: sub select_dom_form {
1653: my ($defdom,$name,$includeempty,$showdomdesc) = @_;
1654: my @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
1655: if ($includeempty) { @domains=('',@domains); }
1656: my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
1657: foreach my $dom (@domains) {
1658: $selectdomain.="<option value=\"$dom\" ".
1659: ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
1660: if ($showdomdesc) {
1661: if ($dom ne '') {
1662: my $domdesc = &Apache::lonnet::domain($dom,'description');
1663: if ($domdesc ne '') {
1664: $selectdomain .= ' ('.$domdesc.')';
1665: }
1666: }
1667: }
1668: $selectdomain .= "</option>\n";
1669: }
1670: $selectdomain.="</select>";
1671: return $selectdomain;
1672: }
1673:
1674: #-------------------------------------------
1675:
1676: =pod
1677:
1678: =item * &home_server_form_item($domain,$name,$defaultflag)
1679:
1680: input: 4 arguments (two required, two optional) -
1681: $domain - domain of new user
1682: $name - name of form element
1683: $default - Value of 'default' causes a default item to be first
1684: option, and selected by default.
1685: $hide - Value of 'hide' causes hiding of the name of the server,
1686: if 1 server found, or default, if 0 found.
1687: output: returns 2 items:
1688: (a) form element which contains either:
1689: (i) <select name="$name">
1690: <option value="$hostid1">$hostid $servers{$hostid}</option>
1691: <option value="$hostid2">$hostid $servers{$hostid}</option>
1692: </select>
1693: form item if there are multiple library servers in $domain, or
1694: (ii) an <input type="hidden" name="$name" value="$hostid" /> form item
1695: if there is only one library server in $domain.
1696:
1697: (b) number of library servers found.
1698:
1699: See loncreateuser.pm for example of use.
1700:
1701: =cut
1702:
1703: #-------------------------------------------
1704: sub home_server_form_item {
1705: my ($domain,$name,$default,$hide) = @_;
1706: my %servers = &Apache::lonnet::get_servers($domain,'library');
1707: my $result;
1708: my $numlib = keys(%servers);
1709: if ($numlib > 1) {
1710: $result .= '<select name="'.$name.'" />'."\n";
1711: if ($default) {
1712: $result .= '<option value="default" selected>'.&mt('default').
1713: '</option>'."\n";
1714: }
1715: foreach my $hostid (sort(keys(%servers))) {
1716: $result.= '<option value="'.$hostid.'">'.
1717: $hostid.' '.$servers{$hostid}."</option>\n";
1718: }
1719: $result .= '</select>'."\n";
1720: } elsif ($numlib == 1) {
1721: my $hostid;
1722: foreach my $item (keys(%servers)) {
1723: $hostid = $item;
1724: }
1725: $result .= '<input type="hidden" name="'.$name.'" value="'.
1726: $hostid.'" />';
1727: if (!$hide) {
1728: $result .= $hostid.' '.$servers{$hostid};
1729: }
1730: $result .= "\n";
1731: } elsif ($default) {
1732: $result .= '<input type="hidden" name="'.$name.
1733: '" value="default" />';
1734: if (!$hide) {
1735: $result .= &mt('default');
1736: }
1737: $result .= "\n";
1738: }
1739: return ($result,$numlib);
1740: }
1741:
1742: =pod
1743:
1744: =back
1745:
1746: =cut
1747:
1748: ###############################################################
1749: ## Decoding User Agent ##
1750: ###############################################################
1751:
1752: =pod
1753:
1754: =head1 Decoding the User Agent
1755:
1756: =over 4
1757:
1758: =item * &decode_user_agent()
1759:
1760: Inputs: $r
1761:
1762: Outputs:
1763:
1764: =over 4
1765:
1766: =item * $httpbrowser
1767:
1768: =item * $clientbrowser
1769:
1770: =item * $clientversion
1771:
1772: =item * $clientmathml
1773:
1774: =item * $clientunicode
1775:
1776: =item * $clientos
1777:
1778: =back
1779:
1780: =back
1781:
1782: =cut
1783:
1784: ###############################################################
1785: ###############################################################
1786: sub decode_user_agent {
1787: my ($r)=@_;
1788: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
1789: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
1790: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1791: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1792: my $clientbrowser='unknown';
1793: my $clientversion='0';
1794: my $clientmathml='';
1795: my $clientunicode='0';
1796: for (my $i=0;$i<=$#browsertype;$i++) {
1797: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
1798: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
1799: $clientbrowser=$bname;
1800: $httpbrowser=~/$vreg/i;
1801: $clientversion=$1;
1802: $clientmathml=($clientversion>=$minv);
1803: $clientunicode=($clientversion>=$univ);
1804: }
1805: }
1806: my $clientos='unknown';
1807: if (($httpbrowser=~/linux/i) ||
1808: ($httpbrowser=~/unix/i) ||
1809: ($httpbrowser=~/ux/i) ||
1810: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
1811: if (($httpbrowser=~/vax/i) ||
1812: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
1813: if ($httpbrowser=~/next/i) { $clientos='next'; }
1814: if (($httpbrowser=~/mac/i) ||
1815: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1816: if ($httpbrowser=~/win/i) { $clientos='win'; }
1817: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1818: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1819: $clientunicode,$clientos,);
1820: }
1821:
1822: ###############################################################
1823: ## Authentication changing form generation subroutines ##
1824: ###############################################################
1825: ##
1826: ## All of the authform_xxxxxxx subroutines take their inputs in a
1827: ## hash, and have reasonable default values.
1828: ##
1829: ## formname = the name given in the <form> tag.
1830: #-------------------------------------------
1831:
1832: =pod
1833:
1834: =head1 Authentication Routines
1835:
1836: =over 4
1837:
1838: =item * &authform_xxxxxx()
1839:
1840: The authform_xxxxxx subroutines provide javascript and html forms which
1841: handle some of the conveniences required for authentication forms.
1842: This is not an optimal method, but it works.
1843:
1844: =over 4
1845:
1846: =item * authform_header
1847:
1848: =item * authform_authorwarning
1849:
1850: =item * authform_nochange
1851:
1852: =item * authform_kerberos
1853:
1854: =item * authform_internal
1855:
1856: =item * authform_filesystem
1857:
1858: =back
1859:
1860: See loncreateuser.pm for invocation and use examples.
1861:
1862: =cut
1863:
1864: #-------------------------------------------
1865: sub authform_header{
1866: my %in = (
1867: formname => 'cu',
1868: kerb_def_dom => '',
1869: @_,
1870: );
1871: $in{'formname'} = 'document.' . $in{'formname'};
1872: my $result='';
1873:
1874: #---------------------------------------------- Code for upper case translation
1875: my $Javascript_toUpperCase;
1876: unless ($in{kerb_def_dom}) {
1877: $Javascript_toUpperCase =<<"END";
1878: switch (choice) {
1879: case 'krb': currentform.elements[choicearg].value =
1880: currentform.elements[choicearg].value.toUpperCase();
1881: break;
1882: default:
1883: }
1884: END
1885: } else {
1886: $Javascript_toUpperCase = "";
1887: }
1888:
1889: my $radioval = "'nochange'";
1890: if (defined($in{'curr_authtype'})) {
1891: if ($in{'curr_authtype'} ne '') {
1892: $radioval = "'".$in{'curr_authtype'}."arg'";
1893: }
1894: }
1895: my $argfield = 'null';
1896: if (defined($in{'mode'})) {
1897: if ($in{'mode'} eq 'modifycourse') {
1898: if (defined($in{'curr_autharg'})) {
1899: if ($in{'curr_autharg'} ne '') {
1900: $argfield = "'$in{'curr_autharg'}'";
1901: }
1902: }
1903: }
1904: }
1905:
1906: $result.=<<"END";
1907: var current = new Object();
1908: current.radiovalue = $radioval;
1909: current.argfield = $argfield;
1910:
1911: function changed_radio(choice,currentform) {
1912: var choicearg = choice + 'arg';
1913: // If a radio button in changed, we need to change the argfield
1914: if (current.radiovalue != choice) {
1915: current.radiovalue = choice;
1916: if (current.argfield != null) {
1917: currentform.elements[current.argfield].value = '';
1918: }
1919: if (choice == 'nochange') {
1920: current.argfield = null;
1921: } else {
1922: current.argfield = choicearg;
1923: switch(choice) {
1924: case 'krb':
1925: currentform.elements[current.argfield].value =
1926: "$in{'kerb_def_dom'}";
1927: break;
1928: default:
1929: break;
1930: }
1931: }
1932: }
1933: return;
1934: }
1935:
1936: function changed_text(choice,currentform) {
1937: var choicearg = choice + 'arg';
1938: if (currentform.elements[choicearg].value !='') {
1939: $Javascript_toUpperCase
1940: // clear old field
1941: if ((current.argfield != choicearg) && (current.argfield != null)) {
1942: currentform.elements[current.argfield].value = '';
1943: }
1944: current.argfield = choicearg;
1945: }
1946: set_auth_radio_buttons(choice,currentform);
1947: return;
1948: }
1949:
1950: function set_auth_radio_buttons(newvalue,currentform) {
1951: var i=0;
1952: while (i < currentform.login.length) {
1953: if (currentform.login[i].value == newvalue) { break; }
1954: i++;
1955: }
1956: if (i == currentform.login.length) {
1957: return;
1958: }
1959: current.radiovalue = newvalue;
1960: currentform.login[i].checked = true;
1961: return;
1962: }
1963: END
1964: return $result;
1965: }
1966:
1967: sub authform_authorwarning{
1968: my $result='';
1969: $result='<i>'.
1970: &mt('As a general rule, only authors or co-authors should be '.
1971: 'filesystem authenticated '.
1972: '(which allows access to the server filesystem).')."</i>\n";
1973: return $result;
1974: }
1975:
1976: sub authform_nochange{
1977: my %in = (
1978: formname => 'document.cu',
1979: kerb_def_dom => 'MSU.EDU',
1980: @_,
1981: );
1982: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1983: my $result;
1984: if (keys(%can_assign) == 0) {
1985: $result = &mt('Under you current role you are not permitted to change login settings for this user');
1986: } else {
1987: $result = '<label>'.&mt('[_1] Do not change login data',
1988: '<input type="radio" name="login" value="nochange" '.
1989: 'checked="checked" onclick="'.
1990: "javascript:changed_radio('nochange',$in{'formname'});".'" />').
1991: '</label>';
1992: }
1993: return $result;
1994: }
1995:
1996: sub authform_kerberos {
1997: my %in = (
1998: formname => 'document.cu',
1999: kerb_def_dom => 'MSU.EDU',
2000: kerb_def_auth => 'krb4',
2001: @_,
2002: );
2003: my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
2004: $autharg,$jscall);
2005: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2006: if ($in{'kerb_def_auth'} eq 'krb5') {
2007: $check5 = ' checked="on"';
2008: } else {
2009: $check4 = ' checked="on"';
2010: }
2011: $krbarg = $in{'kerb_def_dom'};
2012: if (defined($in{'curr_authtype'})) {
2013: if ($in{'curr_authtype'} eq 'krb') {
2014: $krbcheck = ' checked="on"';
2015: if (defined($in{'mode'})) {
2016: if ($in{'mode'} eq 'modifyuser') {
2017: $krbcheck = '';
2018: }
2019: }
2020: if (defined($in{'curr_kerb_ver'})) {
2021: if ($in{'curr_krb_ver'} eq '5') {
2022: $check5 = ' checked="on"';
2023: $check4 = '';
2024: } else {
2025: $check4 = ' checked="on"';
2026: $check5 = '';
2027: }
2028: }
2029: if (defined($in{'curr_autharg'})) {
2030: $krbarg = $in{'curr_autharg'};
2031: }
2032: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2033: if (defined($in{'curr_autharg'})) {
2034: $result =
2035: &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
2036: $in{'curr_autharg'},$krbver);
2037: } else {
2038: $result =
2039: &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
2040: }
2041: return $result;
2042: }
2043: }
2044: } else {
2045: if ($authnum == 1) {
2046: $authtype = '<input type="hidden" name="login" value="krb">';
2047: }
2048: }
2049: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2050: return;
2051: } elsif ($authtype eq '') {
2052: if (defined($in{'mode'})) {
2053: if ($in{'mode'} eq 'modifycourse') {
2054: if ($authnum == 1) {
2055: $authtype = '<input type="hidden" name="login" value="krb">';
2056: }
2057: }
2058: }
2059: }
2060: $jscall = "javascript:changed_radio('krb',$in{'formname'});";
2061: if ($authtype eq '') {
2062: $authtype = '<input type="radio" name="login" value="krb" '.
2063: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
2064: $krbcheck.' />';
2065: }
2066: if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
2067: ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
2068: $in{'curr_authtype'} eq 'krb5') ||
2069: (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
2070: $in{'curr_authtype'} eq 'krb4')) {
2071: $result .= &mt
2072: ('[_1] Kerberos authenticated with domain [_2] '.
2073: '[_3] Version 4 [_4] Version 5 [_5]',
2074: '<label>'.$authtype,
2075: '</label><input type="text" size="10" name="krbarg" '.
2076: 'value="'.$krbarg.'" '.
2077: 'onchange="'.$jscall.'" />',
2078: '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
2079: '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
2080: '</label>');
2081: } elsif ($can_assign{'krb4'}) {
2082: $result .= &mt
2083: ('[_1] Kerberos authenticated with domain [_2] '.
2084: '[_3] Version 4 [_4]',
2085: '<label>'.$authtype,
2086: '</label><input type="text" size="10" name="krbarg" '.
2087: 'value="'.$krbarg.'" '.
2088: 'onchange="'.$jscall.'" />',
2089: '<label><input type="hidden" name="krbver" value="4" />',
2090: '</label>');
2091: } elsif ($can_assign{'krb5'}) {
2092: $result .= &mt
2093: ('[_1] Kerberos authenticated with domain [_2] '.
2094: '[_3] Version 5 [_4]',
2095: '<label>'.$authtype,
2096: '</label><input type="text" size="10" name="krbarg" '.
2097: 'value="'.$krbarg.'" '.
2098: 'onchange="'.$jscall.'" />',
2099: '<label><input type="hidden" name="krbver" value="5" />',
2100: '</label>');
2101: }
2102: return $result;
2103: }
2104:
2105: sub authform_internal{
2106: my %in = (
2107: formname => 'document.cu',
2108: kerb_def_dom => 'MSU.EDU',
2109: @_,
2110: );
2111: my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
2112: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2113: if (defined($in{'curr_authtype'})) {
2114: if ($in{'curr_authtype'} eq 'int') {
2115: if ($can_assign{'int'}) {
2116: $intcheck = 'checked="on" ';
2117: if (defined($in{'mode'})) {
2118: if ($in{'mode'} eq 'modifyuser') {
2119: $intcheck = '';
2120: }
2121: }
2122: if (defined($in{'curr_autharg'})) {
2123: $intarg = $in{'curr_autharg'};
2124: }
2125: } else {
2126: $result = &mt('Currently internally authenticated.');
2127: return $result;
2128: }
2129: }
2130: } else {
2131: if ($authnum == 1) {
2132: $authtype = '<input type="hidden" name="login" value="int">';
2133: }
2134: }
2135: if (!$can_assign{'int'}) {
2136: return;
2137: } elsif ($authtype eq '') {
2138: if (defined($in{'mode'})) {
2139: if ($in{'mode'} eq 'modifycourse') {
2140: if ($authnum == 1) {
2141: $authtype = '<input type="hidden" name="login" value="int">';
2142: }
2143: }
2144: }
2145: }
2146: $jscall = "javascript:changed_radio('int',$in{'formname'});";
2147: if ($authtype eq '') {
2148: $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
2149: ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
2150: }
2151: $autharg = '<input type="password" size="10" name="intarg" value="'.
2152: $intarg.'" onchange="'.$jscall.'" />';
2153: $result = &mt
2154: ('[_1] Internally authenticated (with initial password [_2])',
2155: '<label>'.$authtype,'</label>'.$autharg);
2156: $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>';
2157: return $result;
2158: }
2159:
2160: sub authform_local{
2161: my %in = (
2162: formname => 'document.cu',
2163: kerb_def_dom => 'MSU.EDU',
2164: @_,
2165: );
2166: my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
2167: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2168: if (defined($in{'curr_authtype'})) {
2169: if ($in{'curr_authtype'} eq 'loc') {
2170: if ($can_assign{'loc'}) {
2171: $loccheck = 'checked="on" ';
2172: if (defined($in{'mode'})) {
2173: if ($in{'mode'} eq 'modifyuser') {
2174: $loccheck = '';
2175: }
2176: }
2177: if (defined($in{'curr_autharg'})) {
2178: $locarg = $in{'curr_autharg'};
2179: }
2180: } else {
2181: $result = &mt('Currently using local (institutional) authentication.');
2182: return $result;
2183: }
2184: }
2185: } else {
2186: if ($authnum == 1) {
2187: $authtype = '<input type="hidden" name="login" value="loc">';
2188: }
2189: }
2190: if (!$can_assign{'loc'}) {
2191: return;
2192: } elsif ($authtype eq '') {
2193: if (defined($in{'mode'})) {
2194: if ($in{'mode'} eq 'modifycourse') {
2195: if ($authnum == 1) {
2196: $authtype = '<input type="hidden" name="login" value="loc">';
2197: }
2198: }
2199: }
2200: }
2201: $jscall = "javascript:changed_radio('loc',$in{'formname'});";
2202: if ($authtype eq '') {
2203: $authtype = '<input type="radio" name="login" value="loc" '.
2204: $loccheck.' onchange="'.$jscall.'" onclick="'.
2205: $jscall.'" />';
2206: }
2207: $autharg = '<input type="text" size="10" name="locarg" value="'.
2208: $locarg.'" onchange="'.$jscall.'" />';
2209: $result = &mt('[_1] Local Authentication with argument [_2]',
2210: '<label>'.$authtype,'</label>'.$autharg);
2211: return $result;
2212: }
2213:
2214: sub authform_filesystem{
2215: my %in = (
2216: formname => 'document.cu',
2217: kerb_def_dom => 'MSU.EDU',
2218: @_,
2219: );
2220: my ($fsyscheck,$result,$authtype,$autharg,$jscall);
2221: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2222: if (defined($in{'curr_authtype'})) {
2223: if ($in{'curr_authtype'} eq 'fsys') {
2224: if ($can_assign{'fsys'}) {
2225: $fsyscheck = 'checked="on" ';
2226: if (defined($in{'mode'})) {
2227: if ($in{'mode'} eq 'modifyuser') {
2228: $fsyscheck = '';
2229: }
2230: }
2231: } else {
2232: $result = &mt('Currently Filesystem Authenticated.');
2233: return $result;
2234: }
2235: }
2236: } else {
2237: if ($authnum == 1) {
2238: $authtype = '<input type="hidden" name="login" value="fsys">';
2239: }
2240: }
2241: if (!$can_assign{'fsys'}) {
2242: return;
2243: } elsif ($authtype eq '') {
2244: if (defined($in{'mode'})) {
2245: if ($in{'mode'} eq 'modifycourse') {
2246: if ($authnum == 1) {
2247: $authtype = '<input type="hidden" name="login" value="fsys">';
2248: }
2249: }
2250: }
2251: }
2252: $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
2253: if ($authtype eq '') {
2254: $authtype = '<input type="radio" name="login" value="fsys" '.
2255: $fsyscheck.' onchange="'.$jscall.'" onclick="'.
2256: $jscall.'" />';
2257: }
2258: $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
2259: ' onchange="'.$jscall.'" />';
2260: $result = &mt
2261: ('[_1] Filesystem Authenticated (with initial password [_2])',
2262: '<label><input type="radio" name="login" value="fsys" '.
2263: $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
2264: '</label><input type="password" size="10" name="fsysarg" value="" '.
2265: 'onchange="'.$jscall.'" />');
2266: return $result;
2267: }
2268:
2269: sub get_assignable_auth {
2270: my ($dom) = @_;
2271: if ($dom eq '') {
2272: $dom = $env{'request.role.domain'};
2273: }
2274: my %can_assign = (
2275: krb4 => 1,
2276: krb5 => 1,
2277: int => 1,
2278: loc => 1,
2279: );
2280: my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
2281: if (ref($domconfig{'usercreation'}) eq 'HASH') {
2282: if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
2283: my $authhash = $domconfig{'usercreation'}{'authtypes'};
2284: my $context;
2285: if ($env{'request.role'} =~ /^au/) {
2286: $context = 'author';
2287: } elsif ($env{'request.role'} =~ /^dc/) {
2288: $context = 'domain';
2289: } elsif ($env{'request.course.id'}) {
2290: $context = 'course';
2291: }
2292: if ($context) {
2293: if (ref($authhash->{$context}) eq 'HASH') {
2294: %can_assign = %{$authhash->{$context}};
2295: }
2296: }
2297: }
2298: }
2299: my $authnum = 0;
2300: foreach my $key (keys(%can_assign)) {
2301: if ($can_assign{$key}) {
2302: $authnum ++;
2303: }
2304: }
2305: if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
2306: $authnum --;
2307: }
2308: return ($authnum,%can_assign);
2309: }
2310:
2311: ###############################################################
2312: ## Get Kerberos Defaults for Domain ##
2313: ###############################################################
2314: ##
2315: ## Returns default kerberos version and an associated argument
2316: ## as listed in file domain.tab. If not listed, provides
2317: ## appropriate default domain and kerberos version.
2318: ##
2319: #-------------------------------------------
2320:
2321: =pod
2322:
2323: =item * &get_kerberos_defaults()
2324:
2325: get_kerberos_defaults($target_domain) returns the default kerberos
2326: version and domain. If not found, it defaults to version 4 and the
2327: domain of the server.
2328:
2329: =over 4
2330:
2331: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
2332:
2333: =back
2334:
2335: =back
2336:
2337: =cut
2338:
2339: #-------------------------------------------
2340: sub get_kerberos_defaults {
2341: my $domain=shift;
2342: my ($krbdef,$krbdefdom);
2343: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
2344: if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
2345: $krbdef = $domdefaults{'auth_def'};
2346: $krbdefdom = $domdefaults{'auth_arg_def'};
2347: } else {
2348: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
2349: my $krbdefdom=$1;
2350: $krbdefdom=~tr/a-z/A-Z/;
2351: $krbdef = "krb4";
2352: }
2353: return ($krbdef,$krbdefdom);
2354: }
2355:
2356:
2357: ###############################################################
2358: ## Thesaurus Functions ##
2359: ###############################################################
2360:
2361: =pod
2362:
2363: =head1 Thesaurus Functions
2364:
2365: =over 4
2366:
2367: =item * &initialize_keywords()
2368:
2369: Initializes the package variable %Keywords if it is empty. Uses the
2370: package variable $thesaurus_db_file.
2371:
2372: =cut
2373:
2374: ###################################################
2375:
2376: sub initialize_keywords {
2377: return 1 if (scalar keys(%Keywords));
2378: # If we are here, %Keywords is empty, so fill it up
2379: # Make sure the file we need exists...
2380: if (! -e $thesaurus_db_file) {
2381: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
2382: " failed because it does not exist");
2383: return 0;
2384: }
2385: # Set up the hash as a database
2386: my %thesaurus_db;
2387: if (! tie(%thesaurus_db,'GDBM_File',
2388: $thesaurus_db_file,&GDBM_READER(),0640)){
2389: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
2390: $thesaurus_db_file);
2391: return 0;
2392: }
2393: # Get the average number of appearances of a word.
2394: my $avecount = $thesaurus_db{'average.count'};
2395: # Put keywords (those that appear > average) into %Keywords
2396: while (my ($word,$data)=each (%thesaurus_db)) {
2397: my ($count,undef) = split /:/,$data;
2398: $Keywords{$word}++ if ($count > $avecount);
2399: }
2400: untie %thesaurus_db;
2401: # Remove special values from %Keywords.
2402: foreach my $value ('total.count','average.count') {
2403: delete($Keywords{$value}) if (exists($Keywords{$value}));
2404: }
2405: return 1;
2406: }
2407:
2408: ###################################################
2409:
2410: =pod
2411:
2412: =item * &keyword($word)
2413:
2414: Returns true if $word is a keyword. A keyword is a word that appears more
2415: than the average number of times in the thesaurus database. Calls
2416: &initialize_keywords
2417:
2418: =cut
2419:
2420: ###################################################
2421:
2422: sub keyword {
2423: return if (!&initialize_keywords());
2424: my $word=lc(shift());
2425: $word=~s/\W//g;
2426: return exists($Keywords{$word});
2427: }
2428:
2429: ###############################################################
2430:
2431: =pod
2432:
2433: =item * &get_related_words()
2434:
2435: Look up a word in the thesaurus. Takes a scalar argument and returns
2436: an array of words. If the keyword is not in the thesaurus, an empty array
2437: will be returned. The order of the words returned is determined by the
2438: database which holds them.
2439:
2440: Uses global $thesaurus_db_file.
2441:
2442: =cut
2443:
2444: ###############################################################
2445: sub get_related_words {
2446: my $keyword = shift;
2447: my %thesaurus_db;
2448: if (! -e $thesaurus_db_file) {
2449: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
2450: "failed because the file does not exist");
2451: return ();
2452: }
2453: if (! tie(%thesaurus_db,'GDBM_File',
2454: $thesaurus_db_file,&GDBM_READER(),0640)){
2455: return ();
2456: }
2457: my @Words=();
2458: my $count=0;
2459: if (exists($thesaurus_db{$keyword})) {
2460: # The first element is the number of times
2461: # the word appears. We do not need it now.
2462: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
2463: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
2464: my $threshold=$mostfrequentcount/10;
2465: foreach my $possibleword (@RelatedWords) {
2466: my ($word,$wordcount)=split(/\,/,$possibleword);
2467: if ($wordcount>$threshold) {
2468: push(@Words,$word);
2469: $count++;
2470: if ($count>10) { last; }
2471: }
2472: }
2473: }
2474: untie %thesaurus_db;
2475: return @Words;
2476: }
2477:
2478: =pod
2479:
2480: =back
2481:
2482: =cut
2483:
2484: # -------------------------------------------------------------- Plaintext name
2485: =pod
2486:
2487: =head1 User Name Functions
2488:
2489: =over 4
2490:
2491: =item * &plainname($uname,$udom,$first)
2492:
2493: Takes a users logon name and returns it as a string in
2494: "first middle last generation" form
2495: if $first is set to 'lastname' then it returns it as
2496: 'lastname generation, firstname middlename' if their is a lastname
2497:
2498: =cut
2499:
2500:
2501: ###############################################################
2502: sub plainname {
2503: my ($uname,$udom,$first)=@_;
2504: return if (!defined($uname) || !defined($udom));
2505: my %names=&getnames($uname,$udom);
2506: my $name=&Apache::lonnet::format_name($names{'firstname'},
2507: $names{'middlename'},
2508: $names{'lastname'},
2509: $names{'generation'},$first);
2510: $name=~s/^\s+//;
2511: $name=~s/\s+$//;
2512: $name=~s/\s+/ /g;
2513: if ($name !~ /\S/) { $name=$uname.':'.$udom; }
2514: return $name;
2515: }
2516:
2517: # -------------------------------------------------------------------- Nickname
2518: =pod
2519:
2520: =item * &nickname($uname,$udom)
2521:
2522: Gets a users name and returns it as a string as
2523:
2524: ""nickname""
2525:
2526: if the user has a nickname or
2527:
2528: "first middle last generation"
2529:
2530: if the user does not
2531:
2532: =cut
2533:
2534: sub nickname {
2535: my ($uname,$udom)=@_;
2536: return if (!defined($uname) || !defined($udom));
2537: my %names=&getnames($uname,$udom);
2538: my $name=$names{'nickname'};
2539: if ($name) {
2540: $name='"'.$name.'"';
2541: } else {
2542: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
2543: $names{'lastname'}.' '.$names{'generation'};
2544: $name=~s/\s+$//;
2545: $name=~s/\s+/ /g;
2546: }
2547: return $name;
2548: }
2549:
2550: sub getnames {
2551: my ($uname,$udom)=@_;
2552: return if (!defined($uname) || !defined($udom));
2553: if ($udom eq 'public' && $uname eq 'public') {
2554: return ('lastname' => &mt('Public'));
2555: }
2556: my $id=$uname.':'.$udom;
2557: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
2558: if ($cached) {
2559: return %{$names};
2560: } else {
2561: my %loadnames=&Apache::lonnet::get('environment',
2562: ['firstname','middlename','lastname','generation','nickname'],
2563: $udom,$uname);
2564: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
2565: return %loadnames;
2566: }
2567: }
2568:
2569: # -------------------------------------------------------------------- getemails
2570:
2571: =pod
2572:
2573: =item * &getemails($uname,$udom)
2574:
2575: Gets a user's email information and returns it as a hash with keys:
2576: notification, critnotification, permanentemail
2577:
2578: For notification and critnotification, values are comma-separated lists
2579: of e-mail addresses; for permanentemail, value is a single e-mail address.
2580:
2581:
2582: =cut
2583:
2584:
2585: sub getemails {
2586: my ($uname,$udom)=@_;
2587: if ($udom eq 'public' && $uname eq 'public') {
2588: return;
2589: }
2590: if (!$udom) { $udom=$env{'user.domain'}; }
2591: if (!$uname) { $uname=$env{'user.name'}; }
2592: my $id=$uname.':'.$udom;
2593: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
2594: if ($cached) {
2595: return %{$names};
2596: } else {
2597: my %loadnames=&Apache::lonnet::get('environment',
2598: ['notification','critnotification',
2599: 'permanentemail'],
2600: $udom,$uname);
2601: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
2602: return %loadnames;
2603: }
2604: }
2605:
2606: sub flush_email_cache {
2607: my ($uname,$udom)=@_;
2608: if (!$udom) { $udom =$env{'user.domain'}; }
2609: if (!$uname) { $uname=$env{'user.name'}; }
2610: return if ($udom eq 'public' && $uname eq 'public');
2611: my $id=$uname.':'.$udom;
2612: &Apache::lonnet::devalidate_cache_new('emailscache',$id);
2613: }
2614:
2615: # ------------------------------------------------------------------ Screenname
2616:
2617: =pod
2618:
2619: =item * &screenname($uname,$udom)
2620:
2621: Gets a users screenname and returns it as a string
2622:
2623: =cut
2624:
2625: sub screenname {
2626: my ($uname,$udom)=@_;
2627: if ($uname eq $env{'user.name'} &&
2628: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
2629: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
2630: return $names{'screenname'};
2631: }
2632:
2633:
2634: # ------------------------------------------------------------- Message Wrapper
2635:
2636: sub messagewrapper {
2637: my ($link,$username,$domain,$subject,$text)=@_;
2638: return
2639: '<a href="/adm/email?compose=individual&'.
2640: 'recname='.$username.'&recdom='.$domain.
2641: '&subject='.&escape($subject).'&text='.&escape($text).'" '.
2642: 'title="'.&mt('Send message').'">'.$link.'</a>';
2643: }
2644: # --------------------------------------------------------------- Notes Wrapper
2645:
2646: sub noteswrapper {
2647: my ($link,$un,$do)=@_;
2648: return
2649: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
2650: }
2651: # ------------------------------------------------------------- Aboutme Wrapper
2652:
2653: sub aboutmewrapper {
2654: my ($link,$username,$domain,$target)=@_;
2655: if (!defined($username) && !defined($domain)) {
2656: return;
2657: }
2658: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
2659: ($target?' target="$target"':'').' title="'.&mt("View this user's personal page").'">'.$link.'</a>';
2660: }
2661:
2662: # ------------------------------------------------------------ Syllabus Wrapper
2663:
2664:
2665: sub syllabuswrapper {
2666: my ($linktext,$coursedir,$domain,$fontcolor)=@_;
2667: if ($fontcolor) {
2668: $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>';
2669: }
2670: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
2671: }
2672:
2673: sub track_student_link {
2674: my ($linktext,$sname,$sdom,$target,$start) = @_;
2675: my $link ="/adm/trackstudent?";
2676: my $title = 'View recent activity';
2677: if (defined($sname) && $sname !~ /^\s*$/ &&
2678: defined($sdom) && $sdom !~ /^\s*$/) {
2679: $link .= "selected_student=$sname:$sdom";
2680: $title .= ' of this student';
2681: }
2682: if (defined($target) && $target !~ /^\s*$/) {
2683: $target = qq{target="$target"};
2684: } else {
2685: $target = '';
2686: }
2687: if ($start) { $link.='&start='.$start; }
2688: $title = &mt($title);
2689: $linktext = &mt($linktext);
2690: return qq{<a href="$link" title="$title" $target>$linktext</a>}.
2691: &help_open_topic('View_recent_activity');
2692: }
2693:
2694: # ===================================================== Display a student photo
2695:
2696:
2697: sub student_image_tag {
2698: my ($domain,$user)=@_;
2699: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
2700: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
2701: return '<img src="'.$imgsrc.'" align="right" />';
2702: } else {
2703: return '';
2704: }
2705: }
2706:
2707: =pod
2708:
2709: =back
2710:
2711: =head1 Access .tab File Data
2712:
2713: =over 4
2714:
2715: =item * &languageids()
2716:
2717: returns list of all language ids
2718:
2719: =cut
2720:
2721: sub languageids {
2722: return sort(keys(%language));
2723: }
2724:
2725: =pod
2726:
2727: =item * &languagedescription()
2728:
2729: returns description of a specified language id
2730:
2731: =cut
2732:
2733: sub languagedescription {
2734: my $code=shift;
2735: return ($supported_language{$code}?'* ':'').
2736: $language{$code}.
2737: ($supported_language{$code}?' ('.&mt('interface available').')':'');
2738: }
2739:
2740: sub plainlanguagedescription {
2741: my $code=shift;
2742: return $language{$code};
2743: }
2744:
2745: sub supportedlanguagecode {
2746: my $code=shift;
2747: return $supported_language{$code};
2748: }
2749:
2750: =pod
2751:
2752: =item * ©rightids()
2753:
2754: returns list of all copyrights
2755:
2756: =cut
2757:
2758: sub copyrightids {
2759: return sort(keys(%cprtag));
2760: }
2761:
2762: =pod
2763:
2764: =item * ©rightdescription()
2765:
2766: returns description of a specified copyright id
2767:
2768: =cut
2769:
2770: sub copyrightdescription {
2771: return &mt($cprtag{shift(@_)});
2772: }
2773:
2774: =pod
2775:
2776: =item * &source_copyrightids()
2777:
2778: returns list of all source copyrights
2779:
2780: =cut
2781:
2782: sub source_copyrightids {
2783: return sort(keys(%scprtag));
2784: }
2785:
2786: =pod
2787:
2788: =item * &source_copyrightdescription()
2789:
2790: returns description of a specified source copyright id
2791:
2792: =cut
2793:
2794: sub source_copyrightdescription {
2795: return &mt($scprtag{shift(@_)});
2796: }
2797:
2798: =pod
2799:
2800: =item * &filecategories()
2801:
2802: returns list of all file categories
2803:
2804: =cut
2805:
2806: sub filecategories {
2807: return sort(keys(%category_extensions));
2808: }
2809:
2810: =pod
2811:
2812: =item * &filecategorytypes()
2813:
2814: returns list of file types belonging to a given file
2815: category
2816:
2817: =cut
2818:
2819: sub filecategorytypes {
2820: my ($cat) = @_;
2821: return @{$category_extensions{lc($cat)}};
2822: }
2823:
2824: =pod
2825:
2826: =item * &fileembstyle()
2827:
2828: returns embedding style for a specified file type
2829:
2830: =cut
2831:
2832: sub fileembstyle {
2833: return $fe{lc(shift(@_))};
2834: }
2835:
2836: sub filemimetype {
2837: return $fm{lc(shift(@_))};
2838: }
2839:
2840:
2841: sub filecategoryselect {
2842: my ($name,$value)=@_;
2843: return &select_form($value,$name,
2844: '' => &mt('Any category'),
2845: map { $_,$_ } sort(keys(%category_extensions)));
2846: }
2847:
2848: =pod
2849:
2850: =item * &filedescription()
2851:
2852: returns description for a specified file type
2853:
2854: =cut
2855:
2856: sub filedescription {
2857: my $file_description = $fd{lc(shift())};
2858: $file_description =~ s:([\[\]]):~$1:g;
2859: return &mt($file_description);
2860: }
2861:
2862: =pod
2863:
2864: =item * &filedescriptionex()
2865:
2866: returns description for a specified file type with
2867: extra formatting
2868:
2869: =cut
2870:
2871: sub filedescriptionex {
2872: my $ex=shift;
2873: my $file_description = $fd{lc($ex)};
2874: $file_description =~ s:([\[\]]):~$1:g;
2875: return '.'.$ex.' '.&mt($file_description);
2876: }
2877:
2878: # End of .tab access
2879: =pod
2880:
2881: =back
2882:
2883: =cut
2884:
2885: # ------------------------------------------------------------------ File Types
2886: sub fileextensions {
2887: return sort(keys(%fe));
2888: }
2889:
2890: # ----------------------------------------------------------- Display Languages
2891: # returns a hash with all desired display languages
2892: #
2893:
2894: sub display_languages {
2895: my %languages=();
2896: foreach my $lang (&preferred_languages()) {
2897: $languages{$lang}=1;
2898: }
2899: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
2900: if ($env{'form.displaylanguage'}) {
2901: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
2902: $languages{$lang}=1;
2903: }
2904: }
2905: return %languages;
2906: }
2907:
2908: sub preferred_languages {
2909: my @languages=();
2910: if ($env{'course.'.$env{'request.course.id'}.'.languages'}) {
2911: @languages=(@languages,split(/\s*(\,|\;|\:)\s*/,
2912: $env{'course.'.$env{'request.course.id'}.'.languages'}));
2913: }
2914: if ($env{'environment.languages'}) {
2915: @languages=(@languages,
2916: split(/\s*(\,|\;|\:)\s*/,$env{'environment.languages'}));
2917: }
2918: my $browser=$ENV{'HTTP_ACCEPT_LANGUAGE'};
2919: if ($browser) {
2920: my @browser =
2921: map { (split(/\s*;\s*/,$_))[0] } (split(/\s*,\s*/,$browser));
2922: push(@languages,@browser);
2923: }
2924:
2925: foreach my $domtype ($env{'user.domain'},$env{'request.role.domain'},
2926: $Apache::lonnet::perlvar{'lonDefDomain'}) {
2927: if ($domtype ne '') {
2928: my %domdefs = &Apache::lonnet::get_domain_defaults($domtype);
2929: if ($domdefs{'lang_def'} ne '') {
2930: push(@languages,$domdefs{'lang_def'});
2931: }
2932: }
2933: }
2934: # turn "en-ca" into "en-ca,en"
2935: my @genlanguages;
2936: foreach my $lang (@languages) {
2937: unless ($lang=~/\w/) { next; }
2938: push(@genlanguages,$lang);
2939: if ($lang=~/(\-|\_)/) {
2940: push(@genlanguages,(split(/(\-|\_)/,$lang))[0]);
2941: }
2942: }
2943: #uniqueify the languages list
2944: my %count;
2945: @genlanguages = map { $count{$_}++ == 0 ? $_ : () } @genlanguages;
2946: return @genlanguages;
2947: }
2948:
2949: sub languages {
2950: my ($possible_langs) = @_;
2951: my @preferred_langs = &preferred_languages();
2952: if (!ref($possible_langs)) {
2953: if( wantarray ) {
2954: return @preferred_langs;
2955: } else {
2956: return $preferred_langs[0];
2957: }
2958: }
2959: my %possibilities = map { $_ => 1 } (@$possible_langs);
2960: my @preferred_possibilities;
2961: foreach my $preferred_lang (@preferred_langs) {
2962: if (exists($possibilities{$preferred_lang})) {
2963: push(@preferred_possibilities, $preferred_lang);
2964: }
2965: }
2966: if( wantarray ) {
2967: return @preferred_possibilities;
2968: }
2969: return $preferred_possibilities[0];
2970: }
2971:
2972: ###############################################################
2973: ## Student Answer Attempts ##
2974: ###############################################################
2975:
2976: =pod
2977:
2978: =head1 Alternate Problem Views
2979:
2980: =over 4
2981:
2982: =item * &get_previous_attempt($symb, $username, $domain, $course,
2983: $getattempt, $regexp, $gradesub)
2984:
2985: Return string with previous attempt on problem. Arguments:
2986:
2987: =over 4
2988:
2989: =item * $symb: Problem, including path
2990:
2991: =item * $username: username of the desired student
2992:
2993: =item * $domain: domain of the desired student
2994:
2995: =item * $course: Course ID
2996:
2997: =item * $getattempt: Leave blank for all attempts, otherwise put
2998: something
2999:
3000: =item * $regexp: if string matches this regexp, the string will be
3001: sent to $gradesub
3002:
3003: =item * $gradesub: routine that processes the string if it matches $regexp
3004:
3005: =back
3006:
3007: The output string is a table containing all desired attempts, if any.
3008:
3009: =cut
3010:
3011: sub get_previous_attempt {
3012: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
3013: my $prevattempts='';
3014: no strict 'refs';
3015: if ($symb) {
3016: my (%returnhash)=
3017: &Apache::lonnet::restore($symb,$course,$domain,$username);
3018: if ($returnhash{'version'}) {
3019: my %lasthash=();
3020: my $version;
3021: for ($version=1;$version<=$returnhash{'version'};$version++) {
3022: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
3023: $lasthash{$key}=$returnhash{$version.':'.$key};
3024: }
3025: }
3026: $prevattempts=&start_data_table().&start_data_table_header_row();
3027: $prevattempts.='<th>'.&mt('History').'</th>';
3028: foreach my $key (sort(keys(%lasthash))) {
3029: my ($ign,@parts) = split(/\./,$key);
3030: if ($#parts > 0) {
3031: my $data=$parts[-1];
3032: pop(@parts);
3033: $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.' </th>';
3034: } else {
3035: if ($#parts == 0) {
3036: $prevattempts.='<th>'.$parts[0].'</th>';
3037: } else {
3038: $prevattempts.='<th>'.$ign.'</th>';
3039: }
3040: }
3041: }
3042: $prevattempts.=&end_data_table_header_row();
3043: if ($getattempt eq '') {
3044: for ($version=1;$version<=$returnhash{'version'};$version++) {
3045: $prevattempts.=&start_data_table_row().
3046: '<td>'.&mt('Transaction [_1]',$version).'</td>';
3047: foreach my $key (sort(keys(%lasthash))) {
3048: my $value = &format_previous_attempt_value($key,
3049: $returnhash{$version.':'.$key});
3050: $prevattempts.='<td>'.$value.' </td>';
3051: }
3052: $prevattempts.=&end_data_table_row();
3053: }
3054: }
3055: $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
3056: foreach my $key (sort(keys(%lasthash))) {
3057: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3058: if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
3059: $prevattempts.='<td>'.$value.' </td>';
3060: }
3061: $prevattempts.= &end_data_table_row().&end_data_table();
3062: } else {
3063: $prevattempts=
3064: &start_data_table().&start_data_table_row().
3065: '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
3066: &end_data_table_row().&end_data_table();
3067: }
3068: } else {
3069: $prevattempts=
3070: &start_data_table().&start_data_table_row().
3071: '<td>'.&mt('No data.').'</td>'.
3072: &end_data_table_row().&end_data_table();
3073: }
3074: }
3075:
3076: sub format_previous_attempt_value {
3077: my ($key,$value) = @_;
3078: if ($key =~ /timestamp/) {
3079: $value = &Apache::lonlocal::locallocaltime($value);
3080: } elsif (ref($value) eq 'ARRAY') {
3081: $value = '('.join(', ', @{ $value }).')';
3082: } else {
3083: $value = &unescape($value);
3084: }
3085: return $value;
3086: }
3087:
3088:
3089: sub relative_to_absolute {
3090: my ($url,$output)=@_;
3091: my $parser=HTML::TokeParser->new(\$output);
3092: my $token;
3093: my $thisdir=$url;
3094: my @rlinks=();
3095: while ($token=$parser->get_token) {
3096: if ($token->[0] eq 'S') {
3097: if ($token->[1] eq 'a') {
3098: if ($token->[2]->{'href'}) {
3099: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
3100: }
3101: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
3102: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
3103: } elsif ($token->[1] eq 'base') {
3104: $thisdir=$token->[2]->{'href'};
3105: }
3106: }
3107: }
3108: $thisdir=~s-/[^/]*$--;
3109: foreach my $link (@rlinks) {
3110: unless (($link=~/^http:\/\//i) ||
3111: ($link=~/^\//) ||
3112: ($link=~/^javascript:/i) ||
3113: ($link=~/^mailto:/i) ||
3114: ($link=~/^\#/)) {
3115: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
3116: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
3117: }
3118: }
3119: # -------------------------------------------------- Deal with Applet codebases
3120: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
3121: return $output;
3122: }
3123:
3124: =pod
3125:
3126: =item * &get_student_view()
3127:
3128: show a snapshot of what student was looking at
3129:
3130: =cut
3131:
3132: sub get_student_view {
3133: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
3134: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
3135: my (%form);
3136: my @elements=('symb','courseid','domain','username');
3137: foreach my $element (@elements) {
3138: $form{'grade_'.$element}=eval '$'.$element #'
3139: }
3140: if (defined($moreenv)) {
3141: %form=(%form,%{$moreenv});
3142: }
3143: if (defined($target)) { $form{'grade_target'} = $target; }
3144: $feedurl=&Apache::lonnet::clutter($feedurl);
3145: my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
3146: $userview=~s/\<body[^\>]*\>//gi;
3147: $userview=~s/\<\/body\>//gi;
3148: $userview=~s/\<html\>//gi;
3149: $userview=~s/\<\/html\>//gi;
3150: $userview=~s/\<head\>//gi;
3151: $userview=~s/\<\/head\>//gi;
3152: $userview=~s/action\s*\=/would_be_action\=/gi;
3153: $userview=&relative_to_absolute($feedurl,$userview);
3154: if (wantarray) {
3155: return ($userview,$response);
3156: } else {
3157: return $userview;
3158: }
3159: }
3160:
3161: sub get_student_view_with_retries {
3162: my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
3163:
3164: my $ok = 0; # True if we got a good response.
3165: my $content;
3166: my $response;
3167:
3168: # Try to get the student_view done. within the retries count:
3169:
3170: do {
3171: ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
3172: $ok = $response->is_success;
3173: if (!$ok) {
3174: &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
3175: }
3176: $retries--;
3177: } while (!$ok && ($retries > 0));
3178:
3179: if (!$ok) {
3180: $content = ''; # On error return an empty content.
3181: }
3182: return ($content, $response);
3183: }
3184:
3185: =pod
3186:
3187: =item * &get_student_answers()
3188:
3189: show a snapshot of how student was answering problem
3190:
3191: =cut
3192:
3193: sub get_student_answers {
3194: my ($symb,$username,$domain,$courseid,%form) = @_;
3195: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
3196: my (%moreenv);
3197: my @elements=('symb','courseid','domain','username');
3198: foreach my $element (@elements) {
3199: $moreenv{'grade_'.$element}=eval '$'.$element #'
3200: }
3201: $moreenv{'grade_target'}='answer';
3202: %moreenv=(%form,%moreenv);
3203: $feedurl = &Apache::lonnet::clutter($feedurl);
3204: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
3205: return $userview;
3206: }
3207:
3208: =pod
3209:
3210: =item * &submlink()
3211:
3212: Inputs: $text $uname $udom $symb $target
3213:
3214: Returns: A link to grades.pm such as to see the SUBM view of a student
3215:
3216: =cut
3217:
3218: ###############################################
3219: sub submlink {
3220: my ($text,$uname,$udom,$symb,$target)=@_;
3221: if (!($uname && $udom)) {
3222: (my $cursymb, my $courseid,$udom,$uname)=
3223: &Apache::lonnet::whichuser($symb);
3224: if (!$symb) { $symb=$cursymb; }
3225: }
3226: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
3227: $symb=&escape($symb);
3228: if ($target) { $target="target=\"$target\""; }
3229: return '<a href="/adm/grades?&command=submission&'.
3230: 'symb='.$symb.'&student='.$uname.
3231: '&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
3232: }
3233: ##############################################
3234:
3235: =pod
3236:
3237: =item * &pgrdlink()
3238:
3239: Inputs: $text $uname $udom $symb $target
3240:
3241: Returns: A link to grades.pm such as to see the PGRD view of a student
3242:
3243: =cut
3244:
3245: ###############################################
3246: sub pgrdlink {
3247: my $link=&submlink(@_);
3248: $link=~s/(&command=submission)/$1&showgrading=yes/;
3249: return $link;
3250: }
3251: ##############################################
3252:
3253: =pod
3254:
3255: =item * &pprmlink()
3256:
3257: Inputs: $text $uname $udom $symb $target
3258:
3259: Returns: A link to parmset.pm such as to see the PPRM view of a
3260: student and a specific resource
3261:
3262: =cut
3263:
3264: ###############################################
3265: sub pprmlink {
3266: my ($text,$uname,$udom,$symb,$target)=@_;
3267: if (!($uname && $udom)) {
3268: (my $cursymb, my $courseid,$udom,$uname)=
3269: &Apache::lonnet::whichuser($symb);
3270: if (!$symb) { $symb=$cursymb; }
3271: }
3272: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
3273: $symb=&escape($symb);
3274: if ($target) { $target="target=\"$target\""; }
3275: return '<a href="/adm/parmset?command=set&'.
3276: 'symb='.$symb.'&uname='.$uname.
3277: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
3278: }
3279: ##############################################
3280:
3281: =pod
3282:
3283: =back
3284:
3285: =cut
3286:
3287: ###############################################
3288:
3289:
3290: sub timehash {
3291: my @ltime=localtime(shift);
3292: return ( 'seconds' => $ltime[0],
3293: 'minutes' => $ltime[1],
3294: 'hours' => $ltime[2],
3295: 'day' => $ltime[3],
3296: 'month' => $ltime[4]+1,
3297: 'year' => $ltime[5]+1900,
3298: 'weekday' => $ltime[6],
3299: 'dayyear' => $ltime[7]+1,
3300: 'dlsav' => $ltime[8] );
3301: }
3302:
3303: sub utc_string {
3304: my ($date)=@_;
3305: return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
3306: }
3307:
3308: sub maketime {
3309: my %th=@_;
3310: return POSIX::mktime(
3311: ($th{'seconds'},$th{'minutes'},$th{'hours'},
3312: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
3313: }
3314:
3315: #########################################
3316:
3317: sub findallcourses {
3318: my ($roles,$uname,$udom) = @_;
3319: my %roles;
3320: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
3321: my %courses;
3322: my $now=time;
3323: if (!defined($uname)) {
3324: $uname = $env{'user.name'};
3325: }
3326: if (!defined($udom)) {
3327: $udom = $env{'user.domain'};
3328: }
3329: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
3330: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
3331: if (!%roles) {
3332: %roles = (
3333: cc => 1,
3334: in => 1,
3335: ep => 1,
3336: ta => 1,
3337: cr => 1,
3338: st => 1,
3339: );
3340: }
3341: foreach my $entry (keys(%roleshash)) {
3342: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
3343: if ($trole =~ /^cr/) {
3344: next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
3345: } else {
3346: next if (!exists($roles{$trole}));
3347: }
3348: if ($tend) {
3349: next if ($tend < $now);
3350: }
3351: if ($tstart) {
3352: next if ($tstart > $now);
3353: }
3354: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
3355: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
3356: if ($secpart eq '') {
3357: ($cnum,$role) = split(/_/,$cnumpart);
3358: $sec = 'none';
3359: $realsec = '';
3360: } else {
3361: $cnum = $cnumpart;
3362: ($sec,$role) = split(/_/,$secpart);
3363: $realsec = $sec;
3364: }
3365: $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
3366: }
3367: } else {
3368: foreach my $key (keys(%env)) {
3369: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
3370: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
3371: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
3372: next if ($role eq 'ca' || $role eq 'aa');
3373: next if (%roles && !exists($roles{$role}));
3374: my ($starttime,$endtime)=split(/\./,$env{$key});
3375: my $active=1;
3376: if ($starttime) {
3377: if ($now<$starttime) { $active=0; }
3378: }
3379: if ($endtime) {
3380: if ($now>$endtime) { $active=0; }
3381: }
3382: if ($active) {
3383: if ($sec eq '') {
3384: $sec = 'none';
3385: }
3386: $courses{$cdom.'_'.$cnum}{$sec} =
3387: $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
3388: }
3389: }
3390: }
3391: }
3392: return %courses;
3393: }
3394:
3395: ###############################################
3396:
3397: sub blockcheck {
3398: my ($setters,$activity,$uname,$udom) = @_;
3399:
3400: if (!defined($udom)) {
3401: $udom = $env{'user.domain'};
3402: }
3403: if (!defined($uname)) {
3404: $uname = $env{'user.name'};
3405: }
3406:
3407: # If uname and udom are for a course, check for blocks in the course.
3408:
3409: if (&Apache::lonnet::is_course($udom,$uname)) {
3410: my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
3411: my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
3412: return ($startblock,$endblock);
3413: }
3414:
3415: my $startblock = 0;
3416: my $endblock = 0;
3417: my %live_courses = &findallcourses(undef,$uname,$udom);
3418:
3419: # If uname is for a user, and activity is course-specific, i.e.,
3420: # boards, chat or groups, check for blocking in current course only.
3421:
3422: if (($activity eq 'boards' || $activity eq 'chat' ||
3423: $activity eq 'groups') && ($env{'request.course.id'})) {
3424: foreach my $key (keys(%live_courses)) {
3425: if ($key ne $env{'request.course.id'}) {
3426: delete($live_courses{$key});
3427: }
3428: }
3429: }
3430:
3431: my $otheruser = 0;
3432: my %own_courses;
3433: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
3434: # Resource belongs to user other than current user.
3435: $otheruser = 1;
3436: # Gather courses for current user
3437: %own_courses =
3438: &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
3439: }
3440:
3441: # Gather active course roles - course coordinator, instructor,
3442: # exam proctor, ta, student, or custom role.
3443:
3444: foreach my $course (keys(%live_courses)) {
3445: my ($cdom,$cnum);
3446: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
3447: $cdom = $env{'course.'.$course.'.domain'};
3448: $cnum = $env{'course.'.$course.'.num'};
3449: } else {
3450: ($cdom,$cnum) = split(/_/,$course);
3451: }
3452: my $no_ownblock = 0;
3453: my $no_userblock = 0;
3454: if ($otheruser && $activity ne 'com') {
3455: # Check if current user has 'evb' priv for this
3456: if (defined($own_courses{$course})) {
3457: foreach my $sec (keys(%{$own_courses{$course}})) {
3458: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
3459: if ($sec ne 'none') {
3460: $checkrole .= '/'.$sec;
3461: }
3462: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
3463: $no_ownblock = 1;
3464: last;
3465: }
3466: }
3467: }
3468: # if they have 'evb' priv and are currently not playing student
3469: next if (($no_ownblock) &&
3470: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
3471: }
3472: foreach my $sec (keys(%{$live_courses{$course}})) {
3473: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
3474: if ($sec ne 'none') {
3475: $checkrole .= '/'.$sec;
3476: }
3477: if ($otheruser) {
3478: # Resource belongs to user other than current user.
3479: # Assemble privs for that user, and check for 'evb' priv.
3480: my ($trole,$tdom,$tnum,$tsec);
3481: my $entry = $live_courses{$course}{$sec};
3482: if ($entry =~ /^cr/) {
3483: ($trole,$tdom,$tnum,$tsec) =
3484: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
3485: } else {
3486: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
3487: }
3488: my ($spec,$area,$trest,%allroles,%userroles);
3489: $area = '/'.$tdom.'/'.$tnum;
3490: $trest = $tnum;
3491: if ($tsec ne '') {
3492: $area .= '/'.$tsec;
3493: $trest .= '/'.$tsec;
3494: }
3495: $spec = $trole.'.'.$area;
3496: if ($trole =~ /^cr/) {
3497: &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
3498: $tdom,$spec,$trest,$area);
3499: } else {
3500: &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
3501: $tdom,$spec,$trest,$area);
3502: }
3503: my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
3504: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
3505: if ($1) {
3506: $no_userblock = 1;
3507: last;
3508: }
3509: }
3510: } else {
3511: # Resource belongs to current user
3512: # Check for 'evb' priv via lonnet::allowed().
3513: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
3514: $no_ownblock = 1;
3515: last;
3516: }
3517: }
3518: }
3519: # if they have the evb priv and are currently not playing student
3520: next if (($no_ownblock) &&
3521: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
3522: next if ($no_userblock);
3523:
3524: # Retrieve blocking times and identity of blocker for course
3525: # of specified user, unless user has 'evb' privilege.
3526:
3527: my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
3528: if (($start != 0) &&
3529: (($startblock == 0) || ($startblock > $start))) {
3530: $startblock = $start;
3531: }
3532: if (($end != 0) &&
3533: (($endblock == 0) || ($endblock < $end))) {
3534: $endblock = $end;
3535: }
3536: }
3537: return ($startblock,$endblock);
3538: }
3539:
3540: sub get_blocks {
3541: my ($setters,$activity,$cdom,$cnum) = @_;
3542: my $startblock = 0;
3543: my $endblock = 0;
3544: my $course = $cdom.'_'.$cnum;
3545: $setters->{$course} = {};
3546: $setters->{$course}{'staff'} = [];
3547: $setters->{$course}{'times'} = [];
3548: my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
3549: foreach my $record (keys(%records)) {
3550: my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
3551: if ($start <= time && $end >= time) {
3552: my ($staff_name,$staff_dom,$title,$blocks) =
3553: &parse_block_record($records{$record});
3554: if ($blocks->{$activity} eq 'on') {
3555: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
3556: push(@{$$setters{$course}{'times'}}, [$start,$end]);
3557: if ( ($startblock == 0) || ($startblock > $start) ) {
3558: $startblock = $start;
3559: }
3560: if ( ($endblock == 0) || ($endblock < $end) ) {
3561: $endblock = $end;
3562: }
3563: }
3564: }
3565: }
3566: return ($startblock,$endblock);
3567: }
3568:
3569: sub parse_block_record {
3570: my ($record) = @_;
3571: my ($setuname,$setudom,$title,$blocks);
3572: if (ref($record) eq 'HASH') {
3573: ($setuname,$setudom) = split(/:/,$record->{'setter'});
3574: $title = &unescape($record->{'event'});
3575: $blocks = $record->{'blocks'};
3576: } else {
3577: my @data = split(/:/,$record,3);
3578: if (scalar(@data) eq 2) {
3579: $title = $data[1];
3580: ($setuname,$setudom) = split(/@/,$data[0]);
3581: } else {
3582: ($setuname,$setudom,$title) = @data;
3583: }
3584: $blocks = { 'com' => 'on' };
3585: }
3586: return ($setuname,$setudom,$title,$blocks);
3587: }
3588:
3589: sub build_block_table {
3590: my ($startblock,$endblock,$setters) = @_;
3591: my %lt = &Apache::lonlocal::texthash(
3592: 'cacb' => 'Currently active communication blocks',
3593: 'cour' => 'Course',
3594: 'dura' => 'Duration',
3595: 'blse' => 'Block set by'
3596: );
3597: my $output;
3598: $output = '<br />'.$lt{'cacb'}.':<br />';
3599: $output .= &start_data_table();
3600: $output .= '
3601: <tr>
3602: <th>'.$lt{'cour'}.'</th>
3603: <th>'.$lt{'dura'}.'</th>
3604: <th>'.$lt{'blse'}.'</th>
3605: </tr>
3606: ';
3607: foreach my $course (keys(%{$setters})) {
3608: my %courseinfo=&Apache::lonnet::coursedescription($course);
3609: for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
3610: my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
3611: my $fullname = &plainname($uname,$udom);
3612: if (defined($env{'user.name'}) && defined($env{'user.domain'})
3613: && $env{'user.name'} ne 'public'
3614: && $env{'user.domain'} ne 'public') {
3615: $fullname = &aboutmewrapper($fullname,$uname,$udom);
3616: }
3617: my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
3618: $openblock = &Apache::lonlocal::locallocaltime($openblock);
3619: $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
3620: $output .= &Apache::loncommon::start_data_table_row().
3621: '<td>'.$courseinfo{'description'}.'</td>'.
3622: '<td>'.$openblock.' to '.$closeblock.'</td>'.
3623: '<td>'.$fullname.'</td>'.
3624: &Apache::loncommon::end_data_table_row();
3625: }
3626: }
3627: $output .= &end_data_table();
3628: }
3629:
3630: sub blocking_status {
3631: my ($activity,$uname,$udom) = @_;
3632: my %setters;
3633: my ($blocked,$output,$ownitem,$is_course);
3634: my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
3635: if ($startblock && $endblock) {
3636: $blocked = 1;
3637: if (wantarray) {
3638: my $category;
3639: if ($activity eq 'boards') {
3640: $category = 'Discussion posts in this course';
3641: } elsif ($activity eq 'blogs') {
3642: $category = 'Blogs';
3643: } elsif ($activity eq 'port') {
3644: if (defined($uname) && defined($udom)) {
3645: if ($uname eq $env{'user.name'} &&
3646: $udom eq $env{'user.domain'}) {
3647: $ownitem = 1;
3648: }
3649: }
3650: $is_course = &Apache::lonnet::is_course($udom,$uname);
3651: if ($ownitem) {
3652: $category = 'Your portfolio files';
3653: } elsif ($is_course) {
3654: my $coursedesc;
3655: foreach my $course (keys(%setters)) {
3656: my %courseinfo =
3657: &Apache::lonnet::coursedescription($course);
3658: $coursedesc = $courseinfo{'description'};
3659: }
3660: $category = "Group files in the course '$coursedesc'";
3661: } else {
3662: $category = 'Portfolio files belonging to ';
3663: if ($env{'user.name'} eq 'public' &&
3664: $env{'user.domain'} eq 'public') {
3665: $category .= &plainname($uname,$udom);
3666: } else {
3667: $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);
3668: }
3669: }
3670: } elsif ($activity eq 'groups') {
3671: $category = 'Groups in this course';
3672: }
3673: my $showstart = &Apache::lonlocal::locallocaltime($startblock);
3674: my $showend = &Apache::lonlocal::locallocaltime($endblock);
3675: $output = '<br />'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'<br />';
3676: if (!($activity eq 'port' && !($ownitem) && !($is_course))) {
3677: $output .= &build_block_table($startblock,$endblock,\%setters);
3678: }
3679: }
3680: }
3681: if (wantarray) {
3682: return ($blocked,$output);
3683: } else {
3684: return $blocked;
3685: }
3686: }
3687:
3688: ###############################################
3689:
3690: =pod
3691:
3692: =head1 Domain Template Functions
3693:
3694: =over 4
3695:
3696: =item * &determinedomain()
3697:
3698: Inputs: $domain (usually will be undef)
3699:
3700: Returns: Determines which domain should be used for designs
3701:
3702: =cut
3703:
3704: ###############################################
3705: sub determinedomain {
3706: my $domain=shift;
3707: if (! $domain) {
3708: # Determine domain if we have not been given one
3709: $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
3710: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
3711: if ($env{'request.role.domain'}) {
3712: $domain=$env{'request.role.domain'};
3713: }
3714: }
3715: return $domain;
3716: }
3717: ###############################################
3718:
3719: sub devalidate_domconfig_cache {
3720: my ($udom)=@_;
3721: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
3722: }
3723:
3724: # ---------------------- Get domain configuration for a domain
3725: sub get_domainconf {
3726: my ($udom) = @_;
3727: my $cachetime=1800;
3728: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
3729: if (defined($cached)) { return %{$result}; }
3730:
3731: my %domconfig = &Apache::lonnet::get_dom('configuration',
3732: ['login','rolecolors'],$udom);
3733: my (%designhash,%legacy);
3734: if (keys(%domconfig) > 0) {
3735: if (ref($domconfig{'login'}) eq 'HASH') {
3736: if (keys(%{$domconfig{'login'}})) {
3737: foreach my $key (keys(%{$domconfig{'login'}})) {
3738: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
3739: }
3740: } else {
3741: $legacy{'login'} = 1;
3742: }
3743: } else {
3744: $legacy{'login'} = 1;
3745: }
3746: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
3747: if (keys(%{$domconfig{'rolecolors'}})) {
3748: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
3749: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
3750: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
3751: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
3752: }
3753: }
3754: }
3755: } else {
3756: $legacy{'rolecolors'} = 1;
3757: }
3758: } else {
3759: $legacy{'rolecolors'} = 1;
3760: }
3761: if (keys(%legacy) > 0) {
3762: my %legacyhash = &get_legacy_domconf($udom);
3763: foreach my $item (keys(%legacyhash)) {
3764: if ($item =~ /^\Q$udom\E\.login/) {
3765: if ($legacy{'login'}) {
3766: $designhash{$item} = $legacyhash{$item};
3767: }
3768: } else {
3769: if ($legacy{'rolecolors'}) {
3770: $designhash{$item} = $legacyhash{$item};
3771: }
3772: }
3773: }
3774: }
3775: } else {
3776: %designhash = &get_legacy_domconf($udom);
3777: }
3778: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
3779: $cachetime);
3780: return %designhash;
3781: }
3782:
3783: sub get_legacy_domconf {
3784: my ($udom) = @_;
3785: my %legacyhash;
3786: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
3787: my $designfile = $designdir.'/'.$udom.'.tab';
3788: if (-e $designfile) {
3789: if ( open (my $fh,"<$designfile") ) {
3790: while (my $line = <$fh>) {
3791: next if ($line =~ /^\#/);
3792: chomp($line);
3793: my ($key,$val)=(split(/\=/,$line));
3794: if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
3795: }
3796: close($fh);
3797: }
3798: }
3799: if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
3800: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
3801: }
3802: return %legacyhash;
3803: }
3804:
3805: =pod
3806:
3807: =item * &domainlogo()
3808:
3809: Inputs: $domain (usually will be undef)
3810:
3811: Returns: A link to a domain logo, if the domain logo exists.
3812: If the domain logo does not exist, a description of the domain.
3813:
3814: =cut
3815:
3816: ###############################################
3817: sub domainlogo {
3818: my $domain = &determinedomain(shift);
3819: my %designhash = &get_domainconf($domain);
3820: # See if there is a logo
3821: if ($designhash{$domain.'.login.domlogo'} ne '') {
3822: my $imgsrc = $designhash{$domain.'.login.domlogo'};
3823: if ($imgsrc =~ m{^/(adm|res)/}) {
3824: if ($imgsrc =~ m{^/res/}) {
3825: my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
3826: &Apache::lonnet::repcopy($local_name);
3827: }
3828: $imgsrc = &lonhttpdurl($imgsrc);
3829: }
3830: return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
3831: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
3832: return &Apache::lonnet::domain($domain,'description');
3833: } else {
3834: return '';
3835: }
3836: }
3837: ##############################################
3838:
3839: =pod
3840:
3841: =item * &designparm()
3842:
3843: Inputs: $which parameter; $domain (usually will be undef)
3844:
3845: Returns: value of designparamter $which
3846:
3847: =cut
3848:
3849:
3850: ##############################################
3851: sub designparm {
3852: my ($which,$domain)=@_;
3853: if ($env{'browser.blackwhite'} eq 'on') {
3854: if ($which=~/\.(font|alink|vlink|link|textcol)$/) {
3855: return '#000000';
3856: }
3857: if ($which=~/\.(pgbg|sidebg|bgcol)$/) {
3858: return '#FFFFFF';
3859: }
3860: if ($which=~/\.tabbg$/) {
3861: return '#CCCCCC';
3862: }
3863: }
3864: if (exists($env{'environment.color.'.$which})) {
3865: return $env{'environment.color.'.$which};
3866: }
3867: $domain=&determinedomain($domain);
3868: my %domdesign = &get_domainconf($domain);
3869: my $output;
3870: if ($domdesign{$domain.'.'.$which} ne '') {
3871: $output = $domdesign{$domain.'.'.$which};
3872: } else {
3873: $output = $defaultdesign{$which};
3874: }
3875: if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
3876: ($which =~ /login\.(img|logo|domlogo|login)/)) {
3877: if ($output =~ m{^/(adm|res)/}) {
3878: if ($output =~ m{^/res/}) {
3879: my $local_name = &Apache::lonnet::filelocation('',$output);
3880: &Apache::lonnet::repcopy($local_name);
3881: }
3882: $output = &lonhttpdurl($output);
3883: }
3884: }
3885: return $output;
3886: }
3887:
3888: ###############################################
3889: ###############################################
3890:
3891: =pod
3892:
3893: =back
3894:
3895: =head1 HTML Helpers
3896:
3897: =over 4
3898:
3899: =item * &bodytag()
3900:
3901: Returns a uniform header for LON-CAPA web pages.
3902:
3903: Inputs:
3904:
3905: =over 4
3906:
3907: =item * $title, A title to be displayed on the page.
3908:
3909: =item * $function, the current role (can be undef).
3910:
3911: =item * $addentries, extra parameters for the <body> tag.
3912:
3913: =item * $bodyonly, if defined, only return the <body> tag.
3914:
3915: =item * $domain, if defined, force a given domain.
3916:
3917: =item * $forcereg, if page should register as content page (relevant for
3918: text interface only)
3919:
3920: =item * $customtitle, alternate text to use instead of $title
3921: in the title box that appears, this text
3922: is not auto translated like the $title is
3923:
3924: =item * $notopbar, if true, keep the 'what is this' info but remove the
3925: navigational links
3926:
3927: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
3928:
3929: =item * $notitle, if true keep the nav controls, but remove the title bar
3930:
3931: =item * $no_inline_link, if true and in remote mode, don't show the
3932: 'Switch To Inline Menu' link
3933:
3934: =item * $args, optional argument valid values are
3935: no_auto_mt_title -> prevents &mt()ing the title arg
3936: inherit_jsmath -> when creating popup window in a page,
3937: should it have jsmath forced on by the
3938: current page
3939:
3940: =back
3941:
3942: Returns: A uniform header for LON-CAPA web pages.
3943: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
3944: If $bodyonly is undef or zero, an html string containing a <body> tag and
3945: other decorations will be returned.
3946:
3947: =cut
3948:
3949: sub bodytag {
3950: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
3951: $notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
3952:
3953: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
3954:
3955: $function = &get_users_function() if (!$function);
3956: my $img = &designparm($function.'.img',$domain);
3957: my $font = &designparm($function.'.font',$domain);
3958: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
3959:
3960: my %design = ( 'style' => 'margin-top: 0px',
3961: 'bgcolor' => $pgbg,
3962: 'text' => $font,
3963: 'alink' => &designparm($function.'.alink',$domain),
3964: 'vlink' => &designparm($function.'.vlink',$domain),
3965: 'link' => &designparm($function.'.link',$domain),);
3966: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
3967:
3968: # role and realm
3969: my ($role,$realm) = split(/\./,$env{'request.role'},2);
3970: if ($role eq 'ca') {
3971: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
3972: $realm = &plainname($rname,$rdom);
3973: }
3974: # realm
3975: if ($env{'request.course.id'}) {
3976: if ($env{'request.role'} !~ /^cr/) {
3977: $role = &Apache::lonnet::plaintext($role,&course_type());
3978: }
3979: $realm = $env{'course.'.$env{'request.course.id'}.'.description'};
3980: } else {
3981: $role = &Apache::lonnet::plaintext($role);
3982: }
3983:
3984: if (!$realm) { $realm=' '; }
3985: # Set messages
3986: my $messages=&domainlogo($domain);
3987:
3988: my $extra_body_attr = &make_attr_string($forcereg,\%design);
3989:
3990: # construct main body tag
3991: my $bodytag = "<body $extra_body_attr>".
3992: &Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
3993:
3994: if ($bodyonly) {
3995: return $bodytag;
3996: } elsif ($env{'browser.interface'} eq 'textual') {
3997: # Accessibility
3998:
3999: $bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
4000: if (!$notitle) {
4001: $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
4002: }
4003: return $bodytag;
4004: }
4005:
4006: my $name = &plainname($env{'user.name'},$env{'user.domain'});
4007: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4008: undef($role);
4009: } else {
4010: $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
4011: }
4012:
4013: my $roleinfo=(<<ENDROLE);
4014: <td class="LC_title_bar_who">
4015: <div class="LC_title_bar_name">
4016: $name
4017:
4018: </div>
4019: <div class="LC_title_bar_role">
4020: $role
4021: </div>
4022: <div class="LC_title_bar_realm">
4023: $realm
4024: </div>
4025: </td>
4026: ENDROLE
4027:
4028: my $titleinfo = '<span class="LC_title_bar_title">'.$title.'</span>';
4029: if ($customtitle) {
4030: $titleinfo = $customtitle;
4031: }
4032: #
4033: # Extra info if you are the DC
4034: my $dc_info = '';
4035: if ($env{'user.adv'} && exists($env{'user.role.dc./'.
4036: $env{'course.'.$env{'request.course.id'}.
4037: '.domain'}.'/'})) {
4038: my $cid = $env{'request.course.id'};
4039: $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
4040: $dc_info =~ s/\s+$//;
4041: $dc_info = '('.$dc_info.')';
4042: }
4043:
4044: if (($env{'environment.remote'} eq 'off') || ($args->{'suppress_header_logos'})) {
4045: # No Remote
4046: if ($env{'request.state'} eq 'construct') {
4047: $forcereg=1;
4048: }
4049:
4050: if (!$customtitle && $env{'request.state'} eq 'construct') {
4051: # this is for resources; directories have customtitle, and crumbs
4052: # and select recent are created in lonpubdir.pm
4053: my ($uname,$thisdisfn)=
4054: ($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
4055: my $formaction='/priv/'.$uname.'/'.$thisdisfn;
4056: $formaction=~s/\/+/\//g;
4057:
4058: my $parentpath = '';
4059: my $lastitem = '';
4060: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
4061: $parentpath = $1;
4062: $lastitem = $2;
4063: } else {
4064: $lastitem = $thisdisfn;
4065: }
4066: $titleinfo =
4067: &Apache::loncommon::help_open_menu('','',3,'Authoring')
4068: .'<b>'.&mt('Construction Space').'</b>: '
4069: .'<form name="dirs" method="post" action="'.$formaction
4070: .'" target="_top"><tt><b>'
4071: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<font size=\"+1\">$lastitem</font></b></tt><br />"
4072: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
4073: .'</form>'
4074: .&Apache::lonmenu::constspaceform();
4075: }
4076:
4077: my $titletable;
4078: if (!$notitle) {
4079: $titletable =
4080: '<table id="LC_title_bar">'.
4081: "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
4082: '</tr></table>';
4083: }
4084: if ($notopbar) {
4085: $bodytag .= $titletable;
4086: } else {
4087: if ($env{'request.state'} eq 'construct') {
4088: $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
4089: $titletable);
4090: } else {
4091: $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
4092: $titletable;
4093: }
4094: }
4095: return $bodytag;
4096: }
4097:
4098: #
4099: # Top frame rendering, Remote is up
4100: #
4101:
4102: my $imgsrc = $img;
4103: if ($img =~ /^\/adm/) {
4104: $imgsrc = &lonhttpdurl($img);
4105: }
4106: my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
4107:
4108: # Explicit link to get inline menu
4109: my $menu= ($no_inline_link?''
4110: :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
4111: #
4112: if ($notitle) {
4113: return $bodytag;
4114: }
4115: return(<<ENDBODY);
4116: $bodytag
4117: <table id="LC_title_bar" class="LC_with_remote">
4118: <tr><td class="LC_title_bar_role_logo">$upperleft</td>
4119: <td class="LC_title_bar_domain_logo">$messages </td>
4120: </tr>
4121: <tr><td>$titleinfo $dc_info $menu</td>
4122: $roleinfo
4123: </tr>
4124: </table>
4125: ENDBODY
4126: }
4127:
4128: sub make_attr_string {
4129: my ($register,$attr_ref) = @_;
4130:
4131: if ($attr_ref && !ref($attr_ref)) {
4132: die("addentries Must be a hash ref ".
4133: join(':',caller(1))." ".
4134: join(':',caller(0))." ");
4135: }
4136:
4137: if ($register) {
4138: my ($on_load,$on_unload);
4139: foreach my $key (keys(%{$attr_ref})) {
4140: if (lc($key) eq 'onload') {
4141: $on_load.=$attr_ref->{$key}.';';
4142: delete($attr_ref->{$key});
4143:
4144: } elsif (lc($key) eq 'onunload') {
4145: $on_unload.=$attr_ref->{$key}.';';
4146: delete($attr_ref->{$key});
4147: }
4148: }
4149: $attr_ref->{'onload'} =
4150: &Apache::lonmenu::loadevents(). $on_load;
4151: $attr_ref->{'onunload'}=
4152: &Apache::lonmenu::unloadevents().$on_unload;
4153: }
4154:
4155: # Accessibility font enhance
4156: if ($env{'browser.fontenhance'} eq 'on') {
4157: my $style;
4158: foreach my $key (keys(%{$attr_ref})) {
4159: if (lc($key) eq 'style') {
4160: $style.=$attr_ref->{$key}.';';
4161: delete($attr_ref->{$key});
4162: }
4163: }
4164: $attr_ref->{'style'}=$style.'; font-size: x-large;';
4165: }
4166:
4167: if ($env{'browser.blackwhite'} eq 'on') {
4168: delete($attr_ref->{'font'});
4169: delete($attr_ref->{'link'});
4170: delete($attr_ref->{'alink'});
4171: delete($attr_ref->{'vlink'});
4172: delete($attr_ref->{'bgcolor'});
4173: delete($attr_ref->{'background'});
4174: }
4175:
4176: my $attr_string;
4177: foreach my $attr (keys(%$attr_ref)) {
4178: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
4179: }
4180: return $attr_string;
4181: }
4182:
4183:
4184: ###############################################
4185: ###############################################
4186:
4187: =pod
4188:
4189: =item * &endbodytag()
4190:
4191: Returns a uniform footer for LON-CAPA web pages.
4192:
4193: Inputs: 1 - optional reference to an args hash
4194: If in the hash, key for noredirectlink has a value which evaluates to true,
4195: a 'Continue' link is not displayed if the page contains an
4196: internal redirect in the <head></head> section,
4197: i.e., $env{'internal.head.redirect'} exists
4198:
4199: =cut
4200:
4201: sub endbodytag {
4202: my ($args) = @_;
4203: my $endbodytag='</body>';
4204: $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
4205: if ( exists( $env{'internal.head.redirect'} ) ) {
4206: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
4207: $endbodytag=
4208: "<br /><a href=\"$env{'internal.head.redirect'}\">".
4209: &mt('Continue').'</a>'.
4210: $endbodytag;
4211: }
4212: }
4213: return $endbodytag;
4214: }
4215:
4216: =pod
4217:
4218: =item * &standard_css()
4219:
4220: Returns a style sheet
4221:
4222: Inputs: (all optional)
4223: domain -> force to color decorate a page for a specific
4224: domain
4225: function -> force usage of a specific rolish color scheme
4226: bgcolor -> override the default page bgcolor
4227:
4228: =cut
4229:
4230: sub standard_css {
4231: my ($function,$domain,$bgcolor) = @_;
4232: $function = &get_users_function() if (!$function);
4233: my $img = &designparm($function.'.img', $domain);
4234: my $tabbg = &designparm($function.'.tabbg', $domain);
4235: my $font = &designparm($function.'.font', $domain);
4236: my $sidebg = &designparm($function.'.sidebg',$domain);
4237: my $pgbg_or_bgcolor =
4238: $bgcolor ||
4239: &designparm($function.'.pgbg', $domain);
4240: my $pgbg = &designparm($function.'.pgbg', $domain);
4241: my $alink = &designparm($function.'.alink', $domain);
4242: my $vlink = &designparm($function.'.vlink', $domain);
4243: my $link = &designparm($function.'.link', $domain);
4244:
4245: my $sans = 'Verdana,Arial,Helvetica,sans-serif';
4246: my $mono = 'monospace';
4247: my $data_table_head = $tabbg;
4248: my $data_table_light = '#EEEEEE';
4249: my $data_table_dark = '#DDDDDD';
4250: my $data_table_darker = '#CCCCCC';
4251: my $data_table_highlight = '#FFFF00';
4252: my $mail_new = '#FFBB77';
4253: my $mail_new_hover = '#DD9955';
4254: my $mail_read = '#BBBB77';
4255: my $mail_read_hover = '#999944';
4256: my $mail_replied = '#AAAA88';
4257: my $mail_replied_hover = '#888855';
4258: my $mail_other = '#99BBBB';
4259: my $mail_other_hover = '#669999';
4260: my $table_header = '#DDDDDD';
4261: my $feedback_link_bg = '#BBBBBB';
4262:
4263: my $border = ($env{'browser.type'} eq 'explorer' ||
4264: $env{'browser.type'} eq 'safari' ) ? '0px 2px 0px 2px'
4265: : '0px 3px 0px 4px';
4266:
4267:
4268: return <<END;
4269: h1, h2, h3, th { font-family: $sans }
4270: a:focus { color: red; background: yellow }
4271: table.thinborder,
4272:
4273: table.thinborder tr th {
4274: border-style: solid;
4275: border-width: 1px;
4276: background: $tabbg;
4277: }
4278: table.thinborder tr td {
4279: border-style: solid;
4280: border-width: 1px
4281: }
4282:
4283: form, .inline { display: inline; }
4284: .center { text-align: center; }
4285: .LC_filename {font-family: $mono; white-space:pre;}
4286: .LC_error {
4287: color: red;
4288: font-size: larger;
4289: }
4290: .LC_warning,
4291: .LC_diff_removed {
4292: color: red;
4293: }
4294:
4295: .LC_info,
4296: .LC_success,
4297: .LC_diff_added {
4298: color: green;
4299: }
4300: .LC_unknown {
4301: color: yellow;
4302: }
4303:
4304: .LC_icon {
4305: border: 0px;
4306: }
4307: .LC_indexer_icon {
4308: border: 0px;
4309: height: 22px;
4310: }
4311: .LC_docs_spacer {
4312: width: 25px;
4313: height: 1px;
4314: border: 0px;
4315: }
4316:
4317: .LC_internal_info {
4318: color: #999;
4319: }
4320:
4321: table.LC_pastsubmission {
4322: border: 1px solid black;
4323: margin: 2px;
4324: }
4325:
4326: table#LC_top_nav, table#LC_menubuttons,table#LC_nav_location {
4327: width: 100%;
4328: background: $pgbg;
4329: border: 2px;
4330: border-collapse: separate;
4331: padding: 0px;
4332: }
4333:
4334: table#LC_title_bar, table.LC_breadcrumbs,
4335: table#LC_title_bar.LC_with_remote {
4336: width: 100%;
4337: border-color: $pgbg;
4338: border-style: solid;
4339: border-width: $border;
4340:
4341: background: $pgbg;
4342: font-family: $sans;
4343: border-collapse: collapse;
4344: padding: 0px;
4345: }
4346:
4347: table.LC_docs_path {
4348: width: 100%;
4349: border: 0;
4350: background: $pgbg;
4351: font-family: $sans;
4352: border-collapse: collapse;
4353: padding: 0px;
4354: }
4355:
4356: table#LC_title_bar td {
4357: background: $tabbg;
4358: }
4359: table#LC_title_bar td.LC_title_bar_who {
4360: background: $tabbg;
4361: color: $font;
4362: font: small $sans;
4363: text-align: right;
4364: }
4365: span.LC_metadata {
4366: font-family: $sans;
4367: }
4368: span.LC_title_bar_title {
4369: font: bold x-large $sans;
4370: }
4371: table#LC_title_bar td.LC_title_bar_domain_logo {
4372: background: $sidebg;
4373: text-align: right;
4374: padding: 0px;
4375: }
4376: table#LC_title_bar td.LC_title_bar_role_logo {
4377: background: $sidebg;
4378: padding: 0px;
4379: }
4380:
4381: table#LC_menubuttons_mainmenu {
4382: width: 100%;
4383: border: 0px;
4384: border-spacing: 1px;
4385: padding: 0px 1px;
4386: margin: 0px;
4387: border-collapse: separate;
4388: }
4389: table#LC_menubuttons img, table#LC_menubuttons_mainmenu img {
4390: border: 0px;
4391: }
4392: table#LC_top_nav td {
4393: background: $tabbg;
4394: border: 0px;
4395: font-size: small;
4396: }
4397: table#LC_top_nav td a, div#LC_top_nav a {
4398: color: $font;
4399: font-family: $sans;
4400: }
4401: table#LC_top_nav td.LC_top_nav_logo {
4402: background: $tabbg;
4403: text-align: left;
4404: white-space: nowrap;
4405: width: 31px;
4406: }
4407: table#LC_top_nav td.LC_top_nav_logo img {
4408: border: 0px;
4409: vertical-align: bottom;
4410: }
4411: table#LC_top_nav td.LC_top_nav_exit,
4412: table#LC_top_nav td.LC_top_nav_help {
4413: width: 2.0em;
4414: }
4415: table#LC_top_nav td.LC_top_nav_login {
4416: width: 4.0em;
4417: text-align: center;
4418: }
4419: table.LC_breadcrumbs td, table.LC_docs_path td {
4420: background: $tabbg;
4421: color: $font;
4422: font-family: $sans;
4423: font-size: smaller;
4424: }
4425: table.LC_breadcrumbs td.LC_breadcrumbs_component,
4426: table.LC_docs_path td.LC_docs_path_component {
4427: background: $tabbg;
4428: color: $font;
4429: font-family: $sans;
4430: font-size: larger;
4431: text-align: right;
4432: }
4433: td.LC_table_cell_checkbox {
4434: text-align: center;
4435: }
4436:
4437: table#LC_mainmenu td.LC_mainmenu_column {
4438: vertical-align: top;
4439: }
4440:
4441: .LC_menubuttons_inline_text {
4442: color: $font;
4443: font-family: $sans;
4444: font-size: smaller;
4445: }
4446:
4447: .LC_menubuttons_link {
4448: text-decoration: none;
4449: }
4450:
4451: .LC_menubuttons_category {
4452: color: $font;
4453: background: $pgbg;
4454: font-family: $sans;
4455: font-size: larger;
4456: font-weight: bold;
4457: }
4458:
4459: td.LC_menubuttons_text {
4460: width: 90%;
4461: color: $font;
4462: font-family: $sans;
4463: }
4464:
4465: td.LC_menubuttons_img {
4466: }
4467:
4468: .LC_current_location {
4469: font-family: $sans;
4470: background: $tabbg;
4471: }
4472: .LC_new_mail {
4473: font-family: $sans;
4474: background: $tabbg;
4475: font-weight: bold;
4476: }
4477:
4478: .LC_rolesmenu_is {
4479: font-family: $sans;
4480: }
4481:
4482: .LC_rolesmenu_selected {
4483: font-family: $sans;
4484: }
4485:
4486: .LC_rolesmenu_future {
4487: font-family: $sans;
4488: }
4489:
4490:
4491: .LC_rolesmenu_will {
4492: font-family: $sans;
4493: }
4494:
4495: .LC_rolesmenu_will_not {
4496: font-family: $sans;
4497: }
4498:
4499: .LC_rolesmenu_expired {
4500: font-family: $sans;
4501: }
4502:
4503: .LC_rolesinfo {
4504: font-family: $sans;
4505: }
4506:
4507: .LC_dropadd_labeltext {
4508: font-family: $sans;
4509: text-align: right;
4510: }
4511:
4512: .LC_preferences_labeltext {
4513: font-family: $sans;
4514: text-align: right;
4515: }
4516:
4517: table.LC_aboutme_port {
4518: border: 0px;
4519: border-collapse: collapse;
4520: border-spacing: 0px;
4521: }
4522: table.LC_data_table, table.LC_mail_list {
4523: border: 1px solid #000000;
4524: border-collapse: separate;
4525: border-spacing: 1px;
4526: background: $pgbg;
4527: }
4528: .LC_data_table_dense {
4529: font-size: small;
4530: }
4531: table.LC_nested_outer {
4532: border: 1px solid #000000;
4533: border-collapse: collapse;
4534: border-spacing: 0px;
4535: width: 100%;
4536: }
4537: table.LC_nested {
4538: border: 0px;
4539: border-collapse: collapse;
4540: border-spacing: 0px;
4541: width: 100%;
4542: }
4543: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th,
4544: table.LC_prior_tries tr th {
4545: font-weight: bold;
4546: background-color: $data_table_head;
4547: font-size: smaller;
4548: }
4549: table.LC_data_table tr.LC_odd_row > td,
4550: table.LC_aboutme_port tr td {
4551: background-color: $data_table_light;
4552: padding: 2px;
4553: }
4554: table.LC_data_table tr.LC_even_row > td,
4555: table.LC_aboutme_port tr.LC_even_row td {
4556: background-color: $data_table_dark;
4557: }
4558: table.LC_data_table tr.LC_data_table_highlight td {
4559: background-color: $data_table_darker;
4560: }
4561: table.LC_data_table tr td.LC_leftcol_header {
4562: background-color: $data_table_head;
4563: font-weight: bold;
4564: }
4565: table.LC_data_table tr.LC_empty_row td,
4566: table.LC_nested tr.LC_empty_row td {
4567: background-color: #FFFFFF;
4568: font-weight: bold;
4569: font-style: italic;
4570: text-align: center;
4571: padding: 8px;
4572: }
4573: table.LC_nested tr.LC_empty_row td {
4574: padding: 4ex
4575: }
4576: table.LC_nested_outer tr th {
4577: font-weight: bold;
4578: background-color: $data_table_head;
4579: font-size: smaller;
4580: border-bottom: 1px solid #000000;
4581: }
4582: table.LC_nested_outer tr td.LC_subheader {
4583: background-color: $data_table_head;
4584: font-weight: bold;
4585: font-size: small;
4586: border-bottom: 1px solid #000000;
4587: text-align: right;
4588: }
4589: table.LC_nested tr.LC_info_row td {
4590: background-color: #CCC;
4591: font-weight: bold;
4592: font-size: small;
4593: text-align: center;
4594: }
4595: table.LC_nested tr.LC_info_row td.LC_left_item,
4596: table.LC_nested_outer tr th.LC_left_item {
4597: text-align: left;
4598: }
4599: table.LC_nested td {
4600: background-color: #FFF;
4601: font-size: small;
4602: }
4603: table.LC_nested_outer tr th.LC_right_item,
4604: table.LC_nested tr.LC_info_row td.LC_right_item,
4605: table.LC_nested tr.LC_odd_row td.LC_right_item,
4606: table.LC_nested tr td.LC_right_item {
4607: text-align: right;
4608: }
4609:
4610: table.LC_nested tr.LC_odd_row td {
4611: background-color: #EEE;
4612: }
4613:
4614: table.LC_createuser {
4615: }
4616:
4617: table.LC_createuser tr.LC_section_row td {
4618: font-size: smaller;
4619: }
4620:
4621: table.LC_createuser tr.LC_info_row td {
4622: background-color: #CCC;
4623: font-weight: bold;
4624: text-align: center;
4625: }
4626:
4627: table.LC_calendar {
4628: border: 1px solid #000000;
4629: border-collapse: collapse;
4630: }
4631: table.LC_calendar_pickdate {
4632: font-size: xx-small;
4633: }
4634: table.LC_calendar tr td {
4635: border: 1px solid #000000;
4636: vertical-align: top;
4637: }
4638: table.LC_calendar tr td.LC_calendar_day_empty {
4639: background-color: $data_table_dark;
4640: }
4641: table.LC_calendar tr td.LC_calendar_day_current {
4642: background-color: $data_table_highlight;
4643: }
4644:
4645: table.LC_mail_list tr.LC_mail_new {
4646: background-color: $mail_new;
4647: }
4648: table.LC_mail_list tr.LC_mail_new:hover {
4649: background-color: $mail_new_hover;
4650: }
4651: table.LC_mail_list tr.LC_mail_read {
4652: background-color: $mail_read;
4653: }
4654: table.LC_mail_list tr.LC_mail_read:hover {
4655: background-color: $mail_read_hover;
4656: }
4657: table.LC_mail_list tr.LC_mail_replied {
4658: background-color: $mail_replied;
4659: }
4660: table.LC_mail_list tr.LC_mail_replied:hover {
4661: background-color: $mail_replied_hover;
4662: }
4663: table.LC_mail_list tr.LC_mail_other {
4664: background-color: $mail_other;
4665: }
4666: table.LC_mail_list tr.LC_mail_other:hover {
4667: background-color: $mail_other_hover;
4668: }
4669: table.LC_mail_list tr.LC_mail_even {
4670: }
4671: table.LC_mail_list tr.LC_mail_odd {
4672: }
4673:
4674:
4675: table#LC_portfolio_actions {
4676: width: auto;
4677: background: $pgbg;
4678: border: 0px;
4679: border-spacing: 2px 2px;
4680: padding: 0px;
4681: margin: 0px;
4682: border-collapse: separate;
4683: }
4684: table#LC_portfolio_actions td.LC_label {
4685: background: $tabbg;
4686: text-align: right;
4687: }
4688: table#LC_portfolio_actions td.LC_value {
4689: background: $tabbg;
4690: }
4691:
4692: table#LC_cstr_controls {
4693: width: 100%;
4694: border-collapse: collapse;
4695: }
4696: table#LC_cstr_controls tr td {
4697: border: 4px solid $pgbg;
4698: padding: 4px;
4699: text-align: center;
4700: background: $tabbg;
4701: }
4702: table#LC_cstr_controls tr th {
4703: border: 4px solid $pgbg;
4704: background: $table_header;
4705: text-align: center;
4706: font-family: $sans;
4707: font-size: smaller;
4708: }
4709:
4710: table#LC_browser {
4711:
4712: }
4713: table#LC_browser tr th {
4714: background: $table_header;
4715: }
4716: table#LC_browser tr td {
4717: padding: 2px;
4718: }
4719: table#LC_browser tr.LC_browser_file,
4720: table#LC_browser tr.LC_browser_file_published {
4721: background: #CCFF88;
4722: }
4723: table#LC_browser tr.LC_browser_file_locked,
4724: table#LC_browser tr.LC_browser_file_unpublished {
4725: background: #FFAA99;
4726: }
4727: table#LC_browser tr.LC_browser_file_obsolete {
4728: background: #AAAAAA;
4729: }
4730: table#LC_browser tr.LC_browser_file_modified,
4731: table#LC_browser tr.LC_browser_file_metamodified {
4732: background: #FFFF77;
4733: }
4734: table#LC_browser tr.LC_browser_folder {
4735: background: #CCCCFF;
4736: }
4737: span.LC_current_location {
4738: font-size: x-large;
4739: background: $pgbg;
4740: }
4741:
4742: span.LC_parm_menu_item {
4743: font-size: larger;
4744: font-family: $sans;
4745: }
4746: span.LC_parm_scope_all {
4747: color: red;
4748: }
4749: span.LC_parm_scope_folder {
4750: color: green;
4751: }
4752: span.LC_parm_scope_resource {
4753: color: orange;
4754: }
4755: span.LC_parm_part {
4756: color: blue;
4757: }
4758: span.LC_parm_folder, span.LC_parm_symb {
4759: font-size: x-small;
4760: font-family: $mono;
4761: color: #AAAAAA;
4762: }
4763:
4764: td.LC_parm_overview_level_menu, td.LC_parm_overview_map_menu,
4765: td.LC_parm_overview_parm_selectors, td.LC_parm_overview_parm_restrictions {
4766: border: 1px solid black;
4767: border-collapse: collapse;
4768: }
4769: table.LC_parm_overview_restrictions td {
4770: border-width: 1px 4px 1px 4px;
4771: border-style: solid;
4772: border-color: $pgbg;
4773: text-align: center;
4774: }
4775: table.LC_parm_overview_restrictions th {
4776: background: $tabbg;
4777: border-width: 1px 4px 1px 4px;
4778: border-style: solid;
4779: border-color: $pgbg;
4780: }
4781: table#LC_helpmenu {
4782: border: 0px;
4783: height: 55px;
4784: border-spacing: 0px;
4785: }
4786:
4787: table#LC_helpmenu fieldset legend {
4788: font-size: larger;
4789: font-weight: bold;
4790: }
4791: table#LC_helpmenu_links {
4792: width: 100%;
4793: border: 1px solid black;
4794: background: $pgbg;
4795: padding: 0px;
4796: border-spacing: 1px;
4797: }
4798: table#LC_helpmenu_links tr td {
4799: padding: 1px;
4800: background: $tabbg;
4801: text-align: center;
4802: font-weight: bold;
4803: }
4804:
4805: table#LC_helpmenu_links a:link, table#LC_helpmenu_links a:visited,
4806: table#LC_helpmenu_links a:active {
4807: text-decoration: none;
4808: color: $font;
4809: }
4810: table#LC_helpmenu_links a:hover {
4811: text-decoration: underline;
4812: color: $vlink;
4813: }
4814:
4815: .LC_chrt_popup_exists {
4816: border: 1px solid #339933;
4817: margin: -1px;
4818: }
4819: .LC_chrt_popup_up {
4820: border: 1px solid yellow;
4821: margin: -1px;
4822: }
4823: .LC_chrt_popup {
4824: border: 1px solid #8888FF;
4825: background: #CCCCFF;
4826: }
4827: table.LC_pick_box {
4828: border-collapse: separate;
4829: background: white;
4830: border: 1px solid black;
4831: border-spacing: 1px;
4832: }
4833: table.LC_pick_box td.LC_pick_box_title {
4834: background: $tabbg;
4835: font-weight: bold;
4836: text-align: right;
4837: width: 184px;
4838: padding: 8px;
4839: }
4840: table.LC_pick_box td.LC_selfenroll_pick_box_title {
4841: background: $tabbg;
4842: font-weight: bold;
4843: text-align: right;
4844: width: 350px;
4845: padding: 8px;
4846: }
4847:
4848: table.LC_pick_box td.LC_pick_box_value {
4849: text-align: left;
4850: padding: 8px;
4851: }
4852: table.LC_pick_box td.LC_pick_box_select {
4853: text-align: left;
4854: padding: 8px;
4855: }
4856: table.LC_pick_box td.LC_pick_box_separator {
4857: padding: 0px;
4858: height: 1px;
4859: background: black;
4860: }
4861: table.LC_pick_box td.LC_pick_box_submit {
4862: text-align: right;
4863: }
4864: table.LC_pick_box td.LC_evenrow_value {
4865: text-align: left;
4866: padding: 8px;
4867: background-color: $data_table_light;
4868: }
4869: table.LC_pick_box td.LC_oddrow_value {
4870: text-align: left;
4871: padding: 8px;
4872: background-color: $data_table_light;
4873: }
4874: table.LC_helpform_receipt {
4875: width: 620px;
4876: border-collapse: separate;
4877: background: white;
4878: border: 1px solid black;
4879: border-spacing: 1px;
4880: }
4881: table.LC_helpform_receipt td.LC_pick_box_title {
4882: background: $tabbg;
4883: font-weight: bold;
4884: text-align: right;
4885: width: 184px;
4886: padding: 8px;
4887: }
4888: table.LC_helpform_receipt td.LC_evenrow_value {
4889: text-align: left;
4890: padding: 8px;
4891: background-color: $data_table_light;
4892: }
4893: table.LC_helpform_receipt td.LC_oddrow_value {
4894: text-align: left;
4895: padding: 8px;
4896: background-color: $data_table_light;
4897: }
4898: table.LC_helpform_receipt td.LC_pick_box_separator {
4899: padding: 0px;
4900: height: 1px;
4901: background: black;
4902: }
4903: span.LC_helpform_receipt_cat {
4904: font-weight: bold;
4905: }
4906: table.LC_group_priv_box {
4907: background: white;
4908: border: 1px solid black;
4909: border-spacing: 1px;
4910: }
4911: table.LC_group_priv_box td.LC_pick_box_title {
4912: background: $tabbg;
4913: font-weight: bold;
4914: text-align: right;
4915: width: 184px;
4916: }
4917: table.LC_group_priv_box td.LC_groups_fixed {
4918: background: $data_table_light;
4919: text-align: center;
4920: }
4921: table.LC_group_priv_box td.LC_groups_optional {
4922: background: $data_table_dark;
4923: text-align: center;
4924: }
4925: table.LC_group_priv_box td.LC_groups_functionality {
4926: background: $data_table_darker;
4927: text-align: center;
4928: font-weight: bold;
4929: }
4930: table.LC_group_priv td {
4931: text-align: left;
4932: padding: 0px;
4933: }
4934:
4935: table.LC_notify_front_page {
4936: background: white;
4937: border: 1px solid black;
4938: padding: 8px;
4939: }
4940: table.LC_notify_front_page td {
4941: padding: 8px;
4942: }
4943: .LC_navbuttons {
4944: margin: 2ex 0ex 2ex 0ex;
4945: }
4946: .LC_topic_bar {
4947: font-family: $sans;
4948: font-weight: bold;
4949: width: 100%;
4950: background: $tabbg;
4951: vertical-align: middle;
4952: margin: 2ex 0ex 2ex 0ex;
4953: }
4954: .LC_topic_bar span {
4955: vertical-align: middle;
4956: }
4957: .LC_topic_bar img {
4958: vertical-align: bottom;
4959: }
4960: table.LC_course_group_status {
4961: margin: 20px;
4962: }
4963: table.LC_status_selector td {
4964: vertical-align: top;
4965: text-align: center;
4966: padding: 4px;
4967: }
4968: table.LC_descriptive_input td.LC_description {
4969: vertical-align: top;
4970: text-align: right;
4971: font-weight: bold;
4972: }
4973: div.LC_feedback_link {
4974: clear: both;
4975: background: white;
4976: width: 100%;
4977: }
4978: span.LC_feedback_link {
4979: background: $feedback_link_bg;
4980: font-size: larger;
4981: }
4982: span.LC_message_link {
4983: background: $feedback_link_bg;
4984: font-size: larger;
4985: position: absolute;
4986: right: 1em;
4987: }
4988:
4989: table.LC_prior_tries {
4990: border: 1px solid #000000;
4991: border-collapse: separate;
4992: border-spacing: 1px;
4993: }
4994:
4995: table.LC_prior_tries td {
4996: padding: 2px;
4997: }
4998:
4999: .LC_answer_correct {
5000: background: #AAFFAA;
5001: color: black;
5002: }
5003: .LC_answer_charged_try {
5004: background: #FFAAAA ! important;
5005: color: black;
5006: }
5007: .LC_answer_not_charged_try,
5008: .LC_answer_no_grade,
5009: .LC_answer_late {
5010: background: #FFFFAA;
5011: color: black;
5012: }
5013: .LC_answer_previous {
5014: background: #AAAAFF;
5015: color: black;
5016: }
5017: .LC_answer_no_message {
5018: background: #FFFFFF;
5019: color: black;
5020: }
5021: .LC_answer_unknown {
5022: background: orange;
5023: color: black;
5024: }
5025:
5026:
5027: span.LC_prior_numerical,
5028: span.LC_prior_string,
5029: span.LC_prior_custom,
5030: span.LC_prior_reaction,
5031: span.LC_prior_math {
5032: font-family: monospace;
5033: white-space: pre;
5034: }
5035:
5036: span.LC_prior_string {
5037: font-family: monospace;
5038: white-space: pre;
5039: }
5040:
5041: table.LC_prior_option {
5042: width: 100%;
5043: border-collapse: collapse;
5044: }
5045: table.LC_prior_rank, table.LC_prior_match {
5046: border-collapse: collapse;
5047: }
5048: table.LC_prior_option tr td,
5049: table.LC_prior_rank tr td,
5050: table.LC_prior_match tr td {
5051: border: 1px solid #000000;
5052: }
5053:
5054: span.LC_nobreak {
5055: white-space: nowrap;
5056: }
5057:
5058: span.LC_cusr_emph {
5059: font-style: italic;
5060: }
5061:
5062: span.LC_cusr_subheading {
5063: font-weight: normal;
5064: font-size: 85%;
5065: }
5066:
5067: table.LC_docs_documents {
5068: background: #BBBBBB;
5069: border-width: 0px;
5070: border-collapse: collapse;
5071: }
5072:
5073: table.LC_docs_documents td.LC_docs_document {
5074: border: 2px solid black;
5075: padding: 4px;
5076: }
5077:
5078: .LC_docs_course_commands div {
5079: float: left;
5080: border: 4px solid #AAAAAA;
5081: padding: 4px;
5082: background: #DDDDCC;
5083: }
5084:
5085: .LC_docs_entry_move {
5086: border: 0px;
5087: border-collapse: collapse;
5088: }
5089:
5090: .LC_docs_entry_move td {
5091: border: 2px solid #BBBBBB;
5092: background: #DDDDDD;
5093: }
5094:
5095: .LC_docs_editor td.LC_docs_entry_commands {
5096: background: #DDDDDD;
5097: font-size: x-small;
5098: }
5099: .LC_docs_copy {
5100: color: #000099;
5101: }
5102: .LC_docs_cut {
5103: color: #550044;
5104: }
5105: .LC_docs_rename {
5106: color: #009900;
5107: }
5108: .LC_docs_remove {
5109: color: #990000;
5110: }
5111:
5112: .LC_docs_reinit_warn,
5113: .LC_docs_ext_edit {
5114: font-size: x-small;
5115: }
5116:
5117: .LC_docs_editor td.LC_docs_entry_title,
5118: .LC_docs_editor td.LC_docs_entry_icon {
5119: background: #FFFFBB;
5120: }
5121: .LC_docs_editor td.LC_docs_entry_parameter {
5122: background: #BBBBFF;
5123: font-size: x-small;
5124: white-space: nowrap;
5125: }
5126:
5127: table.LC_docs_adddocs td,
5128: table.LC_docs_adddocs th {
5129: border: 1px solid #BBBBBB;
5130: padding: 4px;
5131: background: #DDDDDD;
5132: }
5133:
5134: table.LC_sty_begin {
5135: background: #BBFFBB;
5136: }
5137: table.LC_sty_end {
5138: background: #FFBBBB;
5139: }
5140:
5141: table.LC_double_column {
5142: border-width: 0px;
5143: border-collapse: collapse;
5144: width: 100%;
5145: padding: 2px;
5146: }
5147:
5148: table.LC_double_column tr td.LC_left_col {
5149: top: 2px;
5150: left: 2px;
5151: width: 47%;
5152: vertical-align: top;
5153: }
5154:
5155: table.LC_double_column tr td.LC_right_col {
5156: top: 2px;
5157: right: 2px;
5158: width: 47%;
5159: vertical-align: top;
5160: }
5161:
5162: span.LC_role_level {
5163: font-weight: bold;
5164: }
5165:
5166: div.LC_left_float {
5167: float: left;
5168: padding-right: 5%;
5169: padding-bottom: 4px;
5170: }
5171:
5172: div.LC_clear_float_header {
5173: padding-bottom: 2px;
5174: }
5175:
5176: div.LC_clear_float_footer {
5177: padding-top: 10px;
5178: clear: both;
5179: }
5180:
5181:
5182: div.LC_grade_select_mode {
5183: font-family: $sans;
5184: }
5185: div.LC_grade_select_mode div div {
5186: margin: 5px;
5187: }
5188: div.LC_grade_select_mode_selector {
5189: margin: 5px;
5190: float: left;
5191: }
5192: div.LC_grade_select_mode_selector_header {
5193: font: bold medium $sans;
5194: }
5195: div.LC_grade_select_mode_type {
5196: clear: left;
5197: }
5198:
5199: div.LC_grade_show_user {
5200: margin-top: 20px;
5201: border: 1px solid black;
5202: }
5203: div.LC_grade_user_name {
5204: background: #DDDDEE;
5205: border-bottom: 1px solid black;
5206: font: bold large $sans;
5207: }
5208: div.LC_grade_show_user_odd_row div.LC_grade_user_name {
5209: background: #DDEEDD;
5210: }
5211:
5212: div.LC_grade_show_problem,
5213: div.LC_grade_submissions,
5214: div.LC_grade_message_center,
5215: div.LC_grade_info_links,
5216: div.LC_grade_assign {
5217: margin: 5px;
5218: width: 99%;
5219: background: #FFFFFF;
5220: }
5221: div.LC_grade_show_problem_header,
5222: div.LC_grade_submissions_header,
5223: div.LC_grade_message_center_header,
5224: div.LC_grade_assign_header {
5225: font: bold large $sans;
5226: }
5227: div.LC_grade_show_problem_problem,
5228: div.LC_grade_submissions_body,
5229: div.LC_grade_message_center_body,
5230: div.LC_grade_assign_body {
5231: border: 1px solid black;
5232: width: 99%;
5233: background: #FFFFFF;
5234: }
5235: span.LC_grade_check_note {
5236: font: normal medium $sans;
5237: display: inline;
5238: position: absolute;
5239: right: 1em;
5240: }
5241:
5242: table.LC_scantron_action {
5243: width: 100%;
5244: }
5245: table.LC_scantron_action tr th {
5246: font: normal bold $sans;
5247: }
5248:
5249: div.LC_edit_problem_header,
5250: div.LC_edit_problem_footer {
5251: font: normal medium $sans;
5252: margin: 2px;
5253: }
5254: div.LC_edit_problem_header,
5255: div.LC_edit_problem_header div,
5256: div.LC_edit_problem_footer,
5257: div.LC_edit_problem_footer div,
5258: div.LC_edit_problem_editxml_header,
5259: div.LC_edit_problem_editxml_header div {
5260: margin-top: 5px;
5261: }
5262: div.LC_edit_problem_header_edit_row {
5263: background: $tabbg;
5264: padding: 3px;
5265: margin-bottom: 5px;
5266: }
5267: div.LC_edit_problem_header_title {
5268: font: larger bold $sans;
5269: background: $tabbg;
5270: padding: 3px;
5271: }
5272: table.LC_edit_problem_header_title {
5273: font: larger bold $sans;
5274: width: 100%;
5275: border-color: $pgbg;
5276: border-style: solid;
5277: border-width: $border;
5278:
5279: background: $tabbg;
5280: border-collapse: collapse;
5281: padding: 0px
5282: }
5283:
5284: div.LC_edit_problem_discards {
5285: float: left;
5286: padding-bottom: 5px;
5287: }
5288: div.LC_edit_problem_saves {
5289: float: right;
5290: padding-bottom: 5px;
5291: }
5292: hr.LC_edit_problem_divide {
5293: clear: both;
5294: color: $tabbg;
5295: background-color: $tabbg;
5296: height: 3px;
5297: border: 0px;
5298: }
5299: END
5300: }
5301:
5302: =pod
5303:
5304: =item * &headtag()
5305:
5306: Returns a uniform footer for LON-CAPA web pages.
5307:
5308: Inputs: $title - optional title for the head
5309: $head_extra - optional extra HTML to put inside the <head>
5310: $args - optional arguments
5311: force_register - if is true call registerurl so the remote is
5312: informed
5313: redirect -> array ref of
5314: 1- seconds before redirect occurs
5315: 2- url to redirect to
5316: 3- whether the side effect should occur
5317: (side effect of setting
5318: $env{'internal.head.redirect'} to the url
5319: redirected too)
5320: domain -> force to color decorate a page for a specific
5321: domain
5322: function -> force usage of a specific rolish color scheme
5323: bgcolor -> override the default page bgcolor
5324: no_auto_mt_title
5325: -> prevent &mt()ing the title arg
5326:
5327: =cut
5328:
5329: sub headtag {
5330: my ($title,$head_extra,$args) = @_;
5331:
5332: my $function = $args->{'function'} || &get_users_function();
5333: my $domain = $args->{'domain'} || &determinedomain();
5334: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
5335: my $url = join(':',$env{'user.name'},$env{'user.domain'},
5336: $Apache::lonnet::perlvar{'lonVersion'},
5337: #time(),
5338: $env{'environment.color.timestamp'},
5339: $function,$domain,$bgcolor);
5340:
5341: $url = '/adm/css/'.&escape($url).'.css';
5342:
5343: my $result =
5344: '<head>'.
5345: &font_settings();
5346:
5347: if (!$args->{'frameset'}) {
5348: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
5349: }
5350: if ($args->{'force_register'}) {
5351: $result .= &Apache::lonmenu::registerurl(1);
5352: }
5353: if (!$args->{'no_nav_bar'}
5354: && !$args->{'only_body'}
5355: && !$args->{'frameset'}) {
5356: $result .= &help_menu_js();
5357: }
5358:
5359: if (ref($args->{'redirect'})) {
5360: my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
5361: $url = &Apache::lonenc::check_encrypt($url);
5362: if (!$inhibit_continue) {
5363: $env{'internal.head.redirect'} = $url;
5364: }
5365: $result.=<<ADDMETA
5366: <meta http-equiv="pragma" content="no-cache" />
5367: <meta http-equiv="Refresh" content="$time; url=$url" />
5368: ADDMETA
5369: }
5370: if (!defined($title)) {
5371: $title = 'The LearningOnline Network with CAPA';
5372: }
5373: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
5374: $result .= '<title> LON-CAPA '.$title.'</title>'
5375: .'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
5376: .$head_extra;
5377: return $result;
5378: }
5379:
5380: =pod
5381:
5382: =item * &font_settings()
5383:
5384: Returns neccessary <meta> to set the proper encoding
5385:
5386: Inputs: none
5387:
5388: =cut
5389:
5390: sub font_settings {
5391: my $headerstring='';
5392: if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
5393: $headerstring.=
5394: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
5395: }
5396: return $headerstring;
5397: }
5398:
5399: =pod
5400:
5401: =item * &xml_begin()
5402:
5403: Returns the needed doctype and <html>
5404:
5405: Inputs: none
5406:
5407: =cut
5408:
5409: sub xml_begin {
5410: my $output='';
5411:
5412: if ($env{'internal.start_page'}==1) {
5413: &Apache::lonhtmlcommon::init_htmlareafields();
5414: }
5415:
5416: if ($env{'browser.mathml'}) {
5417: $output='<?xml version="1.0"?>'
5418: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
5419: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
5420:
5421: # .'<!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">] >'
5422: .'<!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">'
5423: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
5424: .'xmlns="http://www.w3.org/1999/xhtml">';
5425: } else {
5426: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
5427: }
5428: return $output;
5429: }
5430:
5431: =pod
5432:
5433: =item * &endheadtag()
5434:
5435: Returns a uniform </head> for LON-CAPA web pages.
5436:
5437: Inputs: none
5438:
5439: =cut
5440:
5441: sub endheadtag {
5442: return '</head>';
5443: }
5444:
5445: =pod
5446:
5447: =item * &head()
5448:
5449: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
5450:
5451: Inputs:
5452:
5453: =over 4
5454:
5455: $title - optional title for the page
5456:
5457: $head_extra - optional extra HTML to put inside the <head>
5458:
5459: =back
5460:
5461: =cut
5462:
5463: sub head {
5464: my ($title,$head_extra,$args) = @_;
5465: return &headtag($title,$head_extra,$args).&endheadtag();
5466: }
5467:
5468: =pod
5469:
5470: =item * &start_page()
5471:
5472: Returns a complete <html> .. <body> section for LON-CAPA web pages.
5473:
5474: Inputs:
5475:
5476: =over 4
5477:
5478: $title - optional title for the page
5479:
5480: $head_extra - optional extra HTML to incude inside the <head>
5481:
5482: $args - additional optional args supported are:
5483:
5484: =over 8
5485:
5486: only_body -> is true will set &bodytag() onlybodytag
5487: arg on
5488: no_nav_bar -> is true will set &bodytag() notopbar arg on
5489: add_entries -> additional attributes to add to the <body>
5490: domain -> force to color decorate a page for a
5491: specific domain
5492: function -> force usage of a specific rolish color
5493: scheme
5494: redirect -> see &headtag()
5495: bgcolor -> override the default page bg color
5496: js_ready -> return a string ready for being used in
5497: a javascript writeln
5498: html_encode -> return a string ready for being used in
5499: a html attribute
5500: force_register -> if is true will turn on the &bodytag()
5501: $forcereg arg
5502: body_title -> alternate text to use instead of $title
5503: in the title box that appears, this text
5504: is not auto translated like the $title is
5505: frameset -> if true will start with a <frameset>
5506: rather than <body>
5507: no_title -> if true the title bar won't be shown
5508: skip_phases -> hash ref of
5509: head -> skip the <html><head> generation
5510: body -> skip all <body> generation
5511: no_inline_link -> if true and in remote mode, don't show the
5512: 'Switch To Inline Menu' link
5513: no_auto_mt_title -> prevent &mt()ing the title arg
5514: inherit_jsmath -> when creating popup window in a page,
5515: should it have jsmath forced on by the
5516: current page
5517:
5518: =back
5519:
5520: =back
5521:
5522: =cut
5523:
5524: sub start_page {
5525: my ($title,$head_extra,$args) = @_;
5526: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
5527: my %head_args;
5528: foreach my $arg ('redirect','force_register','domain','function',
5529: 'bgcolor','frameset','no_nav_bar','only_body',
5530: 'no_auto_mt_title') {
5531: if (defined($args->{$arg})) {
5532: $head_args{$arg} = $args->{$arg};
5533: }
5534: }
5535:
5536: $env{'internal.start_page'}++;
5537: my $result;
5538: if (! exists($args->{'skip_phases'}{'head'}) ) {
5539: $result.=
5540: &xml_begin().
5541: &headtag($title,$head_extra,\%head_args).&endheadtag();
5542: }
5543:
5544: if (! exists($args->{'skip_phases'}{'body'}) ) {
5545: if ($args->{'frameset'}) {
5546: my $attr_string = &make_attr_string($args->{'force_register'},
5547: $args->{'add_entries'});
5548: $result .= "\n<frameset $attr_string>\n";
5549: } else {
5550: $result .=
5551: &bodytag($title,
5552: $args->{'function'}, $args->{'add_entries'},
5553: $args->{'only_body'}, $args->{'domain'},
5554: $args->{'force_register'}, $args->{'body_title'},
5555: $args->{'no_nav_bar'}, $args->{'bgcolor'},
5556: $args->{'no_title'}, $args->{'no_inline_link'},
5557: $args);
5558: }
5559: }
5560:
5561: if ($args->{'js_ready'}) {
5562: $result = &js_ready($result);
5563: }
5564: if ($args->{'html_encode'}) {
5565: $result = &html_encode($result);
5566: }
5567: return $result;
5568: }
5569:
5570:
5571: =pod
5572:
5573: =item * &head()
5574:
5575: Returns a complete </body></html> section for LON-CAPA web pages.
5576:
5577: Inputs: $args - additional optional args supported are:
5578: js_ready -> return a string ready for being used in
5579: a javascript writeln
5580: html_encode -> return a string ready for being used in
5581: a html attribute
5582: frameset -> if true will start with a <frameset>
5583: rather than <body>
5584: dicsussion -> if true will get discussion from
5585: lonxml::xmlend
5586: (you can pass the target and parser arguments
5587: through optional 'target' and 'parser' args
5588: to this routine)
5589:
5590: =cut
5591:
5592: sub end_page {
5593: my ($args) = @_;
5594: $env{'internal.end_page'}++;
5595: my $result;
5596: if ($args->{'discussion'}) {
5597: my ($target,$parser);
5598: if (ref($args->{'discussion'})) {
5599: ($target,$parser) =($args->{'discussion'}{'target'},
5600: $args->{'discussion'}{'parser'});
5601: }
5602: $result .= &Apache::lonxml::xmlend($target,$parser);
5603: }
5604:
5605: if ($args->{'frameset'}) {
5606: $result .= '</frameset>';
5607: } else {
5608: $result .= &endbodytag($args);
5609: }
5610: $result .= "\n</html>";
5611:
5612: if ($args->{'js_ready'}) {
5613: $result = &js_ready($result);
5614: }
5615:
5616: if ($args->{'html_encode'}) {
5617: $result = &html_encode($result);
5618: }
5619:
5620: return $result;
5621: }
5622:
5623: sub html_encode {
5624: my ($result) = @_;
5625:
5626: $result = &HTML::Entities::encode($result,'<>&"');
5627:
5628: return $result;
5629: }
5630: sub js_ready {
5631: my ($result) = @_;
5632:
5633: $result =~ s/[\n\r]/ /xmsg;
5634: $result =~ s/\\/\\\\/xmsg;
5635: $result =~ s/'/\\'/xmsg;
5636: $result =~ s{</}{<\\/}xmsg;
5637:
5638: return $result;
5639: }
5640:
5641: sub validate_page {
5642: if ( exists($env{'internal.start_page'})
5643: && $env{'internal.start_page'} > 1) {
5644: &Apache::lonnet::logthis('start_page called multiple times '.
5645: $env{'internal.start_page'}.' '.
5646: $ENV{'request.filename'});
5647: }
5648: if ( exists($env{'internal.end_page'})
5649: && $env{'internal.end_page'} > 1) {
5650: &Apache::lonnet::logthis('end_page called multiple times '.
5651: $env{'internal.end_page'}.' '.
5652: $env{'request.filename'});
5653: }
5654: if ( exists($env{'internal.start_page'})
5655: && ! exists($env{'internal.end_page'})) {
5656: &Apache::lonnet::logthis('start_page called without end_page '.
5657: $env{'request.filename'});
5658: }
5659: if ( ! exists($env{'internal.start_page'})
5660: && exists($env{'internal.end_page'})) {
5661: &Apache::lonnet::logthis('end_page called without start_page'.
5662: $env{'request.filename'});
5663: }
5664: }
5665:
5666: sub simple_error_page {
5667: my ($r,$title,$msg) = @_;
5668: my $page =
5669: &Apache::loncommon::start_page($title).
5670: &mt($msg).
5671: &Apache::loncommon::end_page();
5672: if (ref($r)) {
5673: $r->print($page);
5674: return;
5675: }
5676: return $page;
5677: }
5678:
5679: {
5680: my @row_count;
5681: sub start_data_table {
5682: my ($add_class) = @_;
5683: my $css_class = (join(' ','LC_data_table',$add_class));
5684: unshift(@row_count,0);
5685: return '<table class="'.$css_class.'">'."\n";
5686: }
5687:
5688: sub end_data_table {
5689: shift(@row_count);
5690: return '</table>'."\n";;
5691: }
5692:
5693: sub start_data_table_row {
5694: my ($add_class) = @_;
5695: $row_count[0]++;
5696: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
5697: $css_class = (join(' ',$css_class,$add_class));
5698: return '<tr class="'.$css_class.'">'."\n";;
5699: }
5700:
5701: sub continue_data_table_row {
5702: my ($add_class) = @_;
5703: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
5704: $css_class = (join(' ',$css_class,$add_class));
5705: return '<tr class="'.$css_class.'">'."\n";;
5706: }
5707:
5708: sub end_data_table_row {
5709: return '</tr>'."\n";;
5710: }
5711:
5712: sub start_data_table_empty_row {
5713: $row_count[0]++;
5714: return '<tr class="LC_empty_row" >'."\n";;
5715: }
5716:
5717: sub end_data_table_empty_row {
5718: return '</tr>'."\n";;
5719: }
5720:
5721: sub start_data_table_header_row {
5722: return '<tr class="LC_header_row">'."\n";;
5723: }
5724:
5725: sub end_data_table_header_row {
5726: return '</tr>'."\n";;
5727: }
5728: }
5729:
5730: =pod
5731:
5732: =item * &inhibit_menu_check($arg)
5733:
5734: Checks for a inhibitmenu state and generates output to preserve it
5735:
5736: Inputs: $arg - can be any of
5737: - undef - in which case the return value is a string
5738: to add into arguments list of a uri
5739: - 'input' - in which case the return value is a HTML
5740: <form> <input> field of type hidden to
5741: preserve the value
5742: - a url - in which case the return value is the url with
5743: the neccesary cgi args added to preserve the
5744: inhibitmenu state
5745: - a ref to a url - no return value, but the string is
5746: updated to include the neccessary cgi
5747: args to preserve the inhibitmenu state
5748:
5749: =cut
5750:
5751: sub inhibit_menu_check {
5752: my ($arg) = @_;
5753: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
5754: if ($arg eq 'input') {
5755: if ($env{'form.inhibitmenu'}) {
5756: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
5757: } else {
5758: return
5759: }
5760: }
5761: if ($env{'form.inhibitmenu'}) {
5762: if (ref($arg)) {
5763: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
5764: } elsif ($arg eq '') {
5765: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
5766: } else {
5767: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
5768: }
5769: }
5770: if (!ref($arg)) {
5771: return $arg;
5772: }
5773: }
5774:
5775: ###############################################
5776:
5777: =pod
5778:
5779: =back
5780:
5781: =head1 User Information Routines
5782:
5783: =over 4
5784:
5785: =item * &get_users_function()
5786:
5787: Used by &bodytag to determine the current users primary role.
5788: Returns either 'student','coordinator','admin', or 'author'.
5789:
5790: =cut
5791:
5792: ###############################################
5793: sub get_users_function {
5794: my $function = 'student';
5795: if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
5796: $function='coordinator';
5797: }
5798: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
5799: $function='admin';
5800: }
5801: if (($env{'request.role'}=~/^(au|ca)/) ||
5802: ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
5803: $function='author';
5804: }
5805: return $function;
5806: }
5807:
5808: ###############################################
5809:
5810: =pod
5811:
5812: =item * &check_user_status()
5813:
5814: Determines current status of supplied role for a
5815: specific user. Roles can be active, previous or future.
5816:
5817: Inputs:
5818: user's domain, user's username, course's domain,
5819: course's number, optional section ID.
5820:
5821: Outputs:
5822: role status: active, previous or future.
5823:
5824: =cut
5825:
5826: sub check_user_status {
5827: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
5828: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
5829: my @uroles = keys %userinfo;
5830: my $srchstr;
5831: my $active_chk = 'none';
5832: my $now = time;
5833: if (@uroles > 0) {
5834: if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
5835: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
5836: } else {
5837: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
5838: }
5839: if (grep/^\Q$srchstr\E$/,@uroles) {
5840: my $role_end = 0;
5841: my $role_start = 0;
5842: $active_chk = 'active';
5843: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
5844: $role_end = $1;
5845: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
5846: $role_start = $1;
5847: }
5848: }
5849: if ($role_start > 0) {
5850: if ($now < $role_start) {
5851: $active_chk = 'future';
5852: }
5853: }
5854: if ($role_end > 0) {
5855: if ($now > $role_end) {
5856: $active_chk = 'previous';
5857: }
5858: }
5859: }
5860: }
5861: return $active_chk;
5862: }
5863:
5864: ###############################################
5865:
5866: =pod
5867:
5868: =item * &get_sections()
5869:
5870: Determines all the sections for a course including
5871: sections with students and sections containing other roles.
5872: Incoming parameters:
5873:
5874: 1. domain
5875: 2. course number
5876: 3. reference to array containing roles for which sections should
5877: be gathered (optional).
5878: 4. reference to array containing status types for which sections
5879: should be gathered (optional).
5880:
5881: If the third argument is undefined, sections are gathered for any role.
5882: If the fourth argument is undefined, sections are gathered for any status.
5883: Permissible values are 'active' or 'future' or 'previous'.
5884:
5885: Returns section hash (keys are section IDs, values are
5886: number of users in each section), subject to the
5887: optional roles filter, optional status filter
5888:
5889: =cut
5890:
5891: ###############################################
5892: sub get_sections {
5893: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
5894: if (!defined($cdom) || !defined($cnum)) {
5895: my $cid = $env{'request.course.id'};
5896:
5897: return if (!defined($cid));
5898:
5899: $cdom = $env{'course.'.$cid.'.domain'};
5900: $cnum = $env{'course.'.$cid.'.num'};
5901: }
5902:
5903: my %sectioncount;
5904: my $now = time;
5905:
5906: if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
5907: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
5908: my $sec_index = &Apache::loncoursedata::CL_SECTION();
5909: my $status_index = &Apache::loncoursedata::CL_STATUS();
5910: my $start_index = &Apache::loncoursedata::CL_START();
5911: my $end_index = &Apache::loncoursedata::CL_END();
5912: my $status;
5913: while (my ($student,$data) = each(%$classlist)) {
5914: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
5915: $data->[$status_index],
5916: $data->[$start_index],
5917: $data->[$end_index]);
5918: if ($stu_status eq 'Active') {
5919: $status = 'active';
5920: } elsif ($end < $now) {
5921: $status = 'previous';
5922: } elsif ($start > $now) {
5923: $status = 'future';
5924: }
5925: if ($section ne '-1' && $section !~ /^\s*$/) {
5926: if ((!defined($possible_status)) || (($status ne '') &&
5927: (grep/^\Q$status\E$/,@{$possible_status}))) {
5928: $sectioncount{$section}++;
5929: }
5930: }
5931: }
5932: }
5933: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
5934: foreach my $user (sort(keys(%courseroles))) {
5935: if ($user !~ /^(\w{2})/) { next; }
5936: my ($role) = ($user =~ /^(\w{2})/);
5937: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
5938: my ($section,$status);
5939: if ($role eq 'cr' &&
5940: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
5941: $section=$1;
5942: }
5943: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
5944: if (!defined($section) || $section eq '-1') { next; }
5945: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
5946: if ($end == -1 && $start == -1) {
5947: next; #deleted role
5948: }
5949: if (!defined($possible_status)) {
5950: $sectioncount{$section}++;
5951: } else {
5952: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
5953: $status = 'active';
5954: } elsif ($end < $now) {
5955: $status = 'future';
5956: } elsif ($start > $now) {
5957: $status = 'previous';
5958: }
5959: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
5960: $sectioncount{$section}++;
5961: }
5962: }
5963: }
5964: return %sectioncount;
5965: }
5966:
5967: ###############################################
5968:
5969: =pod
5970:
5971: =item * &get_course_users()
5972:
5973: Retrieves usernames:domains for users in the specified course
5974: with specific role(s), and access status.
5975:
5976: Incoming parameters:
5977: 1. course domain
5978: 2. course number
5979: 3. access status: users must have - either active,
5980: previous, future, or all.
5981: 4. reference to array of permissible roles
5982: 5. reference to array of section restrictions (optional)
5983: 6. reference to results object (hash of hashes).
5984: 7. reference to optional userdata hash
5985: 8. reference to optional statushash
5986: 9. flag if privileged users (except those set to unhide in
5987: course settings) should be excluded
5988: Keys of top level results hash are roles.
5989: Keys of inner hashes are username:domain, with
5990: values set to access type.
5991: Optional userdata hash returns an array with arguments in the
5992: same order as loncoursedata::get_classlist() for student data.
5993:
5994: Optional statushash returns
5995:
5996: Entries for end, start, section and status are blank because
5997: of the possibility of multiple values for non-student roles.
5998:
5999: =cut
6000:
6001: ###############################################
6002:
6003: sub get_course_users {
6004: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
6005: my %idx = ();
6006: my %seclists;
6007:
6008: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
6009: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
6010: $idx{end} = &Apache::loncoursedata::CL_END();
6011: $idx{start} = &Apache::loncoursedata::CL_START();
6012: $idx{id} = &Apache::loncoursedata::CL_ID();
6013: $idx{section} = &Apache::loncoursedata::CL_SECTION();
6014: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
6015: $idx{status} = &Apache::loncoursedata::CL_STATUS();
6016:
6017: if (grep(/^st$/,@{$roles})) {
6018: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
6019: my $now = time;
6020: foreach my $student (keys(%{$classlist})) {
6021: my $match = 0;
6022: my $secmatch = 0;
6023: my $section = $$classlist{$student}[$idx{section}];
6024: my $status = $$classlist{$student}[$idx{status}];
6025: if ($section eq '') {
6026: $section = 'none';
6027: }
6028: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
6029: if (grep(/^all$/,@{$sections})) {
6030: $secmatch = 1;
6031: } elsif ($$classlist{$student}[$idx{section}] eq '') {
6032: if (grep(/^none$/,@{$sections})) {
6033: $secmatch = 1;
6034: }
6035: } else {
6036: if (grep(/^\Q$section\E$/,@{$sections})) {
6037: $secmatch = 1;
6038: }
6039: }
6040: if (!$secmatch) {
6041: next;
6042: }
6043: }
6044: if (defined($$types{'active'})) {
6045: if ($$classlist{$student}[$idx{status}] eq 'Active') {
6046: push(@{$$users{st}{$student}},'active');
6047: $match = 1;
6048: }
6049: }
6050: if (defined($$types{'previous'})) {
6051: if ($$classlist{$student}[$idx{status}] eq 'Expired') {
6052: push(@{$$users{st}{$student}},'previous');
6053: $match = 1;
6054: }
6055: }
6056: if (defined($$types{'future'})) {
6057: if ($$classlist{$student}[$idx{status}] eq 'Future') {
6058: push(@{$$users{st}{$student}},'future');
6059: $match = 1;
6060: }
6061: }
6062: if ($match) {
6063: push(@{$seclists{$student}},$section);
6064: if (ref($userdata) eq 'HASH') {
6065: $$userdata{$student} = $$classlist{$student};
6066: }
6067: if (ref($statushash) eq 'HASH') {
6068: $statushash->{$student}{'st'}{$section} = $status;
6069: }
6070: }
6071: }
6072: }
6073: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
6074: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
6075: my $now = time;
6076: my %displaystatus = ( previous => 'Expired',
6077: active => 'Active',
6078: future => 'Future',
6079: );
6080: my %nothide;
6081: if ($hidepriv) {
6082: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
6083: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
6084: if ($user !~ /:/) {
6085: $nothide{join(':',split(/[\@]/,$user))}=1;
6086: } else {
6087: $nothide{$user} = 1;
6088: }
6089: }
6090: }
6091: foreach my $person (sort(keys(%coursepersonnel))) {
6092: my $match = 0;
6093: my $secmatch = 0;
6094: my $status;
6095: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
6096: $user =~ s/:$//;
6097: my ($end,$start) = split(/:/,$coursepersonnel{$person});
6098: if ($end == -1 || $start == -1) {
6099: next;
6100: }
6101: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
6102: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
6103: my ($uname,$udom) = split(/:/,$user);
6104: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
6105: if (grep(/^all$/,@{$sections})) {
6106: $secmatch = 1;
6107: } elsif ($usec eq '') {
6108: if (grep(/^none$/,@{$sections})) {
6109: $secmatch = 1;
6110: }
6111: } else {
6112: if (grep(/^\Q$usec\E$/,@{$sections})) {
6113: $secmatch = 1;
6114: }
6115: }
6116: if (!$secmatch) {
6117: next;
6118: }
6119: }
6120: if ($usec eq '') {
6121: $usec = 'none';
6122: }
6123: if ($uname ne '' && $udom ne '') {
6124: if ($hidepriv) {
6125: if ((&Apache::lonnet::privileged($uname,$udom)) &&
6126: (!$nothide{$uname.':'.$udom})) {
6127: next;
6128: }
6129: }
6130: if ($end > 0 && $end < $now) {
6131: $status = 'previous';
6132: } elsif ($start > $now) {
6133: $status = 'future';
6134: } else {
6135: $status = 'active';
6136: }
6137: foreach my $type (keys(%{$types})) {
6138: if ($status eq $type) {
6139: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
6140: push(@{$$users{$role}{$user}},$type);
6141: }
6142: $match = 1;
6143: }
6144: }
6145: if (($match) && (ref($userdata) eq 'HASH')) {
6146: if (!exists($$userdata{$uname.':'.$udom})) {
6147: &get_user_info($udom,$uname,\%idx,$userdata);
6148: }
6149: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
6150: push(@{$seclists{$uname.':'.$udom}},$usec);
6151: }
6152: if (ref($statushash) eq 'HASH') {
6153: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
6154: }
6155: }
6156: }
6157: }
6158: }
6159: if (grep(/^ow$/,@{$roles})) {
6160: if ((defined($cdom)) && (defined($cnum))) {
6161: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
6162: if ( defined($csettings{'internal.courseowner'}) ) {
6163: my $owner = $csettings{'internal.courseowner'};
6164: next if ($owner eq '');
6165: my ($ownername,$ownerdom);
6166: if ($owner =~ /^([^:]+):([^:]+)$/) {
6167: $ownername = $1;
6168: $ownerdom = $2;
6169: } else {
6170: $ownername = $owner;
6171: $ownerdom = $cdom;
6172: $owner = $ownername.':'.$ownerdom;
6173: }
6174: @{$$users{'ow'}{$owner}} = 'any';
6175: if (defined($userdata) &&
6176: !exists($$userdata{$owner})) {
6177: &get_user_info($ownerdom,$ownername,\%idx,$userdata);
6178: if (!grep(/^none$/,@{$seclists{$owner}})) {
6179: push(@{$seclists{$owner}},'none');
6180: }
6181: if (ref($statushash) eq 'HASH') {
6182: $statushash->{$owner}{'ow'}{'none'} = 'Any';
6183: }
6184: }
6185: }
6186: }
6187: }
6188: foreach my $user (keys(%seclists)) {
6189: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
6190: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
6191: }
6192: }
6193: return;
6194: }
6195:
6196: sub get_user_info {
6197: my ($udom,$uname,$idx,$userdata) = @_;
6198: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
6199: &plainname($uname,$udom,'lastname');
6200: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
6201: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
6202: my %idhash = &Apache::lonnet::idrget($udom,($uname));
6203: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname};
6204: return;
6205: }
6206:
6207: ###############################################
6208:
6209: =pod
6210:
6211: =item * &get_user_quota()
6212:
6213: Retrieves quota assigned for storage of portfolio files for a user
6214:
6215: Incoming parameters:
6216: 1. user's username
6217: 2. user's domain
6218:
6219: Returns:
6220: 1. Disk quota (in Mb) assigned to student.
6221: 2. (Optional) Type of setting: custom or default
6222: (individually assigned or default for user's
6223: institutional status).
6224: 3. (Optional) - User's institutional status (e.g., faculty, staff
6225: or student - types as defined in localenroll::inst_usertypes
6226: for user's domain, which determines default quota for user.
6227: 4. (Optional) - Default quota which would apply to the user.
6228:
6229: If a value has been stored in the user's environment,
6230: it will return that, otherwise it returns the maximal default
6231: defined for the user's instituional status(es) in the domain.
6232:
6233: =cut
6234:
6235: ###############################################
6236:
6237:
6238: sub get_user_quota {
6239: my ($uname,$udom) = @_;
6240: my ($quota,$quotatype,$settingstatus,$defquota);
6241: if (!defined($udom)) {
6242: $udom = $env{'user.domain'};
6243: }
6244: if (!defined($uname)) {
6245: $uname = $env{'user.name'};
6246: }
6247: if (($udom eq '' || $uname eq '') ||
6248: ($udom eq 'public') && ($uname eq 'public')) {
6249: $quota = 0;
6250: $quotatype = 'default';
6251: $defquota = 0;
6252: } else {
6253: my $inststatus;
6254: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
6255: $quota = $env{'environment.portfolioquota'};
6256: $inststatus = $env{'environment.inststatus'};
6257: } else {
6258: my %userenv =
6259: &Apache::lonnet::get('environment',['portfolioquota',
6260: 'inststatus'],$udom,$uname);
6261: my ($tmp) = keys(%userenv);
6262: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
6263: $quota = $userenv{'portfolioquota'};
6264: $inststatus = $userenv{'inststatus'};
6265: } else {
6266: undef(%userenv);
6267: }
6268: }
6269: ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
6270: if ($quota eq '') {
6271: $quota = $defquota;
6272: $quotatype = 'default';
6273: } else {
6274: $quotatype = 'custom';
6275: }
6276: }
6277: if (wantarray) {
6278: return ($quota,$quotatype,$settingstatus,$defquota);
6279: } else {
6280: return $quota;
6281: }
6282: }
6283:
6284: ###############################################
6285:
6286: =pod
6287:
6288: =item * &default_quota()
6289:
6290: Retrieves default quota assigned for storage of user portfolio files,
6291: given an (optional) user's institutional status.
6292:
6293: Incoming parameters:
6294: 1. domain
6295: 2. (Optional) institutional status(es). This is a : separated list of
6296: status types (e.g., faculty, staff, student etc.)
6297: which apply to the user for whom the default is being retrieved.
6298: If the institutional status string in undefined, the domain
6299: default quota will be returned.
6300:
6301: Returns:
6302: 1. Default disk quota (in Mb) for user portfolios in the domain.
6303: 2. (Optional) institutional type which determined the value of the
6304: default quota.
6305:
6306: If a value has been stored in the domain's configuration db,
6307: it will return that, otherwise it returns 20 (for backwards
6308: compatibility with domains which have not set up a configuration
6309: db file; the original statically defined portfolio quota was 20 Mb).
6310:
6311: If the user's status includes multiple types (e.g., staff and student),
6312: the largest default quota which applies to the user determines the
6313: default quota returned.
6314:
6315: =cut
6316:
6317: ###############################################
6318:
6319:
6320: sub default_quota {
6321: my ($udom,$inststatus) = @_;
6322: my ($defquota,$settingstatus);
6323: my %quotahash = &Apache::lonnet::get_dom('configuration',
6324: ['quotas'],$udom);
6325: if (ref($quotahash{'quotas'}) eq 'HASH') {
6326: if ($inststatus ne '') {
6327: my @statuses = split(/:/,$inststatus);
6328: foreach my $item (@statuses) {
6329: if ($quotahash{'quotas'}{$item} ne '') {
6330: if ($defquota eq '') {
6331: $defquota = $quotahash{'quotas'}{$item};
6332: $settingstatus = $item;
6333: } elsif ($quotahash{'quotas'}{$item} > $defquota) {
6334: $defquota = $quotahash{'quotas'}{$item};
6335: $settingstatus = $item;
6336: }
6337: }
6338: }
6339: }
6340: if ($defquota eq '') {
6341: $defquota = $quotahash{'quotas'}{'default'};
6342: $settingstatus = 'default';
6343: }
6344: } else {
6345: $settingstatus = 'default';
6346: $defquota = 20;
6347: }
6348: if (wantarray) {
6349: return ($defquota,$settingstatus);
6350: } else {
6351: return $defquota;
6352: }
6353: }
6354:
6355: sub get_secgrprole_info {
6356: my ($cdom,$cnum,$needroles,$type) = @_;
6357: my %sections_count = &get_sections($cdom,$cnum);
6358: my @sections = (sort {$a <=> $b} keys(%sections_count));
6359: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
6360: my @groups = sort(keys(%curr_groups));
6361: my $allroles = [];
6362: my $rolehash;
6363: my $accesshash = {
6364: active => 'Currently has access',
6365: future => 'Will have future access',
6366: previous => 'Previously had access',
6367: };
6368: if ($needroles) {
6369: $rolehash = {'all' => 'all'};
6370: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
6371: if (&Apache::lonnet::error(%user_roles)) {
6372: undef(%user_roles);
6373: }
6374: foreach my $item (keys(%user_roles)) {
6375: my ($role)=split(/\:/,$item,2);
6376: if ($role eq 'cr') { next; }
6377: if ($role =~ /^cr/) {
6378: $$rolehash{$role} = (split('/',$role))[3];
6379: } else {
6380: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
6381: }
6382: }
6383: foreach my $key (sort(keys(%{$rolehash}))) {
6384: push(@{$allroles},$key);
6385: }
6386: push (@{$allroles},'st');
6387: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
6388: }
6389: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
6390: }
6391:
6392: sub user_picker {
6393: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
6394: my $currdom = $dom;
6395: my %curr_selected = (
6396: srchin => 'dom',
6397: srchby => 'lastname',
6398: );
6399: my $srchterm;
6400: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
6401: if ($srch->{'srchby'} ne '') {
6402: $curr_selected{'srchby'} = $srch->{'srchby'};
6403: }
6404: if ($srch->{'srchin'} ne '') {
6405: $curr_selected{'srchin'} = $srch->{'srchin'};
6406: }
6407: if ($srch->{'srchtype'} ne '') {
6408: $curr_selected{'srchtype'} = $srch->{'srchtype'};
6409: }
6410: if ($srch->{'srchdomain'} ne '') {
6411: $currdom = $srch->{'srchdomain'};
6412: }
6413: $srchterm = $srch->{'srchterm'};
6414: }
6415: my %lt=&Apache::lonlocal::texthash(
6416: 'usr' => 'Search criteria',
6417: 'doma' => 'Domain/institution to search',
6418: 'uname' => 'username',
6419: 'lastname' => 'last name',
6420: 'lastfirst' => 'last name, first name',
6421: 'crs' => 'in this course',
6422: 'dom' => 'in selected LON-CAPA domain',
6423: 'alc' => 'all LON-CAPA',
6424: 'instd' => 'in institutional directory for selected domain',
6425: 'exact' => 'is',
6426: 'contains' => 'contains',
6427: 'begins' => 'begins with',
6428: 'youm' => "You must include some text to search for.",
6429: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
6430: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
6431: 'yomc' => "You must choose a domain when using an institutional directory search.",
6432: 'ymcd' => "You must choose a domain when using a domain search.",
6433: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.",
6434: 'whse' => "When searching by last,first you must include at least one character in the first name.",
6435: 'thfo' => "The following need to be corrected before the search can be run:",
6436: );
6437: my $domform = &select_dom_form($currdom,'srchdomain',1,1);
6438: my $srchinsel = ' <select name="srchin">';
6439:
6440: my @srchins = ('crs','dom','alc','instd');
6441:
6442: foreach my $option (@srchins) {
6443: # FIXME 'alc' option unavailable until
6444: # loncreateuser::print_user_query_page()
6445: # has been completed.
6446: next if ($option eq 'alc');
6447: next if ($option eq 'crs' && !$env{'request.course.id'});
6448: if ($curr_selected{'srchin'} eq $option) {
6449: $srchinsel .= '
6450: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
6451: } else {
6452: $srchinsel .= '
6453: <option value="'.$option.'">'.$lt{$option}.'</option>';
6454: }
6455: }
6456: $srchinsel .= "\n </select>\n";
6457:
6458: my $srchbysel = ' <select name="srchby">';
6459: foreach my $option ('lastname','lastfirst','uname') {
6460: if ($curr_selected{'srchby'} eq $option) {
6461: $srchbysel .= '
6462: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
6463: } else {
6464: $srchbysel .= '
6465: <option value="'.$option.'">'.$lt{$option}.'</option>';
6466: }
6467: }
6468: $srchbysel .= "\n </select>\n";
6469:
6470: my $srchtypesel = ' <select name="srchtype">';
6471: foreach my $option ('begins','contains','exact') {
6472: if ($curr_selected{'srchtype'} eq $option) {
6473: $srchtypesel .= '
6474: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
6475: } else {
6476: $srchtypesel .= '
6477: <option value="'.$option.'">'.$lt{$option}.'</option>';
6478: }
6479: }
6480: $srchtypesel .= "\n </select>\n";
6481:
6482: my ($newuserscript,$new_user_create);
6483:
6484: if ($forcenewuser) {
6485: if (ref($srch) eq 'HASH') {
6486: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
6487: if ($cancreate) {
6488: $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>';
6489: } else {
6490: my $helplink = ' href="javascript:helpMenu('."'display'".')"';
6491: my %usertypetext = (
6492: official => 'institutional',
6493: unofficial => 'non-institutional',
6494: );
6495: $new_user_create = '<br /><span class="LC_warning">'.&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.").' '.&mt('Contact the <a[_1]>helpdesk</a> for assistance.',$helplink).'</span><br /><br />';
6496: }
6497: }
6498: }
6499:
6500: $newuserscript = <<"ENDSCRIPT";
6501:
6502: function setSearch(createnew,callingForm) {
6503: if (createnew == 1) {
6504: for (var i=0; i<callingForm.srchby.length; i++) {
6505: if (callingForm.srchby.options[i].value == 'uname') {
6506: callingForm.srchby.selectedIndex = i;
6507: }
6508: }
6509: for (var i=0; i<callingForm.srchin.length; i++) {
6510: if ( callingForm.srchin.options[i].value == 'dom') {
6511: callingForm.srchin.selectedIndex = i;
6512: }
6513: }
6514: for (var i=0; i<callingForm.srchtype.length; i++) {
6515: if (callingForm.srchtype.options[i].value == 'exact') {
6516: callingForm.srchtype.selectedIndex = i;
6517: }
6518: }
6519: for (var i=0; i<callingForm.srchdomain.length; i++) {
6520: if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
6521: callingForm.srchdomain.selectedIndex = i;
6522: }
6523: }
6524: }
6525: }
6526: ENDSCRIPT
6527:
6528: }
6529:
6530: my $output = <<"END_BLOCK";
6531: <script type="text/javascript">
6532: function validateEntry(callingForm) {
6533:
6534: var checkok = 1;
6535: var srchin;
6536: for (var i=0; i<callingForm.srchin.length; i++) {
6537: if ( callingForm.srchin[i].checked ) {
6538: srchin = callingForm.srchin[i].value;
6539: }
6540: }
6541:
6542: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
6543: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
6544: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
6545: var srchterm = callingForm.srchterm.value;
6546: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
6547: var msg = "";
6548:
6549: if (srchterm == "") {
6550: checkok = 0;
6551: msg += "$lt{'youm'}\\n";
6552: }
6553:
6554: if (srchtype== 'begins') {
6555: if (srchterm.length < 2) {
6556: checkok = 0;
6557: msg += "$lt{'thte'}\\n";
6558: }
6559: }
6560:
6561: if (srchtype== 'contains') {
6562: if (srchterm.length < 3) {
6563: checkok = 0;
6564: msg += "$lt{'thet'}\\n";
6565: }
6566: }
6567: if (srchin == 'instd') {
6568: if (srchdomain == '') {
6569: checkok = 0;
6570: msg += "$lt{'yomc'}\\n";
6571: }
6572: }
6573: if (srchin == 'dom') {
6574: if (srchdomain == '') {
6575: checkok = 0;
6576: msg += "$lt{'ymcd'}\\n";
6577: }
6578: }
6579: if (srchby == 'lastfirst') {
6580: if (srchterm.indexOf(",") == -1) {
6581: checkok = 0;
6582: msg += "$lt{'whus'}\\n";
6583: }
6584: if (srchterm.indexOf(",") == srchterm.length -1) {
6585: checkok = 0;
6586: msg += "$lt{'whse'}\\n";
6587: }
6588: }
6589: if (checkok == 0) {
6590: alert("$lt{'thfo'}\\n"+msg);
6591: return;
6592: }
6593: if (checkok == 1) {
6594: callingForm.submit();
6595: }
6596: }
6597:
6598: $newuserscript
6599:
6600: </script>
6601:
6602: $new_user_create
6603:
6604: <table>
6605: <tr>
6606: <td>$lt{'doma'}:</td>
6607: <td>$domform</td>
6608: </td>
6609: </tr>
6610: <tr>
6611: <td>$lt{'usr'}:</td>
6612: <td>$srchbysel
6613: $srchtypesel
6614: <input type="text" size="15" name="srchterm" value="$srchterm" />
6615: $srchinsel
6616: </td>
6617: </tr>
6618: </table>
6619: <br />
6620: END_BLOCK
6621:
6622: return $output;
6623: }
6624:
6625: sub user_rule_check {
6626: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
6627: my $response;
6628: if (ref($usershash) eq 'HASH') {
6629: foreach my $user (keys(%{$usershash})) {
6630: my ($uname,$udom) = split(/:/,$user);
6631: next if ($udom eq '' || $uname eq '');
6632: my ($id,$newuser);
6633: if (ref($usershash->{$user}) eq 'HASH') {
6634: $newuser = $usershash->{$user}->{'newuser'};
6635: $id = $usershash->{$user}->{'id'};
6636: }
6637: my $inst_response;
6638: if (ref($checks) eq 'HASH') {
6639: if (defined($checks->{'username'})) {
6640: ($inst_response,%{$inst_results->{$user}}) =
6641: &Apache::lonnet::get_instuser($udom,$uname);
6642: } elsif (defined($checks->{'id'})) {
6643: ($inst_response,%{$inst_results->{$user}}) =
6644: &Apache::lonnet::get_instuser($udom,undef,$id);
6645: }
6646: } else {
6647: ($inst_response,%{$inst_results->{$user}}) =
6648: &Apache::lonnet::get_instuser($udom,$uname);
6649: return;
6650: }
6651: if (!$got_rules->{$udom}) {
6652: my %domconfig = &Apache::lonnet::get_dom('configuration',
6653: ['usercreation'],$udom);
6654: if (ref($domconfig{'usercreation'}) eq 'HASH') {
6655: foreach my $item ('username','id') {
6656: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
6657: $$curr_rules{$udom}{$item} =
6658: $domconfig{'usercreation'}{$item.'_rule'};
6659: }
6660: }
6661: }
6662: $got_rules->{$udom} = 1;
6663: }
6664: foreach my $item (keys(%{$checks})) {
6665: if (ref($$curr_rules{$udom}) eq 'HASH') {
6666: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
6667: if (@{$$curr_rules{$udom}{$item}} > 0) {
6668: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
6669: foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
6670: if ($rule_check{$rule}) {
6671: $$rulematch{$user}{$item} = $rule;
6672: if ($inst_response eq 'ok') {
6673: if (ref($inst_results) eq 'HASH') {
6674: if (ref($inst_results->{$user}) eq 'HASH') {
6675: if (keys(%{$inst_results->{$user}}) == 0) {
6676: $$alerts{$item}{$udom}{$uname} = 1;
6677: }
6678: }
6679: }
6680: }
6681: last;
6682: }
6683: }
6684: }
6685: }
6686: }
6687: }
6688: }
6689: }
6690: return;
6691: }
6692:
6693: sub user_rule_formats {
6694: my ($domain,$domdesc,$curr_rules,$check) = @_;
6695: my %text = (
6696: 'username' => 'Usernames',
6697: 'id' => 'IDs',
6698: );
6699: my $output;
6700: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
6701: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
6702: if (@{$ruleorder} > 0) {
6703: $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>';
6704: foreach my $rule (@{$ruleorder}) {
6705: if (ref($curr_rules) eq 'ARRAY') {
6706: if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
6707: if (ref($rules->{$rule}) eq 'HASH') {
6708: $output .= '<li>'.$rules->{$rule}{'name'}.': '.
6709: $rules->{$rule}{'desc'}.'</li>';
6710: }
6711: }
6712: }
6713: }
6714: $output .= '</ul>';
6715: }
6716: }
6717: return $output;
6718: }
6719:
6720: sub instrule_disallow_msg {
6721: my ($checkitem,$domdesc,$count,$mode) = @_;
6722: my $response;
6723: my %text = (
6724: item => 'username',
6725: items => 'usernames',
6726: match => 'matches',
6727: do => 'does',
6728: action => 'a username',
6729: one => 'one',
6730: );
6731: if ($count > 1) {
6732: $text{'item'} = 'usernames';
6733: $text{'match'} ='match';
6734: $text{'do'} = 'do';
6735: $text{'action'} = 'usernames',
6736: $text{'one'} = 'ones';
6737: }
6738: if ($checkitem eq 'id') {
6739: $text{'items'} = 'IDs';
6740: $text{'item'} = 'ID';
6741: $text{'action'} = 'an ID';
6742: if ($count > 1) {
6743: $text{'item'} = 'IDs';
6744: $text{'action'} = 'IDs';
6745: }
6746: }
6747: $response = &mt("The $text{'item'} you chose $text{'match'} the format of $text{'items'} defined for <span class=\"LC_cusr_emph\">[_1]</span>, but the $text{'item'} $text{'do'} not exist in the institutional directory.",$domdesc).'<br />';
6748: if ($mode eq 'upload') {
6749: if ($checkitem eq 'username') {
6750: $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'}.");
6751: } elsif ($checkitem eq 'id') {
6752: $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 ID/Student Number field.");
6753: }
6754: } else {
6755: if ($checkitem eq 'username') {
6756: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
6757: } elsif ($checkitem eq 'id') {
6758: $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.");
6759: }
6760: }
6761: return $response;
6762: }
6763:
6764: sub personal_data_fieldtitles {
6765: my %fieldtitles = &Apache::lonlocal::texthash (
6766: id => 'Student/Employee ID',
6767: permanentemail => 'E-mail address',
6768: lastname => 'Last Name',
6769: firstname => 'First Name',
6770: middlename => 'Middle Name',
6771: generation => 'Generation',
6772: gen => 'Generation',
6773: );
6774: return %fieldtitles;
6775: }
6776:
6777: sub sorted_inst_types {
6778: my ($dom) = @_;
6779: my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
6780: my $othertitle = &mt('All users');
6781: if ($env{'request.course.id'}) {
6782: $othertitle = 'any';
6783: }
6784: my @types;
6785: if (ref($order) eq 'ARRAY') {
6786: @types = @{$order};
6787: }
6788: if (@types == 0) {
6789: if (ref($usertypes) eq 'HASH') {
6790: @types = sort(keys(%{$usertypes}));
6791: }
6792: }
6793: if (keys(%{$usertypes}) > 0) {
6794: $othertitle = &mt('Other users');
6795: if ($env{'request.course.id'}) {
6796: $othertitle = 'other';
6797: }
6798: }
6799: return ($othertitle,$usertypes,\@types);
6800: }
6801:
6802: sub get_institutional_codes {
6803: my ($settings,$allcourses,$LC_code) = @_;
6804: # Get complete list of course sections to update
6805: my @currsections = ();
6806: my @currxlists = ();
6807: my $coursecode = $$settings{'internal.coursecode'};
6808:
6809: if ($$settings{'internal.sectionnums'} ne '') {
6810: @currsections = split(/,/,$$settings{'internal.sectionnums'});
6811: }
6812:
6813: if ($$settings{'internal.crosslistings'} ne '') {
6814: @currxlists = split(/,/,$$settings{'internal.crosslistings'});
6815: }
6816:
6817: if (@currxlists > 0) {
6818: foreach (@currxlists) {
6819: if (m/^([^:]+):(\w*)$/) {
6820: unless (grep/^$1$/,@{$allcourses}) {
6821: push @{$allcourses},$1;
6822: $$LC_code{$1} = $2;
6823: }
6824: }
6825: }
6826: }
6827:
6828: if (@currsections > 0) {
6829: foreach (@currsections) {
6830: if (m/^(\w+):(\w*)$/) {
6831: my $sec = $coursecode.$1;
6832: my $lc_sec = $2;
6833: unless (grep/^$sec$/,@{$allcourses}) {
6834: push @{$allcourses},$sec;
6835: $$LC_code{$sec} = $lc_sec;
6836: }
6837: }
6838: }
6839: }
6840: return;
6841: }
6842:
6843: =pod
6844:
6845: =back
6846:
6847: =head1 HTTP Helpers
6848:
6849: =over 4
6850:
6851: =item * &get_unprocessed_cgi($query,$possible_names)
6852:
6853: Modify the %env hash to contain unprocessed CGI form parameters held in
6854: $query. The parameters listed in $possible_names (an array reference),
6855: will be set in $env{'form.name'} if they do not already exist.
6856:
6857: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
6858: $possible_names is an ref to an array of form element names. As an example:
6859: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
6860: will result in $env{'form.uname'} and $env{'form.udom'} being set.
6861:
6862: =cut
6863:
6864: sub get_unprocessed_cgi {
6865: my ($query,$possible_names)= @_;
6866: # $Apache::lonxml::debug=1;
6867: foreach my $pair (split(/&/,$query)) {
6868: my ($name, $value) = split(/=/,$pair);
6869: $name = &unescape($name);
6870: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
6871: $value =~ tr/+/ /;
6872: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
6873: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
6874: }
6875: }
6876: }
6877:
6878: =pod
6879:
6880: =item * &cacheheader()
6881:
6882: returns cache-controlling header code
6883:
6884: =cut
6885:
6886: sub cacheheader {
6887: unless ($env{'request.method'} eq 'GET') { return ''; }
6888: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
6889: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
6890: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
6891: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
6892: return $output;
6893: }
6894:
6895: =pod
6896:
6897: =item * &no_cache($r)
6898:
6899: specifies header code to not have cache
6900:
6901: =cut
6902:
6903: sub no_cache {
6904: my ($r) = @_;
6905: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
6906: $env{'request.method'} ne 'GET') { return ''; }
6907: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
6908: $r->no_cache(1);
6909: $r->header_out("Expires" => $date);
6910: $r->header_out("Pragma" => "no-cache");
6911: }
6912:
6913: sub content_type {
6914: my ($r,$type,$charset) = @_;
6915: if ($r) {
6916: # Note that printout.pl calls this with undef for $r.
6917: &no_cache($r);
6918: }
6919: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
6920: unless ($charset) {
6921: $charset=&Apache::lonlocal::current_encoding;
6922: }
6923: if ($charset) { $type.='; charset='.$charset; }
6924: if ($r) {
6925: $r->content_type($type);
6926: } else {
6927: print("Content-type: $type\n\n");
6928: }
6929: }
6930:
6931: =pod
6932:
6933: =item * &add_to_env($name,$value)
6934:
6935: adds $name to the %env hash with value
6936: $value, if $name already exists, the entry is converted to an array
6937: reference and $value is added to the array.
6938:
6939: =cut
6940:
6941: sub add_to_env {
6942: my ($name,$value)=@_;
6943: if (defined($env{$name})) {
6944: if (ref($env{$name})) {
6945: #already have multiple values
6946: push(@{ $env{$name} },$value);
6947: } else {
6948: #first time seeing multiple values, convert hash entry to an arrayref
6949: my $first=$env{$name};
6950: undef($env{$name});
6951: push(@{ $env{$name} },$first,$value);
6952: }
6953: } else {
6954: $env{$name}=$value;
6955: }
6956: }
6957:
6958: =pod
6959:
6960: =item * &get_env_multiple($name)
6961:
6962: gets $name from the %env hash, it seemlessly handles the cases where multiple
6963: values may be defined and end up as an array ref.
6964:
6965: returns an array of values
6966:
6967: =cut
6968:
6969: sub get_env_multiple {
6970: my ($name) = @_;
6971: my @values;
6972: if (defined($env{$name})) {
6973: # exists is it an array
6974: if (ref($env{$name})) {
6975: @values=@{ $env{$name} };
6976: } else {
6977: $values[0]=$env{$name};
6978: }
6979: }
6980: return(@values);
6981: }
6982:
6983:
6984: =pod
6985:
6986: =back
6987:
6988: =head1 CSV Upload/Handling functions
6989:
6990: =over 4
6991:
6992: =item * &upfile_store($r)
6993:
6994: Store uploaded file, $r should be the HTTP Request object,
6995: needs $env{'form.upfile'}
6996: returns $datatoken to be put into hidden field
6997:
6998: =cut
6999:
7000: sub upfile_store {
7001: my $r=shift;
7002: $env{'form.upfile'}=~s/\r/\n/gs;
7003: $env{'form.upfile'}=~s/\f/\n/gs;
7004: $env{'form.upfile'}=~s/\n+/\n/gs;
7005: $env{'form.upfile'}=~s/\n+$//gs;
7006:
7007: my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
7008: '_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
7009: {
7010: my $datafile = $r->dir_config('lonDaemons').
7011: '/tmp/'.$datatoken.'.tmp';
7012: if ( open(my $fh,">$datafile") ) {
7013: print $fh $env{'form.upfile'};
7014: close($fh);
7015: }
7016: }
7017: return $datatoken;
7018: }
7019:
7020: =pod
7021:
7022: =item * &load_tmp_file($r)
7023:
7024: Load uploaded file from tmp, $r should be the HTTP Request object,
7025: needs $env{'form.datatoken'},
7026: sets $env{'form.upfile'} to the contents of the file
7027:
7028: =cut
7029:
7030: sub load_tmp_file {
7031: my $r=shift;
7032: my @studentdata=();
7033: {
7034: my $studentfile = $r->dir_config('lonDaemons').
7035: '/tmp/'.$env{'form.datatoken'}.'.tmp';
7036: if ( open(my $fh,"<$studentfile") ) {
7037: @studentdata=<$fh>;
7038: close($fh);
7039: }
7040: }
7041: $env{'form.upfile'}=join('',@studentdata);
7042: }
7043:
7044: =pod
7045:
7046: =item * &upfile_record_sep()
7047:
7048: Separate uploaded file into records
7049: returns array of records,
7050: needs $env{'form.upfile'} and $env{'form.upfiletype'}
7051:
7052: =cut
7053:
7054: sub upfile_record_sep {
7055: if ($env{'form.upfiletype'} eq 'xml') {
7056: } else {
7057: my @records;
7058: foreach my $line (split(/\n/,$env{'form.upfile'})) {
7059: if ($line=~/^\s*$/) { next; }
7060: push(@records,$line);
7061: }
7062: return @records;
7063: }
7064: }
7065:
7066: =pod
7067:
7068: =item * &record_sep($record)
7069:
7070: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
7071:
7072: =cut
7073:
7074: sub takeleft {
7075: my $index=shift;
7076: return substr('0000'.$index,-4,4);
7077: }
7078:
7079: sub record_sep {
7080: my $record=shift;
7081: my %components=();
7082: if ($env{'form.upfiletype'} eq 'xml') {
7083: } elsif ($env{'form.upfiletype'} eq 'space') {
7084: my $i=0;
7085: foreach my $field (split(/\s+/,$record)) {
7086: $field=~s/^(\"|\')//;
7087: $field=~s/(\"|\')$//;
7088: $components{&takeleft($i)}=$field;
7089: $i++;
7090: }
7091: } elsif ($env{'form.upfiletype'} eq 'tab') {
7092: my $i=0;
7093: foreach my $field (split(/\t/,$record)) {
7094: $field=~s/^(\"|\')//;
7095: $field=~s/(\"|\')$//;
7096: $components{&takeleft($i)}=$field;
7097: $i++;
7098: }
7099: } else {
7100: my $separator=',';
7101: if ($env{'form.upfiletype'} eq 'semisv') {
7102: $separator=';';
7103: }
7104: my $i=0;
7105: # the character we are looking for to indicate the end of a quote or a record
7106: my $looking_for=$separator;
7107: # do not add the characters to the fields
7108: my $ignore=0;
7109: # we just encountered a separator (or the beginning of the record)
7110: my $just_found_separator=1;
7111: # store the field we are working on here
7112: my $field='';
7113: # work our way through all characters in record
7114: foreach my $character ($record=~/(.)/g) {
7115: if ($character eq $looking_for) {
7116: if ($character ne $separator) {
7117: # Found the end of a quote, again looking for separator
7118: $looking_for=$separator;
7119: $ignore=1;
7120: } else {
7121: # Found a separator, store away what we got
7122: $components{&takeleft($i)}=$field;
7123: $i++;
7124: $just_found_separator=1;
7125: $ignore=0;
7126: $field='';
7127: }
7128: next;
7129: }
7130: # single or double quotation marks after a separator indicate beginning of a quote
7131: # we are now looking for the end of the quote and need to ignore separators
7132: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) {
7133: $looking_for=$character;
7134: next;
7135: }
7136: # ignore would be true after we reached the end of a quote
7137: if ($ignore) { next; }
7138: if (($just_found_separator) && ($character=~/\s/)) { next; }
7139: $field.=$character;
7140: $just_found_separator=0;
7141: }
7142: # catch the very last entry, since we never encountered the separator
7143: $components{&takeleft($i)}=$field;
7144: }
7145: return %components;
7146: }
7147:
7148: ######################################################
7149: ######################################################
7150:
7151: =pod
7152:
7153: =item * &upfile_select_html()
7154:
7155: Return HTML code to select a file from the users machine and specify
7156: the file type.
7157:
7158: =cut
7159:
7160: ######################################################
7161: ######################################################
7162: sub upfile_select_html {
7163: my %Types = (
7164: csv => &mt('CSV (comma separated values, spreadsheet)'),
7165: semisv => &mt('Semicolon separated values'),
7166: space => &mt('Space separated'),
7167: tab => &mt('Tabulator separated'),
7168: # xml => &mt('HTML/XML'),
7169: );
7170: my $Str = '<input type="file" name="upfile" size="50" />'.
7171: '<br />Type: <select name="upfiletype">';
7172: foreach my $type (sort(keys(%Types))) {
7173: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
7174: }
7175: $Str .= "</select>\n";
7176: return $Str;
7177: }
7178:
7179: sub get_samples {
7180: my ($records,$toget) = @_;
7181: my @samples=({});
7182: my $got=0;
7183: foreach my $rec (@$records) {
7184: my %temp = &record_sep($rec);
7185: if (! grep(/\S/, values(%temp))) { next; }
7186: if (%temp) {
7187: $samples[$got]=\%temp;
7188: $got++;
7189: if ($got == $toget) { last; }
7190: }
7191: }
7192: return \@samples;
7193: }
7194:
7195: ######################################################
7196: ######################################################
7197:
7198: =pod
7199:
7200: =item * &csv_print_samples($r,$records)
7201:
7202: Prints a table of sample values from each column uploaded $r is an
7203: Apache Request ref, $records is an arrayref from
7204: &Apache::loncommon::upfile_record_sep
7205:
7206: =cut
7207:
7208: ######################################################
7209: ######################################################
7210: sub csv_print_samples {
7211: my ($r,$records) = @_;
7212: my $samples = &get_samples($records,3);
7213:
7214: $r->print(&mt('Samples').'<br />'.&start_data_table().
7215: &start_data_table_header_row());
7216: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
7217: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
7218: $r->print(&end_data_table_header_row());
7219: foreach my $hash (@$samples) {
7220: $r->print(&start_data_table_row());
7221: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
7222: $r->print('<td>');
7223: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
7224: $r->print('</td>');
7225: }
7226: $r->print(&end_data_table_row());
7227: }
7228: $r->print(&end_data_table().'<br />'."\n");
7229: }
7230:
7231: ######################################################
7232: ######################################################
7233:
7234: =pod
7235:
7236: =item * &csv_print_select_table($r,$records,$d)
7237:
7238: Prints a table to create associations between values and table columns.
7239:
7240: $r is an Apache Request ref,
7241: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
7242: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
7243:
7244: =cut
7245:
7246: ######################################################
7247: ######################################################
7248: sub csv_print_select_table {
7249: my ($r,$records,$d) = @_;
7250: my $i=0;
7251: my $samples = &get_samples($records,1);
7252: $r->print(&mt('Associate columns with student attributes.')."\n".
7253: &start_data_table().&start_data_table_header_row().
7254: '<th>'.&mt('Attribute').'</th>'.
7255: '<th>'.&mt('Column').'</th>'.
7256: &end_data_table_header_row()."\n");
7257: foreach my $array_ref (@$d) {
7258: my ($value,$display,$defaultcol)=@{ $array_ref };
7259: $r->print(&start_data_table_row().'<tr><td>'.$display.'</td>');
7260:
7261: $r->print('<td><select name=f'.$i.
7262: ' onchange="javascript:flip(this.form,'.$i.');">');
7263: $r->print('<option value="none"></option>');
7264: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
7265: $r->print('<option value="'.$sample.'"'.
7266: ($sample eq $defaultcol ? ' selected="selected" ' : '').
7267: '>Column '.($sample+1).'</option>');
7268: }
7269: $r->print('</select></td>'.&end_data_table_row()."\n");
7270: $i++;
7271: }
7272: $r->print(&end_data_table());
7273: $i--;
7274: return $i;
7275: }
7276:
7277: ######################################################
7278: ######################################################
7279:
7280: =pod
7281:
7282: =item * &csv_samples_select_table($r,$records,$d)
7283:
7284: Prints a table of sample values from the upload and can make associate samples to internal names.
7285:
7286: $r is an Apache Request ref,
7287: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
7288: $d is an array of 2 element arrays (internal name, displayed name)
7289:
7290: =cut
7291:
7292: ######################################################
7293: ######################################################
7294: sub csv_samples_select_table {
7295: my ($r,$records,$d) = @_;
7296: my $i=0;
7297: #
7298: my $samples = &get_samples($records,3);
7299: $r->print(&start_data_table().
7300: &start_data_table_header_row().'<th>'.
7301: &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
7302: &end_data_table_header_row());
7303:
7304: foreach my $key (sort(keys(%{ $samples->[0] }))) {
7305: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
7306: ' onchange="javascript:flip(this.form,'.$i.');">');
7307: foreach my $option (@$d) {
7308: my ($value,$display,$defaultcol)=@{ $option };
7309: $r->print('<option value="'.$value.'"'.
7310: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
7311: $display.'</option>');
7312: }
7313: $r->print('</select></td><td>');
7314: foreach my $line (0..2) {
7315: if (defined($samples->[$line]{$key})) {
7316: $r->print($samples->[$line]{$key}."<br />\n");
7317: }
7318: }
7319: $r->print('</td>'.&end_data_table_row());
7320: $i++;
7321: }
7322: $r->print(&end_data_table());
7323: $i--;
7324: return($i);
7325: }
7326:
7327: ######################################################
7328: ######################################################
7329:
7330: =pod
7331:
7332: =item * &clean_excel_name($name)
7333:
7334: Returns a replacement for $name which does not contain any illegal characters.
7335:
7336: =cut
7337:
7338: ######################################################
7339: ######################################################
7340: sub clean_excel_name {
7341: my ($name) = @_;
7342: $name =~ s/[:\*\?\/\\]//g;
7343: if (length($name) > 31) {
7344: $name = substr($name,0,31);
7345: }
7346: return $name;
7347: }
7348:
7349: =pod
7350:
7351: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
7352:
7353: Returns either 1 or undef
7354:
7355: 1 if the part is to be hidden, undef if it is to be shown
7356:
7357: Arguments are:
7358:
7359: $id the id of the part to be checked
7360: $symb, optional the symb of the resource to check
7361: $udom, optional the domain of the user to check for
7362: $uname, optional the username of the user to check for
7363:
7364: =cut
7365:
7366: sub check_if_partid_hidden {
7367: my ($id,$symb,$udom,$uname) = @_;
7368: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
7369: $symb,$udom,$uname);
7370: my $truth=1;
7371: #if the string starts with !, then the list is the list to show not hide
7372: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
7373: my @hiddenlist=split(/,/,$hiddenparts);
7374: foreach my $checkid (@hiddenlist) {
7375: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
7376: }
7377: return !$truth;
7378: }
7379:
7380:
7381: ############################################################
7382: ############################################################
7383:
7384: =pod
7385:
7386: =back
7387:
7388: =head1 cgi-bin script and graphing routines
7389:
7390: =over 4
7391:
7392: =item * &get_cgi_id()
7393:
7394: Inputs: none
7395:
7396: Returns an id which can be used to pass environment variables
7397: to various cgi-bin scripts. These environment variables will
7398: be removed from the users environment after a given time by
7399: the routine &Apache::lonnet::transfer_profile_to_env.
7400:
7401: =cut
7402:
7403: ############################################################
7404: ############################################################
7405: my $uniq=0;
7406: sub get_cgi_id {
7407: $uniq=($uniq+1)%100000;
7408: return (time.'_'.$$.'_'.$uniq);
7409: }
7410:
7411: ############################################################
7412: ############################################################
7413:
7414: =pod
7415:
7416: =item * &DrawBarGraph()
7417:
7418: Facilitates the plotting of data in a (stacked) bar graph.
7419: Puts plot definition data into the users environment in order for
7420: graph.png to plot it. Returns an <img> tag for the plot.
7421: The bars on the plot are labeled '1','2',...,'n'.
7422:
7423: Inputs:
7424:
7425: =over 4
7426:
7427: =item $Title: string, the title of the plot
7428:
7429: =item $xlabel: string, text describing the X-axis of the plot
7430:
7431: =item $ylabel: string, text describing the Y-axis of the plot
7432:
7433: =item $Max: scalar, the maximum Y value to use in the plot
7434: If $Max is < any data point, the graph will not be rendered.
7435:
7436: =item $colors: array ref holding the colors to be used for the data sets when
7437: they are plotted. If undefined, default values will be used.
7438:
7439: =item $labels: array ref holding the labels to use on the x-axis for the bars.
7440:
7441: =item @Values: An array of array references. Each array reference holds data
7442: to be plotted in a stacked bar chart.
7443:
7444: =item If the final element of @Values is a hash reference the key/value
7445: pairs will be added to the graph definition.
7446:
7447: =back
7448:
7449: Returns:
7450:
7451: An <img> tag which references graph.png and the appropriate identifying
7452: information for the plot.
7453:
7454: =cut
7455:
7456: ############################################################
7457: ############################################################
7458: sub DrawBarGraph {
7459: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
7460: #
7461: if (! defined($colors)) {
7462: $colors = ['#33ff00',
7463: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
7464: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
7465: ];
7466: }
7467: my $extra_settings = {};
7468: if (ref($Values[-1]) eq 'HASH') {
7469: $extra_settings = pop(@Values);
7470: }
7471: #
7472: my $identifier = &get_cgi_id();
7473: my $id = 'cgi.'.$identifier;
7474: if (! @Values || ref($Values[0]) ne 'ARRAY') {
7475: return '';
7476: }
7477: #
7478: my @Labels;
7479: if (defined($labels)) {
7480: @Labels = @$labels;
7481: } else {
7482: for (my $i=0;$i<@{$Values[0]};$i++) {
7483: push (@Labels,$i+1);
7484: }
7485: }
7486: #
7487: my $NumBars = scalar(@{$Values[0]});
7488: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
7489: my %ValuesHash;
7490: my $NumSets=1;
7491: foreach my $array (@Values) {
7492: next if (! ref($array));
7493: $ValuesHash{$id.'.data.'.$NumSets++} =
7494: join(',',@$array);
7495: }
7496: #
7497: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
7498: if ($NumBars < 3) {
7499: $width = 120+$NumBars*32;
7500: $xskip = 1;
7501: $bar_width = 30;
7502: } elsif ($NumBars < 5) {
7503: $width = 120+$NumBars*20;
7504: $xskip = 1;
7505: $bar_width = 20;
7506: } elsif ($NumBars < 10) {
7507: $width = 120+$NumBars*15;
7508: $xskip = 1;
7509: $bar_width = 15;
7510: } elsif ($NumBars <= 25) {
7511: $width = 120+$NumBars*11;
7512: $xskip = 5;
7513: $bar_width = 8;
7514: } elsif ($NumBars <= 50) {
7515: $width = 120+$NumBars*8;
7516: $xskip = 5;
7517: $bar_width = 4;
7518: } else {
7519: $width = 120+$NumBars*8;
7520: $xskip = 5;
7521: $bar_width = 4;
7522: }
7523: #
7524: $Max = 1 if ($Max < 1);
7525: if ( int($Max) < $Max ) {
7526: $Max++;
7527: $Max = int($Max);
7528: }
7529: $Title = '' if (! defined($Title));
7530: $xlabel = '' if (! defined($xlabel));
7531: $ylabel = '' if (! defined($ylabel));
7532: $ValuesHash{$id.'.title'} = &escape($Title);
7533: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
7534: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
7535: $ValuesHash{$id.'.y_max_value'} = $Max;
7536: $ValuesHash{$id.'.NumBars'} = $NumBars;
7537: $ValuesHash{$id.'.NumSets'} = $NumSets;
7538: $ValuesHash{$id.'.PlotType'} = 'bar';
7539: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
7540: $ValuesHash{$id.'.height'} = $height;
7541: $ValuesHash{$id.'.width'} = $width;
7542: $ValuesHash{$id.'.xskip'} = $xskip;
7543: $ValuesHash{$id.'.bar_width'} = $bar_width;
7544: $ValuesHash{$id.'.labels'} = join(',',@Labels);
7545: #
7546: # Deal with other parameters
7547: while (my ($key,$value) = each(%$extra_settings)) {
7548: $ValuesHash{$id.'.'.$key} = $value;
7549: }
7550: #
7551: &Apache::lonnet::appenv(\%ValuesHash);
7552: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
7553: }
7554:
7555: ############################################################
7556: ############################################################
7557:
7558: =pod
7559:
7560: =item * &DrawXYGraph()
7561:
7562: Facilitates the plotting of data in an XY graph.
7563: Puts plot definition data into the users environment in order for
7564: graph.png to plot it. Returns an <img> tag for the plot.
7565:
7566: Inputs:
7567:
7568: =over 4
7569:
7570: =item $Title: string, the title of the plot
7571:
7572: =item $xlabel: string, text describing the X-axis of the plot
7573:
7574: =item $ylabel: string, text describing the Y-axis of the plot
7575:
7576: =item $Max: scalar, the maximum Y value to use in the plot
7577: If $Max is < any data point, the graph will not be rendered.
7578:
7579: =item $colors: Array ref containing the hex color codes for the data to be
7580: plotted in. If undefined, default values will be used.
7581:
7582: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
7583:
7584: =item $Ydata: Array ref containing Array refs.
7585: Each of the contained arrays will be plotted as a separate curve.
7586:
7587: =item %Values: hash indicating or overriding any default values which are
7588: passed to graph.png.
7589: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
7590:
7591: =back
7592:
7593: Returns:
7594:
7595: An <img> tag which references graph.png and the appropriate identifying
7596: information for the plot.
7597:
7598: =cut
7599:
7600: ############################################################
7601: ############################################################
7602: sub DrawXYGraph {
7603: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
7604: #
7605: # Create the identifier for the graph
7606: my $identifier = &get_cgi_id();
7607: my $id = 'cgi.'.$identifier;
7608: #
7609: $Title = '' if (! defined($Title));
7610: $xlabel = '' if (! defined($xlabel));
7611: $ylabel = '' if (! defined($ylabel));
7612: my %ValuesHash =
7613: (
7614: $id.'.title' => &escape($Title),
7615: $id.'.xlabel' => &escape($xlabel),
7616: $id.'.ylabel' => &escape($ylabel),
7617: $id.'.y_max_value'=> $Max,
7618: $id.'.labels' => join(',',@$Xlabels),
7619: $id.'.PlotType' => 'XY',
7620: );
7621: #
7622: if (defined($colors) && ref($colors) eq 'ARRAY') {
7623: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
7624: }
7625: #
7626: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
7627: return '';
7628: }
7629: my $NumSets=1;
7630: foreach my $array (@{$Ydata}){
7631: next if (! ref($array));
7632: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
7633: }
7634: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
7635: #
7636: # Deal with other parameters
7637: while (my ($key,$value) = each(%Values)) {
7638: $ValuesHash{$id.'.'.$key} = $value;
7639: }
7640: #
7641: &Apache::lonnet::appenv(\%ValuesHash);
7642: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
7643: }
7644:
7645: ############################################################
7646: ############################################################
7647:
7648: =pod
7649:
7650: =item * &DrawXYYGraph()
7651:
7652: Facilitates the plotting of data in an XY graph with two Y axes.
7653: Puts plot definition data into the users environment in order for
7654: graph.png to plot it. Returns an <img> tag for the plot.
7655:
7656: Inputs:
7657:
7658: =over 4
7659:
7660: =item $Title: string, the title of the plot
7661:
7662: =item $xlabel: string, text describing the X-axis of the plot
7663:
7664: =item $ylabel: string, text describing the Y-axis of the plot
7665:
7666: =item $colors: Array ref containing the hex color codes for the data to be
7667: plotted in. If undefined, default values will be used.
7668:
7669: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
7670:
7671: =item $Ydata1: The first data set
7672:
7673: =item $Min1: The minimum value of the left Y-axis
7674:
7675: =item $Max1: The maximum value of the left Y-axis
7676:
7677: =item $Ydata2: The second data set
7678:
7679: =item $Min2: The minimum value of the right Y-axis
7680:
7681: =item $Max2: The maximum value of the left Y-axis
7682:
7683: =item %Values: hash indicating or overriding any default values which are
7684: passed to graph.png.
7685: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
7686:
7687: =back
7688:
7689: Returns:
7690:
7691: An <img> tag which references graph.png and the appropriate identifying
7692: information for the plot.
7693:
7694: =cut
7695:
7696: ############################################################
7697: ############################################################
7698: sub DrawXYYGraph {
7699: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
7700: $Ydata2,$Min2,$Max2,%Values)=@_;
7701: #
7702: # Create the identifier for the graph
7703: my $identifier = &get_cgi_id();
7704: my $id = 'cgi.'.$identifier;
7705: #
7706: $Title = '' if (! defined($Title));
7707: $xlabel = '' if (! defined($xlabel));
7708: $ylabel = '' if (! defined($ylabel));
7709: my %ValuesHash =
7710: (
7711: $id.'.title' => &escape($Title),
7712: $id.'.xlabel' => &escape($xlabel),
7713: $id.'.ylabel' => &escape($ylabel),
7714: $id.'.labels' => join(',',@$Xlabels),
7715: $id.'.PlotType' => 'XY',
7716: $id.'.NumSets' => 2,
7717: $id.'.two_axes' => 1,
7718: $id.'.y1_max_value' => $Max1,
7719: $id.'.y1_min_value' => $Min1,
7720: $id.'.y2_max_value' => $Max2,
7721: $id.'.y2_min_value' => $Min2,
7722: );
7723: #
7724: if (defined($colors) && ref($colors) eq 'ARRAY') {
7725: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
7726: }
7727: #
7728: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
7729: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
7730: return '';
7731: }
7732: my $NumSets=1;
7733: foreach my $array ($Ydata1,$Ydata2){
7734: next if (! ref($array));
7735: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
7736: }
7737: #
7738: # Deal with other parameters
7739: while (my ($key,$value) = each(%Values)) {
7740: $ValuesHash{$id.'.'.$key} = $value;
7741: }
7742: #
7743: &Apache::lonnet::appenv(\%ValuesHash);
7744: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
7745: }
7746:
7747: ############################################################
7748: ############################################################
7749:
7750: =pod
7751:
7752: =back
7753:
7754: =head1 Statistics helper routines?
7755:
7756: Bad place for them but what the hell.
7757:
7758: =over 4
7759:
7760: =item * &chartlink()
7761:
7762: Returns a link to the chart for a specific student.
7763:
7764: Inputs:
7765:
7766: =over 4
7767:
7768: =item $linktext: The text of the link
7769:
7770: =item $sname: The students username
7771:
7772: =item $sdomain: The students domain
7773:
7774: =back
7775:
7776: =back
7777:
7778: =cut
7779:
7780: ############################################################
7781: ############################################################
7782: sub chartlink {
7783: my ($linktext, $sname, $sdomain) = @_;
7784: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
7785: '&SelectedStudent='.&escape($sname.':'.$sdomain).
7786: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
7787: '">'.$linktext.'</a>';
7788: }
7789:
7790: #######################################################
7791: #######################################################
7792:
7793: =pod
7794:
7795: =head1 Course Environment Routines
7796:
7797: =over 4
7798:
7799: =item * &restore_course_settings()
7800:
7801: =item * &store_course_settings()
7802:
7803: Restores/Store indicated form parameters from the course environment.
7804: Will not overwrite existing values of the form parameters.
7805:
7806: Inputs:
7807: a scalar describing the data (e.g. 'chart', 'problem_analysis')
7808:
7809: a hash ref describing the data to be stored. For example:
7810:
7811: %Save_Parameters = ('Status' => 'scalar',
7812: 'chartoutputmode' => 'scalar',
7813: 'chartoutputdata' => 'scalar',
7814: 'Section' => 'array',
7815: 'Group' => 'array',
7816: 'StudentData' => 'array',
7817: 'Maps' => 'array');
7818:
7819: Returns: both routines return nothing
7820:
7821: =back
7822:
7823: =cut
7824:
7825: #######################################################
7826: #######################################################
7827: sub store_course_settings {
7828: return &store_settings($env{'request.course.id'},@_);
7829: }
7830:
7831: sub store_settings {
7832: # save to the environment
7833: # appenv the same items, just to be safe
7834: my $udom = $env{'user.domain'};
7835: my $uname = $env{'user.name'};
7836: my ($context,$prefix,$Settings) = @_;
7837: my %SaveHash;
7838: my %AppHash;
7839: while (my ($setting,$type) = each(%$Settings)) {
7840: my $basename = join('.','internal',$context,$prefix,$setting);
7841: my $envname = 'environment.'.$basename;
7842: if (exists($env{'form.'.$setting})) {
7843: # Save this value away
7844: if ($type eq 'scalar' &&
7845: (! exists($env{$envname}) ||
7846: $env{$envname} ne $env{'form.'.$setting})) {
7847: $SaveHash{$basename} = $env{'form.'.$setting};
7848: $AppHash{$envname} = $env{'form.'.$setting};
7849: } elsif ($type eq 'array') {
7850: my $stored_form;
7851: if (ref($env{'form.'.$setting})) {
7852: $stored_form = join(',',
7853: map {
7854: &escape($_);
7855: } sort(@{$env{'form.'.$setting}}));
7856: } else {
7857: $stored_form =
7858: &escape($env{'form.'.$setting});
7859: }
7860: # Determine if the array contents are the same.
7861: if ($stored_form ne $env{$envname}) {
7862: $SaveHash{$basename} = $stored_form;
7863: $AppHash{$envname} = $stored_form;
7864: }
7865: }
7866: }
7867: }
7868: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
7869: $udom,$uname);
7870: if ($put_result !~ /^(ok|delayed)/) {
7871: &Apache::lonnet::logthis('unable to save form parameters, '.
7872: 'got error:'.$put_result);
7873: }
7874: # Make sure these settings stick around in this session, too
7875: &Apache::lonnet::appenv(\%AppHash);
7876: return;
7877: }
7878:
7879: sub restore_course_settings {
7880: return &restore_settings($env{'request.course.id'},@_);
7881: }
7882:
7883: sub restore_settings {
7884: my ($context,$prefix,$Settings) = @_;
7885: while (my ($setting,$type) = each(%$Settings)) {
7886: next if (exists($env{'form.'.$setting}));
7887: my $envname = 'environment.internal.'.$context.'.'.$prefix.
7888: '.'.$setting;
7889: if (exists($env{$envname})) {
7890: if ($type eq 'scalar') {
7891: $env{'form.'.$setting} = $env{$envname};
7892: } elsif ($type eq 'array') {
7893: $env{'form.'.$setting} = [
7894: map {
7895: &unescape($_);
7896: } split(',',$env{$envname})
7897: ];
7898: }
7899: }
7900: }
7901: }
7902:
7903: #######################################################
7904: #######################################################
7905:
7906: =pod
7907:
7908: =head1 Domain E-mail Routines
7909:
7910: =over 4
7911:
7912: =item * &build_recipient_list()
7913:
7914: Build recipient lists for three types of e-mail:
7915: (a) Error Reports, (b) Package Updates, (c) Help requests, generated by
7916: lonerrorhandler.pm, CHECKRPMS and lonsupportreq.pm respectively.
7917:
7918: Inputs:
7919: defmail (scalar - email address of default recipient),
7920: mailing type (scalar - errormail, packagesmail, or helpdeskmail),
7921: defdom (domain for which to retrieve configuration settings),
7922: origmail (scalar - email address of recipient from loncapa.conf,
7923: i.e., predates configuration by DC via domainprefs.pm
7924:
7925: Returns: comma separated list of addresses to which to send e-mail.
7926:
7927: =cut
7928:
7929: ############################################################
7930: ############################################################
7931: sub build_recipient_list {
7932: my ($defmail,$mailing,$defdom,$origmail) = @_;
7933: my @recipients;
7934: my $otheremails;
7935: my %domconfig =
7936: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
7937: if (ref($domconfig{'contacts'}) eq 'HASH') {
7938: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
7939: my @contacts = ('adminemail','supportemail');
7940: foreach my $item (@contacts) {
7941: if ($domconfig{'contacts'}{$mailing}{$item}) {
7942: my $addr = $domconfig{'contacts'}{$item};
7943: if (!grep(/^\Q$addr\E$/,@recipients)) {
7944: push(@recipients,$addr);
7945: }
7946: }
7947: $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
7948: }
7949: }
7950: } elsif ($origmail ne '') {
7951: push(@recipients,$origmail);
7952: }
7953: if ($defmail ne '') {
7954: push(@recipients,$defmail);
7955: }
7956: if ($otheremails) {
7957: my @others;
7958: if ($otheremails =~ /,/) {
7959: @others = split(/,/,$otheremails);
7960: } else {
7961: push(@others,$otheremails);
7962: }
7963: foreach my $addr (@others) {
7964: if (!grep(/^\Q$addr\E$/,@recipients)) {
7965: push(@recipients,$addr);
7966: }
7967: }
7968: }
7969: my $recipientlist = join(',',@recipients);
7970: return $recipientlist;
7971: }
7972:
7973: ############################################################
7974: ############################################################
7975:
7976: sub commit_customrole {
7977: my ($udom,$uname,$url,$three,$four,$five,$start,$end) = @_;
7978: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
7979: ($start?', '.&mt('starting').' '.localtime($start):'').
7980: ($end?', ending '.localtime($end):'').': <b>'.
7981: &Apache::lonnet::assigncustomrole(
7982: $udom,$uname,$url,$three,$four,$five,$end,$start).
7983: '</b><br />';
7984: return $output;
7985: }
7986:
7987: sub commit_standardrole {
7988: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
7989: my ($output,$logmsg,$linefeed);
7990: if ($context eq 'auto') {
7991: $linefeed = "\n";
7992: } else {
7993: $linefeed = "<br />\n";
7994: }
7995: if ($three eq 'st') {
7996: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
7997: $one,$two,$sec,$context);
7998: if (($result =~ /^error/) || ($result eq 'not_in_class') ||
7999: ($result eq 'unknown_course') || ($result eq 'refused')) {
8000: $output = $logmsg.' '.&mt('Error: ').$result."\n";
8001: } else {
8002: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
8003: ($start?', '.&mt('starting').' '.localtime($start):'').
8004: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
8005: if ($context eq 'auto') {
8006: $output .= $result.$linefeed.&mt('Add to classlist').': ok';
8007: } else {
8008: $output .= '<b>'.$result.'</b>'.$linefeed.
8009: &mt('Add to classlist').': <b>ok</b>';
8010: }
8011: $output .= $linefeed;
8012: }
8013: } else {
8014: $output = &mt('Assigning').' '.$three.' in '.$url.
8015: ($start?', '.&mt('starting').' '.localtime($start):'').
8016: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
8017: my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start);
8018: if ($context eq 'auto') {
8019: $output .= $result.$linefeed;
8020: } else {
8021: $output .= '<b>'.$result.'</b>'.$linefeed;
8022: }
8023: }
8024: return $output;
8025: }
8026:
8027: sub commit_studentrole {
8028: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
8029: my ($result,$linefeed,$oldsecurl,$newsecurl);
8030: if ($context eq 'auto') {
8031: $linefeed = "\n";
8032: } else {
8033: $linefeed = '<br />'."\n";
8034: }
8035: if (defined($one) && defined($two)) {
8036: my $cid=$one.'_'.$two;
8037: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
8038: my $secchange = 0;
8039: my $expire_role_result;
8040: my $modify_section_result;
8041: if ($oldsec ne '-1') {
8042: if ($oldsec ne $sec) {
8043: $secchange = 1;
8044: my $now = time;
8045: my $uurl='/'.$cid;
8046: $uurl=~s/\_/\//g;
8047: if ($oldsec) {
8048: $uurl.='/'.$oldsec;
8049: }
8050: $oldsecurl = $uurl;
8051: $expire_role_result =
8052: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now);
8053: if ($env{'request.course.sec'} ne '') {
8054: if ($expire_role_result eq 'refused') {
8055: my @roles = ('st');
8056: my @statuses = ('previous');
8057: my @roledoms = ($one);
8058: my $withsec = 1;
8059: my %roleshash =
8060: &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
8061: \@statuses,\@roles,\@roledoms,$withsec);
8062: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
8063: my ($oldstart,$oldend) =
8064: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
8065: if ($oldend > 0 && $oldend <= $now) {
8066: $expire_role_result = 'ok';
8067: }
8068: }
8069: }
8070: }
8071: $result = $expire_role_result;
8072: }
8073: }
8074: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
8075: $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid);
8076: if ($modify_section_result =~ /^ok/) {
8077: if ($secchange == 1) {
8078: if ($sec eq '') {
8079: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
8080: } else {
8081: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
8082: }
8083: } elsif ($oldsec eq '-1') {
8084: if ($sec eq '') {
8085: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
8086: } else {
8087: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
8088: }
8089: } else {
8090: if ($sec eq '') {
8091: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
8092: } else {
8093: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
8094: }
8095: }
8096: } else {
8097: if ($secchange) {
8098: $$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;
8099: } else {
8100: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
8101: }
8102: }
8103: $result = $modify_section_result;
8104: } elsif ($secchange == 1) {
8105: if ($oldsec eq '') {
8106: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
8107: } else {
8108: $$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;
8109: }
8110: if ($expire_role_result eq 'refused') {
8111: my $newsecurl = '/'.$cid;
8112: $newsecurl =~ s/\_/\//g;
8113: if ($sec ne '') {
8114: $newsecurl.='/'.$sec;
8115: }
8116: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
8117: if ($sec eq '') {
8118: $$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;
8119: } else {
8120: $$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;
8121: }
8122: }
8123: }
8124: }
8125: } else {
8126: $$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;
8127: $result = "error: incomplete course id\n";
8128: }
8129: return $result;
8130: }
8131:
8132: ############################################################
8133: ############################################################
8134:
8135: sub check_clone {
8136: my ($args,$linefeed) = @_;
8137: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
8138: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
8139: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
8140: my $clonemsg;
8141: my $can_clone = 0;
8142:
8143: if ($clonehome eq 'no_host') {
8144: $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'});
8145: } else {
8146: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
8147: if ($env{'request.role.domain'} eq $args->{'clonedomain'}) {
8148: $can_clone = 1;
8149: } else {
8150: my %clonehash = &Apache::lonnet::get('environment',['cloners'],
8151: $args->{'clonedomain'},$args->{'clonecourse'});
8152: my @cloners = split(/,/,$clonehash{'cloners'});
8153: if (grep(/^\*$/,@cloners)) {
8154: $can_clone = 1;
8155: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
8156: $can_clone = 1;
8157: } else {
8158: my %roleshash =
8159: &Apache::lonnet::get_my_roles($args->{'ccuname'},
8160: $args->{'ccdomain'},
8161: 'userroles',['active'],['cc'],
8162: [$args->{'clonedomain'}]);
8163: if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
8164: $can_clone = 1;
8165: } else {
8166: $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'});
8167: }
8168: }
8169: }
8170: }
8171: return ($can_clone, $clonemsg, $cloneid, $clonehome);
8172: }
8173:
8174: sub construct_course {
8175: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context) = @_;
8176: my $outcome;
8177: my $linefeed = '<br />'."\n";
8178: if ($context eq 'auto') {
8179: $linefeed = "\n";
8180: }
8181:
8182: #
8183: # Are we cloning?
8184: #
8185: my ($can_clone, $clonemsg, $cloneid, $clonehome);
8186: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
8187: ($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
8188: if ($context ne 'auto') {
8189: if ($clonemsg ne '') {
8190: $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
8191: }
8192: }
8193: $outcome .= $clonemsg.$linefeed;
8194:
8195: if (!$can_clone) {
8196: return (0,$outcome);
8197: }
8198: }
8199:
8200: #
8201: # Open course
8202: #
8203: my $crstype = lc($args->{'crstype'});
8204: my %cenv=();
8205: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
8206: $args->{'cdescr'},
8207: $args->{'curl'},
8208: $args->{'course_home'},
8209: $args->{'nonstandard'},
8210: $args->{'crscode'},
8211: $args->{'ccuname'}.':'.
8212: $args->{'ccdomain'},
8213: $args->{'crstype'});
8214:
8215: # Note: The testing routines depend on this being output; see
8216: # Utils::Course. This needs to at least be output as a comment
8217: # if anyone ever decides to not show this, and Utils::Course::new
8218: # will need to be suitably modified.
8219: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
8220: #
8221: # Check if created correctly
8222: #
8223: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
8224: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
8225: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
8226:
8227: #
8228: # Do the cloning
8229: #
8230: if ($can_clone && $cloneid) {
8231: $clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
8232: if ($context ne 'auto') {
8233: $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
8234: }
8235: $outcome .= $clonemsg.$linefeed;
8236: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
8237: # Copy all files
8238: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
8239: # Restore URL
8240: $cenv{'url'}=$oldcenv{'url'};
8241: # Restore title
8242: $cenv{'description'}=$oldcenv{'description'};
8243: # Mark as cloned
8244: $cenv{'clonedfrom'}=$cloneid;
8245: # Need to clone grading mode
8246: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
8247: $cenv{'grading'}=$newenv{'grading'};
8248: # Do not clone these environment entries
8249: &Apache::lonnet::del('environment',
8250: ['default_enrollment_start_date',
8251: 'default_enrollment_end_date',
8252: 'question.email',
8253: 'policy.email',
8254: 'comment.email',
8255: 'pch.users.denied',
8256: 'plc.users.denied'],
8257: $$crsudom,$$crsunum);
8258: }
8259:
8260: #
8261: # Set environment (will override cloned, if existing)
8262: #
8263: my @sections = ();
8264: my @xlists = ();
8265: if ($args->{'crstype'}) {
8266: $cenv{'type'}=$args->{'crstype'};
8267: }
8268: if ($args->{'crsid'}) {
8269: $cenv{'courseid'}=$args->{'crsid'};
8270: }
8271: if ($args->{'crscode'}) {
8272: $cenv{'internal.coursecode'}=$args->{'crscode'};
8273: }
8274: if ($args->{'crsquota'} ne '') {
8275: $cenv{'internal.coursequota'}=$args->{'crsquota'};
8276: } else {
8277: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
8278: }
8279: if ($args->{'ccuname'}) {
8280: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
8281: ':'.$args->{'ccdomain'};
8282: } else {
8283: $cenv{'internal.courseowner'} = $args->{'curruser'};
8284: }
8285: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
8286: if ($args->{'crssections'}) {
8287: $cenv{'internal.sectionnums'} = '';
8288: if ($args->{'crssections'} =~ m/,/) {
8289: @sections = split/,/,$args->{'crssections'};
8290: } else {
8291: $sections[0] = $args->{'crssections'};
8292: }
8293: if (@sections > 0) {
8294: foreach my $item (@sections) {
8295: my ($sec,$gp) = split/:/,$item;
8296: my $class = $args->{'crscode'}.$sec;
8297: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
8298: $cenv{'internal.sectionnums'} .= $item.',';
8299: unless ($addcheck eq 'ok') {
8300: push @badclasses, $class;
8301: }
8302: }
8303: $cenv{'internal.sectionnums'} =~ s/,$//;
8304: }
8305: }
8306: # do not hide course coordinator from staff listing,
8307: # even if privileged
8308: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
8309: # add crosslistings
8310: if ($args->{'crsxlist'}) {
8311: $cenv{'internal.crosslistings'}='';
8312: if ($args->{'crsxlist'} =~ m/,/) {
8313: @xlists = split/,/,$args->{'crsxlist'};
8314: } else {
8315: $xlists[0] = $args->{'crsxlist'};
8316: }
8317: if (@xlists > 0) {
8318: foreach my $item (@xlists) {
8319: my ($xl,$gp) = split/:/,$item;
8320: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
8321: $cenv{'internal.crosslistings'} .= $item.',';
8322: unless ($addcheck eq 'ok') {
8323: push @badclasses, $xl;
8324: }
8325: }
8326: $cenv{'internal.crosslistings'} =~ s/,$//;
8327: }
8328: }
8329: if ($args->{'autoadds'}) {
8330: $cenv{'internal.autoadds'}=$args->{'autoadds'};
8331: }
8332: if ($args->{'autodrops'}) {
8333: $cenv{'internal.autodrops'}=$args->{'autodrops'};
8334: }
8335: # check for notification of enrollment changes
8336: my @notified = ();
8337: if ($args->{'notify_owner'}) {
8338: if ($args->{'ccuname'} ne '') {
8339: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
8340: }
8341: }
8342: if ($args->{'notify_dc'}) {
8343: if ($uname ne '') {
8344: push(@notified,$uname.':'.$udom);
8345: }
8346: }
8347: if (@notified > 0) {
8348: my $notifylist;
8349: if (@notified > 1) {
8350: $notifylist = join(',',@notified);
8351: } else {
8352: $notifylist = $notified[0];
8353: }
8354: $cenv{'internal.notifylist'} = $notifylist;
8355: }
8356: if (@badclasses > 0) {
8357: my %lt=&Apache::lonlocal::texthash(
8358: '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',
8359: 'dnhr' => 'does not have rights to access enrollment in these classes',
8360: 'adby' => 'as determined by the policies of your institution on access to official classlists'
8361: );
8362: my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
8363: ' ('.$lt{'adby'}.')';
8364: if ($context eq 'auto') {
8365: $outcome .= $badclass_msg.$linefeed;
8366: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
8367: foreach my $item (@badclasses) {
8368: if ($context eq 'auto') {
8369: $outcome .= " - $item\n";
8370: } else {
8371: $outcome .= "<li>$item</li>\n";
8372: }
8373: }
8374: if ($context eq 'auto') {
8375: $outcome .= $linefeed;
8376: } else {
8377: $outcome .= "</ul><br /><br /></div>\n";
8378: }
8379: }
8380: }
8381: if ($args->{'no_end_date'}) {
8382: $args->{'endaccess'} = 0;
8383: }
8384: $cenv{'internal.autostart'}=$args->{'enrollstart'};
8385: $cenv{'internal.autoend'}=$args->{'enrollend'};
8386: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
8387: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
8388: if ($args->{'showphotos'}) {
8389: $cenv{'internal.showphotos'}=$args->{'showphotos'};
8390: }
8391: $cenv{'internal.authtype'} = $args->{'authtype'};
8392: $cenv{'internal.autharg'} = $args->{'autharg'};
8393: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
8394: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
8395: 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');
8396: if ($context eq 'auto') {
8397: $outcome .= $krb_msg;
8398: } else {
8399: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
8400: }
8401: $outcome .= $linefeed;
8402: }
8403: }
8404: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
8405: if ($args->{'setpolicy'}) {
8406: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
8407: }
8408: if ($args->{'setcontent'}) {
8409: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
8410: }
8411: }
8412: if ($args->{'reshome'}) {
8413: $cenv{'reshome'}=$args->{'reshome'}.'/';
8414: $cenv{'reshome'}=~s/\/+$/\//;
8415: }
8416: #
8417: # course has keyed access
8418: #
8419: if ($args->{'setkeys'}) {
8420: $cenv{'keyaccess'}='yes';
8421: }
8422: # if specified, key authority is not course, but user
8423: # only active if keyaccess is yes
8424: if ($args->{'keyauth'}) {
8425: my ($user,$domain) = split(':',$args->{'keyauth'});
8426: $user = &LONCAPA::clean_username($user);
8427: $domain = &LONCAPA::clean_username($domain);
8428: if ($user ne '' && $domain ne '') {
8429: $cenv{'keyauth'}=$user.':'.$domain;
8430: }
8431: }
8432:
8433: if ($args->{'disresdis'}) {
8434: $cenv{'pch.roles.denied'}='st';
8435: }
8436: if ($args->{'disablechat'}) {
8437: $cenv{'plc.roles.denied'}='st';
8438: }
8439:
8440: # Record we've not yet viewed the Course Initialization Helper for this
8441: # course
8442: $cenv{'course.helper.not.run'} = 1;
8443: #
8444: # Use new Randomseed
8445: #
8446: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
8447: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
8448: #
8449: # The encryption code and receipt prefix for this course
8450: #
8451: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
8452: $cenv{'internal.encpref'}=100+int(9*rand(99));
8453: #
8454: # By default, use standard grading
8455: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
8456:
8457: $outcome .= $linefeed.&mt('Setting environment').': '.
8458: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
8459: #
8460: # Open all assignments
8461: #
8462: if ($args->{'openall'}) {
8463: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
8464: my %storecontent = ($storeunder => time,
8465: $storeunder.'.type' => 'date_start');
8466:
8467: $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
8468: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
8469: }
8470: #
8471: # Set first page
8472: #
8473: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
8474: || ($cloneid)) {
8475: use LONCAPA::map;
8476: $outcome .= &mt('Setting first resource').': ';
8477:
8478: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
8479: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
8480:
8481: $outcome .= ($fatal?$errtext:'read ok').' - ';
8482: my $title; my $url;
8483: if ($args->{'firstres'} eq 'syl') {
8484: $title='Syllabus';
8485: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
8486: } else {
8487: $title='Navigate Contents';
8488: $url='/adm/navmaps';
8489: }
8490:
8491: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
8492: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
8493:
8494: if ($errtext) { $fatal=2; }
8495: $outcome .= ($fatal?$errtext:'write ok').$linefeed;
8496: }
8497:
8498: return (1,$outcome);
8499: }
8500:
8501: ############################################################
8502: ############################################################
8503:
8504: sub course_type {
8505: my ($cid) = @_;
8506: if (!defined($cid)) {
8507: $cid = $env{'request.course.id'};
8508: }
8509: if (defined($env{'course.'.$cid.'.type'})) {
8510: return $env{'course.'.$cid.'.type'};
8511: } else {
8512: return 'Course';
8513: }
8514: }
8515:
8516: sub group_term {
8517: my $crstype = &course_type();
8518: my %names = (
8519: 'Course' => 'group',
8520: 'Group' => 'team',
8521: );
8522: return $names{$crstype};
8523: }
8524:
8525: sub icon {
8526: my ($file)=@_;
8527: my $curfext = lc((split(/\./,$file))[-1]);
8528: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
8529: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
8530: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
8531: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
8532: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
8533: $curfext.".gif") {
8534: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
8535: $curfext.".gif";
8536: }
8537: }
8538: return &lonhttpdurl($iconname);
8539: }
8540:
8541: sub lonhttpd_port {
8542: my $lonhttpd_port=$Apache::lonnet::perlvar{'lonhttpdPort'};
8543: if (!defined($lonhttpd_port)) { $lonhttpd_port='8080'; }
8544: # IE doesn't like a secure page getting images from a non-secure
8545: # port (when logging we haven't parsed the browser type so default
8546: # back to secure
8547: if ((!exists($env{'browser.type'}) || $env{'browser.type'} eq 'explorer')
8548: && $ENV{'SERVER_PORT'} == 443) {
8549: return 443;
8550: }
8551: return $lonhttpd_port;
8552:
8553: }
8554:
8555: sub lonhttpdurl {
8556: my ($url)=@_;
8557:
8558: my $lonhttpd_port = &lonhttpd_port();
8559: if ($lonhttpd_port == 443) {
8560: return 'https://'.$ENV{'SERVER_NAME'}.$url;
8561: }
8562: return 'http://'.$ENV{'SERVER_NAME'}.':'.$lonhttpd_port.$url;
8563: }
8564:
8565: sub connection_aborted {
8566: my ($r)=@_;
8567: $r->print(" ");$r->rflush();
8568: my $c = $r->connection;
8569: return $c->aborted();
8570: }
8571:
8572: # Escapes strings that may have embedded 's that will be put into
8573: # strings as 'strings'.
8574: sub escape_single {
8575: my ($input) = @_;
8576: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
8577: $input =~ s/\'/\\\'/g; # Esacpe the 's....
8578: return $input;
8579: }
8580:
8581: # Same as escape_single, but escape's "'s This
8582: # can be used for "strings"
8583: sub escape_double {
8584: my ($input) = @_;
8585: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
8586: $input =~ s/\"/\\\"/g; # Esacpe the "s....
8587: return $input;
8588: }
8589:
8590: # Escapes the last element of a full URL.
8591: sub escape_url {
8592: my ($url) = @_;
8593: my @urlslices = split(/\//, $url,-1);
8594: my $lastitem = &escape(pop(@urlslices));
8595: return join('/',@urlslices).'/'.$lastitem;
8596: }
8597:
8598: # -------------------------------------------------------- Initliaze user login
8599: sub init_user_environment {
8600: my ($r, $username, $domain, $authhost, $form, $args) = @_;
8601: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
8602:
8603: my $public=($username eq 'public' && $domain eq 'public');
8604:
8605: # See if old ID present, if so, remove
8606:
8607: my ($filename,$cookie,$userroles);
8608: my $now=time;
8609:
8610: if ($public) {
8611: my $max_public=100;
8612: my $oldest;
8613: my $oldest_time=0;
8614: for(my $next=1;$next<=$max_public;$next++) {
8615: if (-e $lonids."/publicuser_$next.id") {
8616: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
8617: if ($mtime<$oldest_time || !$oldest_time) {
8618: $oldest_time=$mtime;
8619: $oldest=$next;
8620: }
8621: } else {
8622: $cookie="publicuser_$next";
8623: last;
8624: }
8625: }
8626: if (!$cookie) { $cookie="publicuser_$oldest"; }
8627: } else {
8628: # if this isn't a robot, kill any existing non-robot sessions
8629: if (!$args->{'robot'}) {
8630: opendir(DIR,$lonids);
8631: while ($filename=readdir(DIR)) {
8632: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
8633: unlink($lonids.'/'.$filename);
8634: }
8635: }
8636: closedir(DIR);
8637: }
8638: # Give them a new cookie
8639: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
8640: : $now);
8641: $cookie="$username\_$id\_$domain\_$authhost";
8642:
8643: # Initialize roles
8644:
8645: $userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
8646: }
8647: # ------------------------------------ Check browser type and MathML capability
8648:
8649: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
8650: $clientunicode,$clientos) = &decode_user_agent($r);
8651:
8652: # -------------------------------------- Any accessibility options to remember?
8653: if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
8654: foreach my $option ('imagesuppress','appletsuppress',
8655: 'embedsuppress','fontenhance','blackwhite') {
8656: if ($form->{$option} eq 'true') {
8657: &Apache::lonnet::put('environment',{$option => 'on'},
8658: $domain,$username);
8659: } else {
8660: &Apache::lonnet::del('environment',[$option],
8661: $domain,$username);
8662: }
8663: }
8664: }
8665: # ------------------------------------------------------------- Get environment
8666:
8667: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
8668: my ($tmp) = keys(%userenv);
8669: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
8670: # default remote control to off
8671: if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
8672: } else {
8673: undef(%userenv);
8674: }
8675: if (($userenv{'interface'}) && (!$form->{'interface'})) {
8676: $form->{'interface'}=$userenv{'interface'};
8677: }
8678: $env{'environment.remote'}=$userenv{'remote'};
8679: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
8680:
8681: # --------------- Do not trust query string to be put directly into environment
8682: foreach my $option ('imagesuppress','appletsuppress',
8683: 'embedsuppress','fontenhance','blackwhite',
8684: 'interface','localpath','localres') {
8685: $form->{$option}=~s/[\n\r\=]//gs;
8686: }
8687: # --------------------------------------------------------- Write first profile
8688:
8689: {
8690: my %initial_env =
8691: ("user.name" => $username,
8692: "user.domain" => $domain,
8693: "user.home" => $authhost,
8694: "browser.type" => $clientbrowser,
8695: "browser.version" => $clientversion,
8696: "browser.mathml" => $clientmathml,
8697: "browser.unicode" => $clientunicode,
8698: "browser.os" => $clientos,
8699: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
8700: "request.course.fn" => '',
8701: "request.course.uri" => '',
8702: "request.course.sec" => '',
8703: "request.role" => 'cm',
8704: "request.role.adv" => $env{'user.adv'},
8705: "request.host" => $ENV{'REMOTE_ADDR'},);
8706:
8707: if ($form->{'localpath'}) {
8708: $initial_env{"browser.localpath"} = $form->{'localpath'};
8709: $initial_env{"browser.localres"} = $form->{'localres'};
8710: }
8711:
8712: if ($public) {
8713: $initial_env{"environment.remote"} = "off";
8714: }
8715: if ($form->{'interface'}) {
8716: $form->{'interface'}=~s/\W//gs;
8717: $initial_env{"browser.interface"} = $form->{'interface'};
8718: $env{'browser.interface'}=$form->{'interface'};
8719: foreach my $option ('imagesuppress','appletsuppress',
8720: 'embedsuppress','fontenhance','blackwhite') {
8721: if (($form->{$option} eq 'true') ||
8722: ($userenv{$option} eq 'on')) {
8723: $initial_env{"browser.$option"} = "on";
8724: }
8725: }
8726: }
8727:
8728: $env{'user.environment'} = "$lonids/$cookie.id";
8729:
8730: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
8731: &GDBM_WRCREAT(),0640)) {
8732: &_add_to_env(\%disk_env,\%initial_env);
8733: &_add_to_env(\%disk_env,\%userenv,'environment.');
8734: &_add_to_env(\%disk_env,$userroles);
8735: if (ref($args->{'extra_env'})) {
8736: &_add_to_env(\%disk_env,$args->{'extra_env'});
8737: }
8738: untie(%disk_env);
8739: } else {
8740: &Apache::lonnet::logthis("<font color=\"blue\">WARNING: ".
8741: 'Could not create environment storage in lonauth: '.$!.'</font>');
8742: return 'error: '.$!;
8743: }
8744: }
8745: $env{'request.role'}='cm';
8746: $env{'request.role.adv'}=$env{'user.adv'};
8747: $env{'browser.type'}=$clientbrowser;
8748:
8749: return $cookie;
8750:
8751: }
8752:
8753: sub _add_to_env {
8754: my ($idf,$env_data,$prefix) = @_;
8755: while (my ($key,$value) = each(%$env_data)) {
8756: $idf->{$prefix.$key} = $value;
8757: $env{$prefix.$key} = $value;
8758: }
8759: }
8760:
8761:
8762: =pod
8763:
8764: =back
8765:
8766: =cut
8767:
8768: 1;
8769: __END__;
8770:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>