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