1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.476 2006/11/29 19:33:29 raeburn Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29: # Makes a table out of the previous attempts
30: # Inputs result_from_symbread, user, domain, course_id
31: # Reads in non-network-related .tab files
32:
33: # POD header:
34:
35: =pod
36:
37: =head1 NAME
38:
39: Apache::loncommon - pile of common routines
40:
41: =head1 SYNOPSIS
42:
43: Common routines for manipulating connections, student answers,
44: domains, common Javascript fragments, etc.
45:
46: =head1 OVERVIEW
47:
48: A collection of commonly used subroutines that don't have a natural
49: home anywhere else. This collection helps remove
50: redundancy from other modules and increase efficiency of memory usage.
51:
52: =cut
53:
54: # End of POD header
55: package Apache::loncommon;
56:
57: use strict;
58: use Apache::lonnet;
59: use GDBM_File;
60: use POSIX qw(strftime mktime);
61: use Apache::lonmenu();
62: use Apache::lonlocal;
63: use HTML::Entities;
64: use Apache::lonhtmlcommon();
65: use Apache::loncoursedata();
66: use Apache::lontexconvert();
67: use Apache::lonclonecourse();
68: use LONCAPA;
69:
70: my $readit;
71:
72: ##
73: ## Global Variables
74: ##
75:
76: # ----------------------------------------------- Filetypes/Languages/Copyright
77: my %language;
78: my %supported_language;
79: my %cprtag;
80: my %scprtag;
81: my %fe; my %fd; my %fm;
82: my %category_extensions;
83:
84: # ---------------------------------------------- Designs
85:
86: my %designhash;
87:
88: # ---------------------------------------------- Thesaurus variables
89: #
90: # %Keywords:
91: # A hash used by &keyword to determine if a word is considered a keyword.
92: # $thesaurus_db_file
93: # Scalar containing the full path to the thesaurus database.
94:
95: my %Keywords;
96: my $thesaurus_db_file;
97:
98: #
99: # Initialize values from language.tab, copyright.tab, filetypes.tab,
100: # thesaurus.tab, and filecategories.tab.
101: #
102: BEGIN {
103: # Variable initialization
104: $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
105: #
106: unless ($readit) {
107: # ------------------------------------------------------------------- languages
108: {
109: my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
110: '/language.tab';
111: if ( open(my $fh,"<$langtabfile") ) {
112: while (my $line = <$fh>) {
113: next if ($line=~/^\#/);
114: chomp($line);
115: my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
116: $language{$key}=$val.' - '.$enc;
117: if ($sup) {
118: $supported_language{$key}=$sup;
119: }
120: }
121: close($fh);
122: }
123: }
124: # ------------------------------------------------------------------ copyrights
125: {
126: my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
127: '/copyright.tab';
128: if ( open (my $fh,"<$copyrightfile") ) {
129: while (my $line = <$fh>) {
130: next if ($line=~/^\#/);
131: chomp($line);
132: my ($key,$val)=(split(/\s+/,$line,2));
133: $cprtag{$key}=$val;
134: }
135: close($fh);
136: }
137: }
138: # ----------------------------------------------------------- source copyrights
139: {
140: my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
141: '/source_copyright.tab';
142: if ( open (my $fh,"<$sourcecopyrightfile") ) {
143: while (my $line = <$fh>) {
144: next if ($line =~ /^\#/);
145: chomp($line);
146: my ($key,$val)=(split(/\s+/,$line,2));
147: $scprtag{$key}=$val;
148: }
149: close($fh);
150: }
151: }
152:
153: # -------------------------------------------------------------- domain designs
154:
155: my $filename;
156: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
157: opendir(DIR,$designdir);
158: while ($filename=readdir(DIR)) {
159: if ($filename!~/\.tab$/) { next; }
160: my ($domain)=($filename=~/^(\w+)\./);
161: {
162: my $designfile = $designdir.'/'.$filename;
163: if ( open (my $fh,"<$designfile") ) {
164: while (my $line = <$fh>) {
165: next if ($line =~ /^\#/);
166: chomp($line);
167: my ($key,$val)=(split(/\=/,$line));
168: if ($val) { $designhash{$domain.'.'.$key}=$val; }
169: }
170: close($fh);
171: }
172: }
173:
174: }
175: closedir(DIR);
176:
177:
178: # ------------------------------------------------------------- file categories
179: {
180: my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
181: '/filecategories.tab';
182: if ( open (my $fh,"<$categoryfile") ) {
183: while (my $line = <$fh>) {
184: next if ($line =~ /^\#/);
185: chomp($line);
186: my ($extension,$category)=(split(/\s+/,$line,2));
187: push @{$category_extensions{lc($category)}},$extension;
188: }
189: close($fh);
190: }
191:
192: }
193: # ------------------------------------------------------------------ file types
194: {
195: my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
196: '/filetypes.tab';
197: if ( open (my $fh,"<$typesfile") ) {
198: while (my $line = <$fh>) {
199: next if ($line =~ /^\#/);
200: chomp($line);
201: my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
202: if ($descr ne '') {
203: $fe{$ending}=lc($emb);
204: $fd{$ending}=$descr;
205: if ($mime ne 'unk') { $fm{$ending}=$mime; }
206: }
207: }
208: close($fh);
209: }
210: }
211: &Apache::lonnet::logthis(
212: "<font color=yellow>INFO: Read file types</font>");
213: $readit=1;
214: } # end of unless($readit)
215:
216: }
217:
218: ###############################################################
219: ## HTML and Javascript Helper Functions ##
220: ###############################################################
221:
222: =pod
223:
224: =head1 HTML and Javascript Functions
225:
226: =over 4
227:
228: =item * browser_and_searcher_javascript ()
229:
230: X<browsing, javascript>X<searching, javascript>Returns a string
231: containing javascript with two functions, C<openbrowser> and
232: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
233: tags.
234:
235: =item * openbrowser(formname,elementname,only,omit) [javascript]
236:
237: inputs: formname, elementname, only, omit
238:
239: formname and elementname indicate the name of the html form and name of
240: the element that the results of the browsing selection are to be placed in.
241:
242: Specifying 'only' will restrict the browser to displaying only files
243: with the given extension. Can be a comma separated list.
244:
245: Specifying 'omit' will restrict the browser to NOT displaying files
246: with the given extension. Can be a comma separated list.
247:
248: =item * opensearcher(formname, elementname) [javascript]
249:
250: Inputs: formname, elementname
251:
252: formname and elementname specify the name of the html form and the name
253: of the element the selection from the search results will be placed in.
254:
255: =cut
256:
257: sub browser_and_searcher_javascript {
258: my ($mode)=@_;
259: if (!defined($mode)) { $mode='edit'; }
260: my $resurl=&escape_single(&lastresurl());
261: return <<END;
262: // <!-- BEGIN LON-CAPA Internal
263: var editbrowser = null;
264: function openbrowser(formname,elementname,only,omit,titleelement) {
265: var url = '$resurl/?';
266: if (editbrowser == null) {
267: url += 'launch=1&';
268: }
269: url += 'catalogmode=interactive&';
270: url += 'mode=$mode&';
271: url += 'form=' + formname + '&';
272: if (only != null) {
273: url += 'only=' + only + '&';
274: } else {
275: url += 'only=&';
276: }
277: if (omit != null) {
278: url += 'omit=' + omit + '&';
279: } else {
280: url += 'omit=&';
281: }
282: if (titleelement != null) {
283: url += 'titleelement=' + titleelement + '&';
284: } else {
285: url += 'titleelement=&';
286: }
287: url += 'element=' + elementname + '';
288: var title = 'Browser';
289: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
290: options += ',width=700,height=600';
291: editbrowser = open(url,title,options,'1');
292: editbrowser.focus();
293: }
294: var editsearcher;
295: function opensearcher(formname,elementname,titleelement) {
296: var url = '/adm/searchcat?';
297: if (editsearcher == null) {
298: url += 'launch=1&';
299: }
300: url += 'catalogmode=interactive&';
301: url += 'mode=$mode&';
302: url += 'form=' + formname + '&';
303: if (titleelement != null) {
304: url += 'titleelement=' + titleelement + '&';
305: } else {
306: url += 'titleelement=&';
307: }
308: url += 'element=' + elementname + '';
309: var title = 'Search';
310: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
311: options += ',width=700,height=600';
312: editsearcher = open(url,title,options,'1');
313: editsearcher.focus();
314: }
315: // END LON-CAPA Internal -->
316: END
317: }
318:
319: sub lastresurl {
320: if ($env{'environment.lastresurl'}) {
321: return $env{'environment.lastresurl'}
322: } else {
323: return '/res';
324: }
325: }
326:
327: sub storeresurl {
328: my $resurl=&Apache::lonnet::clutter(shift);
329: unless ($resurl=~/^\/res/) { return 0; }
330: $resurl=~s/\/$//;
331: &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
332: &Apache::lonnet::appenv('environment.lastresurl' => $resurl);
333: return 1;
334: }
335:
336: sub studentbrowser_javascript {
337: unless (
338: (($env{'request.course.id'}) &&
339: (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
340: || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
341: '/'.$env{'request.course.sec'})
342: ))
343: || ($env{'request.role'}=~/^(au|dc|su)/)
344: ) { return ''; }
345: return (<<'ENDSTDBRW');
346: <script type="text/javascript" language="Javascript" >
347: var stdeditbrowser;
348: function openstdbrowser(formname,uname,udom,roleflag) {
349: var url = '/adm/pickstudent?';
350: var filter;
351: eval('filter=document.'+formname+'.'+uname+'.value;');
352: if (filter != null) {
353: if (filter != '') {
354: url += 'filter='+filter+'&';
355: }
356: }
357: url += 'form=' + formname + '&unameelement='+uname+
358: '&udomelement='+udom;
359: if (roleflag) { url+="&roles=1"; }
360: var title = 'Student_Browser';
361: var options = 'scrollbars=1,resizable=1,menubar=0';
362: options += ',width=700,height=600';
363: stdeditbrowser = open(url,title,options,'1');
364: stdeditbrowser.focus();
365: }
366: </script>
367: ENDSTDBRW
368: }
369:
370: sub selectstudent_link {
371: my ($form,$unameele,$udomele)=@_;
372: if ($env{'request.course.id'}) {
373: if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
374: && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
375: '/'.$env{'request.course.sec'})) {
376: return '';
377: }
378: return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
379: '","'.$udomele.'");'."'>".&mt('Select User')."</a>";
380: }
381: if ($env{'request.role'}=~/^(au|dc|su)/) {
382: return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
383: '","'.$udomele.'",1);'."'>".&mt('Select User')."</a>";
384: }
385: return '';
386: }
387:
388: sub coursebrowser_javascript {
389: my ($domainfilter,$sec_element,$formname)=@_;
390: 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');
391: my $output = '
392: <script type="text/javascript" language="Javascript" >
393: var stdeditbrowser;'."\n";
394: $output .= <<"ENDSTDBRW";
395: function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,crstype) {
396: var url = '/adm/pickcourse?';
397: var domainfilter = '';
398: var formid = getFormIdByName(formname);
399: if (formid > -1) {
400: var domid = getIndexByName(formid,udom);
401: if (domid > -1) {
402: if (document.forms[formid].elements[domid].type == 'select-one') {
403: domainfilter=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
404: }
405: if (document.forms[formid].elements[domid].type == 'hidden') {
406: domainfilter=document.forms[formid].elements[domid].value;
407: }
408: }
409: }
410: if (domainfilter != null) {
411: if (domainfilter != '') {
412: url += 'domainfilter='+domainfilter+'&';
413: }
414: }
415: url += 'form=' + formname + '&cnumelement='+uname+
416: '&cdomelement='+udom+
417: '&cnameelement='+desc;
418: if (extra_element !=null && extra_element != '') {
419: if (formname == 'rolechoice') {
420: url += '&roleelement='+extra_element;
421: if (domainfilter == null || domainfilter == '') {
422: url += '&domainfilter='+extra_element;
423: }
424: }
425: else {
426: if (formname == 'portform') {
427: url += '&setroles='+extra_element;
428: }
429: }
430: }
431: if (multflag !=null && multflag != '') {
432: url += '&multiple='+multflag;
433: }
434: if (crstype == 'Course/Group') {
435: if (formname == 'cu') {
436: crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value;
437: if (crstype == "") {
438: alert("$crs_or_grp_alert");
439: return;
440: }
441: }
442: }
443: if (crstype !=null && crstype != '') {
444: url += '&type='+crstype;
445: }
446: var title = 'Course_Browser';
447: var options = 'scrollbars=1,resizable=1,menubar=0';
448: options += ',width=700,height=600';
449: stdeditbrowser = open(url,title,options,'1');
450: stdeditbrowser.focus();
451: }
452:
453: function getFormIdByName(formname) {
454: for (var i=0;i<document.forms.length;i++) {
455: if (document.forms[i].name == formname) {
456: return i;
457: }
458: }
459: return -1;
460: }
461:
462: function getIndexByName(formid,item) {
463: for (var i=0;i<document.forms[formid].elements.length;i++) {
464: if (document.forms[formid].elements[i].name == item) {
465: return i;
466: }
467: }
468: return -1;
469: }
470: ENDSTDBRW
471: if ($sec_element ne '') {
472: $output .= &setsec_javascript($sec_element,$formname);
473: }
474: $output .= '
475: </script>';
476: return $output;
477: }
478:
479: sub setsec_javascript {
480: my ($sec_element,$formname) = @_;
481: my $setsections = qq|
482: function setSect(sectionlist) {
483: var sectionsArray = sectionlist.split(",");
484: var numSections = sectionsArray.length;
485: document.$formname.$sec_element.length = 0;
486: if (numSections == 0) {
487: document.$formname.$sec_element.multiple=false;
488: document.$formname.$sec_element.size=1;
489: document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
490: } else {
491: if (numSections == 1) {
492: document.$formname.$sec_element.multiple=false;
493: document.$formname.$sec_element.size=1;
494: document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
495: document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
496: document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
497: } else {
498: for (var i=0; i<numSections; i++) {
499: document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
500: }
501: document.$formname.$sec_element.multiple=true
502: if (numSections < 3) {
503: document.$formname.$sec_element.size=numSections;
504: } else {
505: document.$formname.$sec_element.size=3;
506: }
507: document.$formname.$sec_element.options[0].selected = false
508: }
509: }
510: }
511: |;
512: return $setsections;
513: }
514:
515:
516: sub selectcourse_link {
517: my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
518: return "<a href='".'javascript:opencrsbrowser("'.$form.'","'.$unameele.
519: '","'.$udomele.'","'.$desc.'","'.$extra_element.'","'.$multflag.'","'.$selecttype.'");'."'>".&mt('Select [_1]',$selecttype)."</a>";
520: }
521:
522: sub check_uncheck_jscript {
523: my $jscript = <<"ENDSCRT";
524: function checkAll(field) {
525: if (field.length > 0) {
526: for (i = 0; i < field.length; i++) {
527: field[i].checked = true ;
528: }
529: } else {
530: field.checked = true
531: }
532: }
533:
534: function uncheckAll(field) {
535: if (field.length > 0) {
536: for (i = 0; i < field.length; i++) {
537: field[i].checked = false ;
538: } } else {
539: field.checked = false ;
540: }
541: }
542: ENDSCRT
543: return $jscript;
544: }
545:
546:
547: =pod
548:
549: =item * linked_select_forms(...)
550:
551: linked_select_forms returns a string containing a <script></script> block
552: and html for two <select> menus. The select menus will be linked in that
553: changing the value of the first menu will result in new values being placed
554: in the second menu. The values in the select menu will appear in alphabetical
555: order.
556:
557: linked_select_forms takes the following ordered inputs:
558:
559: =over 4
560:
561: =item * $formname, the name of the <form> tag
562:
563: =item * $middletext, the text which appears between the <select> tags
564:
565: =item * $firstdefault, the default value for the first menu
566:
567: =item * $firstselectname, the name of the first <select> tag
568:
569: =item * $secondselectname, the name of the second <select> tag
570:
571: =item * $hashref, a reference to a hash containing the data for the menus.
572:
573: =back
574:
575: Below is an example of such a hash. Only the 'text', 'default', and
576: 'select2' keys must appear as stated. keys(%menu) are the possible
577: values for the first select menu. The text that coincides with the
578: first menu value is given in $menu{$choice1}->{'text'}. The values
579: and text for the second menu are given in the hash pointed to by
580: $menu{$choice1}->{'select2'}.
581:
582: my %menu = ( A1 => { text =>"Choice A1" ,
583: default => "B3",
584: select2 => {
585: B1 => "Choice B1",
586: B2 => "Choice B2",
587: B3 => "Choice B3",
588: B4 => "Choice B4"
589: }
590: },
591: A2 => { text =>"Choice A2" ,
592: default => "C2",
593: select2 => {
594: C1 => "Choice C1",
595: C2 => "Choice C2",
596: C3 => "Choice C3"
597: }
598: },
599: A3 => { text =>"Choice A3" ,
600: default => "D6",
601: select2 => {
602: D1 => "Choice D1",
603: D2 => "Choice D2",
604: D3 => "Choice D3",
605: D4 => "Choice D4",
606: D5 => "Choice D5",
607: D6 => "Choice D6",
608: D7 => "Choice D7"
609: }
610: }
611: );
612:
613: =cut
614:
615: sub linked_select_forms {
616: my ($formname,
617: $middletext,
618: $firstdefault,
619: $firstselectname,
620: $secondselectname,
621: $hashref
622: ) = @_;
623: my $second = "document.$formname.$secondselectname";
624: my $first = "document.$formname.$firstselectname";
625: # output the javascript to do the changing
626: my $result = '';
627: $result.="<script type=\"text/javascript\">\n";
628: $result.="var select2data = new Object();\n";
629: $" = '","';
630: my $debug = '';
631: foreach my $s1 (sort(keys(%$hashref))) {
632: $result.="select2data.d_$s1 = new Object();\n";
633: $result.="select2data.d_$s1.def = new String('".
634: $hashref->{$s1}->{'default'}."');\n";
635: $result.="select2data.d_$s1.values = new Array(";
636: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
637: $result.="\"@s2values\");\n";
638: $result.="select2data.d_$s1.texts = new Array(";
639: my @s2texts;
640: foreach my $value (@s2values) {
641: push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
642: }
643: $result.="\"@s2texts\");\n";
644: }
645: $"=' ';
646: $result.= <<"END";
647:
648: function select1_changed() {
649: // Determine new choice
650: var newvalue = "d_" + $first.value;
651: // update select2
652: var values = select2data[newvalue].values;
653: var texts = select2data[newvalue].texts;
654: var select2def = select2data[newvalue].def;
655: var i;
656: // out with the old
657: for (i = 0; i < $second.options.length; i++) {
658: $second.options[i] = null;
659: }
660: // in with the nuclear
661: for (i=0;i<values.length; i++) {
662: $second.options[i] = new Option(values[i]);
663: $second.options[i].value = values[i];
664: $second.options[i].text = texts[i];
665: if (values[i] == select2def) {
666: $second.options[i].selected = true;
667: }
668: }
669: }
670: </script>
671: END
672: # output the initial values for the selection lists
673: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
674: foreach my $value (sort(keys(%$hashref))) {
675: $result.=" <option value=\"$value\" ";
676: $result.=" selected=\"selected\" " if ($value eq $firstdefault);
677: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
678: }
679: $result .= "</select>\n";
680: my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
681: $result .= $middletext;
682: $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
683: my $seconddefault = $hashref->{$firstdefault}->{'default'};
684: foreach my $value (sort(keys(%select2))) {
685: $result.=" <option value=\"$value\" ";
686: $result.=" selected=\"selected\" " if ($value eq $seconddefault);
687: $result.=">".&mt($select2{$value})."</option>\n";
688: }
689: $result .= "</select>\n";
690: # return $debug;
691: return $result;
692: } # end of sub linked_select_forms {
693:
694: =pod
695:
696: =item * help_open_topic($topic, $text, $stayOnPage, $width, $height)
697:
698: Returns a string corresponding to an HTML link to the given help
699: $topic, where $topic corresponds to the name of a .tex file in
700: /home/httpd/html/adm/help/tex, with underscores replaced by
701: spaces.
702:
703: $text will optionally be linked to the same topic, allowing you to
704: link text in addition to the graphic. If you do not want to link
705: text, but wish to specify one of the later parameters, pass an
706: empty string.
707:
708: $stayOnPage is a value that will be interpreted as a boolean. If true,
709: the link will not open a new window. If false, the link will open
710: a new window using Javascript. (Default is false.)
711:
712: $width and $height are optional numerical parameters that will
713: override the width and height of the popped up window, which may
714: be useful for certain help topics with big pictures included.
715:
716: =cut
717:
718: sub help_open_topic {
719: my ($topic, $text, $stayOnPage, $width, $height) = @_;
720: $text = "" if (not defined $text);
721: $stayOnPage = 0 if (not defined $stayOnPage);
722: if ($env{'browser.interface'} eq 'textual' ||
723: $env{'environment.remote'} eq 'off' ) {
724: $stayOnPage=1;
725: }
726: $width = 350 if (not defined $width);
727: $height = 400 if (not defined $height);
728: my $filename = $topic;
729: $filename =~ s/ /_/g;
730:
731: my $template = "";
732: my $link;
733:
734: $topic=~s/\W/\_/g;
735:
736: if (!$stayOnPage)
737: {
738: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
739: }
740: else
741: {
742: $link = "/adm/help/${filename}.hlp";
743: }
744:
745: # Add the text
746: if ($text ne "")
747: {
748: $template .=
749: "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
750: "<td bgcolor='#5555FF'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
751: }
752:
753: # Add the graphic
754: my $title = &mt('Online Help');
755: my $helpicon=&lonhttpdurl("/adm/help/gif/smallHelp.gif");
756: $template .= <<"ENDTEMPLATE";
757: <a target="_top" href="$link" title="$title"><img src="$helpicon" border="0" alt="(Help: $topic)" /></a>
758: ENDTEMPLATE
759: if ($text ne '') { $template.='</td></tr></table>' };
760: return $template;
761:
762: }
763:
764: # This is a quicky function for Latex cheatsheet editing, since it
765: # appears in at least four places
766: sub helpLatexCheatsheet {
767: my $other = shift;
768: my $addOther = '';
769: if ($other) {
770: $addOther = Apache::loncommon::help_open_topic($other, shift,
771: undef, undef, 600) .
772: '</td><td>';
773: }
774: return '<table><tr><td>'.
775: $addOther .
776: &Apache::loncommon::help_open_topic("Greek_Symbols",'Greek Symbols',
777: undef,undef,600)
778: .'</td><td>'.
779: &Apache::loncommon::help_open_topic("Other_Symbols",'Other Symbols',
780: undef,undef,600)
781: .'</td></tr></table>';
782: }
783:
784: sub general_help {
785: my $helptopic='Student_Intro';
786: if ($env{'request.role'}=~/^(ca|au)/) {
787: $helptopic='Authoring_Intro';
788: } elsif ($env{'request.role'}=~/^cc/) {
789: $helptopic='Course_Coordination_Intro';
790: }
791: return $helptopic;
792: }
793:
794: sub update_help_link {
795: my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
796: my $origurl = $ENV{'REQUEST_URI'};
797: $origurl=~s|^/~|/priv/|;
798: my $timestamp = time;
799: foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
800: $$datum = &escape($$datum);
801: }
802:
803: my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage";
804: my $output .= <<"ENDOUTPUT";
805: <script type="text/javascript">
806: banner_link = '$banner_link';
807: </script>
808: ENDOUTPUT
809: return $output;
810: }
811:
812: # now just updates the help link and generates a blue icon
813: sub help_open_menu {
814: my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text)
815: = @_;
816:
817: $stayOnPage = 0 if (not defined $stayOnPage);
818: if ($env{'browser.interface'} eq 'textual' ||
819: $env{'environment.remote'} eq 'off' ) {
820: $stayOnPage=1;
821: }
822: my $output;
823: if ($component_help) {
824: if (!$text) {
825: $output=&help_open_topic($component_help,undef,$stayOnPage,
826: $width,$height);
827: } else {
828: my $help_text;
829: $help_text=&unescape($topic);
830: $output='<table><tr><td>'.
831: &help_open_topic($component_help,$help_text,$stayOnPage,
832: $width,$height).'</td></tr></table>';
833: }
834: }
835: my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
836: return $output.$banner_link;
837: }
838:
839: sub top_nav_help {
840: my ($text) = @_;
841:
842: $text = &mt($text);
843:
844: my $stayOnPage =
845: ($env{'browser.interface'} eq 'textual' ||
846: $env{'environment.remote'} eq 'off' );
847: my $link= ($stayOnPage) ? "javascript:helpMenu('display')"
848: : "javascript:helpMenu('open')";
849: my $banner_link = &update_help_link(undef,undef,undef,undef,$stayOnPage);
850:
851: my $title = &mt('Get help');
852:
853: return <<"END";
854: $banner_link
855: <a href="$link" title="$title">$text</a>
856: END
857: }
858:
859: sub help_menu_js {
860: my ($text) = @_;
861:
862: my $stayOnPage =
863: ($env{'browser.interface'} eq 'textual' ||
864: $env{'environment.remote'} eq 'off' );
865:
866: my $width = 620;
867: my $height = 600;
868: my $helptopic=&general_help();
869: my $details_link = '/adm/help/'.$helptopic.'.hlp';
870: my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
871: my $start_page =
872: &Apache::loncommon::start_page('Help Menu', undef,
873: {'frameset' => 1,
874: 'js_ready' => 1,
875: 'add_entries' => {
876: 'border' => '0',
877: 'rows' => "105,*",},});
878: my $end_page =
879: &Apache::loncommon::end_page({'frameset' => 1,
880: 'js_ready' => 1,});
881:
882: my $template .= <<"ENDTEMPLATE";
883: <script type="text/javascript">
884: // <!-- BEGIN LON-CAPA Internal
885: // <![CDATA[
886: var banner_link = '';
887: function helpMenu(target) {
888: var caller = this;
889: if (target == 'open') {
890: var newWindow = null;
891: try {
892: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
893: }
894: catch(error) {
895: writeHelp(caller);
896: return;
897: }
898: if (newWindow) {
899: caller = newWindow;
900: }
901: }
902: writeHelp(caller);
903: return;
904: }
905: function writeHelp(caller) {
906: caller.document.writeln('$start_page<frame name="bannerframe" src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
907: caller.document.close()
908: caller.focus()
909: }
910: // ]]>
911: // END LON-CAPA Internal -->
912: </script>
913: ENDTEMPLATE
914: return $template;
915: }
916:
917: sub help_open_bug {
918: my ($topic, $text, $stayOnPage, $width, $height) = @_;
919: unless ($env{'user.adv'}) { return ''; }
920: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
921: $text = "" if (not defined $text);
922: $stayOnPage = 0 if (not defined $stayOnPage);
923: if ($env{'browser.interface'} eq 'textual' ||
924: $env{'environment.remote'} eq 'off' ) {
925: $stayOnPage=1;
926: }
927: $width = 600 if (not defined $width);
928: $height = 600 if (not defined $height);
929:
930: $topic=~s/\W+/\+/g;
931: my $link='';
932: my $template='';
933: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
934: &escape($ENV{'REQUEST_URI'}).'&component='.$topic;
935: if (!$stayOnPage)
936: {
937: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
938: }
939: else
940: {
941: $link = $url;
942: }
943: # Add the text
944: if ($text ne "")
945: {
946: $template .=
947: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
948: "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
949: }
950:
951: # Add the graphic
952: my $title = &mt('Report a Bug');
953: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
954: $template .= <<"ENDTEMPLATE";
955: <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
956: ENDTEMPLATE
957: if ($text ne '') { $template.='</td></tr></table>' };
958: return $template;
959:
960: }
961:
962: sub help_open_faq {
963: my ($topic, $text, $stayOnPage, $width, $height) = @_;
964: unless ($env{'user.adv'}) { return ''; }
965: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
966: $text = "" if (not defined $text);
967: $stayOnPage = 0 if (not defined $stayOnPage);
968: if ($env{'browser.interface'} eq 'textual' ||
969: $env{'environment.remote'} eq 'off' ) {
970: $stayOnPage=1;
971: }
972: $width = 350 if (not defined $width);
973: $height = 400 if (not defined $height);
974:
975: $topic=~s/\W+/\+/g;
976: my $link='';
977: my $template='';
978: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
979: if (!$stayOnPage)
980: {
981: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
982: }
983: else
984: {
985: $link = $url;
986: }
987:
988: # Add the text
989: if ($text ne "")
990: {
991: $template .=
992: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
993: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
994: }
995:
996: # Add the graphic
997: my $title = &mt('View the FAQ');
998: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
999: $template .= <<"ENDTEMPLATE";
1000: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1001: ENDTEMPLATE
1002: if ($text ne '') { $template.='</td></tr></table>' };
1003: return $template;
1004:
1005: }
1006:
1007: ###############################################################
1008: ###############################################################
1009:
1010: =pod
1011:
1012: =item * change_content_javascript():
1013:
1014: This and the next function allow you to create small sections of an
1015: otherwise static HTML page that you can update on the fly with
1016: Javascript, even in Netscape 4.
1017:
1018: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
1019: must be written to the HTML page once. It will prove the Javascript
1020: function "change(name, content)". Calling the change function with the
1021: name of the section
1022: you want to update, matching the name passed to C<changable_area>, and
1023: the new content you want to put in there, will put the content into
1024: that area.
1025:
1026: B<Note>: Netscape 4 only reserves enough space for the changable area
1027: to contain room for the original contents. You need to "make space"
1028: for whatever changes you wish to make, and be B<sure> to check your
1029: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
1030: it's adequate for updating a one-line status display, but little more.
1031: This script will set the space to 100% width, so you only need to
1032: worry about height in Netscape 4.
1033:
1034: Modern browsers are much less limiting, and if you can commit to the
1035: user not using Netscape 4, this feature may be used freely with
1036: pretty much any HTML.
1037:
1038: =cut
1039:
1040: sub change_content_javascript {
1041: # If we're on Netscape 4, we need to use Layer-based code
1042: if ($env{'browser.type'} eq 'netscape' &&
1043: $env{'browser.version'} =~ /^4\./) {
1044: return (<<NETSCAPE4);
1045: function change(name, content) {
1046: doc = document.layers[name+"___escape"].layers[0].document;
1047: doc.open();
1048: doc.write(content);
1049: doc.close();
1050: }
1051: NETSCAPE4
1052: } else {
1053: # Otherwise, we need to use semi-standards-compliant code
1054: # (technically, "innerHTML" isn't standard but the equivalent
1055: # is really scary, and every useful browser supports it
1056: return (<<DOMBASED);
1057: function change(name, content) {
1058: element = document.getElementById(name);
1059: element.innerHTML = content;
1060: }
1061: DOMBASED
1062: }
1063: }
1064:
1065: =pod
1066:
1067: =item * changable_area($name, $origContent):
1068:
1069: This provides a "changable area" that can be modified on the fly via
1070: the Javascript code provided in C<change_content_javascript>. $name is
1071: the name you will use to reference the area later; do not repeat the
1072: same name on a given HTML page more then once. $origContent is what
1073: the area will originally contain, which can be left blank.
1074:
1075: =cut
1076:
1077: sub changable_area {
1078: my ($name, $origContent) = @_;
1079:
1080: if ($env{'browser.type'} eq 'netscape' &&
1081: $env{'browser.version'} =~ /^4\./) {
1082: # If this is netscape 4, we need to use the Layer tag
1083: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
1084: } else {
1085: return "<span id='$name'>$origContent</span>";
1086: }
1087: }
1088:
1089: =pod
1090:
1091: =back
1092:
1093: =head1 Excel and CSV file utility routines
1094:
1095: =over 4
1096:
1097: =cut
1098:
1099: ###############################################################
1100: ###############################################################
1101:
1102: =pod
1103:
1104: =item * csv_translate($text)
1105:
1106: Translate $text to allow it to be output as a 'comma separated values'
1107: format.
1108:
1109: =cut
1110:
1111: ###############################################################
1112: ###############################################################
1113: sub csv_translate {
1114: my $text = shift;
1115: $text =~ s/\"/\"\"/g;
1116: $text =~ s/\n/ /g;
1117: return $text;
1118: }
1119:
1120: ###############################################################
1121: ###############################################################
1122:
1123: =pod
1124:
1125: =item * define_excel_formats
1126:
1127: Define some commonly used Excel cell formats.
1128:
1129: Currently supported formats:
1130:
1131: =over 4
1132:
1133: =item header
1134:
1135: =item bold
1136:
1137: =item h1
1138:
1139: =item h2
1140:
1141: =item h3
1142:
1143: =item h4
1144:
1145: =item i
1146:
1147: =item date
1148:
1149: =back
1150:
1151: Inputs: $workbook
1152:
1153: Returns: $format, a hash reference.
1154:
1155: =cut
1156:
1157: ###############################################################
1158: ###############################################################
1159: sub define_excel_formats {
1160: my ($workbook) = @_;
1161: my $format;
1162: $format->{'header'} = $workbook->add_format(bold => 1,
1163: bottom => 1,
1164: align => 'center');
1165: $format->{'bold'} = $workbook->add_format(bold=>1);
1166: $format->{'h1'} = $workbook->add_format(bold=>1, size=>18);
1167: $format->{'h2'} = $workbook->add_format(bold=>1, size=>16);
1168: $format->{'h3'} = $workbook->add_format(bold=>1, size=>14);
1169: $format->{'h4'} = $workbook->add_format(bold=>1, size=>12);
1170: $format->{'i'} = $workbook->add_format(italic=>1);
1171: $format->{'date'} = $workbook->add_format(num_format=>
1172: 'mm/dd/yyyy hh:mm:ss');
1173: return $format;
1174: }
1175:
1176: ###############################################################
1177: ###############################################################
1178:
1179: =pod
1180:
1181: =item * create_workbook
1182:
1183: Create an Excel worksheet. If it fails, output message on the
1184: request object and return undefs.
1185:
1186: Inputs: Apache request object
1187:
1188: Returns (undef) on failure,
1189: Excel worksheet object, scalar with filename, and formats
1190: from &Apache::loncommon::define_excel_formats on success
1191:
1192: =cut
1193:
1194: ###############################################################
1195: ###############################################################
1196: sub create_workbook {
1197: my ($r) = @_;
1198: #
1199: # Create the excel spreadsheet
1200: my $filename = '/prtspool/'.
1201: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1202: time.'_'.rand(1000000000).'.xls';
1203: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
1204: if (! defined($workbook)) {
1205: $r->log_error("Error creating excel spreadsheet $filename: $!");
1206: $r->print('<p>'.&mt("Unable to create new Excel file. ".
1207: "This error has been logged. ".
1208: "Please alert your LON-CAPA administrator").
1209: '</p>');
1210: return (undef);
1211: }
1212: #
1213: $workbook->set_tempdir('/home/httpd/perl/tmp');
1214: #
1215: my $format = &Apache::loncommon::define_excel_formats($workbook);
1216: return ($workbook,$filename,$format);
1217: }
1218:
1219: ###############################################################
1220: ###############################################################
1221:
1222: =pod
1223:
1224: =item * create_text_file
1225:
1226: Create a file to write to and eventually make available to the usre.
1227: If file creation fails, outputs an error message on the request object and
1228: return undefs.
1229:
1230: Inputs: Apache request object, and file suffix
1231:
1232: Returns (undef) on failure,
1233: Filehandle and filename on success.
1234:
1235: =cut
1236:
1237: ###############################################################
1238: ###############################################################
1239: sub create_text_file {
1240: my ($r,$suffix) = @_;
1241: if (! defined($suffix)) { $suffix = 'txt'; };
1242: my $fh;
1243: my $filename = '/prtspool/'.
1244: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1245: time.'_'.rand(1000000000).'.'.$suffix;
1246: $fh = Apache::File->new('>/home/httpd'.$filename);
1247: if (! defined($fh)) {
1248: $r->log_error("Couldn't open $filename for output $!");
1249: $r->print("Problems occured in creating the output file. ".
1250: "This error has been logged. ".
1251: "Please alert your LON-CAPA administrator.");
1252: }
1253: return ($fh,$filename)
1254: }
1255:
1256:
1257: =pod
1258:
1259: =back
1260:
1261: =cut
1262:
1263: ###############################################################
1264: ## Home server <option> list generating code ##
1265: ###############################################################
1266:
1267: =pod
1268:
1269: =head1 Home Server option list generating code
1270:
1271: =over 4
1272:
1273: =item * get_domains()
1274:
1275: Returns an array containing each of the domains listed in the hosts.tab
1276: file.
1277:
1278: =cut
1279:
1280: #-------------------------------------------
1281: sub get_domains {
1282: # The code below was stolen from "The Perl Cookbook", p 102, 1st ed.
1283: my @domains;
1284: my %seen;
1285: foreach my $dom (sort(values(%Apache::lonnet::hostdom))) {
1286: push(@domains,$dom) unless $seen{$dom}++;
1287: }
1288: return @domains;
1289: }
1290:
1291: # ------------------------------------------
1292:
1293: sub domain_select {
1294: my ($name,$value,$multiple)=@_;
1295: my %domains=map {
1296: $_ => $_.' '.$Apache::lonnet::domaindescription{$_}
1297: } &get_domains;
1298: if ($multiple) {
1299: $domains{''}=&mt('Any domain');
1300: return &multiple_select_form($name,$value,4,\%domains);
1301: } else {
1302: return &select_form($name,$value,%domains);
1303: }
1304: }
1305:
1306: #-------------------------------------------
1307:
1308: =pod
1309:
1310: =item * multiple_select_form($name,$value,$size,$hash,$order)
1311:
1312: Returns a string containing a <select> element int multiple mode
1313:
1314:
1315: Args:
1316: $name - name of the <select> element
1317: $value - sclara or array ref of values that should already be selected
1318: $size - number of rows long the select element is
1319: $hash - the elements should be 'option' => 'shown text'
1320: (shown text should already have been &mt())
1321: $order - (optional) array ref of the order to show the elments in
1322:
1323: =cut
1324:
1325: #-------------------------------------------
1326: sub multiple_select_form {
1327: my ($name,$value,$size,$hash,$order)=@_;
1328: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
1329: my $output='';
1330: if (! defined($size)) {
1331: $size = 4;
1332: if (scalar(keys(%$hash))<4) {
1333: $size = scalar(keys(%$hash));
1334: }
1335: }
1336: $output.="\n<select name='$name' size='$size' multiple='1'>";
1337: my @order = ref($order) ? @$order
1338: : sort(keys(%$hash));
1339: foreach my $key (@order) {
1340: $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1341: $output.='selected="selected" ' if ($selected{$key});
1342: $output.='>'.$hash->{$key}."</option>\n";
1343: }
1344: $output.="</select>\n";
1345: return $output;
1346: }
1347:
1348: #-------------------------------------------
1349:
1350: =pod
1351:
1352: =item * select_form($defdom,$name,%hash)
1353:
1354: Returns a string containing a <select name='$name' size='1'> form to
1355: allow a user to select options from a hash option_name => displayed text.
1356: See lonrights.pm for an example invocation and use.
1357:
1358: =cut
1359:
1360: #-------------------------------------------
1361: sub select_form {
1362: my ($def,$name,%hash) = @_;
1363: my $selectform = "<select name=\"$name\" size=\"1\">\n";
1364: my @keys;
1365: if (exists($hash{'select_form_order'})) {
1366: @keys=@{$hash{'select_form_order'}};
1367: } else {
1368: @keys=sort(keys(%hash));
1369: }
1370: foreach my $key (@keys) {
1371: $selectform.=
1372: '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
1373: ($key eq $def ? 'selected="selected" ' : '').
1374: ">".&mt($hash{$key})."</option>\n";
1375: }
1376: $selectform.="</select>";
1377: return $selectform;
1378: }
1379:
1380: # For display filters
1381:
1382: sub display_filter {
1383: if (!$env{'form.show'}) { $env{'form.show'}=10; }
1384: return '<nobr><label>'.&mt('Records [_1]',
1385: &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
1386: (&mt('all'),10,20,50,100,1000,10000))).
1387: '</label></nobr> <nobr><label>'.
1388: &mt('Filter [_1]',
1389: &select_form(($env{'form.displayfilter'}?$env{'form.displayfilter'}:'currentfolder'),
1390: 'displayfilter',
1391: ('currentfolder' => 'Current folder',
1392: 'containing' => 'Containing phrase',
1393: 'none' => 'None'))).
1394: '<input type="text" name="containingphrase" size="30" /></label></nobr>';
1395: }
1396:
1397: sub gradeleveldescription {
1398: my $gradelevel=shift;
1399: my %gradelevels=(0 => 'Not specified',
1400: 1 => 'Grade 1',
1401: 2 => 'Grade 2',
1402: 3 => 'Grade 3',
1403: 4 => 'Grade 4',
1404: 5 => 'Grade 5',
1405: 6 => 'Grade 6',
1406: 7 => 'Grade 7',
1407: 8 => 'Grade 8',
1408: 9 => 'Grade 9',
1409: 10 => 'Grade 10',
1410: 11 => 'Grade 11',
1411: 12 => 'Grade 12',
1412: 13 => 'Grade 13',
1413: 14 => '100 Level',
1414: 15 => '200 Level',
1415: 16 => '300 Level',
1416: 17 => '400 Level',
1417: 18 => 'Graduate Level');
1418: return &mt($gradelevels{$gradelevel});
1419: }
1420:
1421: sub select_level_form {
1422: my ($deflevel,$name)=@_;
1423: unless ($deflevel) { $deflevel=0; }
1424: my $selectform = "<select name=\"$name\" size=\"1\">\n";
1425: for (my $i=0; $i<=18; $i++) {
1426: $selectform.="<option value=\"$i\" ".
1427: ($i==$deflevel ? 'selected="selected" ' : '').
1428: ">".&gradeleveldescription($i)."</option>\n";
1429: }
1430: $selectform.="</select>";
1431: return $selectform;
1432: }
1433:
1434: #-------------------------------------------
1435:
1436: =pod
1437:
1438: =item * select_dom_form($defdom,$name,$includeempty)
1439:
1440: Returns a string containing a <select name='$name' size='1'> form to
1441: allow a user to select the domain to preform an operation in.
1442: See loncreateuser.pm for an example invocation and use.
1443:
1444: If the $includeempty flag is set, it also includes an empty choice ("no domain
1445: selected");
1446:
1447: =cut
1448:
1449: #-------------------------------------------
1450: sub select_dom_form {
1451: my ($defdom,$name,$includeempty) = @_;
1452: my @domains = get_domains();
1453: if ($includeempty) { @domains=('',@domains); }
1454: my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
1455: foreach my $dom (@domains) {
1456: $selectdomain.="<option value=\"$dom\" ".
1457: ($dom eq $defdom ? 'selected="selected" ' : '').
1458: ">$dom</option>\n";
1459: }
1460: $selectdomain.="</select>";
1461: return $selectdomain;
1462: }
1463:
1464: #-------------------------------------------
1465:
1466: =pod
1467:
1468: =item * get_library_servers($domain)
1469:
1470: Returns a hash which contains keys like '103l3' and values like
1471: 'kirk.lite.msu.edu'. All of the keys will be for machines in the
1472: given $domain.
1473:
1474: =cut
1475:
1476: #-------------------------------------------
1477: sub get_library_servers {
1478: my $domain = shift;
1479: my %library_servers;
1480: foreach my $hostid (keys(%Apache::lonnet::libserv)) {
1481: if ($Apache::lonnet::hostdom{$hostid} eq $domain) {
1482: $library_servers{$hostid} = $Apache::lonnet::hostname{$hostid};
1483: }
1484: }
1485: return %library_servers;
1486: }
1487:
1488: #-------------------------------------------
1489:
1490: =pod
1491:
1492: =item * home_server_option_list($domain)
1493:
1494: returns a string which contains an <option> list to be used in a
1495: <select> form input. See loncreateuser.pm for an example.
1496:
1497: =cut
1498:
1499: #-------------------------------------------
1500: sub home_server_option_list {
1501: my $domain = shift;
1502: my %servers = &get_library_servers($domain);
1503: my $result = '';
1504: foreach my $hostid (sort(keys(%servers))) {
1505: $result.=
1506: '<option value="'.$hostid.'">'.
1507: $hostid.' '.$servers{$hostid}."</option>\n";
1508: }
1509: return $result;
1510: }
1511:
1512: =pod
1513:
1514: =back
1515:
1516: =cut
1517:
1518: ###############################################################
1519: ## Decoding User Agent ##
1520: ###############################################################
1521:
1522: =pod
1523:
1524: =head1 Decoding the User Agent
1525:
1526: =over 4
1527:
1528: =item * &decode_user_agent()
1529:
1530: Inputs: $r
1531:
1532: Outputs:
1533:
1534: =over 4
1535:
1536: =item * $httpbrowser
1537:
1538: =item * $clientbrowser
1539:
1540: =item * $clientversion
1541:
1542: =item * $clientmathml
1543:
1544: =item * $clientunicode
1545:
1546: =item * $clientos
1547:
1548: =back
1549:
1550: =back
1551:
1552: =cut
1553:
1554: ###############################################################
1555: ###############################################################
1556: sub decode_user_agent {
1557: my ($r)=@_;
1558: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
1559: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
1560: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1561: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1562: my $clientbrowser='unknown';
1563: my $clientversion='0';
1564: my $clientmathml='';
1565: my $clientunicode='0';
1566: for (my $i=0;$i<=$#browsertype;$i++) {
1567: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
1568: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
1569: $clientbrowser=$bname;
1570: $httpbrowser=~/$vreg/i;
1571: $clientversion=$1;
1572: $clientmathml=($clientversion>=$minv);
1573: $clientunicode=($clientversion>=$univ);
1574: }
1575: }
1576: my $clientos='unknown';
1577: if (($httpbrowser=~/linux/i) ||
1578: ($httpbrowser=~/unix/i) ||
1579: ($httpbrowser=~/ux/i) ||
1580: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
1581: if (($httpbrowser=~/vax/i) ||
1582: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
1583: if ($httpbrowser=~/next/i) { $clientos='next'; }
1584: if (($httpbrowser=~/mac/i) ||
1585: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1586: if ($httpbrowser=~/win/i) { $clientos='win'; }
1587: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1588: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1589: $clientunicode,$clientos,);
1590: }
1591:
1592: ###############################################################
1593: ## Authentication changing form generation subroutines ##
1594: ###############################################################
1595: ##
1596: ## All of the authform_xxxxxxx subroutines take their inputs in a
1597: ## hash, and have reasonable default values.
1598: ##
1599: ## formname = the name given in the <form> tag.
1600: #-------------------------------------------
1601:
1602: =pod
1603:
1604: =head1 Authentication Routines
1605:
1606: =over 4
1607:
1608: =item * authform_xxxxxx
1609:
1610: The authform_xxxxxx subroutines provide javascript and html forms which
1611: handle some of the conveniences required for authentication forms.
1612: This is not an optimal method, but it works.
1613:
1614: See loncreateuser.pm for invocation and use examples.
1615:
1616: =over 4
1617:
1618: =item * authform_header
1619:
1620: =item * authform_authorwarning
1621:
1622: =item * authform_nochange
1623:
1624: =item * authform_kerberos
1625:
1626: =item * authform_internal
1627:
1628: =item * authform_filesystem
1629:
1630: =back
1631:
1632: =back
1633:
1634: =cut
1635:
1636: #-------------------------------------------
1637: sub authform_header{
1638: my %in = (
1639: formname => 'cu',
1640: kerb_def_dom => '',
1641: @_,
1642: );
1643: $in{'formname'} = 'document.' . $in{'formname'};
1644: my $result='';
1645:
1646: #---------------------------------------------- Code for upper case translation
1647: my $Javascript_toUpperCase;
1648: unless ($in{kerb_def_dom}) {
1649: $Javascript_toUpperCase =<<"END";
1650: switch (choice) {
1651: case 'krb': currentform.elements[choicearg].value =
1652: currentform.elements[choicearg].value.toUpperCase();
1653: break;
1654: default:
1655: }
1656: END
1657: } else {
1658: $Javascript_toUpperCase = "";
1659: }
1660:
1661: my $radioval = "'nochange'";
1662: if (exists($in{'curr_authtype'}) &&
1663: defined($in{'curr_authtype'}) &&
1664: $in{'curr_authtype'} ne '') {
1665: $radioval = "'$in{'curr_authtype'}arg'";
1666: }
1667: my $argfield = 'null';
1668: if ( grep/^mode$/,(keys %in) ) {
1669: if ($in{'mode'} eq 'modifycourse') {
1670: if ( grep/^curr_authtype$/,(keys %in) ) {
1671: $radioval = "'$in{'curr_authtype'}'";
1672: }
1673: if ( grep/^curr_autharg$/,(keys %in) ) {
1674: unless ($in{'curr_autharg'} eq '') {
1675: $argfield = "'$in{'curr_autharg'}'";
1676: }
1677: }
1678: }
1679: }
1680:
1681: $result.=<<"END";
1682: var current = new Object();
1683: current.radiovalue = $radioval;
1684: current.argfield = $argfield;
1685:
1686: function changed_radio(choice,currentform) {
1687: var choicearg = choice + 'arg';
1688: // If a radio button in changed, we need to change the argfield
1689: if (current.radiovalue != choice) {
1690: current.radiovalue = choice;
1691: if (current.argfield != null) {
1692: currentform.elements[current.argfield].value = '';
1693: }
1694: if (choice == 'nochange') {
1695: current.argfield = null;
1696: } else {
1697: current.argfield = choicearg;
1698: switch(choice) {
1699: case 'krb':
1700: currentform.elements[current.argfield].value =
1701: "$in{'kerb_def_dom'}";
1702: break;
1703: default:
1704: break;
1705: }
1706: }
1707: }
1708: return;
1709: }
1710:
1711: function changed_text(choice,currentform) {
1712: var choicearg = choice + 'arg';
1713: if (currentform.elements[choicearg].value !='') {
1714: $Javascript_toUpperCase
1715: // clear old field
1716: if ((current.argfield != choicearg) && (current.argfield != null)) {
1717: currentform.elements[current.argfield].value = '';
1718: }
1719: current.argfield = choicearg;
1720: }
1721: set_auth_radio_buttons(choice,currentform);
1722: return;
1723: }
1724:
1725: function set_auth_radio_buttons(newvalue,currentform) {
1726: var i=0;
1727: while (i < currentform.login.length) {
1728: if (currentform.login[i].value == newvalue) { break; }
1729: i++;
1730: }
1731: if (i == currentform.login.length) {
1732: return;
1733: }
1734: current.radiovalue = newvalue;
1735: currentform.login[i].checked = true;
1736: return;
1737: }
1738: END
1739: return $result;
1740: }
1741:
1742: sub authform_authorwarning{
1743: my $result='';
1744: $result='<i>'.
1745: &mt('As a general rule, only authors or co-authors should be '.
1746: 'filesystem authenticated '.
1747: '(which allows access to the server filesystem).')."</i>\n";
1748: return $result;
1749: }
1750:
1751: sub authform_nochange{
1752: my %in = (
1753: formname => 'document.cu',
1754: kerb_def_dom => 'MSU.EDU',
1755: @_,
1756: );
1757: my $result = '<label>'.&mt('[_1] Do not change login data',
1758: '<input type="radio" name="login" value="nochange" '.
1759: 'checked="checked" onclick="'.
1760: "javascript:changed_radio('nochange',$in{'formname'});".'" />').
1761: '</label>';
1762: return $result;
1763: }
1764:
1765: sub authform_kerberos{
1766: my %in = (
1767: formname => 'document.cu',
1768: kerb_def_dom => 'MSU.EDU',
1769: kerb_def_auth => 'krb4',
1770: @_,
1771: );
1772: my ($check4,$check5,$krbarg);
1773: if ($in{'kerb_def_auth'} eq 'krb5') {
1774: $check5 = " checked=\"on\"";
1775: } else {
1776: $check4 = " checked=\"on\"";
1777: }
1778: $krbarg = $in{'kerb_def_dom'};
1779:
1780: my $krbcheck = "";
1781: if ( grep/^curr_authtype$/,(keys %in) ) {
1782: if ($in{'curr_authtype'} =~ m/^krb/) {
1783: $krbcheck = " checked=\"on\"";
1784: if ( grep/^curr_autharg$/,(keys %in) ) {
1785: $krbarg = $in{'curr_autharg'};
1786: }
1787: }
1788: }
1789:
1790: my $jscall = "javascript:changed_radio('krb',$in{'formname'});";
1791: my $result .= &mt
1792: ('[_1] Kerberos authenticated with domain [_2] '.
1793: '[_3] Version 4 [_4] Version 5 [_5]',
1794: '<label><input type="radio" name="login" value="krb" '.
1795: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'.$krbcheck.' />',
1796: '</label><input type="text" size="10" name="krbarg" '.
1797: 'value="'.$krbarg.'" '.
1798: 'onchange="'.$jscall.'" />',
1799: '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
1800: '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
1801: '</label>');
1802: return $result;
1803: }
1804:
1805: sub authform_internal{
1806: my %args = (
1807: formname => 'document.cu',
1808: kerb_def_dom => 'MSU.EDU',
1809: @_,
1810: );
1811:
1812: my $intcheck = "";
1813: my $intarg = 'value=""';
1814: if ( grep/^curr_authtype$/,(keys %args) ) {
1815: if ($args{'curr_authtype'} eq 'int') {
1816: $intcheck = " checked=\"on\"";
1817: if ( grep/^curr_autharg$/,(keys %args) ) {
1818: $intarg = "value=\"$args{'curr_autharg'}\"";
1819: }
1820: }
1821: }
1822:
1823: my $jscall = "javascript:changed_radio('int',$args{'formname'});";
1824: my $result.=&mt
1825: ('[_1] Internally authenticated (with initial password [_2])',
1826: '<label><input type="radio" name="login" value="int" '.$intcheck.
1827: ' onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1828: '</label><input type="text" size="10" name="intarg" '.$intarg.
1829: ' onchange="'.$jscall.'" />');
1830: return $result;
1831: }
1832:
1833: sub authform_local{
1834: my %in = (
1835: formname => 'document.cu',
1836: kerb_def_dom => 'MSU.EDU',
1837: @_,
1838: );
1839:
1840: my $loccheck = "";
1841: my $locarg = 'value=""';
1842: if ( grep/^curr_authtype$/,(keys %in) ) {
1843: if ($in{'curr_authtype'} eq 'loc') {
1844: $loccheck = " checked=\"on\"";
1845: if ( grep/^curr_autharg$/,(keys %in) ) {
1846: $locarg = "value=\"$in{'curr_autharg'}\"";
1847: }
1848: }
1849: }
1850:
1851: my $jscall = "javascript:changed_radio('loc',$in{'formname'});";
1852: my $result.=&mt('[_1] Local Authentication with argument [_2]',
1853: '<label><input type="radio" name="login" value="loc" '.$loccheck.
1854: ' onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1855: '</label><input type="text" size="10" name="locarg" '.$locarg.
1856: ' onchange="'.$jscall.'" />');
1857: return $result;
1858: }
1859:
1860: sub authform_filesystem{
1861: my %in = (
1862: formname => 'document.cu',
1863: kerb_def_dom => 'MSU.EDU',
1864: @_,
1865: );
1866: my $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
1867: my $result.= &mt
1868: ('[_1] Filesystem Authenticated (with initial password [_2])',
1869: '<label><input type="radio" name="login" value="fsys" '.
1870: 'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1871: '</label><input type="text" size="10" name="fsysarg" value="" '.
1872: 'onchange="'.$jscall.'" />');
1873: return $result;
1874: }
1875:
1876: ###############################################################
1877: ## Get Authentication Defaults for Domain ##
1878: ###############################################################
1879:
1880: =pod
1881:
1882: =head1 Domains and Authentication
1883:
1884: Returns default authentication type and an associated argument as
1885: listed in file 'domain.tab'.
1886:
1887: =over 4
1888:
1889: =item * get_auth_defaults
1890:
1891: get_auth_defaults($target_domain) returns the default authentication
1892: type and an associated argument (initial password or a kerberos domain).
1893: These values are stored in lonTabs/domain.tab
1894:
1895: ($def_auth, $def_arg) = &get_auth_defaults($target_domain);
1896:
1897: If target_domain is not found in domain.tab, returns nothing ('').
1898:
1899: =cut
1900:
1901: #-------------------------------------------
1902: sub get_auth_defaults {
1903: my $domain=shift;
1904: return ($Apache::lonnet::domain_auth_def{$domain},$Apache::lonnet::domain_auth_arg_def{$domain});
1905: }
1906: ###############################################################
1907: ## End Get Authentication Defaults for Domain ##
1908: ###############################################################
1909:
1910: ###############################################################
1911: ## Get Kerberos Defaults for Domain ##
1912: ###############################################################
1913: ##
1914: ## Returns default kerberos version and an associated argument
1915: ## as listed in file domain.tab. If not listed, provides
1916: ## appropriate default domain and kerberos version.
1917: ##
1918: #-------------------------------------------
1919:
1920: =pod
1921:
1922: =item * get_kerberos_defaults
1923:
1924: get_kerberos_defaults($target_domain) returns the default kerberos
1925: version and domain. If not found in domain.tabs, it defaults to
1926: version 4 and the domain of the server.
1927:
1928: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
1929:
1930: =cut
1931:
1932: #-------------------------------------------
1933: sub get_kerberos_defaults {
1934: my $domain=shift;
1935: my ($krbdef,$krbdefdom) =
1936: &Apache::loncommon::get_auth_defaults($domain);
1937: unless ($krbdef =~/^krb/ && $krbdefdom) {
1938: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
1939: my $krbdefdom=$1;
1940: $krbdefdom=~tr/a-z/A-Z/;
1941: $krbdef = "krb4";
1942: }
1943: return ($krbdef,$krbdefdom);
1944: }
1945:
1946: =pod
1947:
1948: =back
1949:
1950: =cut
1951:
1952: ###############################################################
1953: ## Thesaurus Functions ##
1954: ###############################################################
1955:
1956: =pod
1957:
1958: =head1 Thesaurus Functions
1959:
1960: =over 4
1961:
1962: =item * initialize_keywords
1963:
1964: Initializes the package variable %Keywords if it is empty. Uses the
1965: package variable $thesaurus_db_file.
1966:
1967: =cut
1968:
1969: ###################################################
1970:
1971: sub initialize_keywords {
1972: return 1 if (scalar keys(%Keywords));
1973: # If we are here, %Keywords is empty, so fill it up
1974: # Make sure the file we need exists...
1975: if (! -e $thesaurus_db_file) {
1976: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
1977: " failed because it does not exist");
1978: return 0;
1979: }
1980: # Set up the hash as a database
1981: my %thesaurus_db;
1982: if (! tie(%thesaurus_db,'GDBM_File',
1983: $thesaurus_db_file,&GDBM_READER(),0640)){
1984: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
1985: $thesaurus_db_file);
1986: return 0;
1987: }
1988: # Get the average number of appearances of a word.
1989: my $avecount = $thesaurus_db{'average.count'};
1990: # Put keywords (those that appear > average) into %Keywords
1991: while (my ($word,$data)=each (%thesaurus_db)) {
1992: my ($count,undef) = split /:/,$data;
1993: $Keywords{$word}++ if ($count > $avecount);
1994: }
1995: untie %thesaurus_db;
1996: # Remove special values from %Keywords.
1997: foreach my $value ('total.count','average.count') {
1998: delete($Keywords{$value}) if (exists($Keywords{$value}));
1999: }
2000: return 1;
2001: }
2002:
2003: ###################################################
2004:
2005: =pod
2006:
2007: =item * keyword($word)
2008:
2009: Returns true if $word is a keyword. A keyword is a word that appears more
2010: than the average number of times in the thesaurus database. Calls
2011: &initialize_keywords
2012:
2013: =cut
2014:
2015: ###################################################
2016:
2017: sub keyword {
2018: return if (!&initialize_keywords());
2019: my $word=lc(shift());
2020: $word=~s/\W//g;
2021: return exists($Keywords{$word});
2022: }
2023:
2024: ###############################################################
2025:
2026: =pod
2027:
2028: =item * get_related_words
2029:
2030: Look up a word in the thesaurus. Takes a scalar argument and returns
2031: an array of words. If the keyword is not in the thesaurus, an empty array
2032: will be returned. The order of the words returned is determined by the
2033: database which holds them.
2034:
2035: Uses global $thesaurus_db_file.
2036:
2037: =cut
2038:
2039: ###############################################################
2040: sub get_related_words {
2041: my $keyword = shift;
2042: my %thesaurus_db;
2043: if (! -e $thesaurus_db_file) {
2044: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
2045: "failed because the file does not exist");
2046: return ();
2047: }
2048: if (! tie(%thesaurus_db,'GDBM_File',
2049: $thesaurus_db_file,&GDBM_READER(),0640)){
2050: return ();
2051: }
2052: my @Words=();
2053: my $count=0;
2054: if (exists($thesaurus_db{$keyword})) {
2055: # The first element is the number of times
2056: # the word appears. We do not need it now.
2057: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
2058: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
2059: my $threshold=$mostfrequentcount/10;
2060: foreach my $possibleword (@RelatedWords) {
2061: my ($word,$wordcount)=split(/\,/,$possibleword);
2062: if ($wordcount>$threshold) {
2063: push(@Words,$word);
2064: $count++;
2065: if ($count>10) { last; }
2066: }
2067: }
2068: }
2069: untie %thesaurus_db;
2070: return @Words;
2071: }
2072:
2073: =pod
2074:
2075: =back
2076:
2077: =cut
2078:
2079: # -------------------------------------------------------------- Plaintext name
2080: =pod
2081:
2082: =head1 User Name Functions
2083:
2084: =over 4
2085:
2086: =item * plainname($uname,$udom,$first)
2087:
2088: Takes a users logon name and returns it as a string in
2089: "first middle last generation" form
2090: if $first is set to 'lastname' then it returns it as
2091: 'lastname generation, firstname middlename' if their is a lastname
2092:
2093: =cut
2094:
2095:
2096: ###############################################################
2097: sub plainname {
2098: my ($uname,$udom,$first)=@_;
2099: my %names=&getnames($uname,$udom);
2100: my $name=&Apache::lonnet::format_name($names{'firstname'},
2101: $names{'middlename'},
2102: $names{'lastname'},
2103: $names{'generation'},$first);
2104: $name=~s/^\s+//;
2105: $name=~s/\s+$//;
2106: $name=~s/\s+/ /g;
2107: if ($name !~ /\S/) { $name=$uname.':'.$udom; }
2108: return $name;
2109: }
2110:
2111: # -------------------------------------------------------------------- Nickname
2112: =pod
2113:
2114: =item * nickname($uname,$udom)
2115:
2116: Gets a users name and returns it as a string as
2117:
2118: ""nickname""
2119:
2120: if the user has a nickname or
2121:
2122: "first middle last generation"
2123:
2124: if the user does not
2125:
2126: =cut
2127:
2128: sub nickname {
2129: my ($uname,$udom)=@_;
2130: my %names=&getnames($uname,$udom);
2131: my $name=$names{'nickname'};
2132: if ($name) {
2133: $name='"'.$name.'"';
2134: } else {
2135: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
2136: $names{'lastname'}.' '.$names{'generation'};
2137: $name=~s/\s+$//;
2138: $name=~s/\s+/ /g;
2139: }
2140: return $name;
2141: }
2142:
2143: sub getnames {
2144: my ($uname,$udom)=@_;
2145: if ($udom eq 'public' && $uname eq 'public') {
2146: return ('lastname' => &mt('Public'));
2147: }
2148: my $id=$uname.':'.$udom;
2149: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
2150: if ($cached) {
2151: return %{$names};
2152: } else {
2153: my %loadnames=&Apache::lonnet::get('environment',
2154: ['firstname','middlename','lastname','generation','nickname'],
2155: $udom,$uname);
2156: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
2157: return %loadnames;
2158: }
2159: }
2160:
2161: sub getemails {
2162: my ($uname,$udom)=@_;
2163: if ($udom eq 'public' && $uname eq 'public') {
2164: return;
2165: }
2166: if (!$udom) { $udom=$env{'user.domain'}; }
2167: if (!$uname) { $uname=$env{'user.name'}; }
2168: my $id=$uname.':'.$udom;
2169: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
2170: if ($cached) {
2171: return %{$names};
2172: } else {
2173: my %loadnames=&Apache::lonnet::get('environment',
2174: ['notification','critnotification',
2175: 'permanentemail'],
2176: $udom,$uname);
2177: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
2178: return %loadnames;
2179: }
2180: }
2181:
2182: # ------------------------------------------------------------------ Screenname
2183:
2184: =pod
2185:
2186: =item * screenname($uname,$udom)
2187:
2188: Gets a users screenname and returns it as a string
2189:
2190: =cut
2191:
2192: sub screenname {
2193: my ($uname,$udom)=@_;
2194: if ($uname eq $env{'user.name'} &&
2195: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
2196: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
2197: return $names{'screenname'};
2198: }
2199:
2200:
2201: # ------------------------------------------------------------- Message Wrapper
2202:
2203: sub messagewrapper {
2204: my ($link,$username,$domain,$subject,$text)=@_;
2205: return
2206: '<a href="/adm/email?compose=individual&'.
2207: 'recname='.$username.'&recdom='.$domain.
2208: '&subject='.&escape($subject).'&text='.&escape($text).'" '.
2209: 'title="'.&mt('Send message').'">'.$link.'</a>';
2210: }
2211: # --------------------------------------------------------------- Notes Wrapper
2212:
2213: sub noteswrapper {
2214: my ($link,$un,$do)=@_;
2215: return
2216: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
2217: }
2218: # ------------------------------------------------------------- Aboutme Wrapper
2219:
2220: sub aboutmewrapper {
2221: my ($link,$username,$domain,$target)=@_;
2222: if (!defined($username) && !defined($domain)) {
2223: return;
2224: }
2225: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
2226: ($target?' target="$target"':'').' title="'.&mt("View this user's personal page").'">'.$link.'</a>';
2227: }
2228:
2229: # ------------------------------------------------------------ Syllabus Wrapper
2230:
2231:
2232: sub syllabuswrapper {
2233: my ($linktext,$coursedir,$domain,$fontcolor)=@_;
2234: if ($fontcolor) {
2235: $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>';
2236: }
2237: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
2238: }
2239:
2240: sub track_student_link {
2241: my ($linktext,$sname,$sdom,$target,$start) = @_;
2242: my $link ="/adm/trackstudent?";
2243: my $title = 'View recent activity';
2244: if (defined($sname) && $sname !~ /^\s*$/ &&
2245: defined($sdom) && $sdom !~ /^\s*$/) {
2246: $link .= "selected_student=$sname:$sdom";
2247: $title .= ' of this student';
2248: }
2249: if (defined($target) && $target !~ /^\s*$/) {
2250: $target = qq{target="$target"};
2251: } else {
2252: $target = '';
2253: }
2254: if ($start) { $link.='&start='.$start; }
2255:
2256: return qq{<a href="$link" title="$title" $target>$linktext</a>}.
2257: &help_open_topic('View_recent_activity');
2258: }
2259:
2260: =pod
2261:
2262: =back
2263:
2264: =head1 Access .tab File Data
2265:
2266: =over 4
2267:
2268: =item * languageids()
2269:
2270: returns list of all language ids
2271:
2272: =cut
2273:
2274: sub languageids {
2275: return sort(keys(%language));
2276: }
2277:
2278: =pod
2279:
2280: =item * languagedescription()
2281:
2282: returns description of a specified language id
2283:
2284: =cut
2285:
2286: sub languagedescription {
2287: my $code=shift;
2288: return ($supported_language{$code}?'* ':'').
2289: $language{$code}.
2290: ($supported_language{$code}?' ('.&mt('interface available').')':'');
2291: }
2292:
2293: sub plainlanguagedescription {
2294: my $code=shift;
2295: return $language{$code};
2296: }
2297:
2298: sub supportedlanguagecode {
2299: my $code=shift;
2300: return $supported_language{$code};
2301: }
2302:
2303: =pod
2304:
2305: =item * copyrightids()
2306:
2307: returns list of all copyrights
2308:
2309: =cut
2310:
2311: sub copyrightids {
2312: return sort(keys(%cprtag));
2313: }
2314:
2315: =pod
2316:
2317: =item * copyrightdescription()
2318:
2319: returns description of a specified copyright id
2320:
2321: =cut
2322:
2323: sub copyrightdescription {
2324: return &mt($cprtag{shift(@_)});
2325: }
2326:
2327: =pod
2328:
2329: =item * source_copyrightids()
2330:
2331: returns list of all source copyrights
2332:
2333: =cut
2334:
2335: sub source_copyrightids {
2336: return sort(keys(%scprtag));
2337: }
2338:
2339: =pod
2340:
2341: =item * source_copyrightdescription()
2342:
2343: returns description of a specified source copyright id
2344:
2345: =cut
2346:
2347: sub source_copyrightdescription {
2348: return &mt($scprtag{shift(@_)});
2349: }
2350:
2351: =pod
2352:
2353: =item * filecategories()
2354:
2355: returns list of all file categories
2356:
2357: =cut
2358:
2359: sub filecategories {
2360: return sort(keys(%category_extensions));
2361: }
2362:
2363: =pod
2364:
2365: =item * filecategorytypes()
2366:
2367: returns list of file types belonging to a given file
2368: category
2369:
2370: =cut
2371:
2372: sub filecategorytypes {
2373: my ($cat) = @_;
2374: return @{$category_extensions{lc($cat)}};
2375: }
2376:
2377: =pod
2378:
2379: =item * fileembstyle()
2380:
2381: returns embedding style for a specified file type
2382:
2383: =cut
2384:
2385: sub fileembstyle {
2386: return $fe{lc(shift(@_))};
2387: }
2388:
2389: sub filemimetype {
2390: return $fm{lc(shift(@_))};
2391: }
2392:
2393:
2394: sub filecategoryselect {
2395: my ($name,$value)=@_;
2396: return &select_form($value,$name,
2397: '' => &mt('Any category'),
2398: map { $_,$_ } sort(keys(%category_extensions)));
2399: }
2400:
2401: =pod
2402:
2403: =item * filedescription()
2404:
2405: returns description for a specified file type
2406:
2407: =cut
2408:
2409: sub filedescription {
2410: my $file_description = $fd{lc(shift())};
2411: $file_description =~ s:([\[\]]):~$1:g;
2412: return &mt($file_description);
2413: }
2414:
2415: =pod
2416:
2417: =item * filedescriptionex()
2418:
2419: returns description for a specified file type with
2420: extra formatting
2421:
2422: =cut
2423:
2424: sub filedescriptionex {
2425: my $ex=shift;
2426: my $file_description = $fd{lc($ex)};
2427: $file_description =~ s:([\[\]]):~$1:g;
2428: return '.'.$ex.' '.&mt($file_description);
2429: }
2430:
2431: # End of .tab access
2432: =pod
2433:
2434: =back
2435:
2436: =cut
2437:
2438: # ------------------------------------------------------------------ File Types
2439: sub fileextensions {
2440: return sort(keys(%fe));
2441: }
2442:
2443: # ----------------------------------------------------------- Display Languages
2444: # returns a hash with all desired display languages
2445: #
2446:
2447: sub display_languages {
2448: my %languages=();
2449: foreach my $lang (&preferred_languages()) {
2450: $languages{$lang}=1;
2451: }
2452: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
2453: if ($env{'form.displaylanguage'}) {
2454: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
2455: $languages{$lang}=1;
2456: }
2457: }
2458: return %languages;
2459: }
2460:
2461: sub preferred_languages {
2462: my @languages=();
2463: if ($env{'course.'.$env{'request.course.id'}.'.languages'}) {
2464: @languages=(@languages,split(/\s*(\,|\;|\:)\s*/,
2465: $env{'course.'.$env{'request.course.id'}.'.languages'}));
2466: }
2467: if ($env{'environment.languages'}) {
2468: @languages=(@languages,
2469: split(/\s*(\,|\;|\:)\s*/,$env{'environment.languages'}));
2470: }
2471: my $browser=(split(/\;/,$ENV{'HTTP_ACCEPT_LANGUAGE'}))[0];
2472: if ($browser) {
2473: @languages=(@languages,split(/\s*(\,|\;|\:)\s*/,$browser));
2474: }
2475: if ($Apache::lonnet::domain_lang_def{$env{'user.domain'}}) {
2476: @languages=(@languages,
2477: $Apache::lonnet::domain_lang_def{$env{'user.domain'}});
2478: }
2479: if ($Apache::lonnet::domain_lang_def{$env{'request.role.domain'}}) {
2480: @languages=(@languages,
2481: $Apache::lonnet::domain_lang_def{$env{'request.role.domain'}});
2482: }
2483: if ($Apache::lonnet::domain_lang_def{
2484: $Apache::lonnet::perlvar{'lonDefDomain'}}) {
2485: @languages=(@languages,
2486: $Apache::lonnet::domain_lang_def{
2487: $Apache::lonnet::perlvar{'lonDefDomain'}});
2488: }
2489: # turn "en-ca" into "en-ca,en"
2490: my @genlanguages;
2491: foreach my $lang (@languages) {
2492: unless ($lang=~/\w/) { next; }
2493: push (@genlanguages,$lang);
2494: if ($lang=~/(\-|\_)/) {
2495: push(@genlanguages,(split(/(\-|\_)/,$lang))[0]);
2496: }
2497: }
2498: return @genlanguages;
2499: }
2500:
2501: ###############################################################
2502: ## Student Answer Attempts ##
2503: ###############################################################
2504:
2505: =pod
2506:
2507: =head1 Alternate Problem Views
2508:
2509: =over 4
2510:
2511: =item * get_previous_attempt($symb, $username, $domain, $course,
2512: $getattempt, $regexp, $gradesub)
2513:
2514: Return string with previous attempt on problem. Arguments:
2515:
2516: =over 4
2517:
2518: =item * $symb: Problem, including path
2519:
2520: =item * $username: username of the desired student
2521:
2522: =item * $domain: domain of the desired student
2523:
2524: =item * $course: Course ID
2525:
2526: =item * $getattempt: Leave blank for all attempts, otherwise put
2527: something
2528:
2529: =item * $regexp: if string matches this regexp, the string will be
2530: sent to $gradesub
2531:
2532: =item * $gradesub: routine that processes the string if it matches $regexp
2533:
2534: =back
2535:
2536: The output string is a table containing all desired attempts, if any.
2537:
2538: =cut
2539:
2540: sub get_previous_attempt {
2541: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
2542: my $prevattempts='';
2543: no strict 'refs';
2544: if ($symb) {
2545: my (%returnhash)=
2546: &Apache::lonnet::restore($symb,$course,$domain,$username);
2547: if ($returnhash{'version'}) {
2548: my %lasthash=();
2549: my $version;
2550: for ($version=1;$version<=$returnhash{'version'};$version++) {
2551: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
2552: $lasthash{$key}=$returnhash{$version.':'.$key};
2553: }
2554: }
2555: $prevattempts='<table border="0" width="100%"><tr><td bgcolor="#777777">';
2556: $prevattempts.='<table border="0" width="100%"><tr bgcolor="#e6ffff"><td>History</td>';
2557: foreach my $key (sort(keys(%lasthash))) {
2558: my ($ign,@parts) = split(/\./,$key);
2559: if ($#parts > 0) {
2560: my $data=$parts[-1];
2561: pop(@parts);
2562: $prevattempts.='<td>Part '.join('.',@parts).'<br />'.$data.' </td>';
2563: } else {
2564: if ($#parts == 0) {
2565: $prevattempts.='<th>'.$parts[0].'</th>';
2566: } else {
2567: $prevattempts.='<th>'.$ign.'</th>';
2568: }
2569: }
2570: }
2571: if ($getattempt eq '') {
2572: for ($version=1;$version<=$returnhash{'version'};$version++) {
2573: $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Transaction '.$version.'</td>';
2574: foreach my $key (sort(keys(%lasthash))) {
2575: my $value;
2576: if ($key =~ /timestamp/) {
2577: $value=scalar(localtime($returnhash{$version.':'.$key}));
2578: } else {
2579: $value=$returnhash{$version.':'.$key};
2580: }
2581: $prevattempts.='<td>'.&unescape($value).' </td>';
2582: }
2583: }
2584: }
2585: $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Current</td>';
2586: foreach my $key (sort(keys(%lasthash))) {
2587: my $value;
2588: if ($key =~ /timestamp/) {
2589: $value=scalar(localtime($lasthash{$key}));
2590: } else {
2591: $value=$lasthash{$key};
2592: }
2593: $value=&unescape($value);
2594: if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
2595: $prevattempts.='<td>'.$value.' </td>';
2596: }
2597: $prevattempts.='</tr></table></td></tr></table>';
2598: } else {
2599: $prevattempts='Nothing submitted - no attempts.';
2600: }
2601: } else {
2602: $prevattempts='No data.';
2603: }
2604: }
2605:
2606: sub relative_to_absolute {
2607: my ($url,$output)=@_;
2608: my $parser=HTML::TokeParser->new(\$output);
2609: my $token;
2610: my $thisdir=$url;
2611: my @rlinks=();
2612: while ($token=$parser->get_token) {
2613: if ($token->[0] eq 'S') {
2614: if ($token->[1] eq 'a') {
2615: if ($token->[2]->{'href'}) {
2616: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
2617: }
2618: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
2619: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
2620: } elsif ($token->[1] eq 'base') {
2621: $thisdir=$token->[2]->{'href'};
2622: }
2623: }
2624: }
2625: $thisdir=~s-/[^/]*$--;
2626: foreach my $link (@rlinks) {
2627: unless (($link=~/^http:\/\//i) ||
2628: ($link=~/^\//) ||
2629: ($link=~/^javascript:/i) ||
2630: ($link=~/^mailto:/i) ||
2631: ($link=~/^\#/)) {
2632: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
2633: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
2634: }
2635: }
2636: # -------------------------------------------------- Deal with Applet codebases
2637: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
2638: return $output;
2639: }
2640:
2641: =pod
2642:
2643: =item * get_student_view
2644:
2645: show a snapshot of what student was looking at
2646:
2647: =cut
2648:
2649: sub get_student_view {
2650: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
2651: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
2652: my (%form);
2653: my @elements=('symb','courseid','domain','username');
2654: foreach my $element (@elements) {
2655: $form{'grade_'.$element}=eval '$'.$element #'
2656: }
2657: if (defined($moreenv)) {
2658: %form=(%form,%{$moreenv});
2659: }
2660: if (defined($target)) { $form{'grade_target'} = $target; }
2661: $feedurl=&Apache::lonnet::clutter($feedurl);
2662: my $userview=&Apache::lonnet::ssi_body($feedurl,%form);
2663: $userview=~s/\<body[^\>]*\>//gi;
2664: $userview=~s/\<\/body\>//gi;
2665: $userview=~s/\<html\>//gi;
2666: $userview=~s/\<\/html\>//gi;
2667: $userview=~s/\<head\>//gi;
2668: $userview=~s/\<\/head\>//gi;
2669: $userview=~s/action\s*\=/would_be_action\=/gi;
2670: $userview=&relative_to_absolute($feedurl,$userview);
2671: return $userview;
2672: }
2673:
2674: =pod
2675:
2676: =item * get_student_answers()
2677:
2678: show a snapshot of how student was answering problem
2679:
2680: =cut
2681:
2682: sub get_student_answers {
2683: my ($symb,$username,$domain,$courseid,%form) = @_;
2684: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
2685: my (%moreenv);
2686: my @elements=('symb','courseid','domain','username');
2687: foreach my $element (@elements) {
2688: $moreenv{'grade_'.$element}=eval '$'.$element #'
2689: }
2690: $moreenv{'grade_target'}='answer';
2691: %moreenv=(%form,%moreenv);
2692: my $userview=&Apache::lonnet::ssi('/res/'.$feedurl,%moreenv);
2693: return $userview;
2694: }
2695:
2696: =pod
2697:
2698: =item * &submlink()
2699:
2700: Inputs: $text $uname $udom $symb $target
2701:
2702: Returns: A link to grades.pm such as to see the SUBM view of a student
2703:
2704: =cut
2705:
2706: ###############################################
2707: sub submlink {
2708: my ($text,$uname,$udom,$symb,$target)=@_;
2709: if (!($uname && $udom)) {
2710: (my $cursymb, my $courseid,$udom,$uname)=
2711: &Apache::lonnet::whichuser($symb);
2712: if (!$symb) { $symb=$cursymb; }
2713: }
2714: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
2715: $symb=&escape($symb);
2716: if ($target) { $target="target=\"$target\""; }
2717: return '<a href="/adm/grades?&command=submission&'.
2718: 'symb='.$symb.'&student='.$uname.
2719: '&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
2720: }
2721: ##############################################
2722:
2723: =pod
2724:
2725: =item * &pgrdlink()
2726:
2727: Inputs: $text $uname $udom $symb $target
2728:
2729: Returns: A link to grades.pm such as to see the PGRD view of a student
2730:
2731: =cut
2732:
2733: ###############################################
2734: sub pgrdlink {
2735: my $link=&submlink(@_);
2736: $link=~s/(&command=submission)/$1&showgrading=yes/;
2737: return $link;
2738: }
2739: ##############################################
2740:
2741: =pod
2742:
2743: =item * &pprmlink()
2744:
2745: Inputs: $text $uname $udom $symb $target
2746:
2747: Returns: A link to parmset.pm such as to see the PPRM view of a
2748: student and a specific resource
2749:
2750: =cut
2751:
2752: ###############################################
2753: sub pprmlink {
2754: my ($text,$uname,$udom,$symb,$target)=@_;
2755: if (!($uname && $udom)) {
2756: (my $cursymb, my $courseid,$udom,$uname)=
2757: &Apache::lonnet::whichuser($symb);
2758: if (!$symb) { $symb=$cursymb; }
2759: }
2760: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
2761: $symb=&escape($symb);
2762: if ($target) { $target="target=\"$target\""; }
2763: return '<a href="/adm/parmset?&command=set&'.
2764: 'symb='.$symb.'&uname='.$uname.
2765: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
2766: }
2767: ##############################################
2768:
2769: =pod
2770:
2771: =back
2772:
2773: =cut
2774:
2775: ###############################################
2776:
2777:
2778: sub timehash {
2779: my @ltime=localtime(shift);
2780: return ( 'seconds' => $ltime[0],
2781: 'minutes' => $ltime[1],
2782: 'hours' => $ltime[2],
2783: 'day' => $ltime[3],
2784: 'month' => $ltime[4]+1,
2785: 'year' => $ltime[5]+1900,
2786: 'weekday' => $ltime[6],
2787: 'dayyear' => $ltime[7]+1,
2788: 'dlsav' => $ltime[8] );
2789: }
2790:
2791: sub utc_string {
2792: my ($date)=@_;
2793: return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
2794: }
2795:
2796: sub maketime {
2797: my %th=@_;
2798: return POSIX::mktime(
2799: ($th{'seconds'},$th{'minutes'},$th{'hours'},
2800: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
2801: }
2802:
2803: #########################################
2804:
2805: sub findallcourses {
2806: my ($roles) = @_;
2807: my %roles;
2808: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
2809: my %courses;
2810: my $now=time;
2811: foreach my $key (keys(%env)) {
2812: if ( $key=~m{^user\.role\.(\w+)\./(\w+)/(\w+)/?(\w*)$} ||
2813: $key=~m{^user\.role\.(cr/\w+/\w+/\w+)\./(\w+)/(\w+)}) {
2814: my ($role,$domain,$id,$sec) = ($1,$2,$3,$4);
2815: next if ($role eq 'ca' || $role eq 'aa');
2816: next if (%roles && !exists($roles{$role}));
2817: my ($starttime,$endtime)=split(/\./,$env{$key});
2818: my $active=1;
2819: if ($starttime) {
2820: if ($now<$starttime) { $active=0; }
2821: }
2822: if ($endtime) {
2823: if ($now>$endtime) { $active=0; }
2824: }
2825: if ($active) {
2826: if ($sec eq '') {
2827: $sec = 'none';
2828: }
2829: $courses{$domain.'_'.$id}{$sec} = 1;
2830: }
2831: }
2832: }
2833: return %courses;
2834: }
2835:
2836: ###############################################
2837:
2838: sub blockcheck {
2839: my ($setters,$activity) = @_;
2840: # Retrieve active student roles and active course coordinator/instructor roles
2841:
2842: my %live_courses = &findallcourses();
2843:
2844: # Retrieve blocking times and identity of blocker for active courses
2845: # unless user has 'evb' privilege.
2846:
2847: my $startblock = 0;
2848: my $endblock = 0;
2849:
2850: foreach my $course (keys(%live_courses)) {
2851: my $cdom = $env{'course.'.$course.'.domain'};
2852: my $cnum = $env{'course.'.$course.'.num'};
2853: my $noblock = 0;
2854: foreach my $sec (keys(%{$live_courses{$course}})) {
2855: my $role = 'cm./'.$cdom.'/'.$cnum;
2856: if ($sec ne 'none') {
2857: $role .= '/'.$sec;
2858: }
2859: if (&Apache::lonnet::allowed('evb',undef,undef,$role)) {
2860: $noblock = 1;
2861: last;
2862: }
2863: }
2864: # if they have the evb priv and are currently not playing student
2865: next if (($noblock) &&
2866: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
2867:
2868: $setters->{$course} = {};
2869: $setters->{$course}{'staff'} = [];
2870: $setters->{$course}{'times'} = [];
2871: my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
2872: foreach my $record (keys(%records)) {
2873: my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
2874: if ($start <= time && $end >= time) {
2875: my ($staff_name,$staff_dom,$title,$blocks) =
2876: &parse_block_record($records{$record});
2877: if ($blocks->{$activity} eq 'on') {
2878: push(@{$$setters{$course}{'staff'}}, [$staff_name,$staff_dom]); push(@{$$setters{$course}{'times'}}, [$start,$end]);
2879: if ( ($startblock == 0) || ($startblock > $1) ) {
2880: $startblock = $1;
2881: }
2882: if ( ($endblock == 0) || ($endblock < $2) ) {
2883: $endblock = $2;
2884: }
2885: }
2886: }
2887: }
2888: }
2889: return ($startblock,$endblock);
2890: }
2891:
2892: sub parse_block_record {
2893: my ($record) = @_;
2894: my ($setuname,$setudom,$title,$blocks);
2895: if (ref($record) eq 'HASH') {
2896: ($setuname,$setudom) = split(/:/,$record->{'setter'});
2897: $title = &unescape($record->{'event'});
2898: $blocks = $record->{'blocks'};
2899: } else {
2900: my @data = split(/:/,$record,3);
2901: if (scalar(@data) eq 2) {
2902: $title = $data[1];
2903: ($setuname,$setudom) = split(/@/,$data[0]);
2904: } else {
2905: ($setuname,$setudom,$title) = @data;
2906: }
2907: $blocks = { 'com' => 'on' };
2908: }
2909: return ($setuname,$setudom,$title,$blocks);
2910: }
2911:
2912: sub build_block_table {
2913: my ($startblock,$endblock,$setters) = @_;
2914: my %lt = &Apache::lonlocal::texthash(
2915: 'cacb' => 'Currently active communication blocks',
2916: 'cour' => 'Course',
2917: 'dura' => 'Duration',
2918: 'blse' => 'Block set by'
2919: );
2920: my $output;
2921: $output = '<br />'.$lt{'cacb'}.':<br />';
2922: $output .= &start_data_table();
2923: $output .= '
2924: <tr>
2925: <th>'.$lt{'cour'}.'</th>
2926: <th>'.$lt{'dura'}.'</th>
2927: <th>'.$lt{'blse'}.'</th>
2928: </tr>
2929: ';
2930: foreach my $course (keys(%{$setters})) {
2931: my %courseinfo=&Apache::lonnet::coursedescription($course);
2932: for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
2933: my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
2934: my $fullname = &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);
2935: my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
2936: $openblock = &Apache::lonlocal::locallocaltime($openblock);
2937: $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
2938: $output .= &Apache::loncommon::start_data_table_row().
2939: '<td>'.$courseinfo{'description'}.'</td>'.
2940: '<td>'.$openblock.' to '.$closeblock.'</td>'.
2941: '<td>'.$fullname.'.</td>'.
2942: &Apache::loncommon::end_data_table_row();
2943: }
2944: }
2945: $output .= &end_data_table();
2946: }
2947:
2948: ###############################################
2949:
2950: =pod
2951:
2952: =head1 Domain Template Functions
2953:
2954: =over 4
2955:
2956: =item * &determinedomain()
2957:
2958: Inputs: $domain (usually will be undef)
2959:
2960: Returns: Determines which domain should be used for designs
2961:
2962: =cut
2963:
2964: ###############################################
2965: sub determinedomain {
2966: my $domain=shift;
2967: if (! $domain) {
2968: # Determine domain if we have not been given one
2969: $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
2970: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
2971: if ($env{'request.role.domain'}) {
2972: $domain=$env{'request.role.domain'};
2973: }
2974: }
2975: return $domain;
2976: }
2977: ###############################################
2978: =pod
2979:
2980: =item * &domainlogo()
2981:
2982: Inputs: $domain (usually will be undef)
2983:
2984: Returns: A link to a domain logo, if the domain logo exists.
2985: If the domain logo does not exist, a description of the domain.
2986:
2987: =cut
2988:
2989: ###############################################
2990: sub domainlogo {
2991: my $domain = &determinedomain(shift);
2992: # See if there is a logo
2993: if (-e '/home/httpd/html/adm/lonDomLogos/'.$domain.'.gif') {
2994: my $logo=&lonhttpdurl("/adm/lonDomLogos/$domain.gif");
2995: return '<img src="'.$logo.'" alt="'.$domain.'" />';
2996: } elsif(exists($Apache::lonnet::domaindescription{$domain})) {
2997: return $Apache::lonnet::domaindescription{$domain};
2998: } else {
2999: return '';
3000: }
3001: }
3002: ##############################################
3003:
3004: =pod
3005:
3006: =item * &designparm()
3007:
3008: Inputs: $which parameter; $domain (usually will be undef)
3009:
3010: Returns: value of designparamter $which
3011:
3012: =cut
3013:
3014:
3015: ##############################################
3016: sub designparm {
3017: my ($which,$domain)=@_;
3018: if ($env{'browser.blackwhite'} eq 'on') {
3019: if ($which=~/\.(font|alink|vlink|link)$/) {
3020: return '#000000';
3021: }
3022: if ($which=~/\.(pgbg|sidebg)$/) {
3023: return '#FFFFFF';
3024: }
3025: if ($which=~/\.tabbg$/) {
3026: return '#CCCCCC';
3027: }
3028: }
3029: if (exists($env{'environment.color.'.$which})) {
3030: return $env{'environment.color.'.$which};
3031: }
3032: $domain=&determinedomain($domain);
3033: if (exists($designhash{$domain.'.'.$which})) {
3034: return $designhash{$domain.'.'.$which};
3035: } else {
3036: return $designhash{'default.'.$which};
3037: }
3038: }
3039:
3040: ###############################################
3041: ###############################################
3042:
3043: =pod
3044:
3045: =back
3046:
3047: =head1 HTTP Helpers
3048:
3049: =over 4
3050:
3051: =item * &bodytag()
3052:
3053: Returns a uniform header for LON-CAPA web pages.
3054:
3055: Inputs:
3056:
3057: =over 4
3058:
3059: =item * $title, A title to be displayed on the page.
3060:
3061: =item * $function, the current role (can be undef).
3062:
3063: =item * $addentries, extra parameters for the <body> tag.
3064:
3065: =item * $bodyonly, if defined, only return the <body> tag.
3066:
3067: =item * $domain, if defined, force a given domain.
3068:
3069: =item * $forcereg, if page should register as content page (relevant for
3070: text interface only)
3071:
3072: =item * $customtitle, alternate text to use instead of $title
3073: in the title box that appears, this text
3074: is not auto translated like the $title is
3075:
3076: =item * $notopbar, if true, keep the 'what is this' info but remove the
3077: navigational links
3078:
3079: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
3080:
3081: =item * $notitle, if true keep the nav controls, but remove the title bar
3082:
3083: =item * $no_inline_link, if true and in remote mode, don't show the
3084: 'Switch To Inline Menu' link
3085:
3086: =item * $args, optional argument valid values are
3087: no_auto_mt_title -> prevents &mt()ing the title arg
3088:
3089: =back
3090:
3091: Returns: A uniform header for LON-CAPA web pages.
3092: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
3093: If $bodyonly is undef or zero, an html string containing a <body> tag and
3094: other decorations will be returned.
3095:
3096: =cut
3097:
3098: sub bodytag {
3099: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
3100: $notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
3101:
3102: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
3103:
3104: $function = &get_users_function() if (!$function);
3105: my $img = &designparm($function.'.img',$domain);
3106: my $font = &designparm($function.'.font',$domain);
3107: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
3108:
3109: my %design = ( 'style' => 'margin-top: 0px',
3110: 'bgcolor' => $pgbg,
3111: 'text' => $font,
3112: 'alink' => &designparm($function.'.alink',$domain),
3113: 'vlink' => &designparm($function.'.vlink',$domain),
3114: 'link' => &designparm($function.'.link',$domain),);
3115: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
3116:
3117: # role and realm
3118: my ($role,$realm) = split(/\./,$env{'request.role'},2);
3119: if ($role eq 'ca') {
3120: my ($rdom,$rname) = ($realm =~ m-^/(\w+)/(\w+)$-);
3121: $realm = &plainname($rname,$rdom).':'.$rdom;
3122: }
3123: # realm
3124: if ($env{'request.course.id'}) {
3125: if ($env{'request.role'} !~ /^cr/) {
3126: $role = &Apache::lonnet::plaintext($role,&course_type());
3127: }
3128: $realm = $env{'course.'.$env{'request.course.id'}.'.description'};
3129: } else {
3130: $role = &Apache::lonnet::plaintext($role);
3131: }
3132:
3133: if (!$realm) { $realm=' '; }
3134: # Set messages
3135: my $messages=&domainlogo($domain);
3136: # Port for miniserver
3137: my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
3138: if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
3139:
3140: my $extra_body_attr = &make_attr_string($forcereg,\%design);
3141:
3142: # construct main body tag
3143: my $bodytag = "<body $extra_body_attr>".
3144: &Apache::lontexconvert::init_math_support();
3145:
3146: if ($bodyonly
3147: || ($env{'request.state'} eq 'construct'
3148: && $env{'environment.remote'} ne 'off' )) {
3149: return $bodytag;
3150: } elsif ($env{'browser.interface'} eq 'textual') {
3151: # Accessibility
3152:
3153: $bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
3154: if (!$notitle) {
3155: $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
3156: }
3157: return $bodytag;
3158: }
3159:
3160: my $name = &plainname($env{'user.name'},$env{'user.domain'});
3161: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3162: undef($role);
3163: } else {
3164: $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
3165: }
3166:
3167: my $roleinfo=(<<ENDROLE);
3168: <td class="LC_title_bar_who">
3169: <div class="LC_title_bar_name">
3170: $name
3171:
3172: </div>
3173: <div class="LC_title_bar_role">
3174: $role
3175: </div>
3176: <div class="LC_title_bar_realm">
3177: $realm
3178: </div>
3179: </td>
3180: ENDROLE
3181:
3182: my $titleinfo = '<span class="LC_title_bar_title">'.$title.'</span>';
3183: if ($customtitle) {
3184: $titleinfo = $customtitle;
3185: }
3186: #
3187: # Extra info if you are the DC
3188: my $dc_info = '';
3189: if ($env{'user.adv'} && exists($env{'user.role.dc./'.
3190: $env{'course.'.$env{'request.course.id'}.
3191: '.domain'}.'/'})) {
3192: my $cid = $env{'request.course.id'};
3193: $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
3194: $dc_info =~ s/\s+$//;
3195: $dc_info = '('.$dc_info.')';
3196: }
3197:
3198: if ($env{'environment.remote'} eq 'off') {
3199: # No Remote
3200: if ($env{'request.state'} eq 'construct') {
3201: $forcereg=1;
3202: }
3203:
3204: if (!$customtitle && $env{'request.state'} eq 'construct') {
3205: # this is for resources; directories have customtitle, and crumbs
3206: # and select recent are created in lonpubdir.pm
3207: my ($uname,$thisdisfn)=
3208: ($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
3209: my $formaction='/priv/'.$uname.'/'.$thisdisfn;
3210: $formaction=~s/\/+/\//g;
3211:
3212: my $parentpath = '';
3213: my $lastitem = '';
3214: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
3215: $parentpath = $1;
3216: $lastitem = $2;
3217: } else {
3218: $lastitem = $thisdisfn;
3219: }
3220: $titleinfo =
3221: &Apache::loncommon::help_open_menu('','',3,'Authoring').
3222: '<b>Construction Space</b>: '.
3223: '<form name="dirs" method="post" action="'.$formaction
3224: .'" target="_top"><tt><b>'
3225: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<font size=\"+1\">$lastitem</font></b></tt><br />"
3226: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
3227: .'</form>'
3228: .&Apache::lonmenu::constspaceform();
3229: }
3230:
3231: my $titletable;
3232: if (!$notitle) {
3233: $titletable =
3234: '<table id="LC_title_bar">'.
3235: "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
3236: '</tr></table>';
3237: }
3238: if ($notopbar) {
3239: $bodytag .= $titletable;
3240: } else {
3241: if ($env{'request.state'} eq 'construct') {
3242: $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
3243: $titletable);
3244: } else {
3245: $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
3246: $titletable;
3247: }
3248: }
3249: return $bodytag;
3250: }
3251:
3252: #
3253: # Top frame rendering, Remote is up
3254: #
3255:
3256: my $upperleft='<img src="http://'.$ENV{'HTTP_HOST'}.':'.
3257: $lonhttpdPort.$img.'" alt="'.$function.'" />';
3258:
3259: # Explicit link to get inline menu
3260: my $menu= ($no_inline_link?''
3261: :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
3262: #
3263: if ($notitle) {
3264: return $bodytag;
3265: }
3266: return(<<ENDBODY);
3267: $bodytag
3268: <table id="LC_title_bar" class="LC_with_remote">
3269: <tr><td class="LC_title_bar_role_logo">$upperleft</td>
3270: <td class="LC_title_bar_domain_logo">$messages </td>
3271: </tr>
3272: <tr><td>$titleinfo $dc_info $menu</td>
3273: $roleinfo
3274: </tr>
3275: </table>
3276: ENDBODY
3277: }
3278:
3279: sub make_attr_string {
3280: my ($register,$attr_ref) = @_;
3281:
3282: if ($attr_ref && !ref($attr_ref)) {
3283: die("addentries Must be a hash ref ".
3284: join(':',caller(1))." ".
3285: join(':',caller(0))." ");
3286: }
3287:
3288: if ($register) {
3289: my ($on_load,$on_unload);
3290: foreach my $key (keys(%{$attr_ref})) {
3291: if (lc($key) eq 'onload') {
3292: $on_load.=$attr_ref->{$key}.';';
3293: delete($attr_ref->{$key});
3294:
3295: } elsif (lc($key) eq 'onunload') {
3296: $on_unload.=$attr_ref->{$key}.';';
3297: delete($attr_ref->{$key});
3298: }
3299: }
3300: $attr_ref->{'onload'} =
3301: &Apache::lonmenu::loadevents(). $on_load;
3302: $attr_ref->{'onunload'}=
3303: &Apache::lonmenu::unloadevents().$on_unload;
3304: }
3305:
3306: # Accessibility font enhance
3307: if ($env{'browser.fontenhance'} eq 'on') {
3308: my $style;
3309: foreach my $key (keys(%{$attr_ref})) {
3310: if (lc($key) eq 'style') {
3311: $style.=$attr_ref->{$key}.';';
3312: delete($attr_ref->{$key});
3313: }
3314: }
3315: $attr_ref->{'style'}=$style.'; font-size: x-large;';
3316: }
3317:
3318: if ($env{'browser.blackwhite'} eq 'on') {
3319: delete($attr_ref->{'font'});
3320: delete($attr_ref->{'link'});
3321: delete($attr_ref->{'alink'});
3322: delete($attr_ref->{'vlink'});
3323: delete($attr_ref->{'bgcolor'});
3324: delete($attr_ref->{'background'});
3325: }
3326:
3327: my $attr_string;
3328: foreach my $attr (keys(%$attr_ref)) {
3329: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
3330: }
3331: return $attr_string;
3332: }
3333:
3334:
3335: ###############################################
3336: ###############################################
3337:
3338: =pod
3339:
3340: =back
3341:
3342: =head1 HTML Helpers
3343:
3344: =over 4
3345:
3346: =item * &endbodytag()
3347:
3348: Returns a uniform footer for LON-CAPA web pages.
3349:
3350: Inputs: none
3351:
3352: =back
3353:
3354: =cut
3355:
3356: sub endbodytag {
3357: my $endbodytag='</body>';
3358: $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
3359: if ( exists( $env{'internal.head.redirect'} ) ) {
3360: $endbodytag=
3361: "<br /><a href=\"$env{'internal.head.redirect'}\">".
3362: &mt('Continue').'</a>'.
3363: $endbodytag;
3364: }
3365: return $endbodytag;
3366: }
3367:
3368: =pod
3369:
3370: =over 4
3371:
3372: =item * &standard_css()
3373:
3374: Returns a style sheet
3375:
3376: Inputs: (all optional)
3377: domain -> force to color decorate a page for a specific
3378: domain
3379: function -> force usage of a specific rolish color scheme
3380: bgcolor -> override the default page bgcolor
3381:
3382: =back
3383:
3384: =cut
3385:
3386: sub standard_css {
3387: my ($function,$domain,$bgcolor) = @_;
3388: $function = &get_users_function() if (!$function);
3389: my $img = &designparm($function.'.img', $domain);
3390: my $tabbg = &designparm($function.'.tabbg', $domain);
3391: my $font = &designparm($function.'.font', $domain);
3392: my $sidebg = &designparm($function.'.sidebg',$domain);
3393: my $pgbg_or_bgcolor =
3394: $bgcolor ||
3395: &designparm($function.'.pgbg', $domain);
3396: my $pgbg = &designparm($function.'.pgbg', $domain);
3397: my $alink = &designparm($function.'.alink', $domain);
3398: my $vlink = &designparm($function.'.vlink', $domain);
3399: my $link = &designparm($function.'.link', $domain);
3400:
3401: my $sans = 'Arial,Helvetica,sans-serif';
3402: my $mono = 'monospace';
3403: my $data_table_head = $tabbg;
3404: my $data_table_light = '#EEEEEE';
3405: my $data_table_dark = '#DDDDDD';
3406: my $data_table_darker = '#CCCCCC';
3407: my $data_table_highlight = '#FFFF00';
3408: my $mail_new = '#FFBB77';
3409: my $mail_new_hover = '#DD9955';
3410: my $mail_read = '#BBBB77';
3411: my $mail_read_hover = '#999944';
3412: my $mail_replied = '#AAAA88';
3413: my $mail_replied_hover = '#888855';
3414: my $mail_other = '#99BBBB';
3415: my $mail_other_hover = '#669999';
3416: my $table_header = '#DDDDDD';
3417:
3418: my $border = ($env{'browser.type'} eq 'explorer') ? '0px 2px 0px 2px'
3419: : '0px 3px 0px 4px';
3420:
3421: return <<END;
3422: h1, h2, h3, th { font-family: $sans }
3423: a:focus { color: red; background: yellow }
3424: table.thinborder { border-collapse: collapse; }
3425: table.thinborder tr th { border-style: solid; border-width: 1px; background: $tabbg;}
3426: table.thinborder tr td { border-style: solid; border-width: 1px}
3427:
3428: form, .inline { display: inline; }
3429: .center { text-align: center; }
3430: .LC_filename {font-family: $mono;}
3431: .LC_error {
3432: color: red;
3433: font-size: larger;
3434: }
3435: .LC_warning,
3436: .LC_diff_removed {
3437: color: red;
3438: }
3439: .LC_success,
3440: .LC_diff_added {
3441: color: green;
3442: }
3443: .LC_icon {
3444: border: 0px;
3445: }
3446:
3447: table.LC_pastsubmission {
3448: border: 1px solid black;
3449: margin: 2px;
3450: }
3451:
3452: table#LC_top_nav, table#LC_menubuttons {
3453: width: 100%;
3454: background: $pgbg;
3455: border: 2px;
3456: border-collapse: separate;
3457: padding: 0px;
3458: }
3459:
3460: table#LC_title_bar, table.LC_breadcrumbs, table#LC_nav_location,
3461: table#LC_title_bar.LC_with_remote {
3462: width: 100%;
3463: border-color: $pgbg;
3464: border-style: solid;
3465: border-width: $border;
3466:
3467: background: $pgbg;
3468: font-family: $sans;
3469: border-collapse: collapse;
3470: padding: 0px;
3471: }
3472:
3473: table.LC_docs_path {
3474: width: 100%;
3475: border: 0;
3476: background: $pgbg;
3477: font-family: $sans;
3478: border-collapse: collapse;
3479: padding: 0px;
3480: }
3481:
3482: table#LC_title_bar td {
3483: background: $tabbg;
3484: }
3485: table#LC_title_bar td.LC_title_bar_who {
3486: background: $tabbg;
3487: color: $font;
3488: font: small $sans;
3489: text-align: right;
3490: }
3491: span.LC_metadata {
3492: font-family: $sans;
3493: }
3494: span.LC_title_bar_title {
3495: font: bold x-large $sans;
3496: }
3497: table#LC_title_bar td.LC_title_bar_domain_logo {
3498: background: $sidebg;
3499: text-align: right;
3500: padding: 0px;
3501: }
3502: table#LC_title_bar td.LC_title_bar_role_logo {
3503: background: $sidebg;
3504: padding: 0px;
3505: }
3506:
3507: table#LC_menubuttons_mainmenu {
3508: background: $pgbg;
3509: border: 0px;
3510: border-spacing: 1px;
3511: padding: 0px 1px;
3512: margin: 0px;
3513: border-collapse: separate;
3514: }
3515: table#LC_menubuttons img, table#LC_menubuttons_mainmenu img {
3516: border: 0px;
3517: }
3518: table#LC_top_nav td {
3519: background: $tabbg;
3520: border: 0px;
3521: font-size: small;
3522: }
3523: table#LC_top_nav td a, div#LC_top_nav a {
3524: color: $font;
3525: font-family: $sans;
3526: }
3527: table#LC_top_nav td.LC_top_nav_logo {
3528: background: $tabbg;
3529: text-align: left;
3530: white-space: nowrap;
3531: width: 31px;
3532: }
3533: table#LC_top_nav td.LC_top_nav_logo img {
3534: border: 0px;
3535: vertical-align: bottom;
3536: }
3537: table#LC_top_nav td.LC_top_nav_exit,
3538: table#LC_top_nav td.LC_top_nav_help {
3539: width: 2.0em;
3540: }
3541: table#LC_top_nav td.LC_top_nav_login {
3542: width: 4.0em;
3543: text-align: center;
3544: }
3545: table.LC_breadcrumbs td, table.LC_docs_path td {
3546: background: $tabbg;
3547: color: $font;
3548: font-family: $sans;
3549: font-size: smaller;
3550: }
3551: table.LC_breadcrumbs td.LC_breadcrumbs_component,
3552: table.LC_docs_path td.LC_docs_path_component {
3553: background: $tabbg;
3554: color: $font;
3555: font-family: $sans;
3556: font-size: larger;
3557: text-align: right;
3558: }
3559: td.LC_table_cell_checkbox {
3560: text-align: center;
3561: }
3562:
3563: .LC_menubuttons_inline_text {
3564: color: $font;
3565: font-family: $sans;
3566: font-size: smaller;
3567: }
3568:
3569: td.LC_menubuttons_text {
3570: color: $font;
3571: font-family: $sans;
3572: }
3573: td.LC_menubuttons_img {
3574: background: $tabbg;
3575: }
3576: .LC_current_location {
3577: font-family: $sans;
3578: background: $tabbg;
3579: }
3580: .LC_new_mail {
3581: font-family: $sans;
3582: font-weight: bold;
3583: }
3584:
3585: table.LC_aboutme_port {
3586: border: 0px;
3587: border-collapse: collapse;
3588: border-spacing: 0px;
3589: }
3590: table.LC_data_table, table.LC_mail_list {
3591: border: 1px solid #000000;
3592: border-collapse: separate;
3593: border-spacing: 1px;
3594: }
3595: .LC_data_table_dense {
3596: font-size: small;
3597: }
3598: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th {
3599: font-weight: bold;
3600: background-color: $data_table_head;
3601: font-size: smaller;
3602: }
3603: table.LC_data_table tr td,
3604: table.LC_aboutme_port tr td {
3605: background-color: $data_table_light;
3606: padding: 2px;
3607: }
3608: table.LC_data_table tr.LC_even_row td,
3609: table.LC_aboutme_port tr.LC_even_row td {
3610: background-color: $data_table_dark;
3611: }
3612: table.LC_data_table tr.LC_data_table_highlight td {
3613: background-color: $data_table_darker;
3614: }
3615: table.LC_data_table tr.LC_empty_row td,
3616: table.LC_whatsnew tr.LC_empty_row td {
3617: background-color: #FFFFFF;
3618: font-weight: bold;
3619: font-style: italic;
3620: text-align: center;
3621: padding: 8px;
3622: }
3623: table.LC_whatsnew tr.LC_empty_row td {
3624: padding: 4ex
3625: }
3626:
3627:
3628: table.LC_whatsnew {
3629: }
3630:
3631: table.LC_whatsnew tr th,
3632: table.LC_whatsnew tr.LC_info_row td {
3633: background-color: #CCC;
3634: font-weight: bold;
3635: font-size: small;
3636: text-align: right;
3637: }
3638: table.LC_whatsnew tr td {
3639: background-color: #FFF;
3640: font-size: small;
3641: text-align: right;
3642: }
3643: table.LC_whatsnew tr td.LC_first_item {
3644: text-align: left;
3645: }
3646:
3647: table.LC_whatsnew tr.LC_odd_row td {
3648: background-color: #EEE;
3649: }
3650:
3651: table.LC_createuser {
3652: }
3653:
3654: table.LC_createuser tr.LC_section_row td {
3655: font-size: smaller;
3656: }
3657:
3658: table.LC_createuser tr.LC_info_row td {
3659: background-color: #CCC;
3660: font-weight: bold;
3661: text-align: center;
3662: }
3663:
3664: table.LC_calendar {
3665: border: 1px solid #000000;
3666: border-collapse: collapse;
3667: }
3668: table.LC_calendar_pickdate {
3669: font-size: xx-small;
3670: }
3671: table.LC_calendar tr td {
3672: border: 1px solid #000000;
3673: vertical-align: top;
3674: }
3675: table.LC_calendar tr td.LC_calendar_day_empty {
3676: background-color: $data_table_dark;
3677: }
3678: table.LC_calendar tr td.LC_calendar_day_current {
3679: background-color: $data_table_highlight;
3680: }
3681:
3682: table.LC_mail_list tr.LC_mail_new {
3683: background-color: $mail_new;
3684: }
3685: table.LC_mail_list tr.LC_mail_new:hover {
3686: background-color: $mail_new_hover;
3687: }
3688: table.LC_mail_list tr.LC_mail_read {
3689: background-color: $mail_read;
3690: }
3691: table.LC_mail_list tr.LC_mail_read:hover {
3692: background-color: $mail_read_hover;
3693: }
3694: table.LC_mail_list tr.LC_mail_replied {
3695: background-color: $mail_replied;
3696: }
3697: table.LC_mail_list tr.LC_mail_replied:hover {
3698: background-color: $mail_replied_hover;
3699: }
3700: table.LC_mail_list tr.LC_mail_other {
3701: background-color: $mail_other;
3702: }
3703: table.LC_mail_list tr.LC_mail_other:hover {
3704: background-color: $mail_other_hover;
3705: }
3706:
3707: table#LC_portfolio_actions {
3708: width: auto;
3709: background: $pgbg;
3710: border: 0px;
3711: border-spacing: 2px 2px;
3712: padding: 0px;
3713: margin: 0px;
3714: border-collapse: separate;
3715: }
3716: table#LC_portfolio_actions td.LC_label {
3717: background: $tabbg;
3718: text-align: right;
3719: }
3720: table#LC_portfolio_actions td.LC_value {
3721: background: $tabbg;
3722: }
3723:
3724: table#LC_cstr_controls {
3725: width: 100%;
3726: border-collapse: collapse;
3727: }
3728: table#LC_cstr_controls tr td {
3729: border: 4px solid $pgbg;
3730: padding: 4px;
3731: text-align: center;
3732: background: $tabbg;
3733: }
3734: table#LC_cstr_controls tr th {
3735: border: 4px solid $pgbg;
3736: background: $table_header;
3737: text-align: center;
3738: font-family: $sans;
3739: font-size: smaller;
3740: }
3741:
3742: table#LC_browser {
3743:
3744: }
3745: table#LC_browser tr th {
3746: background: $table_header;
3747: }
3748: table#LC_browser tr td {
3749: padding: 2px;
3750: }
3751: table#LC_browser tr.LC_browser_file,
3752: table#LC_browser tr.LC_browser_file_published {
3753: background: #CCFF88;
3754: }
3755: table#LC_browser tr.LC_browser_file_locked,
3756: table#LC_browser tr.LC_browser_file_unpublished {
3757: background: #FFAA99;
3758: }
3759: table#LC_browser tr.LC_browser_file_obsolete {
3760: background: #AAAAAA;
3761: }
3762: table#LC_browser tr.LC_browser_file_modified,
3763: table#LC_browser tr.LC_browser_file_metamodified {
3764: background: #FFFF77;
3765: }
3766: table#LC_browser tr.LC_browser_folder {
3767: background: #CCCCFF;
3768: }
3769: span.LC_current_location {
3770: font-size: x-large;
3771: background: $pgbg;
3772: }
3773:
3774: span.LC_parm_menu_item {
3775: font-size: larger;
3776: font-family: $sans;
3777: }
3778: span.LC_parm_scope_all {
3779: color: red;
3780: }
3781: span.LC_parm_scope_folder {
3782: color: green;
3783: }
3784: span.LC_parm_scope_resource {
3785: color: orange;
3786: }
3787: span.LC_parm_part {
3788: color: blue;
3789: }
3790: span.LC_parm_folder, span.LC_parm_symb {
3791: font-size: x-small;
3792: font-family: $mono;
3793: color: #AAAAAA;
3794: }
3795:
3796: td.LC_parm_overview_level_menu, td.LC_parm_overview_map_menu,
3797: td.LC_parm_overview_parm_selectors, td.LC_parm_overview_parm_restrictions {
3798: border: 1px solid black;
3799: border-collapse: collapse;
3800: }
3801: table.LC_parm_overview_restrictions td {
3802: border-width: 1px 4px 1px 4px;
3803: border-style: solid;
3804: border-color: $pgbg;
3805: text-align: center;
3806: }
3807: table.LC_parm_overview_restrictions th {
3808: background: $tabbg;
3809: border-width: 1px 4px 1px 4px;
3810: border-style: solid;
3811: border-color: $pgbg;
3812: }
3813: table#LC_helpmenu {
3814: border: 0px;
3815: height: 55px;
3816: border-spacing: 0px;
3817: }
3818:
3819: table#LC_helpmenu fieldset legend {
3820: font-size: larger;
3821: font-weight: bold;
3822: }
3823: table#LC_helpmenu_links {
3824: width: 100%;
3825: border: 1px solid black;
3826: background: $pgbg;
3827: padding: 0px;
3828: border-spacing: 1px;
3829: }
3830: table#LC_helpmenu_links tr td {
3831: padding: 1px;
3832: background: $tabbg;
3833: text-align: center;
3834: font-weight: bold;
3835: }
3836:
3837: table#LC_helpmenu_links a:link, table#LC_helpmenu_links a:visited,
3838: table#LC_helpmenu_links a:active {
3839: text-decoration: none;
3840: color: $font;
3841: }
3842: table#LC_helpmenu_links a:hover {
3843: text-decoration: underline;
3844: color: $vlink;
3845: }
3846:
3847: .LC_chrt_popup_exists {
3848: border: 1px solid #339933;
3849: margin: -1px;
3850: }
3851: .LC_chrt_popup_up {
3852: border: 1px solid yellow;
3853: margin: -1px;
3854: }
3855: .LC_chrt_popup {
3856: border: 1px solid #8888FF;
3857: background: #CCCCFF;
3858: }
3859:
3860: table.LC_pick_box {
3861: width: 100%;
3862: border-collapse: separate;
3863: background: white;
3864: border: 1px solid black;
3865: border-spacing: 1px;
3866: }
3867: table.LC_pick_box td.LC_pick_box_title {
3868: background: $tabbg;
3869: font-weight: bold;
3870: text-align: right;
3871: width: 184px;
3872: padding: 8px;
3873: }
3874: table.LC_pick_box td.LC_pick_box_separator {
3875: padding: 0px;
3876: height: 1px;
3877: background: black;
3878: }
3879: table.LC_pick_box td.LC_pick_box_submit {
3880: text-align: right;
3881: }
3882:
3883: table.LC_group_priv_box {
3884: background: white;
3885: border: 1px solid black;
3886: border-spacing: 1px;
3887: }
3888: table.LC_group_priv_box td.LC_pick_box_title {
3889: background: $tabbg;
3890: font-weight: bold;
3891: text-align: right;
3892: width: 184px;
3893: }
3894: table.LC_group_priv_box td.LC_groups_fixed {
3895: background: $data_table_light;
3896: text-align: center;
3897: }
3898: table.LC_group_priv_box td.LC_groups_optional {
3899: background: $data_table_dark;
3900: text-align: center;
3901: }
3902: table.LC_group_priv_box td.LC_groups_functionality {
3903: background: $data_table_darker;
3904: text-align: center;
3905: font-weight: bold;
3906: }
3907: table.LC_group_priv td {
3908: text-align: left;
3909: padding: 0px;
3910: }
3911:
3912: table.LC_notify_front_page {
3913: background: white;
3914: border: 1px solid black;
3915: padding: 8px;
3916: }
3917: table.LC_notify_front_page td {
3918: padding: 8px;
3919: }
3920: .LC_navbuttons {
3921: margin: 2ex 0ex 2ex 0ex;
3922: }
3923: .LC_topic_bar {
3924: font-family: $sans;
3925: font-weight: bold;
3926: width: 100%;
3927: background: $tabbg;
3928: vertical-align: middle;
3929: margin: 2ex 0ex 2ex 0ex;
3930: }
3931: .LC_topic_bar span {
3932: vertical-align: middle;
3933: }
3934: .LC_topic_bar img {
3935: vertical-align: bottom;
3936: }
3937: table.LC_course_group_status {
3938: margin: 20px;
3939: }
3940: table.LC_status_selector td {
3941: vertical-align: top;
3942: text-align: center;
3943: padding: 4px;
3944: }
3945: table.LC_descriptive_input td.LC_description {
3946: vertical-align: top;
3947: text-align: right;
3948: font-weight: bold;
3949: }
3950:
3951: END
3952: }
3953:
3954: =pod
3955:
3956: =over 4
3957:
3958: =item * &headtag()
3959:
3960: Returns a uniform footer for LON-CAPA web pages.
3961:
3962: Inputs: $title - optional title for the head
3963: $head_extra - optional extra HTML to put inside the <head>
3964: $args - optional arguments
3965: force_register - if is true call registerurl so the remote is
3966: informed
3967: redirect -> array ref of
3968: 1- seconds before redirect occurs
3969: 2- url to redirect to
3970: 3- whether the side effect should occur
3971: (side effect of setting
3972: $env{'internal.head.redirect'} to the url
3973: redirected too)
3974: domain -> force to color decorate a page for a specific
3975: domain
3976: function -> force usage of a specific rolish color scheme
3977: bgcolor -> override the default page bgcolor
3978: no_auto_mt_title
3979: -> prevent &mt()ing the title arg
3980:
3981: =back
3982:
3983: =cut
3984:
3985: sub headtag {
3986: my ($title,$head_extra,$args) = @_;
3987:
3988: my $function = $args->{'function'} || &get_users_function();
3989: my $domain = $args->{'domain'} || &determinedomain();
3990: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
3991: my $url = join(':',$env{'user.name'},$env{'user.domain'},
3992: $Apache::lonnet::perlvar{'lonVersion'},
3993: #time(),
3994: $env{'environment.color.timestamp'},
3995: $function,$domain,$bgcolor);
3996:
3997: $url = '/adm/css/'.&escape($url).'.css';
3998:
3999: my $result =
4000: '<head>'.
4001: &font_settings();
4002:
4003: if (!$args->{'frameset'}) {
4004: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
4005: }
4006: if ($args->{'force_register'}) {
4007: $result .= &Apache::lonmenu::registerurl(1);
4008: }
4009: if (!$args->{'no_nav_bar'}
4010: && !$args->{'only_body'}
4011: && !$args->{'frameset'}) {
4012: $result .= &help_menu_js();
4013: }
4014:
4015: if (ref($args->{'redirect'})) {
4016: my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
4017: $url = &Apache::lonenc::check_encrypt($url);
4018: if (!$inhibit_continue) {
4019: $env{'internal.head.redirect'} = $url;
4020: }
4021: $result.=<<ADDMETA
4022: <meta http-equiv="pragma" content="no-cache" />
4023: <meta http-equiv="Refresh" content="$time; url=$url" />
4024: ADDMETA
4025: }
4026: if (!defined($title)) {
4027: $title = 'The LearningOnline Network with CAPA';
4028: }
4029: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
4030: $result .= '<title> LON-CAPA '.$title.'</title>'
4031: .'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
4032: .$head_extra;
4033: return $result;
4034: }
4035:
4036: =pod
4037:
4038: =over 4
4039:
4040: =item * &font_settings()
4041:
4042: Returns neccessary <meta> to set the proper encoding
4043:
4044: Inputs: none
4045:
4046: =back
4047:
4048: =cut
4049:
4050: sub font_settings {
4051: my $headerstring='';
4052: if (($env{'browser.os'} eq 'mac') && (!$env{'browser.mathml'})) {
4053: $headerstring.=
4054: '<meta Content-Type="text/html; charset=x-mac-roman" />';
4055: } elsif (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
4056: $headerstring.=
4057: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
4058: }
4059: return $headerstring;
4060: }
4061:
4062: =pod
4063:
4064: =over 4
4065:
4066: =item * &xml_begin()
4067:
4068: Returns the needed doctype and <html>
4069:
4070: Inputs: none
4071:
4072: =back
4073:
4074: =cut
4075:
4076: sub xml_begin {
4077: my $output='';
4078:
4079: &Apache::lonhtmlcommon::init_htmlareafields();
4080:
4081: if ($env{'browser.mathml'}) {
4082: $output='<?xml version="1.0"?>'
4083: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
4084: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
4085:
4086: # .'<!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">] >'
4087: .'<!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">'
4088: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
4089: .'xmlns="http://www.w3.org/1999/xhtml">';
4090: } else {
4091: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
4092: }
4093: return $output;
4094: }
4095:
4096: =pod
4097:
4098: =over 4
4099:
4100: =item * &endheadtag()
4101:
4102: Returns a uniform </head> for LON-CAPA web pages.
4103:
4104: Inputs: none
4105:
4106: =back
4107:
4108: =cut
4109:
4110: sub endheadtag {
4111: return '</head>';
4112: }
4113:
4114: =pod
4115:
4116: =over 4
4117:
4118: =item * &head()
4119:
4120: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
4121:
4122: Inputs: $title - optional title for the page
4123: $head_extra - optional extra HTML to put inside the <head>
4124:
4125: =back
4126:
4127: =cut
4128:
4129: sub head {
4130: my ($title,$head_extra,$args) = @_;
4131: return &headtag($title,$head_extra,$args).&endheadtag();
4132: }
4133:
4134: =pod
4135:
4136: =over 4
4137:
4138: =item * &start_page()
4139:
4140: Returns a complete <html> .. <body> section for LON-CAPA web pages.
4141:
4142: Inputs: $title - optional title for the page
4143: $head_extra - optional extra HTML to incude inside the <head>
4144: $args - additional optional args supported are:
4145: only_body -> is true will set &bodytag() onlybodytag
4146: arg on
4147: no_nav_bar -> is true will set &bodytag() notopbar arg on
4148: add_entries -> additional attributes to add to the <body>
4149: domain -> force to color decorate a page for a
4150: specific domain
4151: function -> force usage of a specific rolish color
4152: scheme
4153: redirect -> see &headtag()
4154: bgcolor -> override the default page bg color
4155: js_ready -> return a string ready for being used in
4156: a javascript writeln
4157: html_encode -> return a string ready for being used in
4158: a html attribute
4159: force_register -> if is true will turn on the &bodytag()
4160: $forcereg arg
4161: body_title -> alternate text to use instead of $title
4162: in the title box that appears, this text
4163: is not auto translated like the $title is
4164: frameset -> if true will start with a <frameset>
4165: rather than <body>
4166: no_title -> if true the title bar won't be shown
4167: skip_phases -> hash ref of
4168: head -> skip the <html><head> generation
4169: body -> skip all <body> generation
4170:
4171: no_inline_link -> if true and in remote mode, don't show the
4172: 'Switch To Inline Menu' link
4173:
4174: no_auto_mt_title -> prevent &mt()ing the title arg
4175:
4176: =back
4177:
4178: =cut
4179:
4180: sub start_page {
4181: my ($title,$head_extra,$args) = @_;
4182: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
4183: my %head_args;
4184: foreach my $arg ('redirect','force_register','domain','function',
4185: 'bgcolor','frameset','no_nav_bar','only_body',
4186: 'no_auto_mt_title') {
4187: if (defined($args->{$arg})) {
4188: $head_args{$arg} = $args->{$arg};
4189: }
4190: }
4191:
4192: $env{'internal.start_page'}++;
4193: my $result;
4194: if (! exists($args->{'skip_phases'}{'head'}) ) {
4195: $result.=
4196: &xml_begin().
4197: &headtag($title,$head_extra,\%head_args).&endheadtag();
4198: }
4199:
4200: if (! exists($args->{'skip_phases'}{'body'}) ) {
4201: if ($args->{'frameset'}) {
4202: my $attr_string = &make_attr_string($args->{'force_register'},
4203: $args->{'add_entries'});
4204: $result .= "\n<frameset $attr_string>\n";
4205: } else {
4206: $result .=
4207: &bodytag($title,
4208: $args->{'function'}, $args->{'add_entries'},
4209: $args->{'only_body'}, $args->{'domain'},
4210: $args->{'force_register'}, $args->{'body_title'},
4211: $args->{'no_nav_bar'}, $args->{'bgcolor'},
4212: $args->{'no_title'}, $args->{'no_inline_link'},
4213: $args);
4214: }
4215: }
4216:
4217: if ($args->{'js_ready'}) {
4218: $result = &js_ready($result);
4219: }
4220: if ($args->{'html_encode'}) {
4221: $result = &html_encode($result);
4222: }
4223: return $result;
4224: }
4225:
4226:
4227: =pod
4228:
4229: =over 4
4230:
4231: =item * &head()
4232:
4233: Returns a complete </body></html> section for LON-CAPA web pages.
4234:
4235: Inputs: $args - additional optional args supported are:
4236: js_ready -> return a string ready for being used in
4237: a javascript writeln
4238: html_encode -> return a string ready for being used in
4239: a html attribute
4240: frameset -> if true will start with a <frameset>
4241: rather than <body>
4242:
4243: =cut
4244:
4245: sub end_page {
4246: my ($args) = @_;
4247: $env{'internal.end_page'}++;
4248: my $result;
4249: if ($args->{'discussion'}) {
4250: my ($target,$parser);
4251: if (ref($args->{'discussion'})) {
4252: ($target,$parser) =($args->{'discussion'}{'target'},
4253: $args->{'discussion'}{'parser'});
4254: }
4255: $result .= &Apache::lonxml::xmlend($target,$parser);
4256: }
4257:
4258: if ($args->{'frameset'}) {
4259: $result .= '</frameset>';
4260: } else {
4261: $result .= &endbodytag();
4262: }
4263: $result .= "\n</html>";
4264:
4265: if ($args->{'js_ready'}) {
4266: $result = &js_ready($result);
4267: }
4268:
4269: if ($args->{'html_encode'}) {
4270: $result = &html_encode($result);
4271: }
4272:
4273: return $result;
4274: }
4275:
4276: sub html_encode {
4277: my ($result) = @_;
4278:
4279: $result = &HTML::Entities::encode($result,'<>&"');
4280:
4281: return $result;
4282: }
4283: sub js_ready {
4284: my ($result) = @_;
4285:
4286: $result =~ s/[\n\r]/ /xmsg;
4287: $result =~ s/\\/\\\\/xmsg;
4288: $result =~ s/'/\\'/xmsg;
4289: $result =~ s{</}{<\\/}xmsg;
4290:
4291: return $result;
4292: }
4293:
4294: sub validate_page {
4295: if ( exists($env{'internal.start_page'})
4296: && $env{'internal.start_page'} > 1) {
4297: &Apache::lonnet::logthis('start_page called multiple times '.
4298: $env{'internal.start_page'}.' '.
4299: $ENV{'request.filename'});
4300: }
4301: if ( exists($env{'internal.end_page'})
4302: && $env{'internal.end_page'} > 1) {
4303: &Apache::lonnet::logthis('end_page called multiple times '.
4304: $env{'internal.end_page'}.' '.
4305: $env{'request.filename'});
4306: }
4307: if ( exists($env{'internal.start_page'})
4308: && ! exists($env{'internal.end_page'})) {
4309: &Apache::lonnet::logthis('start_page called without end_page '.
4310: $env{'request.filename'});
4311: }
4312: if ( ! exists($env{'internal.start_page'})
4313: && exists($env{'internal.end_page'})) {
4314: &Apache::lonnet::logthis('end_page called without start_page'.
4315: $env{'request.filename'});
4316: }
4317: }
4318:
4319: sub simple_error_page {
4320: my ($r,$title,$msg) = @_;
4321: my $page =
4322: &Apache::loncommon::start_page($title).
4323: &mt($msg).
4324: &Apache::loncommon::end_page();
4325: if (ref($r)) {
4326: $r->print($page);
4327: return;
4328: }
4329: return $page;
4330: }
4331:
4332: {
4333: my $row_count;
4334: sub start_data_table {
4335: my ($add_class) = @_;
4336: my $css_class = (join(' ','LC_data_table',$add_class));
4337: undef($row_count);
4338: return '<table class="'.$css_class.'">'."\n";
4339: }
4340:
4341: sub end_data_table {
4342: undef($row_count);
4343: return '</table>'."\n";;
4344: }
4345:
4346: sub start_data_table_row {
4347: my ($add_class) = @_;
4348: $row_count++;
4349: my $css_class = ($row_count % 2)?'':'LC_even_row';
4350: $css_class = (join(' ',$css_class,$add_class));
4351: return '<tr class="'.$css_class.'">'."\n";;
4352: }
4353:
4354: sub continue_data_table_row {
4355: my ($add_class) = @_;
4356: my $css_class = ($row_count % 2)?'':'LC_even_row';
4357: $css_class = (join(' ',$css_class,$add_class));
4358: return '<tr class="'.$css_class.'">'."\n";;
4359: }
4360:
4361: sub end_data_table_row {
4362: return '</tr>'."\n";;
4363: }
4364:
4365: sub start_data_table_empty_row {
4366: $row_count++;
4367: return '<tr class="LC_empty_row" >'."\n";;
4368: }
4369:
4370: sub end_data_table_empty_row {
4371: return '</tr>'."\n";;
4372: }
4373:
4374: sub start_data_table_header_row {
4375: return '<tr class="LC_header_row">'."\n";;
4376: }
4377:
4378: sub end_data_table_header_row {
4379: return '</tr>'."\n";;
4380: }
4381: }
4382:
4383: ###############################################
4384:
4385: =pod
4386:
4387: =item * &get_users_function()
4388:
4389: Used by &bodytag to determine the current users primary role.
4390: Returns either 'student','coordinator','admin', or 'author'.
4391:
4392: =cut
4393:
4394: ###############################################
4395: sub get_users_function {
4396: my $function = 'student';
4397: if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
4398: $function='coordinator';
4399: }
4400: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
4401: $function='admin';
4402: }
4403: if (($env{'request.role'}=~/^(au|ca)/) ||
4404: ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
4405: $function='author';
4406: }
4407: return $function;
4408: }
4409:
4410: ###############################################
4411:
4412: =pod
4413:
4414: =item * &check_user_status
4415:
4416: Determines current status of supplied role for a
4417: specific user. Roles can be active, previous or future.
4418:
4419: Inputs:
4420: user's domain, user's username, course's domain,
4421: course's number, optional section ID.
4422:
4423: Outputs:
4424: role status: active, previous or future.
4425:
4426: =cut
4427:
4428: sub check_user_status {
4429: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
4430: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
4431: my @uroles = keys %userinfo;
4432: my $srchstr;
4433: my $active_chk = 'none';
4434: my $now = time;
4435: if (@uroles > 0) {
4436: if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
4437: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
4438: } else {
4439: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
4440: }
4441: if (grep/^\Q$srchstr\E$/,@uroles) {
4442: my $role_end = 0;
4443: my $role_start = 0;
4444: $active_chk = 'active';
4445: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
4446: $role_end = $1;
4447: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
4448: $role_start = $1;
4449: }
4450: }
4451: if ($role_start > 0) {
4452: if ($now < $role_start) {
4453: $active_chk = 'future';
4454: }
4455: }
4456: if ($role_end > 0) {
4457: if ($now > $role_end) {
4458: $active_chk = 'previous';
4459: }
4460: }
4461: }
4462: }
4463: return $active_chk;
4464: }
4465:
4466: ###############################################
4467:
4468: =pod
4469:
4470: =item * &get_sections()
4471:
4472: Determines all the sections for a course including
4473: sections with students and sections containing other roles.
4474: Incoming parameters:
4475:
4476: 1. domain
4477: 2. course number
4478: 3. reference to array containing roles for which sections should
4479: be gathered (optional).
4480: 4. reference to array containing status types for which sections
4481: should be gathered (optional).
4482:
4483: If the third argument is undefined, sections are gathered for any role.
4484: If the fourth argument is undefined, sections are gathered for any status.
4485: Permissible values are 'active' or 'future' or 'previous'.
4486:
4487: Returns section hash (keys are section IDs, values are
4488: number of users in each section), subject to the
4489: optional roles filter, optional status filter
4490:
4491: =cut
4492:
4493: ###############################################
4494: sub get_sections {
4495: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
4496: if (!defined($cdom) || !defined($cnum)) {
4497: my $cid = $env{'request.course.id'};
4498:
4499: return if (!defined($cid));
4500:
4501: $cdom = $env{'course.'.$cid.'.domain'};
4502: $cnum = $env{'course.'.$cid.'.num'};
4503: }
4504:
4505: my %sectioncount;
4506: my $now = time;
4507:
4508: if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
4509: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
4510: my $sec_index = &Apache::loncoursedata::CL_SECTION();
4511: my $status_index = &Apache::loncoursedata::CL_STATUS();
4512: my $start_index = &Apache::loncoursedata::CL_START();
4513: my $end_index = &Apache::loncoursedata::CL_END();
4514: my $status;
4515: while (my ($student,$data) = each(%$classlist)) {
4516: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
4517: $data->[$status_index],
4518: $data->[$start_index],
4519: $data->[$end_index]);
4520: if ($stu_status eq 'Active') {
4521: $status = 'active';
4522: } elsif ($end < $now) {
4523: $status = 'previous';
4524: } elsif ($start > $now) {
4525: $status = 'future';
4526: }
4527: if ($section ne '-1' && $section !~ /^\s*$/) {
4528: if ((!defined($possible_status)) || (($status ne '') &&
4529: (grep/^\Q$status\E$/,@{$possible_status}))) {
4530: $sectioncount{$section}++;
4531: }
4532: }
4533: }
4534: }
4535: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
4536: foreach my $user (sort(keys(%courseroles))) {
4537: if ($user !~ /^(\w{2})/) { next; }
4538: my ($role) = ($user =~ /^(\w{2})/);
4539: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
4540: my ($section,$status);
4541: if ($role eq 'cr' &&
4542: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
4543: $section=$1;
4544: }
4545: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
4546: if (!defined($section) || $section eq '-1') { next; }
4547: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
4548: if ($end == -1 && $start == -1) {
4549: next; #deleted role
4550: }
4551: if (!defined($possible_status)) {
4552: $sectioncount{$section}++;
4553: } else {
4554: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
4555: $status = 'active';
4556: } elsif ($end < $now) {
4557: $status = 'future';
4558: } elsif ($start > $now) {
4559: $status = 'previous';
4560: }
4561: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
4562: $sectioncount{$section}++;
4563: }
4564: }
4565: }
4566: return %sectioncount;
4567: }
4568:
4569: ###############################################
4570:
4571: =pod
4572:
4573: =item * &get_course_users()
4574:
4575: Retrieves usernames:domains for users in the specified course
4576: with specific role(s), and access status.
4577:
4578: Incoming parameters:
4579: 1. course domain
4580: 2. course number
4581: 3. access status: users must have - either active,
4582: previous, future, or all.
4583: 4. reference to array of permissible roles
4584: 5. reference to array of section restrictions (optional)
4585: 6. reference to results object (hash of hashes).
4586: 7. reference to optional userdata hash
4587: Keys of top level hash are roles.
4588: Keys of inner hashes are username:domain, with
4589: values set to access type.
4590: Optional userdata hash returns an array with arguments in the
4591: same order as loncoursedata::get_classlist() for student data.
4592:
4593: Entries for end, start, section and status are blank because
4594: of the possibility of multiple values for non-student roles.
4595:
4596: =cut
4597:
4598: ###############################################
4599:
4600: sub get_course_users {
4601: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata) = @_;
4602: my %idx = ();
4603: my %seclists;
4604:
4605: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
4606: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
4607: $idx{end} = &Apache::loncoursedata::CL_END();
4608: $idx{start} = &Apache::loncoursedata::CL_START();
4609: $idx{id} = &Apache::loncoursedata::CL_ID();
4610: $idx{section} = &Apache::loncoursedata::CL_SECTION();
4611: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
4612: $idx{status} = &Apache::loncoursedata::CL_STATUS();
4613:
4614: if (grep(/^st$/,@{$roles})) {
4615: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
4616: my $now = time;
4617: foreach my $student (keys(%{$classlist})) {
4618: my $match = 0;
4619: my $secmatch = 0;
4620: my $section = $$classlist{$student}[$idx{section}];
4621: if ($section eq '') {
4622: $section = 'none';
4623: }
4624: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
4625: if (grep(/^all$/,@{$sections})) {
4626: $secmatch = 1;
4627: } elsif ($$classlist{$student}[$idx{section}] eq '') {
4628: if (grep(/^none$/,@{$sections})) {
4629: $secmatch = 1;
4630: }
4631: } else {
4632: if (grep(/^\Q$section\E$/,@{$sections})) {
4633: $secmatch = 1;
4634: }
4635: }
4636: if (!$secmatch) {
4637: next;
4638: }
4639: }
4640: push(@{$seclists{$student}},$section);
4641: if (defined($$types{'active'})) {
4642: if ($$classlist{$student}[$idx{status}] eq 'Active') {
4643: push(@{$$users{st}{$student}},'active');
4644: $match = 1;
4645: }
4646: }
4647: if (defined($$types{'previous'})) {
4648: if ($$classlist{$student}[$idx{end}] <= $now) {
4649: push(@{$$users{st}{$student}},'previous');
4650: $match = 1;
4651: }
4652: }
4653: if (defined($$types{'future'})) {
4654: if (($$classlist{$student}[$idx{start}] > $now) && ($$classlist{$student}[$idx{end}] > $now) || ($$classlist{$student}[$idx{end}] == 0) || ($$classlist{$student}[$idx{end}] eq '')) {
4655: push(@{$$users{st}{$student}},'future');
4656: $match = 1;
4657: }
4658: }
4659: if ($match && ref($userdata) eq 'HASH') {
4660: $$userdata{$student} = $$classlist{$student};
4661: }
4662: }
4663: }
4664: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
4665: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
4666: my $now = time;
4667: foreach my $person (sort(keys(%coursepersonnel))) {
4668: my $match = 0;
4669: my $secmatch = 0;
4670: my $status;
4671: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
4672: $user =~ s/:$//;
4673: my ($end,$start) = split(/:/,$coursepersonnel{$person});
4674: if ($end == -1 || $start == -1) {
4675: next;
4676: }
4677: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
4678: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
4679: my ($uname,$udom) = split(/:/,$user);
4680: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
4681: if (grep(/^all$/,@{$sections})) {
4682: $secmatch = 1;
4683: } elsif ($usec eq '') {
4684: if (grep(/^none$/,@{$sections})) {
4685: $secmatch = 1;
4686: }
4687: } else {
4688: if (grep(/^\Q$usec\E$/,@{$sections})) {
4689: $secmatch = 1;
4690: }
4691: }
4692: if (!$secmatch) {
4693: next;
4694: }
4695: }
4696: if ($usec eq '') {
4697: $usec = 'none';
4698: }
4699: if ($uname ne '' && $udom ne '') {
4700: if ($end < $now) {
4701: $status = 'previous';
4702: } elsif ($start > $now) {
4703: $status = 'future';
4704: } else {
4705: $status = 'active';
4706: }
4707: foreach my $type (keys(%{$types})) {
4708: if ($status eq $type) {
4709: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
4710: push(@{$$users{$role}{$user}},$type);
4711: }
4712: $match = 1;
4713: }
4714: }
4715: if (($match) && (ref($userdata) eq 'HASH')) {
4716: if (!exists($$userdata{$uname.':'.$udom})) {
4717: &get_user_info($udom,$uname,\%idx,$userdata);
4718: }
4719: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
4720: push(@{$seclists{$uname.':'.$udom}},$usec);
4721: }
4722: }
4723: }
4724: }
4725: }
4726: if (grep(/^ow$/,@{$roles})) {
4727: if ((defined($cdom)) && (defined($cnum))) {
4728: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
4729: if ( defined($csettings{'internal.courseowner'}) ) {
4730: my $owner = $csettings{'internal.courseowner'};
4731: if ($owner !~ /^[^:]+:[^:]+$/) {
4732: $owner = $owner.':'.$cdom;
4733: }
4734: @{$$users{'ow'}{$owner}} = 'any';
4735: if (defined($userdata) &&
4736: !exists($$userdata{$owner.':'.$cdom})) {
4737: &get_user_info($cdom,$owner,\%idx,$userdata);
4738: if (!grep(/^none$/,@{$seclists{$owner.':'.$cdom}})) {
4739: push(@{$seclists{$owner.':'.$cdom}},'none');
4740: }
4741: }
4742: }
4743: }
4744: }
4745: foreach my $user (keys(%seclists)) {
4746: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
4747: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
4748: }
4749: }
4750: return;
4751: }
4752:
4753: sub get_user_info {
4754: my ($udom,$uname,$idx,$userdata) = @_;
4755: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
4756: &plainname($uname,$udom,'lastname');
4757: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
4758: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
4759: return;
4760: }
4761:
4762: ###############################################
4763:
4764: =pod
4765:
4766: =item * &get_user_quota()
4767:
4768: Retrieves quota assigned for storage of portfolio files for a user
4769:
4770: Incoming parameters:
4771: 1. user's username
4772: 2. user's domain
4773:
4774: Returns:
4775: 1. Disk quota (in Mb) assigned to student.
4776:
4777: If a value has been stored in the user's environment,
4778: it will return that, otherwise it returns the default
4779: for users in the domain.
4780:
4781: =cut
4782:
4783: ###############################################
4784:
4785:
4786: sub get_user_quota {
4787: my ($uname,$udom) = @_;
4788: my $quota;
4789: if (!defined($udom)) {
4790: $udom = $env{'user.domain'};
4791: }
4792: if (!defined($uname)) {
4793: $uname = $env{'user.name'};
4794: }
4795: if (($udom eq '' || $uname eq '') ||
4796: ($udom eq 'public') && ($uname eq 'public')) {
4797: $quota = 0;
4798: } else {
4799: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
4800: $quota = $env{'environment.portfolioquota'};
4801: } else {
4802: my %userenv = &Apache::lonnet::dump('environment',$udom,$uname);
4803: my ($tmp) = keys(%userenv);
4804: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
4805: $quota = $userenv{'portfolioquota'};
4806: } else {
4807: undef(%userenv);
4808: }
4809: }
4810: if ($quota eq '') {
4811: $quota = &default_quota($udom);
4812: }
4813: }
4814: return $quota;
4815: }
4816:
4817: ###############################################
4818:
4819: =pod
4820:
4821: =item * &default_quota()
4822:
4823: Retrieves default quota assigned for storage of user portfolio files
4824:
4825: Incoming parameters:
4826: 1. domain
4827:
4828: Returns:
4829: 1. Default disk quota (in Mb) for user portfolios in the domain.
4830:
4831: If a value has been stored in the domain's configuration db,
4832: it will return that, otherwise it returns 20 (for backwards
4833: compatibility with domains which have not set up a configuration
4834: db file; the original statically defined portfolio quota was 20 Mb).
4835:
4836: =cut
4837:
4838: ###############################################
4839:
4840:
4841: sub default_quota {
4842: my ($udom) = @_;
4843: my %defaults = &Apache::lonnet::get_dom('configuration',
4844: ['portfolioquota'],$udom);
4845: if ($defaults{'portfolioquota'} ne '') {
4846: return $defaults{'portfolioquota'};
4847: } else {
4848: return '20';
4849: }
4850: }
4851:
4852: sub get_secgrprole_info {
4853: my ($cdom,$cnum,$needroles,$type) = @_;
4854: my %sections_count = &get_sections($cdom,$cnum);
4855: my @sections = (sort {$a <=> $b} keys(%sections_count));
4856: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
4857: my @groups = sort(keys(%curr_groups));
4858: my $allroles = [];
4859: my $rolehash;
4860: my $accesshash = {
4861: active => 'Currently has access',
4862: future => 'Will have future access',
4863: previous => 'Previously had access',
4864: };
4865: if ($needroles) {
4866: $rolehash = {'all' => 'all'};
4867: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
4868: if (&Apache::lonnet::error(%user_roles)) {
4869: undef(%user_roles);
4870: }
4871: foreach my $item (keys(%user_roles)) {
4872: my ($role)=split(/\:/,$item,2);
4873: if ($role eq 'cr') { next; }
4874: if ($role =~ /^cr/) {
4875: $$rolehash{$role} = (split('/',$role))[3];
4876: } else {
4877: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
4878: }
4879: }
4880: foreach my $key (sort(keys(%{$rolehash}))) {
4881: push(@{$allroles},$key);
4882: }
4883: push (@{$allroles},'st');
4884: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
4885: }
4886: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
4887: }
4888:
4889: =pod
4890:
4891: =item * get_unprocessed_cgi($query,$possible_names)
4892:
4893: Modify the %env hash to contain unprocessed CGI form parameters held in
4894: $query. The parameters listed in $possible_names (an array reference),
4895: will be set in $env{'form.name'} if they do not already exist.
4896:
4897: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
4898: $possible_names is an ref to an array of form element names. As an example:
4899: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
4900: will result in $env{'form.uname'} and $env{'form.udom'} being set.
4901:
4902: =cut
4903:
4904: sub get_unprocessed_cgi {
4905: my ($query,$possible_names)= @_;
4906: # $Apache::lonxml::debug=1;
4907: foreach my $pair (split(/&/,$query)) {
4908: my ($name, $value) = split(/=/,$pair);
4909: $name = &unescape($name);
4910: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
4911: $value =~ tr/+/ /;
4912: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
4913: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
4914: }
4915: }
4916: }
4917:
4918: =pod
4919:
4920: =item * cacheheader()
4921:
4922: returns cache-controlling header code
4923:
4924: =cut
4925:
4926: sub cacheheader {
4927: unless ($env{'request.method'} eq 'GET') { return ''; }
4928: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
4929: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
4930: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
4931: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
4932: return $output;
4933: }
4934:
4935: =pod
4936:
4937: =item * no_cache($r)
4938:
4939: specifies header code to not have cache
4940:
4941: =cut
4942:
4943: sub no_cache {
4944: my ($r) = @_;
4945: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
4946: $env{'request.method'} ne 'GET') { return ''; }
4947: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
4948: $r->no_cache(1);
4949: $r->header_out("Expires" => $date);
4950: $r->header_out("Pragma" => "no-cache");
4951: }
4952:
4953: sub content_type {
4954: my ($r,$type,$charset) = @_;
4955: if ($r) {
4956: # Note that printout.pl calls this with undef for $r.
4957: &no_cache($r);
4958: }
4959: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
4960: unless ($charset) {
4961: $charset=&Apache::lonlocal::current_encoding;
4962: }
4963: if ($charset) { $type.='; charset='.$charset; }
4964: if ($r) {
4965: $r->content_type($type);
4966: } else {
4967: print("Content-type: $type\n\n");
4968: }
4969: }
4970:
4971: =pod
4972:
4973: =item * add_to_env($name,$value)
4974:
4975: adds $name to the %env hash with value
4976: $value, if $name already exists, the entry is converted to an array
4977: reference and $value is added to the array.
4978:
4979: =cut
4980:
4981: sub add_to_env {
4982: my ($name,$value)=@_;
4983: if (defined($env{$name})) {
4984: if (ref($env{$name})) {
4985: #already have multiple values
4986: push(@{ $env{$name} },$value);
4987: } else {
4988: #first time seeing multiple values, convert hash entry to an arrayref
4989: my $first=$env{$name};
4990: undef($env{$name});
4991: push(@{ $env{$name} },$first,$value);
4992: }
4993: } else {
4994: $env{$name}=$value;
4995: }
4996: }
4997:
4998: =pod
4999:
5000: =item * get_env_multiple($name)
5001:
5002: gets $name from the %env hash, it seemlessly handles the cases where multiple
5003: values may be defined and end up as an array ref.
5004:
5005: returns an array of values
5006:
5007: =cut
5008:
5009: sub get_env_multiple {
5010: my ($name) = @_;
5011: my @values;
5012: if (defined($env{$name})) {
5013: # exists is it an array
5014: if (ref($env{$name})) {
5015: @values=@{ $env{$name} };
5016: } else {
5017: $values[0]=$env{$name};
5018: }
5019: }
5020: return(@values);
5021: }
5022:
5023:
5024: =pod
5025:
5026: =back
5027:
5028: =head1 CSV Upload/Handling functions
5029:
5030: =over 4
5031:
5032: =item * upfile_store($r)
5033:
5034: Store uploaded file, $r should be the HTTP Request object,
5035: needs $env{'form.upfile'}
5036: returns $datatoken to be put into hidden field
5037:
5038: =cut
5039:
5040: sub upfile_store {
5041: my $r=shift;
5042: $env{'form.upfile'}=~s/\r/\n/gs;
5043: $env{'form.upfile'}=~s/\f/\n/gs;
5044: $env{'form.upfile'}=~s/\n+/\n/gs;
5045: $env{'form.upfile'}=~s/\n+$//gs;
5046:
5047: my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
5048: '_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
5049: {
5050: my $datafile = $r->dir_config('lonDaemons').
5051: '/tmp/'.$datatoken.'.tmp';
5052: if ( open(my $fh,">$datafile") ) {
5053: print $fh $env{'form.upfile'};
5054: close($fh);
5055: }
5056: }
5057: return $datatoken;
5058: }
5059:
5060: =pod
5061:
5062: =item * load_tmp_file($r)
5063:
5064: Load uploaded file from tmp, $r should be the HTTP Request object,
5065: needs $env{'form.datatoken'},
5066: sets $env{'form.upfile'} to the contents of the file
5067:
5068: =cut
5069:
5070: sub load_tmp_file {
5071: my $r=shift;
5072: my @studentdata=();
5073: {
5074: my $studentfile = $r->dir_config('lonDaemons').
5075: '/tmp/'.$env{'form.datatoken'}.'.tmp';
5076: if ( open(my $fh,"<$studentfile") ) {
5077: @studentdata=<$fh>;
5078: close($fh);
5079: }
5080: }
5081: $env{'form.upfile'}=join('',@studentdata);
5082: }
5083:
5084: =pod
5085:
5086: =item * upfile_record_sep()
5087:
5088: Separate uploaded file into records
5089: returns array of records,
5090: needs $env{'form.upfile'} and $env{'form.upfiletype'}
5091:
5092: =cut
5093:
5094: sub upfile_record_sep {
5095: if ($env{'form.upfiletype'} eq 'xml') {
5096: } else {
5097: my @records;
5098: foreach my $line (split(/\n/,$env{'form.upfile'})) {
5099: if ($line=~/^\s*$/) { next; }
5100: push(@records,$line);
5101: }
5102: return @records;
5103: }
5104: }
5105:
5106: =pod
5107:
5108: =item * record_sep($record)
5109:
5110: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
5111:
5112: =cut
5113:
5114: sub takeleft {
5115: my $index=shift;
5116: return substr('0000'.$index,-4,4);
5117: }
5118:
5119: sub record_sep {
5120: my $record=shift;
5121: my %components=();
5122: if ($env{'form.upfiletype'} eq 'xml') {
5123: } elsif ($env{'form.upfiletype'} eq 'space') {
5124: my $i=0;
5125: foreach my $field (split(/\s+/,$record)) {
5126: $field=~s/^(\"|\')//;
5127: $field=~s/(\"|\')$//;
5128: $components{&takeleft($i)}=$field;
5129: $i++;
5130: }
5131: } elsif ($env{'form.upfiletype'} eq 'tab') {
5132: my $i=0;
5133: foreach my $field (split(/\t/,$record)) {
5134: $field=~s/^(\"|\')//;
5135: $field=~s/(\"|\')$//;
5136: $components{&takeleft($i)}=$field;
5137: $i++;
5138: }
5139: } else {
5140: my @allfields=split(/\,/,$record);
5141: my $i=0;
5142: my $j;
5143: for ($j=0;$j<=$#allfields;$j++) {
5144: my $field=$allfields[$j];
5145: if ($field=~/^\s*(\"|\')/) {
5146: my $delimiter=$1;
5147: while (($field!~/$delimiter$/) && ($j<$#allfields)) {
5148: $j++;
5149: $field.=','.$allfields[$j];
5150: }
5151: $field=~s/^\s*$delimiter//;
5152: $field=~s/$delimiter\s*$//;
5153: }
5154: $components{&takeleft($i)}=$field;
5155: $i++;
5156: }
5157: }
5158: return %components;
5159: }
5160:
5161: ######################################################
5162: ######################################################
5163:
5164: =pod
5165:
5166: =item * upfile_select_html()
5167:
5168: Return HTML code to select a file from the users machine and specify
5169: the file type.
5170:
5171: =cut
5172:
5173: ######################################################
5174: ######################################################
5175: sub upfile_select_html {
5176: my %Types = (
5177: csv => &mt('CSV (comma separated values, spreadsheet)'),
5178: space => &mt('Space separated'),
5179: tab => &mt('Tabulator separated'),
5180: # xml => &mt('HTML/XML'),
5181: );
5182: my $Str = '<input type="file" name="upfile" size="50" />'.
5183: '<br />Type: <select name="upfiletype">';
5184: foreach my $type (sort(keys(%Types))) {
5185: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
5186: }
5187: $Str .= "</select>\n";
5188: return $Str;
5189: }
5190:
5191: sub get_samples {
5192: my ($records,$toget) = @_;
5193: my @samples=({});
5194: my $got=0;
5195: foreach my $rec (@$records) {
5196: my %temp = &record_sep($rec);
5197: if (! grep(/\S/, values(%temp))) { next; }
5198: if (%temp) {
5199: $samples[$got]=\%temp;
5200: $got++;
5201: if ($got == $toget) { last; }
5202: }
5203: }
5204: return \@samples;
5205: }
5206:
5207: ######################################################
5208: ######################################################
5209:
5210: =pod
5211:
5212: =item * csv_print_samples($r,$records)
5213:
5214: Prints a table of sample values from each column uploaded $r is an
5215: Apache Request ref, $records is an arrayref from
5216: &Apache::loncommon::upfile_record_sep
5217:
5218: =cut
5219:
5220: ######################################################
5221: ######################################################
5222: sub csv_print_samples {
5223: my ($r,$records) = @_;
5224: my $samples = &get_samples($records,3);
5225:
5226: $r->print(&mt('Samples').'<br /><table border="2"><tr>');
5227: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
5228: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
5229: $r->print('</tr>');
5230: foreach my $hash (@$samples) {
5231: $r->print('<tr>');
5232: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
5233: $r->print('<td>');
5234: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
5235: $r->print('</td>');
5236: }
5237: $r->print('</tr>');
5238: }
5239: $r->print('</tr></table><br />'."\n");
5240: }
5241:
5242: ######################################################
5243: ######################################################
5244:
5245: =pod
5246:
5247: =item * csv_print_select_table($r,$records,$d)
5248:
5249: Prints a table to create associations between values and table columns.
5250:
5251: $r is an Apache Request ref,
5252: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
5253: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
5254:
5255: =cut
5256:
5257: ######################################################
5258: ######################################################
5259: sub csv_print_select_table {
5260: my ($r,$records,$d) = @_;
5261: my $i=0;
5262: my $samples = &get_samples($records,1);
5263: $r->print(&mt('Associate columns with student attributes.')."\n".
5264: '<table border="2"><tr>'.
5265: '<th>'.&mt('Attribute').'</th>'.
5266: '<th>'.&mt('Column').'</th></tr>'."\n");
5267: foreach my $array_ref (@$d) {
5268: my ($value,$display,$defaultcol)=@{ $array_ref };
5269: $r->print('<tr><td>'.$display.'</td>');
5270:
5271: $r->print('<td><select name=f'.$i.
5272: ' onchange="javascript:flip(this.form,'.$i.');">');
5273: $r->print('<option value="none"></option>');
5274: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
5275: $r->print('<option value="'.$sample.'"'.
5276: ($sample eq $defaultcol ? ' selected="selected" ' : '').
5277: '>Column '.($sample+1).'</option>');
5278: }
5279: $r->print('</select></td></tr>'."\n");
5280: $i++;
5281: }
5282: $i--;
5283: return $i;
5284: }
5285:
5286: ######################################################
5287: ######################################################
5288:
5289: =pod
5290:
5291: =item * csv_samples_select_table($r,$records,$d)
5292:
5293: Prints a table of sample values from the upload and can make associate samples to internal names.
5294:
5295: $r is an Apache Request ref,
5296: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
5297: $d is an array of 2 element arrays (internal name, displayed name)
5298:
5299: =cut
5300:
5301: ######################################################
5302: ######################################################
5303: sub csv_samples_select_table {
5304: my ($r,$records,$d) = @_;
5305: my $i=0;
5306: #
5307: my $samples = &get_samples($records,3);
5308: $r->print('<table border=2><tr><th>'.
5309: &mt('Field').'</th><th>'.&mt('Samples').'</th></tr>');
5310:
5311: foreach my $key (sort(keys(%{ $samples->[0] }))) {
5312: $r->print('<tr><td><select name="f'.$i.'"'.
5313: ' onchange="javascript:flip(this.form,'.$i.');">');
5314: foreach my $option (@$d) {
5315: my ($value,$display,$defaultcol)=@{ $option };
5316: $r->print('<option value="'.$value.'"'.
5317: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
5318: $display.'</option>');
5319: }
5320: $r->print('</select></td><td>');
5321: foreach my $line (0..2) {
5322: if (defined($samples->[$line]{$key})) {
5323: $r->print($samples->[$line]{$key}."<br />\n");
5324: }
5325: }
5326: $r->print('</td></tr>');
5327: $i++;
5328: }
5329: $i--;
5330: return($i);
5331: }
5332:
5333: ######################################################
5334: ######################################################
5335:
5336: =pod
5337:
5338: =item clean_excel_name($name)
5339:
5340: Returns a replacement for $name which does not contain any illegal characters.
5341:
5342: =cut
5343:
5344: ######################################################
5345: ######################################################
5346: sub clean_excel_name {
5347: my ($name) = @_;
5348: $name =~ s/[:\*\?\/\\]//g;
5349: if (length($name) > 31) {
5350: $name = substr($name,0,31);
5351: }
5352: return $name;
5353: }
5354:
5355: =pod
5356:
5357: =item * check_if_partid_hidden($id,$symb,$udom,$uname)
5358:
5359: Returns either 1 or undef
5360:
5361: 1 if the part is to be hidden, undef if it is to be shown
5362:
5363: Arguments are:
5364:
5365: $id the id of the part to be checked
5366: $symb, optional the symb of the resource to check
5367: $udom, optional the domain of the user to check for
5368: $uname, optional the username of the user to check for
5369:
5370: =cut
5371:
5372: sub check_if_partid_hidden {
5373: my ($id,$symb,$udom,$uname) = @_;
5374: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
5375: $symb,$udom,$uname);
5376: my $truth=1;
5377: #if the string starts with !, then the list is the list to show not hide
5378: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
5379: my @hiddenlist=split(/,/,$hiddenparts);
5380: foreach my $checkid (@hiddenlist) {
5381: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
5382: }
5383: return !$truth;
5384: }
5385:
5386:
5387: ############################################################
5388: ############################################################
5389:
5390: =pod
5391:
5392: =back
5393:
5394: =head1 cgi-bin script and graphing routines
5395:
5396: =over 4
5397:
5398: =item get_cgi_id
5399:
5400: Inputs: none
5401:
5402: Returns an id which can be used to pass environment variables
5403: to various cgi-bin scripts. These environment variables will
5404: be removed from the users environment after a given time by
5405: the routine &Apache::lonnet::transfer_profile_to_env.
5406:
5407: =cut
5408:
5409: ############################################################
5410: ############################################################
5411: my $uniq=0;
5412: sub get_cgi_id {
5413: $uniq=($uniq+1)%100000;
5414: return (time.'_'.$$.'_'.$uniq);
5415: }
5416:
5417: ############################################################
5418: ############################################################
5419:
5420: =pod
5421:
5422: =item DrawBarGraph
5423:
5424: Facilitates the plotting of data in a (stacked) bar graph.
5425: Puts plot definition data into the users environment in order for
5426: graph.png to plot it. Returns an <img> tag for the plot.
5427: The bars on the plot are labeled '1','2',...,'n'.
5428:
5429: Inputs:
5430:
5431: =over 4
5432:
5433: =item $Title: string, the title of the plot
5434:
5435: =item $xlabel: string, text describing the X-axis of the plot
5436:
5437: =item $ylabel: string, text describing the Y-axis of the plot
5438:
5439: =item $Max: scalar, the maximum Y value to use in the plot
5440: If $Max is < any data point, the graph will not be rendered.
5441:
5442: =item $colors: array ref holding the colors to be used for the data sets when
5443: they are plotted. If undefined, default values will be used.
5444:
5445: =item $labels: array ref holding the labels to use on the x-axis for the bars.
5446:
5447: =item @Values: An array of array references. Each array reference holds data
5448: to be plotted in a stacked bar chart.
5449:
5450: =item If the final element of @Values is a hash reference the key/value
5451: pairs will be added to the graph definition.
5452:
5453: =back
5454:
5455: Returns:
5456:
5457: An <img> tag which references graph.png and the appropriate identifying
5458: information for the plot.
5459:
5460: =cut
5461:
5462: ############################################################
5463: ############################################################
5464: sub DrawBarGraph {
5465: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
5466: #
5467: if (! defined($colors)) {
5468: $colors = ['#33ff00',
5469: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
5470: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
5471: ];
5472: }
5473: my $extra_settings = {};
5474: if (ref($Values[-1]) eq 'HASH') {
5475: $extra_settings = pop(@Values);
5476: }
5477: #
5478: my $identifier = &get_cgi_id();
5479: my $id = 'cgi.'.$identifier;
5480: if (! @Values || ref($Values[0]) ne 'ARRAY') {
5481: return '';
5482: }
5483: #
5484: my @Labels;
5485: if (defined($labels)) {
5486: @Labels = @$labels;
5487: } else {
5488: for (my $i=0;$i<@{$Values[0]};$i++) {
5489: push (@Labels,$i+1);
5490: }
5491: }
5492: #
5493: my $NumBars = scalar(@{$Values[0]});
5494: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
5495: my %ValuesHash;
5496: my $NumSets=1;
5497: foreach my $array (@Values) {
5498: next if (! ref($array));
5499: $ValuesHash{$id.'.data.'.$NumSets++} =
5500: join(',',@$array);
5501: }
5502: #
5503: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
5504: if ($NumBars < 3) {
5505: $width = 120+$NumBars*32;
5506: $xskip = 1;
5507: $bar_width = 30;
5508: } elsif ($NumBars < 5) {
5509: $width = 120+$NumBars*20;
5510: $xskip = 1;
5511: $bar_width = 20;
5512: } elsif ($NumBars < 10) {
5513: $width = 120+$NumBars*15;
5514: $xskip = 1;
5515: $bar_width = 15;
5516: } elsif ($NumBars <= 25) {
5517: $width = 120+$NumBars*11;
5518: $xskip = 5;
5519: $bar_width = 8;
5520: } elsif ($NumBars <= 50) {
5521: $width = 120+$NumBars*8;
5522: $xskip = 5;
5523: $bar_width = 4;
5524: } else {
5525: $width = 120+$NumBars*8;
5526: $xskip = 5;
5527: $bar_width = 4;
5528: }
5529: #
5530: $Max = 1 if ($Max < 1);
5531: if ( int($Max) < $Max ) {
5532: $Max++;
5533: $Max = int($Max);
5534: }
5535: $Title = '' if (! defined($Title));
5536: $xlabel = '' if (! defined($xlabel));
5537: $ylabel = '' if (! defined($ylabel));
5538: $ValuesHash{$id.'.title'} = &escape($Title);
5539: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
5540: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
5541: $ValuesHash{$id.'.y_max_value'} = $Max;
5542: $ValuesHash{$id.'.NumBars'} = $NumBars;
5543: $ValuesHash{$id.'.NumSets'} = $NumSets;
5544: $ValuesHash{$id.'.PlotType'} = 'bar';
5545: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
5546: $ValuesHash{$id.'.height'} = $height;
5547: $ValuesHash{$id.'.width'} = $width;
5548: $ValuesHash{$id.'.xskip'} = $xskip;
5549: $ValuesHash{$id.'.bar_width'} = $bar_width;
5550: $ValuesHash{$id.'.labels'} = join(',',@Labels);
5551: #
5552: # Deal with other parameters
5553: while (my ($key,$value) = each(%$extra_settings)) {
5554: $ValuesHash{$id.'.'.$key} = $value;
5555: }
5556: #
5557: &Apache::lonnet::appenv(%ValuesHash);
5558: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
5559: }
5560:
5561: ############################################################
5562: ############################################################
5563:
5564: =pod
5565:
5566: =item DrawXYGraph
5567:
5568: Facilitates the plotting of data in an XY graph.
5569: Puts plot definition data into the users environment in order for
5570: graph.png to plot it. Returns an <img> tag for the plot.
5571:
5572: Inputs:
5573:
5574: =over 4
5575:
5576: =item $Title: string, the title of the plot
5577:
5578: =item $xlabel: string, text describing the X-axis of the plot
5579:
5580: =item $ylabel: string, text describing the Y-axis of the plot
5581:
5582: =item $Max: scalar, the maximum Y value to use in the plot
5583: If $Max is < any data point, the graph will not be rendered.
5584:
5585: =item $colors: Array ref containing the hex color codes for the data to be
5586: plotted in. If undefined, default values will be used.
5587:
5588: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
5589:
5590: =item $Ydata: Array ref containing Array refs.
5591: Each of the contained arrays will be plotted as a separate curve.
5592:
5593: =item %Values: hash indicating or overriding any default values which are
5594: passed to graph.png.
5595: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
5596:
5597: =back
5598:
5599: Returns:
5600:
5601: An <img> tag which references graph.png and the appropriate identifying
5602: information for the plot.
5603:
5604: =cut
5605:
5606: ############################################################
5607: ############################################################
5608: sub DrawXYGraph {
5609: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
5610: #
5611: # Create the identifier for the graph
5612: my $identifier = &get_cgi_id();
5613: my $id = 'cgi.'.$identifier;
5614: #
5615: $Title = '' if (! defined($Title));
5616: $xlabel = '' if (! defined($xlabel));
5617: $ylabel = '' if (! defined($ylabel));
5618: my %ValuesHash =
5619: (
5620: $id.'.title' => &escape($Title),
5621: $id.'.xlabel' => &escape($xlabel),
5622: $id.'.ylabel' => &escape($ylabel),
5623: $id.'.y_max_value'=> $Max,
5624: $id.'.labels' => join(',',@$Xlabels),
5625: $id.'.PlotType' => 'XY',
5626: );
5627: #
5628: if (defined($colors) && ref($colors) eq 'ARRAY') {
5629: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
5630: }
5631: #
5632: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
5633: return '';
5634: }
5635: my $NumSets=1;
5636: foreach my $array (@{$Ydata}){
5637: next if (! ref($array));
5638: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
5639: }
5640: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
5641: #
5642: # Deal with other parameters
5643: while (my ($key,$value) = each(%Values)) {
5644: $ValuesHash{$id.'.'.$key} = $value;
5645: }
5646: #
5647: &Apache::lonnet::appenv(%ValuesHash);
5648: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
5649: }
5650:
5651: ############################################################
5652: ############################################################
5653:
5654: =pod
5655:
5656: =item DrawXYYGraph
5657:
5658: Facilitates the plotting of data in an XY graph with two Y axes.
5659: Puts plot definition data into the users environment in order for
5660: graph.png to plot it. Returns an <img> tag for the plot.
5661:
5662: Inputs:
5663:
5664: =over 4
5665:
5666: =item $Title: string, the title of the plot
5667:
5668: =item $xlabel: string, text describing the X-axis of the plot
5669:
5670: =item $ylabel: string, text describing the Y-axis of the plot
5671:
5672: =item $colors: Array ref containing the hex color codes for the data to be
5673: plotted in. If undefined, default values will be used.
5674:
5675: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
5676:
5677: =item $Ydata1: The first data set
5678:
5679: =item $Min1: The minimum value of the left Y-axis
5680:
5681: =item $Max1: The maximum value of the left Y-axis
5682:
5683: =item $Ydata2: The second data set
5684:
5685: =item $Min2: The minimum value of the right Y-axis
5686:
5687: =item $Max2: The maximum value of the left Y-axis
5688:
5689: =item %Values: hash indicating or overriding any default values which are
5690: passed to graph.png.
5691: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
5692:
5693: =back
5694:
5695: Returns:
5696:
5697: An <img> tag which references graph.png and the appropriate identifying
5698: information for the plot.
5699:
5700: =cut
5701:
5702: ############################################################
5703: ############################################################
5704: sub DrawXYYGraph {
5705: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
5706: $Ydata2,$Min2,$Max2,%Values)=@_;
5707: #
5708: # Create the identifier for the graph
5709: my $identifier = &get_cgi_id();
5710: my $id = 'cgi.'.$identifier;
5711: #
5712: $Title = '' if (! defined($Title));
5713: $xlabel = '' if (! defined($xlabel));
5714: $ylabel = '' if (! defined($ylabel));
5715: my %ValuesHash =
5716: (
5717: $id.'.title' => &escape($Title),
5718: $id.'.xlabel' => &escape($xlabel),
5719: $id.'.ylabel' => &escape($ylabel),
5720: $id.'.labels' => join(',',@$Xlabels),
5721: $id.'.PlotType' => 'XY',
5722: $id.'.NumSets' => 2,
5723: $id.'.two_axes' => 1,
5724: $id.'.y1_max_value' => $Max1,
5725: $id.'.y1_min_value' => $Min1,
5726: $id.'.y2_max_value' => $Max2,
5727: $id.'.y2_min_value' => $Min2,
5728: );
5729: #
5730: if (defined($colors) && ref($colors) eq 'ARRAY') {
5731: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
5732: }
5733: #
5734: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
5735: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
5736: return '';
5737: }
5738: my $NumSets=1;
5739: foreach my $array ($Ydata1,$Ydata2){
5740: next if (! ref($array));
5741: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
5742: }
5743: #
5744: # Deal with other parameters
5745: while (my ($key,$value) = each(%Values)) {
5746: $ValuesHash{$id.'.'.$key} = $value;
5747: }
5748: #
5749: &Apache::lonnet::appenv(%ValuesHash);
5750: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
5751: }
5752:
5753: ############################################################
5754: ############################################################
5755:
5756: =pod
5757:
5758: =back
5759:
5760: =head1 Statistics helper routines?
5761:
5762: Bad place for them but what the hell.
5763:
5764: =over 4
5765:
5766: =item &chartlink
5767:
5768: Returns a link to the chart for a specific student.
5769:
5770: Inputs:
5771:
5772: =over 4
5773:
5774: =item $linktext: The text of the link
5775:
5776: =item $sname: The students username
5777:
5778: =item $sdomain: The students domain
5779:
5780: =back
5781:
5782: =back
5783:
5784: =cut
5785:
5786: ############################################################
5787: ############################################################
5788: sub chartlink {
5789: my ($linktext, $sname, $sdomain) = @_;
5790: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
5791: '&SelectedStudent='.&escape($sname.':'.$sdomain).
5792: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
5793: '">'.$linktext.'</a>';
5794: }
5795:
5796: #######################################################
5797: #######################################################
5798:
5799: =pod
5800:
5801: =head1 Course Environment Routines
5802:
5803: =over 4
5804:
5805: =item &restore_course_settings
5806:
5807: =item &store_course_settings
5808:
5809: Restores/Store indicated form parameters from the course environment.
5810: Will not overwrite existing values of the form parameters.
5811:
5812: Inputs:
5813: a scalar describing the data (e.g. 'chart', 'problem_analysis')
5814:
5815: a hash ref describing the data to be stored. For example:
5816:
5817: %Save_Parameters = ('Status' => 'scalar',
5818: 'chartoutputmode' => 'scalar',
5819: 'chartoutputdata' => 'scalar',
5820: 'Section' => 'array',
5821: 'Group' => 'array',
5822: 'StudentData' => 'array',
5823: 'Maps' => 'array');
5824:
5825: Returns: both routines return nothing
5826:
5827: =cut
5828:
5829: #######################################################
5830: #######################################################
5831: sub store_course_settings {
5832: # save to the environment
5833: # appenv the same items, just to be safe
5834: my $courseid = $env{'request.course.id'};
5835: my $udom = $env{'user.domain'};
5836: my $uname = $env{'user.name'};
5837: my ($prefix,$Settings) = @_;
5838: my %SaveHash;
5839: my %AppHash;
5840: while (my ($setting,$type) = each(%$Settings)) {
5841: my $basename = join('.','internal',$courseid,$prefix,$setting);
5842: my $envname = 'environment.'.$basename;
5843: if (exists($env{'form.'.$setting})) {
5844: # Save this value away
5845: if ($type eq 'scalar' &&
5846: (! exists($env{$envname}) ||
5847: $env{$envname} ne $env{'form.'.$setting})) {
5848: $SaveHash{$basename} = $env{'form.'.$setting};
5849: $AppHash{$envname} = $env{'form.'.$setting};
5850: } elsif ($type eq 'array') {
5851: my $stored_form;
5852: if (ref($env{'form.'.$setting})) {
5853: $stored_form = join(',',
5854: map {
5855: &escape($_);
5856: } sort(@{$env{'form.'.$setting}}));
5857: } else {
5858: $stored_form =
5859: &escape($env{'form.'.$setting});
5860: }
5861: # Determine if the array contents are the same.
5862: if ($stored_form ne $env{$envname}) {
5863: $SaveHash{$basename} = $stored_form;
5864: $AppHash{$envname} = $stored_form;
5865: }
5866: }
5867: }
5868: }
5869: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
5870: $udom,$uname);
5871: if ($put_result !~ /^(ok|delayed)/) {
5872: &Apache::lonnet::logthis('unable to save form parameters, '.
5873: 'got error:'.$put_result);
5874: }
5875: # Make sure these settings stick around in this session, too
5876: &Apache::lonnet::appenv(%AppHash);
5877: return;
5878: }
5879:
5880: sub restore_course_settings {
5881: my $courseid = $env{'request.course.id'};
5882: my ($prefix,$Settings) = @_;
5883: while (my ($setting,$type) = each(%$Settings)) {
5884: next if (exists($env{'form.'.$setting}));
5885: my $envname = 'environment.internal.'.$courseid.'.'.$prefix.
5886: '.'.$setting;
5887: if (exists($env{$envname})) {
5888: if ($type eq 'scalar') {
5889: $env{'form.'.$setting} = $env{$envname};
5890: } elsif ($type eq 'array') {
5891: $env{'form.'.$setting} = [
5892: map {
5893: &unescape($_);
5894: } split(',',$env{$envname})
5895: ];
5896: }
5897: }
5898: }
5899: }
5900:
5901: ############################################################
5902: ############################################################
5903:
5904: sub commit_customrole {
5905: my ($udom,$uname,$url,$three,$four,$five,$start,$end) = @_;
5906: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.'@'.$three.' in '.$url.
5907: ($start?', '.&mt('starting').' '.localtime($start):'').
5908: ($end?', ending '.localtime($end):'').': <b>'.
5909: &Apache::lonnet::assigncustomrole(
5910: $udom,$uname,$url,$three,$four,$five,$end,$start).
5911: '</b><br />';
5912: return $output;
5913: }
5914:
5915: sub commit_standardrole {
5916: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec) = @_;
5917: my $output;
5918: my $logmsg;
5919: if ($three eq 'st') {
5920: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec);
5921: if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course')) {
5922: $output = "Error: $result\n";
5923: } else {
5924: $output = &mt('Assigning').' '.$three.' in '.$url.
5925: ($start?', '.&mt('starting').' '.localtime($start):'').
5926: ($end?', '.&mt('ending').' '.localtime($end):'').
5927: ': <b>'.$result.'</b><br />'.
5928: &mt('Add to classlist').': <b>ok</b><br />';
5929: }
5930: } else {
5931: $output = &mt('Assigning').' '.$three.' in '.$url.
5932: ($start?', '.&mt('starting').' '.localtime($start):'').
5933: ($end?', '.&mt('ending').' '.localtime($end):'').': <b>'.
5934: &Apache::lonnet::assignrole(
5935: $udom,$uname,$url,$three,$end,$start).
5936: '</b><br />';
5937: }
5938: return $output;
5939: }
5940:
5941: sub commit_studentrole {
5942: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec) = @_;
5943: my $linefeed = '<br />'."\n";
5944: my $result;
5945: if (defined($one) && defined($two)) {
5946: my $cid=$one.'_'.$two;
5947: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
5948: my $secchange = 0;
5949: my $expire_role_result;
5950: my $modify_section_result;
5951: unless ($oldsec eq '-1') {
5952: unless ($sec eq $oldsec) {
5953: $secchange = 1;
5954: my $uurl='/'.$cid;
5955: $uurl=~s/\_/\//g;
5956: if ($oldsec) {
5957: $uurl.='/'.$oldsec;
5958: }
5959: $expire_role_result = &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',time);
5960: $result = $expire_role_result;
5961: }
5962: }
5963: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
5964: $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid);
5965: if ($modify_section_result =~ /^ok/) {
5966: if ($secchange == 1) {
5967: $$logmsg .= "Section for $uname switched from old section: $oldsec to new section: $sec".$linefeed;
5968: } elsif ($oldsec eq '-1') {
5969: $$logmsg .= "New student role for $uname in section $sec in course $cid".$linefeed;
5970: } else {
5971: $$logmsg .= "Student $uname assigned to unchanged section $sec in course $cid".$linefeed;
5972: }
5973: } else {
5974: $$logmsg .= "Error when attempting section change for $uname from old section $oldsec to new section: $sec in course $cid -error: $modify_section_result".$linefeed;
5975: }
5976: $result = $modify_section_result;
5977: } elsif ($secchange == 1) {
5978: $$logmsg .= "Error when attempting to expire role for $uname in old section $oldsec in course $cid -error: $expire_role_result".$linefeed;
5979: }
5980: } else {
5981: $$logmsg .= "Incomplete course id defined. Addition of user $uname from domain $udom to course $one\_$two, section $sec not completed.$linefeed";
5982: $result = "error: incomplete course id\n";
5983: }
5984: return $result;
5985: }
5986:
5987: ############################################################
5988: ############################################################
5989:
5990: sub construct_course {
5991: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname) = @_;
5992: my $outcome;
5993:
5994: #
5995: # Open course
5996: #
5997: my $crstype = lc($args->{'crstype'});
5998: my %cenv=();
5999: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
6000: $args->{'cdescr'},
6001: $args->{'curl'},
6002: $args->{'course_home'},
6003: $args->{'nonstandard'},
6004: $args->{'crscode'},
6005: $args->{'ccuname'}.':'.
6006: $args->{'ccdomain'},
6007: $args->{'crstype'});
6008:
6009: # Note: The testing routines depend on this being output; see
6010: # Utils::Course. This needs to at least be output as a comment
6011: # if anyone ever decides to not show this, and Utils::Course::new
6012: # will need to be suitably modified.
6013: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]<br />',$crstype,$$courseid);
6014: #
6015: # Check if created correctly
6016: #
6017: ($$crsudom,$$crsunum)=($$courseid=~/^\/(\w+)\/(\w+)$/);
6018: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
6019: $outcome .= &mt('Created on').': '.$crsuhome.'<br>';
6020: #
6021: # Are we cloning?
6022: #
6023: my $cloneid='';
6024: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
6025: $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
6026: my ($clonecrsudom,$clonecrsunum)=($cloneid=~/^\/(\w+)\/(\w+)$/);
6027: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
6028: if ($clonehome eq 'no_host') {
6029: $outcome .=
6030: '<br /><font color="red">'.&mt('Attempting to clone non-existing [_1]',$crstype).' '.$cloneid.'</font>';
6031: } else {
6032: $outcome .=
6033: '<br /><font color="green">'.&mt('Cloning [_1] from [_2]',$crstype,$clonehome).'</font>';
6034: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
6035: # Copy all files
6036: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid);
6037: # Restore URL
6038: $cenv{'url'}=$oldcenv{'url'};
6039: # Restore title
6040: $cenv{'description'}=$oldcenv{'description'};
6041: # restore grading mode
6042: if (defined($oldcenv{'grading'})) {
6043: $cenv{'grading'}=$oldcenv{'grading'};
6044: }
6045: # Mark as cloned
6046: $cenv{'clonedfrom'}=$cloneid;
6047: delete($cenv{'default_enrollment_start_date'});
6048: delete($cenv{'default_enrollment_end_date'});
6049: }
6050: }
6051: #
6052: # Set environment (will override cloned, if existing)
6053: #
6054: my @sections = ();
6055: my @xlists = ();
6056: if ($args->{'crstype'}) {
6057: $cenv{'type'}=$args->{'crstype'};
6058: }
6059: if ($args->{'crsid'}) {
6060: $cenv{'courseid'}=$args->{'crsid'};
6061: }
6062: if ($args->{'crscode'}) {
6063: $cenv{'internal.coursecode'}=$args->{'crscode'};
6064: }
6065: if ($args->{'crsquota'} ne '') {
6066: $cenv{'internal.coursequota'}=$args->{'crsquota'};
6067: } else {
6068: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
6069: }
6070: if ($args->{'ccuname'}) {
6071: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
6072: ':'.$args->{'ccdomain'};
6073: } else {
6074: $cenv{'internal.courseowner'} = $args->{'curruser'};
6075: }
6076:
6077: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
6078: if ($args->{'crssections'}) {
6079: $cenv{'internal.sectionnums'} = '';
6080: if ($args->{'crssections'} =~ m/,/) {
6081: @sections = split/,/,$args->{'crssections'};
6082: } else {
6083: $sections[0] = $args->{'crssections'};
6084: }
6085: if (@sections > 0) {
6086: foreach my $item (@sections) {
6087: my ($sec,$gp) = split/:/,$item;
6088: my $class = $args->{'crscode'}.$sec;
6089: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
6090: $cenv{'internal.sectionnums'} .= $item.',';
6091: unless ($addcheck eq 'ok') {
6092: push @badclasses, $class;
6093: }
6094: }
6095: $cenv{'internal.sectionnums'} =~ s/,$//;
6096: }
6097: }
6098: # do not hide course coordinator from staff listing,
6099: # even if privileged
6100: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
6101: # add crosslistings
6102: if ($args->{'crsxlist'}) {
6103: $cenv{'internal.crosslistings'}='';
6104: if ($args->{'crsxlist'} =~ m/,/) {
6105: @xlists = split/,/,$args->{'crsxlist'};
6106: } else {
6107: $xlists[0] = $args->{'crsxlist'};
6108: }
6109: if (@xlists > 0) {
6110: foreach my $item (@xlists) {
6111: my ($xl,$gp) = split/:/,$item;
6112: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
6113: $cenv{'internal.crosslistings'} .= $item.',';
6114: unless ($addcheck eq 'ok') {
6115: push @badclasses, $xl;
6116: }
6117: }
6118: $cenv{'internal.crosslistings'} =~ s/,$//;
6119: }
6120: }
6121: if ($args->{'autoadds'}) {
6122: $cenv{'internal.autoadds'}=$args->{'autoadds'};
6123: }
6124: if ($args->{'autodrops'}) {
6125: $cenv{'internal.autodrops'}=$args->{'autodrops'};
6126: }
6127: # check for notification of enrollment changes
6128: my @notified = ();
6129: if ($args->{'notify_owner'}) {
6130: if ($args->{'ccuname'} ne '') {
6131: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
6132: }
6133: }
6134: if ($args->{'notify_dc'}) {
6135: if ($uname ne '') {
6136: push(@notified,$uname.'@'.$udom);
6137: }
6138: }
6139: if (@notified > 0) {
6140: my $notifylist;
6141: if (@notified > 1) {
6142: $notifylist = join(',',@notified);
6143: } else {
6144: $notifylist = $notified[0];
6145: }
6146: $cenv{'internal.notifylist'} = $notifylist;
6147: }
6148: if (@badclasses > 0) {
6149: my %lt=&Apache::lonlocal::texthash(
6150: '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',
6151: 'dnhr' => 'does not have rights to access enrollment in these classes',
6152: 'adby' => 'as determined by the policies of your institution on access to official classlists'
6153: );
6154: $outcome .= '<font color="red">'.$lt{'tclb'}.' ('.$cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.' ('.$lt{'adby'}.').<br /><ul>'."\n";
6155: foreach (@badclasses) {
6156: $outcome .= "<li>$_</li>\n";
6157: }
6158: $outcome .= "</ul><br /><br /></font>\n";
6159: }
6160: if ($args->{'no_end_date'}) {
6161: $args->{'endaccess'} = 0;
6162: }
6163: $cenv{'internal.autostart'}=$args->{'enrollstart'};
6164: $cenv{'internal.autoend'}=$args->{'enrollend'};
6165: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
6166: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
6167: if ($args->{'showphotos'}) {
6168: $cenv{'internal.showphotos'}=$args->{'showphotos'};
6169: }
6170: $cenv{'internal.authtype'} = $args->{'authtype'};
6171: $cenv{'internal.autharg'} = $args->{'autharg'};
6172: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
6173: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
6174: $outcome .= '<font color="red" size="+1">'.
6175: &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').'</font></p>';
6176: }
6177: }
6178: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
6179: if ($args->{'setpolicy'}) {
6180: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
6181: }
6182: if ($args->{'setcontent'}) {
6183: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
6184: }
6185: }
6186: if ($args->{'reshome'}) {
6187: $cenv{'reshome'}=$args->{'reshome'}.'/';
6188: $cenv{'reshome'}=~s/\/+$/\//;
6189: }
6190: #
6191: # course has keyed access
6192: #
6193: if ($args->{'setkeys'}) {
6194: $cenv{'keyaccess'}='yes';
6195: }
6196: # if specified, key authority is not course, but user
6197: # only active if keyaccess is yes
6198: if ($args->{'keyauth'}) {
6199: $args->{'keyauth'}=~s/[^\w\@]//g;
6200: if ($args->{'keyauth'}) {
6201: $cenv{'keyauth'}=$args->{'keyauth'};
6202: }
6203: }
6204:
6205: if ($args->{'disresdis'}) {
6206: $cenv{'pch.roles.denied'}='st';
6207: }
6208: if ($args->{'disablechat'}) {
6209: $cenv{'plc.roles.denied'}='st';
6210: }
6211:
6212: # Record we've not yet viewed the Course Initialization Helper for this
6213: # course
6214: $cenv{'course.helper.not.run'} = 1;
6215: #
6216: # Use new Randomseed
6217: #
6218: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
6219: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
6220: #
6221: # The encryption code and receipt prefix for this course
6222: #
6223: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
6224: $cenv{'internal.encpref'}=100+int(9*rand(99));
6225: #
6226: # By default, use standard grading
6227: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
6228:
6229: $outcome .= ('<br />'.&mt('Setting environment').': '.
6230: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).'<br>');
6231: #
6232: # Open all assignments
6233: #
6234: if ($args->{'openall'}) {
6235: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
6236: my %storecontent = ($storeunder => time,
6237: $storeunder.'.type' => 'date_start');
6238:
6239: $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
6240: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).'<br>';
6241: }
6242: #
6243: # Set first page
6244: #
6245: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
6246: || ($cloneid)) {
6247: use LONCAPA::map;
6248: $outcome .= &mt('Setting first resource').': ';
6249:
6250: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
6251: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
6252:
6253: $outcome .= ($fatal?$errtext:'read ok').' - ';
6254: my $title; my $url;
6255: if ($args->{'firstres'} eq 'syl') {
6256: $title='Syllabus';
6257: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
6258: } else {
6259: $title='Navigate Contents';
6260: $url='/adm/navmaps';
6261: }
6262:
6263: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
6264: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
6265:
6266: if ($errtext) { $fatal=2; }
6267: $outcome .= ($fatal?$errtext:'write ok').'<br />';
6268: }
6269: return $outcome;
6270: }
6271:
6272: ############################################################
6273: ############################################################
6274:
6275: sub course_type {
6276: my ($cid) = @_;
6277: if (!defined($cid)) {
6278: $cid = $env{'request.course.id'};
6279: }
6280: if (defined($env{'course.'.$cid.'.type'})) {
6281: return $env{'course.'.$cid.'.type'};
6282: } else {
6283: return 'Course';
6284: }
6285: }
6286:
6287: sub group_term {
6288: my $crstype = &course_type();
6289: my %names = (
6290: 'Course' => 'group',
6291: 'Group' => 'team',
6292: );
6293: return $names{$crstype};
6294: }
6295:
6296: sub icon {
6297: my ($file)=@_;
6298: my $curfext = (split(/\./,$file))[-1];
6299: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
6300: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
6301: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
6302: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
6303: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
6304: $curfext.".gif") {
6305: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
6306: $curfext.".gif";
6307: }
6308: }
6309: return &lonhttpdurl($iconname);
6310: }
6311:
6312: sub lonhttpdurl {
6313: my ($url)=@_;
6314: my $lonhttpd_port=$Apache::lonnet::perlvar{'lonhttpdPort'};
6315: if (!defined($lonhttpd_port)) { $lonhttpd_port='8080'; }
6316: return 'http://'.$ENV{'SERVER_NAME'}.':'.$lonhttpd_port.$url;
6317: }
6318:
6319: sub connection_aborted {
6320: my ($r)=@_;
6321: $r->print(" ");$r->rflush();
6322: my $c = $r->connection;
6323: return $c->aborted();
6324: }
6325:
6326: # Escapes strings that may have embedded 's that will be put into
6327: # strings as 'strings'.
6328: sub escape_single {
6329: my ($input) = @_;
6330: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
6331: $input =~ s/\'/\\\'/g; # Esacpe the 's....
6332: return $input;
6333: }
6334:
6335: # Same as escape_single, but escape's "'s This
6336: # can be used for "strings"
6337: sub escape_double {
6338: my ($input) = @_;
6339: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
6340: $input =~ s/\"/\\\"/g; # Esacpe the "s....
6341: return $input;
6342: }
6343:
6344: # Escapes the last element of a full URL.
6345: sub escape_url {
6346: my ($url) = @_;
6347: my @urlslices = split(/\//, $url,-1);
6348: my $lastitem = &escape(pop(@urlslices));
6349: return join('/',@urlslices).'/'.$lastitem;
6350: }
6351:
6352: # -------------------------------------------------------- Initliaze user login
6353: sub init_user_environment {
6354: my ($r, $username, $domain, $authhost, $form, $args) = @_;
6355: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
6356:
6357: my $public=($username eq 'public' && $domain eq 'public');
6358:
6359: # See if old ID present, if so, remove
6360:
6361: my ($filename,$cookie,$userroles);
6362: my $now=time;
6363:
6364: if ($public) {
6365: my $max_public=100;
6366: my $oldest;
6367: my $oldest_time=0;
6368: for(my $next=1;$next<=$max_public;$next++) {
6369: if (-e $lonids."/publicuser_$next.id") {
6370: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
6371: if ($mtime<$oldest_time || !$oldest_time) {
6372: $oldest_time=$mtime;
6373: $oldest=$next;
6374: }
6375: } else {
6376: $cookie="publicuser_$next";
6377: last;
6378: }
6379: }
6380: if (!$cookie) { $cookie="publicuser_$oldest"; }
6381: } else {
6382: # if this isn't a robot, kill any existing non-robot sessions
6383: if (!$args->{'robot'}) {
6384: opendir(DIR,$lonids);
6385: while ($filename=readdir(DIR)) {
6386: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
6387: unlink($lonids.'/'.$filename);
6388: }
6389: }
6390: closedir(DIR);
6391: }
6392: # Give them a new cookie
6393: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
6394: : $now);
6395: $cookie="$username\_$id\_$domain\_$authhost";
6396:
6397: # Initialize roles
6398:
6399: $userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
6400: }
6401: # ------------------------------------ Check browser type and MathML capability
6402:
6403: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
6404: $clientunicode,$clientos) = &decode_user_agent($r);
6405:
6406: # -------------------------------------- Any accessibility options to remember?
6407: if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
6408: foreach my $option ('imagesuppress','appletsuppress',
6409: 'embedsuppress','fontenhance','blackwhite') {
6410: if ($form->{$option} eq 'true') {
6411: &Apache::lonnet::put('environment',{$option => 'on'},
6412: $domain,$username);
6413: } else {
6414: &Apache::lonnet::del('environment',[$option],
6415: $domain,$username);
6416: }
6417: }
6418: }
6419: # ------------------------------------------------------------- Get environment
6420:
6421: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
6422: my ($tmp) = keys(%userenv);
6423: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
6424: # default remote control to off
6425: if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
6426: } else {
6427: undef(%userenv);
6428: }
6429: if (($userenv{'interface'}) && (!$form->{'interface'})) {
6430: $form->{'interface'}=$userenv{'interface'};
6431: }
6432: $env{'environment.remote'}=$userenv{'remote'};
6433: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
6434:
6435: # --------------- Do not trust query string to be put directly into environment
6436: foreach my $option ('imagesuppress','appletsuppress',
6437: 'embedsuppress','fontenhance','blackwhite',
6438: 'interface','localpath','localres') {
6439: $form->{$option}=~s/[\n\r\=]//gs;
6440: }
6441: # --------------------------------------------------------- Write first profile
6442:
6443: {
6444: my %initial_env =
6445: ("user.name" => $username,
6446: "user.domain" => $domain,
6447: "user.home" => $authhost,
6448: "browser.type" => $clientbrowser,
6449: "browser.version" => $clientversion,
6450: "browser.mathml" => $clientmathml,
6451: "browser.unicode" => $clientunicode,
6452: "browser.os" => $clientos,
6453: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
6454: "request.course.fn" => '',
6455: "request.course.uri" => '',
6456: "request.course.sec" => '',
6457: "request.role" => 'cm',
6458: "request.role.adv" => $env{'user.adv'},
6459: "request.host" => $ENV{'REMOTE_ADDR'},);
6460:
6461: if ($form->{'localpath'}) {
6462: $initial_env{"browser.localpath"} = $form->{'localpath'};
6463: $initial_env{"browser.localres"} = $form->{'localres'};
6464: }
6465:
6466: if ($public) {
6467: $initial_env{"environment.remote"} = "off";
6468: }
6469: if ($form->{'interface'}) {
6470: $form->{'interface'}=~s/\W//gs;
6471: $initial_env{"browser.interface"} = $form->{'interface'};
6472: $env{'browser.interface'}=$form->{'interface'};
6473: foreach my $option ('imagesuppress','appletsuppress',
6474: 'embedsuppress','fontenhance','blackwhite') {
6475: if (($form->{$option} eq 'true') ||
6476: ($userenv{$option} eq 'on')) {
6477: $initial_env{"browser.$option"} = "on";
6478: }
6479: }
6480: }
6481:
6482: $env{'user.environment'} = "$lonids/$cookie.id";
6483:
6484: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
6485: &GDBM_WRCREAT(),0640)) {
6486: &_add_to_env(\%disk_env,\%initial_env);
6487: &_add_to_env(\%disk_env,\%userenv,'environment.');
6488: &_add_to_env(\%disk_env,$userroles);
6489: if (ref($args->{'extra_env'})) {
6490: &_add_to_env(\%disk_env,$args->{'extra_env'});
6491: }
6492: untie(%disk_env);
6493: } else {
6494: &Apache::lonnet::logthis("<font color=\"blue\">WARNING: ".
6495: 'Could not create environment storage in lonauth: '.$!.'</font>');
6496: return 'error: '.$!;
6497: }
6498: }
6499: $env{'request.role'}='cm';
6500: $env{'request.role.adv'}=$env{'user.adv'};
6501: $env{'browser.type'}=$clientbrowser;
6502:
6503: return $cookie;
6504:
6505: }
6506:
6507: sub _add_to_env {
6508: my ($idf,$env_data,$prefix) = @_;
6509: while (my ($key,$value) = each(%$env_data)) {
6510: $idf->{$prefix.$key} = $value;
6511: $env{$prefix.$key} = $value;
6512: }
6513: }
6514:
6515:
6516: =pod
6517:
6518: =back
6519:
6520: =cut
6521:
6522: 1;
6523: __END__;
6524:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>