File:
[LON-CAPA] /
loncom /
interface /
loncommon.pm
Revision
1.693:
download - view:
text,
annotated -
select for diffs
Fri Nov 14 13:29:28 2008 UTC (15 years, 9 months ago) by
droeschl
Branches:
MAIN
CVS tags:
HEAD
Changes related to LON-CAPA redesign project.
Added new CSS definitions. These styles will be subject to change during the course of this project. They also might interfere with existing styles. This issue is currently being worked on.
1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.693 2008/11/14 13:29:28 droeschl Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29: # Makes a table out of the previous attempts
30: # Inputs result_from_symbread, user, domain, course_id
31: # Reads in non-network-related .tab files
32:
33: # POD header:
34:
35: =pod
36:
37: =head1 NAME
38:
39: Apache::loncommon - pile of common routines
40:
41: =head1 SYNOPSIS
42:
43: Common routines for manipulating connections, student answers,
44: domains, common Javascript fragments, etc.
45:
46: =head1 OVERVIEW
47:
48: A collection of commonly used subroutines that don't have a natural
49: home anywhere else. This collection helps remove
50: redundancy from other modules and increase efficiency of memory usage.
51:
52: =cut
53:
54: # End of POD header
55: package Apache::loncommon;
56:
57: use strict;
58: use Apache::lonnet;
59: use GDBM_File;
60: use POSIX qw(strftime mktime);
61: use Apache::lonmenu();
62: use Apache::lonenc();
63: use Apache::lonlocal;
64: use Apache::lonnet();
65: use HTML::Entities;
66: use Apache::lonhtmlcommon();
67: use Apache::loncoursedata();
68: use Apache::lontexconvert();
69: use Apache::lonclonecourse();
70: use LONCAPA qw(:DEFAULT :match);
71: use DateTime::TimeZone;
72: use DateTime::Locale::Catalog;
73:
74: # ---------------------------------------------- Designs
75: use vars qw(%defaultdesign);
76:
77: my $readit;
78:
79:
80: ##
81: ## Global Variables
82: ##
83:
84:
85: # ----------------------------------------------- SSI with retries:
86: #
87:
88: =pod
89:
90: =head1 Server Side include with retries:
91:
92: =over 4
93:
94: =item * &ssi_with_retries(resource,retries form)
95:
96: Performs an ssi with some number of retries. Retries continue either
97: until the result is ok or until the retry count supplied by the
98: caller is exhausted.
99:
100: Inputs:
101:
102: =over 4
103:
104: resource - Identifies the resource to insert.
105:
106: retries - Count of the number of retries allowed.
107:
108: form - Hash that identifies the rendering options.
109:
110: =back
111:
112: Returns:
113:
114: =over 4
115:
116: content - The content of the response. If retries were exhausted this is empty.
117:
118: response - The response from the last attempt (which may or may not have been successful.
119:
120: =back
121:
122: =back
123:
124: =cut
125:
126: sub ssi_with_retries {
127: my ($resource, $retries, %form) = @_;
128:
129:
130: my $ok = 0; # True if we got a good response.
131: my $content;
132: my $response;
133:
134: # Try to get the ssi done. within the retries count:
135:
136: do {
137: ($content, $response) = &Apache::lonnet::ssi($resource, %form);
138: $ok = $response->is_success;
139: if (!$ok) {
140: &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
141: }
142: $retries--;
143: } while (!$ok && ($retries > 0));
144:
145: if (!$ok) {
146: $content = ''; # On error return an empty content.
147: }
148: return ($content, $response);
149:
150: }
151:
152:
153:
154: # ----------------------------------------------- Filetypes/Languages/Copyright
155: my %language;
156: my %supported_language;
157: my %cprtag;
158: my %scprtag;
159: my %fe; my %fd; my %fm;
160: my %category_extensions;
161:
162: # ---------------------------------------------- Thesaurus variables
163: #
164: # %Keywords:
165: # A hash used by &keyword to determine if a word is considered a keyword.
166: # $thesaurus_db_file
167: # Scalar containing the full path to the thesaurus database.
168:
169: my %Keywords;
170: my $thesaurus_db_file;
171:
172: #
173: # Initialize values from language.tab, copyright.tab, filetypes.tab,
174: # thesaurus.tab, and filecategories.tab.
175: #
176: BEGIN {
177: # Variable initialization
178: $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
179: #
180: unless ($readit) {
181: # ------------------------------------------------------------------- languages
182: {
183: my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
184: '/language.tab';
185: if ( open(my $fh,"<$langtabfile") ) {
186: while (my $line = <$fh>) {
187: next if ($line=~/^\#/);
188: chomp($line);
189: my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
190: $language{$key}=$val.' - '.$enc;
191: if ($sup) {
192: $supported_language{$key}=$sup;
193: }
194: }
195: close($fh);
196: }
197: }
198: # ------------------------------------------------------------------ copyrights
199: {
200: my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
201: '/copyright.tab';
202: if ( open (my $fh,"<$copyrightfile") ) {
203: while (my $line = <$fh>) {
204: next if ($line=~/^\#/);
205: chomp($line);
206: my ($key,$val)=(split(/\s+/,$line,2));
207: $cprtag{$key}=$val;
208: }
209: close($fh);
210: }
211: }
212: # ----------------------------------------------------------- source copyrights
213: {
214: my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
215: '/source_copyright.tab';
216: if ( open (my $fh,"<$sourcecopyrightfile") ) {
217: while (my $line = <$fh>) {
218: next if ($line =~ /^\#/);
219: chomp($line);
220: my ($key,$val)=(split(/\s+/,$line,2));
221: $scprtag{$key}=$val;
222: }
223: close($fh);
224: }
225: }
226:
227: # -------------------------------------------------------------- default domain designs
228: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
229: my $designfile = $designdir.'/default.tab';
230: if ( open (my $fh,"<$designfile") ) {
231: while (my $line = <$fh>) {
232: next if ($line =~ /^\#/);
233: chomp($line);
234: my ($key,$val)=(split(/\=/,$line));
235: if ($val) { $defaultdesign{$key}=$val; }
236: }
237: close($fh);
238: }
239:
240: # ------------------------------------------------------------- file categories
241: {
242: my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
243: '/filecategories.tab';
244: if ( open (my $fh,"<$categoryfile") ) {
245: while (my $line = <$fh>) {
246: next if ($line =~ /^\#/);
247: chomp($line);
248: my ($extension,$category)=(split(/\s+/,$line,2));
249: push @{$category_extensions{lc($category)}},$extension;
250: }
251: close($fh);
252: }
253:
254: }
255: # ------------------------------------------------------------------ file types
256: {
257: my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
258: '/filetypes.tab';
259: if ( open (my $fh,"<$typesfile") ) {
260: while (my $line = <$fh>) {
261: next if ($line =~ /^\#/);
262: chomp($line);
263: my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
264: if ($descr ne '') {
265: $fe{$ending}=lc($emb);
266: $fd{$ending}=$descr;
267: if ($mime ne 'unk') { $fm{$ending}=$mime; }
268: }
269: }
270: close($fh);
271: }
272: }
273: &Apache::lonnet::logthis(
274: "<font color=yellow>INFO: Read file types</font>");
275: $readit=1;
276: } # end of unless($readit)
277:
278: }
279:
280: ###############################################################
281: ## HTML and Javascript Helper Functions ##
282: ###############################################################
283:
284: =pod
285:
286: =head1 HTML and Javascript Functions
287:
288: =over 4
289:
290: =item * &browser_and_searcher_javascript()
291:
292: X<browsing, javascript>X<searching, javascript>Returns a string
293: containing javascript with two functions, C<openbrowser> and
294: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
295: tags.
296:
297: =item * &openbrowser(formname,elementname,only,omit) [javascript]
298:
299: inputs: formname, elementname, only, omit
300:
301: formname and elementname indicate the name of the html form and name of
302: the element that the results of the browsing selection are to be placed in.
303:
304: Specifying 'only' will restrict the browser to displaying only files
305: with the given extension. Can be a comma separated list.
306:
307: Specifying 'omit' will restrict the browser to NOT displaying files
308: with the given extension. Can be a comma separated list.
309:
310: =item * &opensearcher(formname,elementname) [javascript]
311:
312: Inputs: formname, elementname
313:
314: formname and elementname specify the name of the html form and the name
315: of the element the selection from the search results will be placed in.
316:
317: =cut
318:
319: sub browser_and_searcher_javascript {
320: my ($mode)=@_;
321: if (!defined($mode)) { $mode='edit'; }
322: my $resurl=&escape_single(&lastresurl());
323: return <<END;
324: // <!-- BEGIN LON-CAPA Internal
325: var editbrowser = null;
326: function openbrowser(formname,elementname,only,omit,titleelement) {
327: var url = '$resurl/?';
328: if (editbrowser == null) {
329: url += 'launch=1&';
330: }
331: url += 'catalogmode=interactive&';
332: url += 'mode=$mode&';
333: url += 'inhibitmenu=yes&';
334: url += 'form=' + formname + '&';
335: if (only != null) {
336: url += 'only=' + only + '&';
337: } else {
338: url += 'only=&';
339: }
340: if (omit != null) {
341: url += 'omit=' + omit + '&';
342: } else {
343: url += 'omit=&';
344: }
345: if (titleelement != null) {
346: url += 'titleelement=' + titleelement + '&';
347: } else {
348: url += 'titleelement=&';
349: }
350: url += 'element=' + elementname + '';
351: var title = 'Browser';
352: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
353: options += ',width=700,height=600';
354: editbrowser = open(url,title,options,'1');
355: editbrowser.focus();
356: }
357: var editsearcher;
358: function opensearcher(formname,elementname,titleelement) {
359: var url = '/adm/searchcat?';
360: if (editsearcher == null) {
361: url += 'launch=1&';
362: }
363: url += 'catalogmode=interactive&';
364: url += 'mode=$mode&';
365: url += 'form=' + formname + '&';
366: if (titleelement != null) {
367: url += 'titleelement=' + titleelement + '&';
368: } else {
369: url += 'titleelement=&';
370: }
371: url += 'element=' + elementname + '';
372: var title = 'Search';
373: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
374: options += ',width=700,height=600';
375: editsearcher = open(url,title,options,'1');
376: editsearcher.focus();
377: }
378: // END LON-CAPA Internal -->
379: END
380: }
381:
382: sub lastresurl {
383: if ($env{'environment.lastresurl'}) {
384: return $env{'environment.lastresurl'}
385: } else {
386: return '/res';
387: }
388: }
389:
390: sub storeresurl {
391: my $resurl=&Apache::lonnet::clutter(shift);
392: unless ($resurl=~/^\/res/) { return 0; }
393: $resurl=~s/\/$//;
394: &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
395: &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
396: return 1;
397: }
398:
399: sub studentbrowser_javascript {
400: unless (
401: (($env{'request.course.id'}) &&
402: (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
403: || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
404: '/'.$env{'request.course.sec'})
405: ))
406: || ($env{'request.role'}=~/^(au|dc|su)/)
407: ) { return ''; }
408: return (<<'ENDSTDBRW');
409: <script type="text/javascript" language="Javascript" >
410: var stdeditbrowser;
411: function openstdbrowser(formname,uname,udom,roleflag,ignorefilter) {
412: var url = '/adm/pickstudent?';
413: var filter;
414: if (!ignorefilter) {
415: eval('filter=document.'+formname+'.'+uname+'.value;');
416: }
417: if (filter != null) {
418: if (filter != '') {
419: url += 'filter='+filter+'&';
420: }
421: }
422: url += 'form=' + formname + '&unameelement='+uname+
423: '&udomelement='+udom;
424: if (roleflag) { url+="&roles=1"; }
425: var title = 'Student_Browser';
426: var options = 'scrollbars=1,resizable=1,menubar=0';
427: options += ',width=700,height=600';
428: stdeditbrowser = open(url,title,options,'1');
429: stdeditbrowser.focus();
430: }
431: </script>
432: ENDSTDBRW
433: }
434:
435: sub selectstudent_link {
436: my ($form,$unameele,$udomele)=@_;
437: if ($env{'request.course.id'}) {
438: if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
439: && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
440: '/'.$env{'request.course.sec'})) {
441: return '';
442: }
443: return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
444: '","'.$udomele.'");'."'>".&mt('Select User')."</a>";
445: }
446: if ($env{'request.role'}=~/^(au|dc|su)/) {
447: return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
448: '","'.$udomele.'",1);'."'>".&mt('Select User')."</a>";
449: }
450: return '';
451: }
452:
453: sub authorbrowser_javascript {
454: return <<"ENDAUTHORBRW";
455: <script type="text/javascript">
456: var stdeditbrowser;
457:
458: function openauthorbrowser(formname,udom) {
459: var url = '/adm/pickauthor?';
460: url += 'form='+formname+'&roledom='+udom;
461: var title = 'Author_Browser';
462: var options = 'scrollbars=1,resizable=1,menubar=0';
463: options += ',width=700,height=600';
464: stdeditbrowser = open(url,title,options,'1');
465: stdeditbrowser.focus();
466: }
467:
468: </script>
469: ENDAUTHORBRW
470: }
471:
472: sub coursebrowser_javascript {
473: my ($domainfilter,$sec_element,$formname)=@_;
474: 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');
475: my $output = '
476: <script type="text/javascript">
477: var stdeditbrowser;'."\n";
478: $output .= <<"ENDSTDBRW";
479: function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,crstype) {
480: var url = '/adm/pickcourse?';
481: var domainfilter = '';
482: var formid = getFormIdByName(formname);
483: if (formid > -1) {
484: var domid = getIndexByName(formid,udom);
485: if (domid > -1) {
486: if (document.forms[formid].elements[domid].type == 'select-one') {
487: domainfilter=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
488: }
489: if (document.forms[formid].elements[domid].type == 'hidden') {
490: domainfilter=document.forms[formid].elements[domid].value;
491: }
492: }
493: }
494: if (domainfilter != null) {
495: if (domainfilter != '') {
496: url += 'domainfilter='+domainfilter+'&';
497: }
498: }
499: url += 'form=' + formname + '&cnumelement='+uname+
500: '&cdomelement='+udom+
501: '&cnameelement='+desc;
502: if (extra_element !=null && extra_element != '') {
503: if (formname == 'rolechoice' || formname == 'studentform') {
504: url += '&roleelement='+extra_element;
505: if (domainfilter == null || domainfilter == '') {
506: url += '&domainfilter='+extra_element;
507: }
508: }
509: else {
510: if (formname == 'portform') {
511: url += '&setroles='+extra_element;
512: }
513: }
514: }
515: if (multflag !=null && multflag != '') {
516: url += '&multiple='+multflag;
517: }
518: if (crstype == 'Course/Group') {
519: if (formname == 'cu') {
520: crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value;
521: if (crstype == "") {
522: alert("$crs_or_grp_alert");
523: return;
524: }
525: }
526: }
527: if (crstype !=null && crstype != '') {
528: url += '&type='+crstype;
529: }
530: var title = 'Course_Browser';
531: var options = 'scrollbars=1,resizable=1,menubar=0';
532: options += ',width=700,height=600';
533: stdeditbrowser = open(url,title,options,'1');
534: stdeditbrowser.focus();
535: }
536:
537: function getFormIdByName(formname) {
538: for (var i=0;i<document.forms.length;i++) {
539: if (document.forms[i].name == formname) {
540: return i;
541: }
542: }
543: return -1;
544: }
545:
546: function getIndexByName(formid,item) {
547: for (var i=0;i<document.forms[formid].elements.length;i++) {
548: if (document.forms[formid].elements[i].name == item) {
549: return i;
550: }
551: }
552: return -1;
553: }
554: ENDSTDBRW
555: if ($sec_element ne '') {
556: $output .= &setsec_javascript($sec_element,$formname);
557: }
558: $output .= '
559: </script>';
560: return $output;
561: }
562:
563: sub setsec_javascript {
564: my ($sec_element,$formname) = @_;
565: my $setsections = qq|
566: function setSect(sectionlist) {
567: var sectionsArray = new Array();
568: if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
569: sectionsArray = sectionlist.split(",");
570: }
571: var numSections = sectionsArray.length;
572: document.$formname.$sec_element.length = 0;
573: if (numSections == 0) {
574: document.$formname.$sec_element.multiple=false;
575: document.$formname.$sec_element.size=1;
576: document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
577: } else {
578: if (numSections == 1) {
579: document.$formname.$sec_element.multiple=false;
580: document.$formname.$sec_element.size=1;
581: document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
582: document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
583: document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
584: } else {
585: for (var i=0; i<numSections; i++) {
586: document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
587: }
588: document.$formname.$sec_element.multiple=true
589: if (numSections < 3) {
590: document.$formname.$sec_element.size=numSections;
591: } else {
592: document.$formname.$sec_element.size=3;
593: }
594: document.$formname.$sec_element.options[0].selected = false
595: }
596: }
597: }
598: |;
599: return $setsections;
600: }
601:
602:
603: sub selectcourse_link {
604: my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
605: return "<a href='".'javascript:opencrsbrowser("'.$form.'","'.$unameele.
606: '","'.$udomele.'","'.$desc.'","'.$extra_element.'","'.$multflag.'","'.$selecttype.'");'."'>".&mt('Select Course')."</a>";
607: }
608:
609: sub selectauthor_link {
610: my ($form,$udom)=@_;
611: return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
612: &mt('Select Author').'</a>';
613: }
614:
615: sub check_uncheck_jscript {
616: my $jscript = <<"ENDSCRT";
617: function checkAll(field) {
618: if (field.length > 0) {
619: for (i = 0; i < field.length; i++) {
620: field[i].checked = true ;
621: }
622: } else {
623: field.checked = true
624: }
625: }
626:
627: function uncheckAll(field) {
628: if (field.length > 0) {
629: for (i = 0; i < field.length; i++) {
630: field[i].checked = false ;
631: }
632: } else {
633: field.checked = false ;
634: }
635: }
636: ENDSCRT
637: return $jscript;
638: }
639:
640: sub select_timezone {
641: my ($name,$selected,$onchange,$includeempty)=@_;
642: my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
643: if ($includeempty) {
644: $output .= '<option value=""';
645: if (($selected eq '') || ($selected eq 'local')) {
646: $output .= ' selected="selected" ';
647: }
648: $output .= '> </option>';
649: }
650: my @timezones = DateTime::TimeZone->all_names;
651: foreach my $tzone (@timezones) {
652: $output.= '<option value="'.$tzone.'"';
653: if ($tzone eq $selected) {
654: $output.=' selected="selected"';
655: }
656: $output.=">$tzone</option>\n";
657: }
658: $output.="</select>";
659: return $output;
660: }
661:
662: sub select_datelocale {
663: my ($name,$selected,$onchange,$includeempty)=@_;
664: my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
665: if ($includeempty) {
666: $output .= '<option value=""';
667: if ($selected eq '') {
668: $output .= ' selected="selected" ';
669: }
670: $output .= '> </option>';
671: }
672: my (@possibles,%locale_names);
673: my @locales = DateTime::Locale::Catalog::Locales;
674: foreach my $locale (@locales) {
675: if (ref($locale) eq 'HASH') {
676: my $id = $locale->{'id'};
677: if ($id ne '') {
678: my $en_terr = $locale->{'en_territory'};
679: my $native_terr = $locale->{'native_territory'};
680: my @languages = &preferred_languages();
681: if (grep(/^en$/,@languages) || !@languages) {
682: if ($en_terr ne '') {
683: $locale_names{$id} = '('.$en_terr.')';
684: } elsif ($native_terr ne '') {
685: $locale_names{$id} = $native_terr;
686: }
687: } else {
688: if ($native_terr ne '') {
689: $locale_names{$id} = $native_terr.' ';
690: } elsif ($en_terr ne '') {
691: $locale_names{$id} = '('.$en_terr.')';
692: }
693: }
694: push (@possibles,$id);
695: }
696: }
697: }
698: foreach my $item (sort(@possibles)) {
699: $output.= '<option value="'.$item.'"';
700: if ($item eq $selected) {
701: $output.=' selected="selected"';
702: }
703: $output.=">$item";
704: if ($locale_names{$item} ne '') {
705: $output.=" $locale_names{$item}</option>\n";
706: }
707: $output.="</option>\n";
708: }
709: $output.="</select>";
710: return $output;
711: }
712:
713: =pod
714:
715: =item * &linked_select_forms(...)
716:
717: linked_select_forms returns a string containing a <script></script> block
718: and html for two <select> menus. The select menus will be linked in that
719: changing the value of the first menu will result in new values being placed
720: in the second menu. The values in the select menu will appear in alphabetical
721: order unless a defined order is provided.
722:
723: linked_select_forms takes the following ordered inputs:
724:
725: =over 4
726:
727: =item * $formname, the name of the <form> tag
728:
729: =item * $middletext, the text which appears between the <select> tags
730:
731: =item * $firstdefault, the default value for the first menu
732:
733: =item * $firstselectname, the name of the first <select> tag
734:
735: =item * $secondselectname, the name of the second <select> tag
736:
737: =item * $hashref, a reference to a hash containing the data for the menus.
738:
739: =item * $menuorder, the order of values in the first menu
740:
741: =back
742:
743: Below is an example of such a hash. Only the 'text', 'default', and
744: 'select2' keys must appear as stated. keys(%menu) are the possible
745: values for the first select menu. The text that coincides with the
746: first menu value is given in $menu{$choice1}->{'text'}. The values
747: and text for the second menu are given in the hash pointed to by
748: $menu{$choice1}->{'select2'}.
749:
750: my %menu = ( A1 => { text =>"Choice A1" ,
751: default => "B3",
752: select2 => {
753: B1 => "Choice B1",
754: B2 => "Choice B2",
755: B3 => "Choice B3",
756: B4 => "Choice B4"
757: },
758: order => ['B4','B3','B1','B2'],
759: },
760: A2 => { text =>"Choice A2" ,
761: default => "C2",
762: select2 => {
763: C1 => "Choice C1",
764: C2 => "Choice C2",
765: C3 => "Choice C3"
766: },
767: order => ['C2','C1','C3'],
768: },
769: A3 => { text =>"Choice A3" ,
770: default => "D6",
771: select2 => {
772: D1 => "Choice D1",
773: D2 => "Choice D2",
774: D3 => "Choice D3",
775: D4 => "Choice D4",
776: D5 => "Choice D5",
777: D6 => "Choice D6",
778: D7 => "Choice D7"
779: },
780: order => ['D4','D3','D2','D1','D7','D6','D5'],
781: }
782: );
783:
784: =cut
785:
786: sub linked_select_forms {
787: my ($formname,
788: $middletext,
789: $firstdefault,
790: $firstselectname,
791: $secondselectname,
792: $hashref,
793: $menuorder,
794: ) = @_;
795: my $second = "document.$formname.$secondselectname";
796: my $first = "document.$formname.$firstselectname";
797: # output the javascript to do the changing
798: my $result = '';
799: $result.="<script type=\"text/javascript\">\n";
800: $result.="var select2data = new Object();\n";
801: $" = '","';
802: my $debug = '';
803: foreach my $s1 (sort(keys(%$hashref))) {
804: $result.="select2data.d_$s1 = new Object();\n";
805: $result.="select2data.d_$s1.def = new String('".
806: $hashref->{$s1}->{'default'}."');\n";
807: $result.="select2data.d_$s1.values = new Array(";
808: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
809: if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
810: @s2values = @{$hashref->{$s1}->{'order'}};
811: }
812: $result.="\"@s2values\");\n";
813: $result.="select2data.d_$s1.texts = new Array(";
814: my @s2texts;
815: foreach my $value (@s2values) {
816: push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
817: }
818: $result.="\"@s2texts\");\n";
819: }
820: $"=' ';
821: $result.= <<"END";
822:
823: function select1_changed() {
824: // Determine new choice
825: var newvalue = "d_" + $first.value;
826: // update select2
827: var values = select2data[newvalue].values;
828: var texts = select2data[newvalue].texts;
829: var select2def = select2data[newvalue].def;
830: var i;
831: // out with the old
832: for (i = 0; i < $second.options.length; i++) {
833: $second.options[i] = null;
834: }
835: // in with the nuclear
836: for (i=0;i<values.length; i++) {
837: $second.options[i] = new Option(values[i]);
838: $second.options[i].value = values[i];
839: $second.options[i].text = texts[i];
840: if (values[i] == select2def) {
841: $second.options[i].selected = true;
842: }
843: }
844: }
845: </script>
846: END
847: # output the initial values for the selection lists
848: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
849: my @order = sort(keys(%{$hashref}));
850: if (ref($menuorder) eq 'ARRAY') {
851: @order = @{$menuorder};
852: }
853: foreach my $value (@order) {
854: $result.=" <option value=\"$value\" ";
855: $result.=" selected=\"selected\" " if ($value eq $firstdefault);
856: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
857: }
858: $result .= "</select>\n";
859: my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
860: $result .= $middletext;
861: $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
862: my $seconddefault = $hashref->{$firstdefault}->{'default'};
863:
864: my @secondorder = sort(keys(%select2));
865: if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
866: @secondorder = @{$hashref->{$firstdefault}->{'order'}};
867: }
868: foreach my $value (@secondorder) {
869: $result.=" <option value=\"$value\" ";
870: $result.=" selected=\"selected\" " if ($value eq $seconddefault);
871: $result.=">".&mt($select2{$value})."</option>\n";
872: }
873: $result .= "</select>\n";
874: # return $debug;
875: return $result;
876: } # end of sub linked_select_forms {
877:
878: =pod
879:
880: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height)
881:
882: Returns a string corresponding to an HTML link to the given help
883: $topic, where $topic corresponds to the name of a .tex file in
884: /home/httpd/html/adm/help/tex, with underscores replaced by
885: spaces.
886:
887: $text will optionally be linked to the same topic, allowing you to
888: link text in addition to the graphic. If you do not want to link
889: text, but wish to specify one of the later parameters, pass an
890: empty string.
891:
892: $stayOnPage is a value that will be interpreted as a boolean. If true,
893: the link will not open a new window. If false, the link will open
894: a new window using Javascript. (Default is false.)
895:
896: $width and $height are optional numerical parameters that will
897: override the width and height of the popped up window, which may
898: be useful for certain help topics with big pictures included.
899:
900: =cut
901:
902: sub help_open_topic {
903: my ($topic, $text, $stayOnPage, $width, $height) = @_;
904: $text = "" if (not defined $text);
905: $stayOnPage = 0 if (not defined $stayOnPage);
906: if ($env{'browser.interface'} eq 'textual') {
907: $stayOnPage=1;
908: }
909: $width = 350 if (not defined $width);
910: $height = 400 if (not defined $height);
911: my $filename = $topic;
912: $filename =~ s/ /_/g;
913:
914: my $template = "";
915: my $link;
916:
917: $topic=~s/\W/\_/g;
918:
919: if (!$stayOnPage) {
920: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
921: } else {
922: $link = "/adm/help/${filename}.hlp";
923: }
924:
925: # Add the text
926: if ($text ne "") {
927: $template .=
928: "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
929: "<td bgcolor='#5555FF'><span class=\"LC_nobreak\"><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
930: }
931:
932: # Add the graphic
933: my $title = &mt('Online Help');
934: my $helpicon=&lonhttpdurl("/adm/help/help.png");
935: $template .= <<"ENDTEMPLATE";
936: <a target="_top" href="$link" title="$title"><img src="$helpicon" border="0" alt="(Help: $topic)" /></a>
937: ENDTEMPLATE
938: if ($text ne '') { $template.='</span></td></tr></table>' };
939: return $template;
940:
941: }
942:
943: # This is a quicky function for Latex cheatsheet editing, since it
944: # appears in at least four places
945: sub helpLatexCheatsheet {
946: my $other = shift;
947: my $addOther = '';
948: if ($other) {
949: $addOther = Apache::loncommon::help_open_topic($other, shift,
950: undef, undef, 600) .
951: '</td><td>';
952: }
953: return '<table><tr><td>'.
954: $addOther .
955: &Apache::loncommon::help_open_topic("Greek_Symbols",&mt('Greek Symbols'),
956: undef,undef,600)
957: .'</td><td>'.
958: &Apache::loncommon::help_open_topic("Other_Symbols",&mt('Other Symbols'),
959: undef,undef,600)
960: .'</td><td>'.
961: &Apache::loncommon::help_open_topic("Authoring_Output_Tags",&mt('Output Tags'),
962: undef,undef,600)
963: .'</td></tr></table>';
964: }
965:
966: sub general_help {
967: my $helptopic='Student_Intro';
968: if ($env{'request.role'}=~/^(ca|au)/) {
969: $helptopic='Authoring_Intro';
970: } elsif ($env{'request.role'}=~/^cc/) {
971: $helptopic='Course_Coordination_Intro';
972: } elsif ($env{'request.role'}=~/^dc/) {
973: $helptopic='Domain_Coordination_Intro';
974: }
975: return $helptopic;
976: }
977:
978: sub update_help_link {
979: my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
980: my $origurl = $ENV{'REQUEST_URI'};
981: $origurl=~s|^/~|/priv/|;
982: my $timestamp = time;
983: foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
984: $$datum = &escape($$datum);
985: }
986:
987: my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage";
988: my $output .= <<"ENDOUTPUT";
989: <script type="text/javascript">
990: banner_link = '$banner_link';
991: </script>
992: ENDOUTPUT
993: return $output;
994: }
995:
996: # now just updates the help link and generates a blue icon
997: sub help_open_menu {
998: my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text)
999: = @_;
1000: $stayOnPage = 0 if (not defined $stayOnPage);
1001: # only use pop-up help (stayOnPage == 0)
1002: # if environment.remote is on (using remote control UI)
1003: if ($env{'browser.interface'} eq 'textual' ||
1004: $env{'environment.remote'} eq 'off' ) {
1005: $stayOnPage=1;
1006: }
1007: my $output;
1008: if ($component_help) {
1009: if (!$text) {
1010: $output=&help_open_topic($component_help,undef,$stayOnPage,
1011: $width,$height);
1012: } else {
1013: my $help_text;
1014: $help_text=&unescape($topic);
1015: $output='<table><tr><td>'.
1016: &help_open_topic($component_help,$help_text,$stayOnPage,
1017: $width,$height).'</td></tr></table>';
1018: }
1019: }
1020: my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
1021: return $output.$banner_link;
1022: }
1023:
1024: sub top_nav_help {
1025: my ($text) = @_;
1026: $text = &mt($text);
1027: my $stay_on_page =
1028: ($env{'browser.interface'} eq 'textual' ||
1029: $env{'environment.remote'} eq 'off' );
1030: my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1031: : "javascript:helpMenu('open')";
1032: my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1033:
1034: my $title = &mt('Get help');
1035:
1036: return <<"END";
1037: $banner_link
1038: <a href="$link" title="$title">$text</a>
1039: END
1040: }
1041:
1042: sub help_menu_js {
1043: my ($text) = @_;
1044:
1045: my $stayOnPage =
1046: ($env{'browser.interface'} eq 'textual' ||
1047: $env{'environment.remote'} eq 'off' );
1048:
1049: my $width = 620;
1050: my $height = 600;
1051: my $helptopic=&general_help();
1052: my $details_link = '/adm/help/'.$helptopic.'.hlp';
1053: my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1054: my $start_page =
1055: &Apache::loncommon::start_page('Help Menu', undef,
1056: {'frameset' => 1,
1057: 'js_ready' => 1,
1058: 'add_entries' => {
1059: 'border' => '0',
1060: 'rows' => "110,*",},});
1061: my $end_page =
1062: &Apache::loncommon::end_page({'frameset' => 1,
1063: 'js_ready' => 1,});
1064:
1065: my $template .= <<"ENDTEMPLATE";
1066: <script type="text/javascript">
1067: // <!-- BEGIN LON-CAPA Internal
1068: // <![CDATA[
1069: var banner_link = '';
1070: function helpMenu(target) {
1071: var caller = this;
1072: if (target == 'open') {
1073: var newWindow = null;
1074: try {
1075: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1076: }
1077: catch(error) {
1078: writeHelp(caller);
1079: return;
1080: }
1081: if (newWindow) {
1082: caller = newWindow;
1083: }
1084: }
1085: writeHelp(caller);
1086: return;
1087: }
1088: function writeHelp(caller) {
1089: caller.document.writeln('$start_page<frame name="bannerframe" src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
1090: caller.document.close()
1091: caller.focus()
1092: }
1093: // ]]>
1094: // END LON-CAPA Internal -->
1095: </script>
1096: ENDTEMPLATE
1097: return $template;
1098: }
1099:
1100: sub help_open_bug {
1101: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1102: unless ($env{'user.adv'}) { return ''; }
1103: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
1104: $text = "" if (not defined $text);
1105: $stayOnPage = 0 if (not defined $stayOnPage);
1106: if ($env{'browser.interface'} eq 'textual' ||
1107: $env{'environment.remote'} eq 'off' ) {
1108: $stayOnPage=1;
1109: }
1110: $width = 600 if (not defined $width);
1111: $height = 600 if (not defined $height);
1112:
1113: $topic=~s/\W+/\+/g;
1114: my $link='';
1115: my $template='';
1116: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
1117: &escape($ENV{'REQUEST_URI'}).'&component='.$topic;
1118: if (!$stayOnPage)
1119: {
1120: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1121: }
1122: else
1123: {
1124: $link = $url;
1125: }
1126: # Add the text
1127: if ($text ne "")
1128: {
1129: $template .=
1130: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1131: "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
1132: }
1133:
1134: # Add the graphic
1135: my $title = &mt('Report a Bug');
1136: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1137: $template .= <<"ENDTEMPLATE";
1138: <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1139: ENDTEMPLATE
1140: if ($text ne '') { $template.='</td></tr></table>' };
1141: return $template;
1142:
1143: }
1144:
1145: sub help_open_faq {
1146: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1147: unless ($env{'user.adv'}) { return ''; }
1148: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
1149: $text = "" if (not defined $text);
1150: $stayOnPage = 0 if (not defined $stayOnPage);
1151: if ($env{'browser.interface'} eq 'textual' ||
1152: $env{'environment.remote'} eq 'off' ) {
1153: $stayOnPage=1;
1154: }
1155: $width = 350 if (not defined $width);
1156: $height = 400 if (not defined $height);
1157:
1158: $topic=~s/\W+/\+/g;
1159: my $link='';
1160: my $template='';
1161: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
1162: if (!$stayOnPage)
1163: {
1164: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1165: }
1166: else
1167: {
1168: $link = $url;
1169: }
1170:
1171: # Add the text
1172: if ($text ne "")
1173: {
1174: $template .=
1175: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1176: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
1177: }
1178:
1179: # Add the graphic
1180: my $title = &mt('View the FAQ');
1181: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1182: $template .= <<"ENDTEMPLATE";
1183: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1184: ENDTEMPLATE
1185: if ($text ne '') { $template.='</td></tr></table>' };
1186: return $template;
1187:
1188: }
1189:
1190: ###############################################################
1191: ###############################################################
1192:
1193: =pod
1194:
1195: =item * &change_content_javascript():
1196:
1197: This and the next function allow you to create small sections of an
1198: otherwise static HTML page that you can update on the fly with
1199: Javascript, even in Netscape 4.
1200:
1201: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
1202: must be written to the HTML page once. It will prove the Javascript
1203: function "change(name, content)". Calling the change function with the
1204: name of the section
1205: you want to update, matching the name passed to C<changable_area>, and
1206: the new content you want to put in there, will put the content into
1207: that area.
1208:
1209: B<Note>: Netscape 4 only reserves enough space for the changable area
1210: to contain room for the original contents. You need to "make space"
1211: for whatever changes you wish to make, and be B<sure> to check your
1212: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
1213: it's adequate for updating a one-line status display, but little more.
1214: This script will set the space to 100% width, so you only need to
1215: worry about height in Netscape 4.
1216:
1217: Modern browsers are much less limiting, and if you can commit to the
1218: user not using Netscape 4, this feature may be used freely with
1219: pretty much any HTML.
1220:
1221: =cut
1222:
1223: sub change_content_javascript {
1224: # If we're on Netscape 4, we need to use Layer-based code
1225: if ($env{'browser.type'} eq 'netscape' &&
1226: $env{'browser.version'} =~ /^4\./) {
1227: return (<<NETSCAPE4);
1228: function change(name, content) {
1229: doc = document.layers[name+"___escape"].layers[0].document;
1230: doc.open();
1231: doc.write(content);
1232: doc.close();
1233: }
1234: NETSCAPE4
1235: } else {
1236: # Otherwise, we need to use semi-standards-compliant code
1237: # (technically, "innerHTML" isn't standard but the equivalent
1238: # is really scary, and every useful browser supports it
1239: return (<<DOMBASED);
1240: function change(name, content) {
1241: element = document.getElementById(name);
1242: element.innerHTML = content;
1243: }
1244: DOMBASED
1245: }
1246: }
1247:
1248: =pod
1249:
1250: =item * &changable_area($name,$origContent):
1251:
1252: This provides a "changable area" that can be modified on the fly via
1253: the Javascript code provided in C<change_content_javascript>. $name is
1254: the name you will use to reference the area later; do not repeat the
1255: same name on a given HTML page more then once. $origContent is what
1256: the area will originally contain, which can be left blank.
1257:
1258: =cut
1259:
1260: sub changable_area {
1261: my ($name, $origContent) = @_;
1262:
1263: if ($env{'browser.type'} eq 'netscape' &&
1264: $env{'browser.version'} =~ /^4\./) {
1265: # If this is netscape 4, we need to use the Layer tag
1266: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
1267: } else {
1268: return "<span id='$name'>$origContent</span>";
1269: }
1270: }
1271:
1272: =pod
1273:
1274: =item * &viewport_geometry_js
1275:
1276: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
1277:
1278: =cut
1279:
1280:
1281: sub viewport_geometry_js {
1282: return <<"GEOMETRY";
1283: var Geometry = {};
1284: function init_geometry() {
1285: if (Geometry.init) { return };
1286: Geometry.init=1;
1287: if (window.innerHeight) {
1288: Geometry.getViewportHeight = function() { return window.innerHeight; };
1289: Geometry.getViewportWidth = function() { return window.innerWidth; };
1290: Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
1291: Geometry.getVerticalScroll = function() { return window.pageYOffset; };
1292: }
1293: else if (document.documentElement && document.documentElement.clientHeight) {
1294: Geometry.getViewportHeight =
1295: function() { return document.documentElement.clientHeight; };
1296: Geometry.getViewportWidth =
1297: function() { return document.documentElement.clientWidth; };
1298:
1299: Geometry.getHorizontalScroll =
1300: function() { return document.documentElement.scrollLeft; };
1301: Geometry.getVerticalScroll =
1302: function() { return document.documentElement.scrollTop; };
1303: }
1304: else if (document.body.clientHeight) {
1305: Geometry.getViewportHeight =
1306: function() { return document.body.clientHeight; };
1307: Geometry.getViewportWidth =
1308: function() { return document.body.clientWidth; };
1309: Geometry.getHorizontalScroll =
1310: function() { return document.body.scrollLeft; };
1311: Geometry.getVerticalScroll =
1312: function() { return document.body.scrollTop; };
1313: }
1314: }
1315:
1316: GEOMETRY
1317: }
1318:
1319: =pod
1320:
1321: =item * &viewport_size_js()
1322:
1323: Provides a javascript function to set values of two form elements - width and height (elements are passed in as arguments to the javascript function) to the dimensions of the user's browser window.
1324:
1325: =cut
1326:
1327: sub viewport_size_js {
1328: my $geometry = &viewport_geometry_js();
1329: return <<"DIMS";
1330:
1331: $geometry
1332:
1333: function getViewportDims(width,height) {
1334: init_geometry();
1335: width.value = Geometry.getViewportWidth();
1336: height.value = Geometry.getViewportHeight();
1337: return;
1338: }
1339:
1340: DIMS
1341: }
1342:
1343: =pod
1344:
1345: =item * &resize_textarea_js()
1346:
1347: emits the needed javascript to resize a textarea to be as big as possible
1348:
1349: creates a function resize_textrea that takes two IDs first should be
1350: the id of the element to resize, second should be the id of a div that
1351: surrounds everything that comes after the textarea, this routine needs
1352: to be attached to the <body> for the onload and onresize events.
1353:
1354: =back
1355:
1356: =cut
1357:
1358: sub resize_textarea_js {
1359: my $geometry = &viewport_geometry_js();
1360: return <<"RESIZE";
1361: <script type="text/javascript">
1362: $geometry
1363:
1364: function getX(element) {
1365: var x = 0;
1366: while (element) {
1367: x += element.offsetLeft;
1368: element = element.offsetParent;
1369: }
1370: return x;
1371: }
1372: function getY(element) {
1373: var y = 0;
1374: while (element) {
1375: y += element.offsetTop;
1376: element = element.offsetParent;
1377: }
1378: return y;
1379: }
1380:
1381:
1382: function resize_textarea(textarea_id,bottom_id) {
1383: init_geometry();
1384: var textarea = document.getElementById(textarea_id);
1385: //alert(textarea);
1386:
1387: var textarea_top = getY(textarea);
1388: var textarea_height = textarea.offsetHeight;
1389: var bottom = document.getElementById(bottom_id);
1390: var bottom_top = getY(bottom);
1391: var bottom_height = bottom.offsetHeight;
1392: var window_height = Geometry.getViewportHeight();
1393: var fudge = 23;
1394: var new_height = window_height-fudge-textarea_top-bottom_height;
1395: if (new_height < 300) {
1396: new_height = 300;
1397: }
1398: textarea.style.height=new_height+'px';
1399: }
1400: </script>
1401: RESIZE
1402:
1403: }
1404:
1405: =pod
1406:
1407: =head1 Excel and CSV file utility routines
1408:
1409: =over 4
1410:
1411: =cut
1412:
1413: ###############################################################
1414: ###############################################################
1415:
1416: =pod
1417:
1418: =item * &csv_translate($text)
1419:
1420: Translate $text to allow it to be output as a 'comma separated values'
1421: format.
1422:
1423: =cut
1424:
1425: ###############################################################
1426: ###############################################################
1427: sub csv_translate {
1428: my $text = shift;
1429: $text =~ s/\"/\"\"/g;
1430: $text =~ s/\n/ /g;
1431: return $text;
1432: }
1433:
1434: ###############################################################
1435: ###############################################################
1436:
1437: =pod
1438:
1439: =item * &define_excel_formats()
1440:
1441: Define some commonly used Excel cell formats.
1442:
1443: Currently supported formats:
1444:
1445: =over 4
1446:
1447: =item header
1448:
1449: =item bold
1450:
1451: =item h1
1452:
1453: =item h2
1454:
1455: =item h3
1456:
1457: =item h4
1458:
1459: =item i
1460:
1461: =item date
1462:
1463: =back
1464:
1465: Inputs: $workbook
1466:
1467: Returns: $format, a hash reference.
1468:
1469: =cut
1470:
1471: ###############################################################
1472: ###############################################################
1473: sub define_excel_formats {
1474: my ($workbook) = @_;
1475: my $format;
1476: $format->{'header'} = $workbook->add_format(bold => 1,
1477: bottom => 1,
1478: align => 'center');
1479: $format->{'bold'} = $workbook->add_format(bold=>1);
1480: $format->{'h1'} = $workbook->add_format(bold=>1, size=>18);
1481: $format->{'h2'} = $workbook->add_format(bold=>1, size=>16);
1482: $format->{'h3'} = $workbook->add_format(bold=>1, size=>14);
1483: $format->{'h4'} = $workbook->add_format(bold=>1, size=>12);
1484: $format->{'i'} = $workbook->add_format(italic=>1);
1485: $format->{'date'} = $workbook->add_format(num_format=>
1486: 'mm/dd/yyyy hh:mm:ss');
1487: return $format;
1488: }
1489:
1490: ###############################################################
1491: ###############################################################
1492:
1493: =pod
1494:
1495: =item * &create_workbook()
1496:
1497: Create an Excel worksheet. If it fails, output message on the
1498: request object and return undefs.
1499:
1500: Inputs: Apache request object
1501:
1502: Returns (undef) on failure,
1503: Excel worksheet object, scalar with filename, and formats
1504: from &Apache::loncommon::define_excel_formats on success
1505:
1506: =cut
1507:
1508: ###############################################################
1509: ###############################################################
1510: sub create_workbook {
1511: my ($r) = @_;
1512: #
1513: # Create the excel spreadsheet
1514: my $filename = '/prtspool/'.
1515: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1516: time.'_'.rand(1000000000).'.xls';
1517: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
1518: if (! defined($workbook)) {
1519: $r->log_error("Error creating excel spreadsheet $filename: $!");
1520: $r->print('<p>'.&mt("Unable to create new Excel file. ".
1521: "This error has been logged. ".
1522: "Please alert your LON-CAPA administrator").
1523: '</p>');
1524: return (undef);
1525: }
1526: #
1527: $workbook->set_tempdir('/home/httpd/perl/tmp');
1528: #
1529: my $format = &Apache::loncommon::define_excel_formats($workbook);
1530: return ($workbook,$filename,$format);
1531: }
1532:
1533: ###############################################################
1534: ###############################################################
1535:
1536: =pod
1537:
1538: =item * &create_text_file()
1539:
1540: Create a file to write to and eventually make available to the user.
1541: If file creation fails, outputs an error message on the request object and
1542: return undefs.
1543:
1544: Inputs: Apache request object, and file suffix
1545:
1546: Returns (undef) on failure,
1547: Filehandle and filename on success.
1548:
1549: =cut
1550:
1551: ###############################################################
1552: ###############################################################
1553: sub create_text_file {
1554: my ($r,$suffix) = @_;
1555: if (! defined($suffix)) { $suffix = 'txt'; };
1556: my $fh;
1557: my $filename = '/prtspool/'.
1558: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1559: time.'_'.rand(1000000000).'.'.$suffix;
1560: $fh = Apache::File->new('>/home/httpd'.$filename);
1561: if (! defined($fh)) {
1562: $r->log_error("Couldn't open $filename for output $!");
1563: $r->print(&mt('Problems occurred in creating the output file. '
1564: .'This error has been logged. '
1565: .'Please alert your LON-CAPA administrator.'));
1566: }
1567: return ($fh,$filename)
1568: }
1569:
1570:
1571: =pod
1572:
1573: =back
1574:
1575: =cut
1576:
1577: ###############################################################
1578: ## Home server <option> list generating code ##
1579: ###############################################################
1580:
1581: # ------------------------------------------
1582:
1583: sub domain_select {
1584: my ($name,$value,$multiple)=@_;
1585: my %domains=map {
1586: $_ => $_.' '. &Apache::lonnet::domain($_,'description')
1587: } &Apache::lonnet::all_domains();
1588: if ($multiple) {
1589: $domains{''}=&mt('Any domain');
1590: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1591: return &multiple_select_form($name,$value,4,\%domains);
1592: } else {
1593: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1594: return &select_form($name,$value,%domains);
1595: }
1596: }
1597:
1598: #-------------------------------------------
1599:
1600: =pod
1601:
1602: =head1 Routines for form select boxes
1603:
1604: =over 4
1605:
1606: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1607:
1608: Returns a string containing a <select> element int multiple mode
1609:
1610:
1611: Args:
1612: $name - name of the <select> element
1613: $value - scalar or array ref of values that should already be selected
1614: $size - number of rows long the select element is
1615: $hash - the elements should be 'option' => 'shown text'
1616: (shown text should already have been &mt())
1617: $order - (optional) array ref of the order to show the elements in
1618:
1619: =cut
1620:
1621: #-------------------------------------------
1622: sub multiple_select_form {
1623: my ($name,$value,$size,$hash,$order)=@_;
1624: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
1625: my $output='';
1626: if (! defined($size)) {
1627: $size = 4;
1628: if (scalar(keys(%$hash))<4) {
1629: $size = scalar(keys(%$hash));
1630: }
1631: }
1632: $output.="\n<select name='$name' size='$size' multiple='1'>";
1633: my @order;
1634: if (ref($order) eq 'ARRAY') {
1635: @order = @{$order};
1636: } else {
1637: @order = sort(keys(%$hash));
1638: }
1639: if (exists($$hash{'select_form_order'})) {
1640: @order = @{$$hash{'select_form_order'}};
1641: }
1642:
1643: foreach my $key (@order) {
1644: $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1645: $output.='selected="selected" ' if ($selected{$key});
1646: $output.='>'.$hash->{$key}."</option>\n";
1647: }
1648: $output.="</select>\n";
1649: return $output;
1650: }
1651:
1652: #-------------------------------------------
1653:
1654: =pod
1655:
1656: =item * &select_form($defdom,$name,%hash)
1657:
1658: Returns a string containing a <select name='$name' size='1'> form to
1659: allow a user to select options from a hash option_name => displayed text.
1660: See lonrights.pm for an example invocation and use.
1661:
1662: =cut
1663:
1664: #-------------------------------------------
1665: sub select_form {
1666: my ($def,$name,%hash) = @_;
1667: my $selectform = "<select name=\"$name\" size=\"1\">\n";
1668: my @keys;
1669: if (exists($hash{'select_form_order'})) {
1670: @keys=@{$hash{'select_form_order'}};
1671: } else {
1672: @keys=sort(keys(%hash));
1673: }
1674: foreach my $key (@keys) {
1675: $selectform.=
1676: '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
1677: ($key eq $def ? 'selected="selected" ' : '').
1678: ">".&mt($hash{$key})."</option>\n";
1679: }
1680: $selectform.="</select>";
1681: return $selectform;
1682: }
1683:
1684: # For display filters
1685:
1686: sub display_filter {
1687: if (!$env{'form.show'}) { $env{'form.show'}=10; }
1688: if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1689: return '<nobr><label>'.&mt('Records [_1]',
1690: &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
1691: (&mt('all'),10,20,50,100,1000,10000))).
1692: '</label></nobr> <nobr>'.
1693: &mt('Filter [_1]',
1694: &select_form($env{'form.displayfilter'},
1695: 'displayfilter',
1696: ('currentfolder' => 'Current folder/page',
1697: 'containing' => 'Containing phrase',
1698: 'none' => 'None'))).
1699: '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></nobr>';
1700: }
1701:
1702: sub gradeleveldescription {
1703: my $gradelevel=shift;
1704: my %gradelevels=(0 => 'Not specified',
1705: 1 => 'Grade 1',
1706: 2 => 'Grade 2',
1707: 3 => 'Grade 3',
1708: 4 => 'Grade 4',
1709: 5 => 'Grade 5',
1710: 6 => 'Grade 6',
1711: 7 => 'Grade 7',
1712: 8 => 'Grade 8',
1713: 9 => 'Grade 9',
1714: 10 => 'Grade 10',
1715: 11 => 'Grade 11',
1716: 12 => 'Grade 12',
1717: 13 => 'Grade 13',
1718: 14 => '100 Level',
1719: 15 => '200 Level',
1720: 16 => '300 Level',
1721: 17 => '400 Level',
1722: 18 => 'Graduate Level');
1723: return &mt($gradelevels{$gradelevel});
1724: }
1725:
1726: sub select_level_form {
1727: my ($deflevel,$name)=@_;
1728: unless ($deflevel) { $deflevel=0; }
1729: my $selectform = "<select name=\"$name\" size=\"1\">\n";
1730: for (my $i=0; $i<=18; $i++) {
1731: $selectform.="<option value=\"$i\" ".
1732: ($i==$deflevel ? 'selected="selected" ' : '').
1733: ">".&gradeleveldescription($i)."</option>\n";
1734: }
1735: $selectform.="</select>";
1736: return $selectform;
1737: }
1738:
1739: #-------------------------------------------
1740:
1741: =pod
1742:
1743: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc)
1744:
1745: Returns a string containing a <select name='$name' size='1'> form to
1746: allow a user to select the domain to preform an operation in.
1747: See loncreateuser.pm for an example invocation and use.
1748:
1749: If the $includeempty flag is set, it also includes an empty choice ("no domain
1750: selected");
1751:
1752: If the $showdomdesc flag is set, the domain name is followed by the domain description.
1753:
1754: =cut
1755:
1756: #-------------------------------------------
1757: sub select_dom_form {
1758: my ($defdom,$name,$includeempty,$showdomdesc) = @_;
1759: my @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
1760: if ($includeempty) { @domains=('',@domains); }
1761: my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
1762: foreach my $dom (@domains) {
1763: $selectdomain.="<option value=\"$dom\" ".
1764: ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
1765: if ($showdomdesc) {
1766: if ($dom ne '') {
1767: my $domdesc = &Apache::lonnet::domain($dom,'description');
1768: if ($domdesc ne '') {
1769: $selectdomain .= ' ('.$domdesc.')';
1770: }
1771: }
1772: }
1773: $selectdomain .= "</option>\n";
1774: }
1775: $selectdomain.="</select>";
1776: return $selectdomain;
1777: }
1778:
1779: #-------------------------------------------
1780:
1781: =pod
1782:
1783: =item * &home_server_form_item($domain,$name,$defaultflag)
1784:
1785: input: 4 arguments (two required, two optional) -
1786: $domain - domain of new user
1787: $name - name of form element
1788: $default - Value of 'default' causes a default item to be first
1789: option, and selected by default.
1790: $hide - Value of 'hide' causes hiding of the name of the server,
1791: if 1 server found, or default, if 0 found.
1792: output: returns 2 items:
1793: (a) form element which contains either:
1794: (i) <select name="$name">
1795: <option value="$hostid1">$hostid $servers{$hostid}</option>
1796: <option value="$hostid2">$hostid $servers{$hostid}</option>
1797: </select>
1798: form item if there are multiple library servers in $domain, or
1799: (ii) an <input type="hidden" name="$name" value="$hostid" /> form item
1800: if there is only one library server in $domain.
1801:
1802: (b) number of library servers found.
1803:
1804: See loncreateuser.pm for example of use.
1805:
1806: =cut
1807:
1808: #-------------------------------------------
1809: sub home_server_form_item {
1810: my ($domain,$name,$default,$hide) = @_;
1811: my %servers = &Apache::lonnet::get_servers($domain,'library');
1812: my $result;
1813: my $numlib = keys(%servers);
1814: if ($numlib > 1) {
1815: $result .= '<select name="'.$name.'" />'."\n";
1816: if ($default) {
1817: $result .= '<option value="default" selected>'.&mt('default').
1818: '</option>'."\n";
1819: }
1820: foreach my $hostid (sort(keys(%servers))) {
1821: $result.= '<option value="'.$hostid.'">'.
1822: $hostid.' '.$servers{$hostid}."</option>\n";
1823: }
1824: $result .= '</select>'."\n";
1825: } elsif ($numlib == 1) {
1826: my $hostid;
1827: foreach my $item (keys(%servers)) {
1828: $hostid = $item;
1829: }
1830: $result .= '<input type="hidden" name="'.$name.'" value="'.
1831: $hostid.'" />';
1832: if (!$hide) {
1833: $result .= $hostid.' '.$servers{$hostid};
1834: }
1835: $result .= "\n";
1836: } elsif ($default) {
1837: $result .= '<input type="hidden" name="'.$name.
1838: '" value="default" />';
1839: if (!$hide) {
1840: $result .= &mt('default');
1841: }
1842: $result .= "\n";
1843: }
1844: return ($result,$numlib);
1845: }
1846:
1847: =pod
1848:
1849: =back
1850:
1851: =cut
1852:
1853: ###############################################################
1854: ## Decoding User Agent ##
1855: ###############################################################
1856:
1857: =pod
1858:
1859: =head1 Decoding the User Agent
1860:
1861: =over 4
1862:
1863: =item * &decode_user_agent()
1864:
1865: Inputs: $r
1866:
1867: Outputs:
1868:
1869: =over 4
1870:
1871: =item * $httpbrowser
1872:
1873: =item * $clientbrowser
1874:
1875: =item * $clientversion
1876:
1877: =item * $clientmathml
1878:
1879: =item * $clientunicode
1880:
1881: =item * $clientos
1882:
1883: =back
1884:
1885: =back
1886:
1887: =cut
1888:
1889: ###############################################################
1890: ###############################################################
1891: sub decode_user_agent {
1892: my ($r)=@_;
1893: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
1894: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
1895: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1896: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1897: my $clientbrowser='unknown';
1898: my $clientversion='0';
1899: my $clientmathml='';
1900: my $clientunicode='0';
1901: for (my $i=0;$i<=$#browsertype;$i++) {
1902: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
1903: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
1904: $clientbrowser=$bname;
1905: $httpbrowser=~/$vreg/i;
1906: $clientversion=$1;
1907: $clientmathml=($clientversion>=$minv);
1908: $clientunicode=($clientversion>=$univ);
1909: }
1910: }
1911: my $clientos='unknown';
1912: if (($httpbrowser=~/linux/i) ||
1913: ($httpbrowser=~/unix/i) ||
1914: ($httpbrowser=~/ux/i) ||
1915: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
1916: if (($httpbrowser=~/vax/i) ||
1917: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
1918: if ($httpbrowser=~/next/i) { $clientos='next'; }
1919: if (($httpbrowser=~/mac/i) ||
1920: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1921: if ($httpbrowser=~/win/i) { $clientos='win'; }
1922: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1923: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1924: $clientunicode,$clientos,);
1925: }
1926:
1927: ###############################################################
1928: ## Authentication changing form generation subroutines ##
1929: ###############################################################
1930: ##
1931: ## All of the authform_xxxxxxx subroutines take their inputs in a
1932: ## hash, and have reasonable default values.
1933: ##
1934: ## formname = the name given in the <form> tag.
1935: #-------------------------------------------
1936:
1937: =pod
1938:
1939: =head1 Authentication Routines
1940:
1941: =over 4
1942:
1943: =item * &authform_xxxxxx()
1944:
1945: The authform_xxxxxx subroutines provide javascript and html forms which
1946: handle some of the conveniences required for authentication forms.
1947: This is not an optimal method, but it works.
1948:
1949: =over 4
1950:
1951: =item * authform_header
1952:
1953: =item * authform_authorwarning
1954:
1955: =item * authform_nochange
1956:
1957: =item * authform_kerberos
1958:
1959: =item * authform_internal
1960:
1961: =item * authform_filesystem
1962:
1963: =back
1964:
1965: See loncreateuser.pm for invocation and use examples.
1966:
1967: =cut
1968:
1969: #-------------------------------------------
1970: sub authform_header{
1971: my %in = (
1972: formname => 'cu',
1973: kerb_def_dom => '',
1974: @_,
1975: );
1976: $in{'formname'} = 'document.' . $in{'formname'};
1977: my $result='';
1978:
1979: #---------------------------------------------- Code for upper case translation
1980: my $Javascript_toUpperCase;
1981: unless ($in{kerb_def_dom}) {
1982: $Javascript_toUpperCase =<<"END";
1983: switch (choice) {
1984: case 'krb': currentform.elements[choicearg].value =
1985: currentform.elements[choicearg].value.toUpperCase();
1986: break;
1987: default:
1988: }
1989: END
1990: } else {
1991: $Javascript_toUpperCase = "";
1992: }
1993:
1994: my $radioval = "'nochange'";
1995: if (defined($in{'curr_authtype'})) {
1996: if ($in{'curr_authtype'} ne '') {
1997: $radioval = "'".$in{'curr_authtype'}."arg'";
1998: }
1999: }
2000: my $argfield = 'null';
2001: if (defined($in{'mode'})) {
2002: if ($in{'mode'} eq 'modifycourse') {
2003: if (defined($in{'curr_autharg'})) {
2004: if ($in{'curr_autharg'} ne '') {
2005: $argfield = "'$in{'curr_autharg'}'";
2006: }
2007: }
2008: }
2009: }
2010:
2011: $result.=<<"END";
2012: var current = new Object();
2013: current.radiovalue = $radioval;
2014: current.argfield = $argfield;
2015:
2016: function changed_radio(choice,currentform) {
2017: var choicearg = choice + 'arg';
2018: // If a radio button in changed, we need to change the argfield
2019: if (current.radiovalue != choice) {
2020: current.radiovalue = choice;
2021: if (current.argfield != null) {
2022: currentform.elements[current.argfield].value = '';
2023: }
2024: if (choice == 'nochange') {
2025: current.argfield = null;
2026: } else {
2027: current.argfield = choicearg;
2028: switch(choice) {
2029: case 'krb':
2030: currentform.elements[current.argfield].value =
2031: "$in{'kerb_def_dom'}";
2032: break;
2033: default:
2034: break;
2035: }
2036: }
2037: }
2038: return;
2039: }
2040:
2041: function changed_text(choice,currentform) {
2042: var choicearg = choice + 'arg';
2043: if (currentform.elements[choicearg].value !='') {
2044: $Javascript_toUpperCase
2045: // clear old field
2046: if ((current.argfield != choicearg) && (current.argfield != null)) {
2047: currentform.elements[current.argfield].value = '';
2048: }
2049: current.argfield = choicearg;
2050: }
2051: set_auth_radio_buttons(choice,currentform);
2052: return;
2053: }
2054:
2055: function set_auth_radio_buttons(newvalue,currentform) {
2056: var i=0;
2057: while (i < currentform.login.length) {
2058: if (currentform.login[i].value == newvalue) { break; }
2059: i++;
2060: }
2061: if (i == currentform.login.length) {
2062: return;
2063: }
2064: current.radiovalue = newvalue;
2065: currentform.login[i].checked = true;
2066: return;
2067: }
2068: END
2069: return $result;
2070: }
2071:
2072: sub authform_authorwarning{
2073: my $result='';
2074: $result='<i>'.
2075: &mt('As a general rule, only authors or co-authors should be '.
2076: 'filesystem authenticated '.
2077: '(which allows access to the server filesystem).')."</i>\n";
2078: return $result;
2079: }
2080:
2081: sub authform_nochange{
2082: my %in = (
2083: formname => 'document.cu',
2084: kerb_def_dom => 'MSU.EDU',
2085: @_,
2086: );
2087: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2088: my $result;
2089: if (keys(%can_assign) == 0) {
2090: $result = &mt('Under you current role you are not permitted to change login settings for this user');
2091: } else {
2092: $result = '<label>'.&mt('[_1] Do not change login data',
2093: '<input type="radio" name="login" value="nochange" '.
2094: 'checked="checked" onclick="'.
2095: "javascript:changed_radio('nochange',$in{'formname'});".'" />').
2096: '</label>';
2097: }
2098: return $result;
2099: }
2100:
2101: sub authform_kerberos {
2102: my %in = (
2103: formname => 'document.cu',
2104: kerb_def_dom => 'MSU.EDU',
2105: kerb_def_auth => 'krb4',
2106: @_,
2107: );
2108: my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
2109: $autharg,$jscall);
2110: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2111: if ($in{'kerb_def_auth'} eq 'krb5') {
2112: $check5 = ' checked="on"';
2113: } else {
2114: $check4 = ' checked="on"';
2115: }
2116: $krbarg = $in{'kerb_def_dom'};
2117: if (defined($in{'curr_authtype'})) {
2118: if ($in{'curr_authtype'} eq 'krb') {
2119: $krbcheck = ' checked="on"';
2120: if (defined($in{'mode'})) {
2121: if ($in{'mode'} eq 'modifyuser') {
2122: $krbcheck = '';
2123: }
2124: }
2125: if (defined($in{'curr_kerb_ver'})) {
2126: if ($in{'curr_krb_ver'} eq '5') {
2127: $check5 = ' checked="on"';
2128: $check4 = '';
2129: } else {
2130: $check4 = ' checked="on"';
2131: $check5 = '';
2132: }
2133: }
2134: if (defined($in{'curr_autharg'})) {
2135: $krbarg = $in{'curr_autharg'};
2136: }
2137: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2138: if (defined($in{'curr_autharg'})) {
2139: $result =
2140: &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
2141: $in{'curr_autharg'},$krbver);
2142: } else {
2143: $result =
2144: &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
2145: }
2146: return $result;
2147: }
2148: }
2149: } else {
2150: if ($authnum == 1) {
2151: $authtype = '<input type="hidden" name="login" value="krb">';
2152: }
2153: }
2154: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2155: return;
2156: } elsif ($authtype eq '') {
2157: if (defined($in{'mode'})) {
2158: if ($in{'mode'} eq 'modifycourse') {
2159: if ($authnum == 1) {
2160: $authtype = '<input type="hidden" name="login" value="krb">';
2161: }
2162: }
2163: }
2164: }
2165: $jscall = "javascript:changed_radio('krb',$in{'formname'});";
2166: if ($authtype eq '') {
2167: $authtype = '<input type="radio" name="login" value="krb" '.
2168: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
2169: $krbcheck.' />';
2170: }
2171: if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
2172: ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
2173: $in{'curr_authtype'} eq 'krb5') ||
2174: (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
2175: $in{'curr_authtype'} eq 'krb4')) {
2176: $result .= &mt
2177: ('[_1] Kerberos authenticated with domain [_2] '.
2178: '[_3] Version 4 [_4] Version 5 [_5]',
2179: '<label>'.$authtype,
2180: '</label><input type="text" size="10" name="krbarg" '.
2181: 'value="'.$krbarg.'" '.
2182: 'onchange="'.$jscall.'" />',
2183: '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
2184: '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
2185: '</label>');
2186: } elsif ($can_assign{'krb4'}) {
2187: $result .= &mt
2188: ('[_1] Kerberos authenticated with domain [_2] '.
2189: '[_3] Version 4 [_4]',
2190: '<label>'.$authtype,
2191: '</label><input type="text" size="10" name="krbarg" '.
2192: 'value="'.$krbarg.'" '.
2193: 'onchange="'.$jscall.'" />',
2194: '<label><input type="hidden" name="krbver" value="4" />',
2195: '</label>');
2196: } elsif ($can_assign{'krb5'}) {
2197: $result .= &mt
2198: ('[_1] Kerberos authenticated with domain [_2] '.
2199: '[_3] Version 5 [_4]',
2200: '<label>'.$authtype,
2201: '</label><input type="text" size="10" name="krbarg" '.
2202: 'value="'.$krbarg.'" '.
2203: 'onchange="'.$jscall.'" />',
2204: '<label><input type="hidden" name="krbver" value="5" />',
2205: '</label>');
2206: }
2207: return $result;
2208: }
2209:
2210: sub authform_internal{
2211: my %in = (
2212: formname => 'document.cu',
2213: kerb_def_dom => 'MSU.EDU',
2214: @_,
2215: );
2216: my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
2217: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2218: if (defined($in{'curr_authtype'})) {
2219: if ($in{'curr_authtype'} eq 'int') {
2220: if ($can_assign{'int'}) {
2221: $intcheck = 'checked="on" ';
2222: if (defined($in{'mode'})) {
2223: if ($in{'mode'} eq 'modifyuser') {
2224: $intcheck = '';
2225: }
2226: }
2227: if (defined($in{'curr_autharg'})) {
2228: $intarg = $in{'curr_autharg'};
2229: }
2230: } else {
2231: $result = &mt('Currently internally authenticated.');
2232: return $result;
2233: }
2234: }
2235: } else {
2236: if ($authnum == 1) {
2237: $authtype = '<input type="hidden" name="login" value="int">';
2238: }
2239: }
2240: if (!$can_assign{'int'}) {
2241: return;
2242: } elsif ($authtype eq '') {
2243: if (defined($in{'mode'})) {
2244: if ($in{'mode'} eq 'modifycourse') {
2245: if ($authnum == 1) {
2246: $authtype = '<input type="hidden" name="login" value="int">';
2247: }
2248: }
2249: }
2250: }
2251: $jscall = "javascript:changed_radio('int',$in{'formname'});";
2252: if ($authtype eq '') {
2253: $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
2254: ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
2255: }
2256: $autharg = '<input type="password" size="10" name="intarg" value="'.
2257: $intarg.'" onchange="'.$jscall.'" />';
2258: $result = &mt
2259: ('[_1] Internally authenticated (with initial password [_2])',
2260: '<label>'.$authtype,'</label>'.$autharg);
2261: $result.="<label><input type=\"checkbox\" name=\"visible\" onClick='if (this.checked) { this.form.intarg.type=\"text\" } else { this.form.intarg.type=\"password\" }' />".&mt('Visible input').'</label>';
2262: return $result;
2263: }
2264:
2265: sub authform_local{
2266: my %in = (
2267: formname => 'document.cu',
2268: kerb_def_dom => 'MSU.EDU',
2269: @_,
2270: );
2271: my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
2272: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2273: if (defined($in{'curr_authtype'})) {
2274: if ($in{'curr_authtype'} eq 'loc') {
2275: if ($can_assign{'loc'}) {
2276: $loccheck = 'checked="on" ';
2277: if (defined($in{'mode'})) {
2278: if ($in{'mode'} eq 'modifyuser') {
2279: $loccheck = '';
2280: }
2281: }
2282: if (defined($in{'curr_autharg'})) {
2283: $locarg = $in{'curr_autharg'};
2284: }
2285: } else {
2286: $result = &mt('Currently using local (institutional) authentication.');
2287: return $result;
2288: }
2289: }
2290: } else {
2291: if ($authnum == 1) {
2292: $authtype = '<input type="hidden" name="login" value="loc">';
2293: }
2294: }
2295: if (!$can_assign{'loc'}) {
2296: return;
2297: } elsif ($authtype eq '') {
2298: if (defined($in{'mode'})) {
2299: if ($in{'mode'} eq 'modifycourse') {
2300: if ($authnum == 1) {
2301: $authtype = '<input type="hidden" name="login" value="loc">';
2302: }
2303: }
2304: }
2305: }
2306: $jscall = "javascript:changed_radio('loc',$in{'formname'});";
2307: if ($authtype eq '') {
2308: $authtype = '<input type="radio" name="login" value="loc" '.
2309: $loccheck.' onchange="'.$jscall.'" onclick="'.
2310: $jscall.'" />';
2311: }
2312: $autharg = '<input type="text" size="10" name="locarg" value="'.
2313: $locarg.'" onchange="'.$jscall.'" />';
2314: $result = &mt('[_1] Local Authentication with argument [_2]',
2315: '<label>'.$authtype,'</label>'.$autharg);
2316: return $result;
2317: }
2318:
2319: sub authform_filesystem{
2320: my %in = (
2321: formname => 'document.cu',
2322: kerb_def_dom => 'MSU.EDU',
2323: @_,
2324: );
2325: my ($fsyscheck,$result,$authtype,$autharg,$jscall);
2326: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2327: if (defined($in{'curr_authtype'})) {
2328: if ($in{'curr_authtype'} eq 'fsys') {
2329: if ($can_assign{'fsys'}) {
2330: $fsyscheck = 'checked="on" ';
2331: if (defined($in{'mode'})) {
2332: if ($in{'mode'} eq 'modifyuser') {
2333: $fsyscheck = '';
2334: }
2335: }
2336: } else {
2337: $result = &mt('Currently Filesystem Authenticated.');
2338: return $result;
2339: }
2340: }
2341: } else {
2342: if ($authnum == 1) {
2343: $authtype = '<input type="hidden" name="login" value="fsys">';
2344: }
2345: }
2346: if (!$can_assign{'fsys'}) {
2347: return;
2348: } elsif ($authtype eq '') {
2349: if (defined($in{'mode'})) {
2350: if ($in{'mode'} eq 'modifycourse') {
2351: if ($authnum == 1) {
2352: $authtype = '<input type="hidden" name="login" value="fsys">';
2353: }
2354: }
2355: }
2356: }
2357: $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
2358: if ($authtype eq '') {
2359: $authtype = '<input type="radio" name="login" value="fsys" '.
2360: $fsyscheck.' onchange="'.$jscall.'" onclick="'.
2361: $jscall.'" />';
2362: }
2363: $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
2364: ' onchange="'.$jscall.'" />';
2365: $result = &mt
2366: ('[_1] Filesystem Authenticated (with initial password [_2])',
2367: '<label><input type="radio" name="login" value="fsys" '.
2368: $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
2369: '</label><input type="password" size="10" name="fsysarg" value="" '.
2370: 'onchange="'.$jscall.'" />');
2371: return $result;
2372: }
2373:
2374: sub get_assignable_auth {
2375: my ($dom) = @_;
2376: if ($dom eq '') {
2377: $dom = $env{'request.role.domain'};
2378: }
2379: my %can_assign = (
2380: krb4 => 1,
2381: krb5 => 1,
2382: int => 1,
2383: loc => 1,
2384: );
2385: my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
2386: if (ref($domconfig{'usercreation'}) eq 'HASH') {
2387: if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
2388: my $authhash = $domconfig{'usercreation'}{'authtypes'};
2389: my $context;
2390: if ($env{'request.role'} =~ /^au/) {
2391: $context = 'author';
2392: } elsif ($env{'request.role'} =~ /^dc/) {
2393: $context = 'domain';
2394: } elsif ($env{'request.course.id'}) {
2395: $context = 'course';
2396: }
2397: if ($context) {
2398: if (ref($authhash->{$context}) eq 'HASH') {
2399: %can_assign = %{$authhash->{$context}};
2400: }
2401: }
2402: }
2403: }
2404: my $authnum = 0;
2405: foreach my $key (keys(%can_assign)) {
2406: if ($can_assign{$key}) {
2407: $authnum ++;
2408: }
2409: }
2410: if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
2411: $authnum --;
2412: }
2413: return ($authnum,%can_assign);
2414: }
2415:
2416: ###############################################################
2417: ## Get Kerberos Defaults for Domain ##
2418: ###############################################################
2419: ##
2420: ## Returns default kerberos version and an associated argument
2421: ## as listed in file domain.tab. If not listed, provides
2422: ## appropriate default domain and kerberos version.
2423: ##
2424: #-------------------------------------------
2425:
2426: =pod
2427:
2428: =item * &get_kerberos_defaults()
2429:
2430: get_kerberos_defaults($target_domain) returns the default kerberos
2431: version and domain. If not found, it defaults to version 4 and the
2432: domain of the server.
2433:
2434: =over 4
2435:
2436: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
2437:
2438: =back
2439:
2440: =back
2441:
2442: =cut
2443:
2444: #-------------------------------------------
2445: sub get_kerberos_defaults {
2446: my $domain=shift;
2447: my ($krbdef,$krbdefdom);
2448: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
2449: if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
2450: $krbdef = $domdefaults{'auth_def'};
2451: $krbdefdom = $domdefaults{'auth_arg_def'};
2452: } else {
2453: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
2454: my $krbdefdom=$1;
2455: $krbdefdom=~tr/a-z/A-Z/;
2456: $krbdef = "krb4";
2457: }
2458: return ($krbdef,$krbdefdom);
2459: }
2460:
2461:
2462: ###############################################################
2463: ## Thesaurus Functions ##
2464: ###############################################################
2465:
2466: =pod
2467:
2468: =head1 Thesaurus Functions
2469:
2470: =over 4
2471:
2472: =item * &initialize_keywords()
2473:
2474: Initializes the package variable %Keywords if it is empty. Uses the
2475: package variable $thesaurus_db_file.
2476:
2477: =cut
2478:
2479: ###################################################
2480:
2481: sub initialize_keywords {
2482: return 1 if (scalar keys(%Keywords));
2483: # If we are here, %Keywords is empty, so fill it up
2484: # Make sure the file we need exists...
2485: if (! -e $thesaurus_db_file) {
2486: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
2487: " failed because it does not exist");
2488: return 0;
2489: }
2490: # Set up the hash as a database
2491: my %thesaurus_db;
2492: if (! tie(%thesaurus_db,'GDBM_File',
2493: $thesaurus_db_file,&GDBM_READER(),0640)){
2494: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
2495: $thesaurus_db_file);
2496: return 0;
2497: }
2498: # Get the average number of appearances of a word.
2499: my $avecount = $thesaurus_db{'average.count'};
2500: # Put keywords (those that appear > average) into %Keywords
2501: while (my ($word,$data)=each (%thesaurus_db)) {
2502: my ($count,undef) = split /:/,$data;
2503: $Keywords{$word}++ if ($count > $avecount);
2504: }
2505: untie %thesaurus_db;
2506: # Remove special values from %Keywords.
2507: foreach my $value ('total.count','average.count') {
2508: delete($Keywords{$value}) if (exists($Keywords{$value}));
2509: }
2510: return 1;
2511: }
2512:
2513: ###################################################
2514:
2515: =pod
2516:
2517: =item * &keyword($word)
2518:
2519: Returns true if $word is a keyword. A keyword is a word that appears more
2520: than the average number of times in the thesaurus database. Calls
2521: &initialize_keywords
2522:
2523: =cut
2524:
2525: ###################################################
2526:
2527: sub keyword {
2528: return if (!&initialize_keywords());
2529: my $word=lc(shift());
2530: $word=~s/\W//g;
2531: return exists($Keywords{$word});
2532: }
2533:
2534: ###############################################################
2535:
2536: =pod
2537:
2538: =item * &get_related_words()
2539:
2540: Look up a word in the thesaurus. Takes a scalar argument and returns
2541: an array of words. If the keyword is not in the thesaurus, an empty array
2542: will be returned. The order of the words returned is determined by the
2543: database which holds them.
2544:
2545: Uses global $thesaurus_db_file.
2546:
2547: =cut
2548:
2549: ###############################################################
2550: sub get_related_words {
2551: my $keyword = shift;
2552: my %thesaurus_db;
2553: if (! -e $thesaurus_db_file) {
2554: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
2555: "failed because the file does not exist");
2556: return ();
2557: }
2558: if (! tie(%thesaurus_db,'GDBM_File',
2559: $thesaurus_db_file,&GDBM_READER(),0640)){
2560: return ();
2561: }
2562: my @Words=();
2563: my $count=0;
2564: if (exists($thesaurus_db{$keyword})) {
2565: # The first element is the number of times
2566: # the word appears. We do not need it now.
2567: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
2568: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
2569: my $threshold=$mostfrequentcount/10;
2570: foreach my $possibleword (@RelatedWords) {
2571: my ($word,$wordcount)=split(/\,/,$possibleword);
2572: if ($wordcount>$threshold) {
2573: push(@Words,$word);
2574: $count++;
2575: if ($count>10) { last; }
2576: }
2577: }
2578: }
2579: untie %thesaurus_db;
2580: return @Words;
2581: }
2582:
2583: =pod
2584:
2585: =back
2586:
2587: =cut
2588:
2589: # -------------------------------------------------------------- Plaintext name
2590: =pod
2591:
2592: =head1 User Name Functions
2593:
2594: =over 4
2595:
2596: =item * &plainname($uname,$udom,$first)
2597:
2598: Takes a users logon name and returns it as a string in
2599: "first middle last generation" form
2600: if $first is set to 'lastname' then it returns it as
2601: 'lastname generation, firstname middlename' if their is a lastname
2602:
2603: =cut
2604:
2605:
2606: ###############################################################
2607: sub plainname {
2608: my ($uname,$udom,$first)=@_;
2609: return if (!defined($uname) || !defined($udom));
2610: my %names=&getnames($uname,$udom);
2611: my $name=&Apache::lonnet::format_name($names{'firstname'},
2612: $names{'middlename'},
2613: $names{'lastname'},
2614: $names{'generation'},$first);
2615: $name=~s/^\s+//;
2616: $name=~s/\s+$//;
2617: $name=~s/\s+/ /g;
2618: if ($name !~ /\S/) { $name=$uname.':'.$udom; }
2619: return $name;
2620: }
2621:
2622: # -------------------------------------------------------------------- Nickname
2623: =pod
2624:
2625: =item * &nickname($uname,$udom)
2626:
2627: Gets a users name and returns it as a string as
2628:
2629: ""nickname""
2630:
2631: if the user has a nickname or
2632:
2633: "first middle last generation"
2634:
2635: if the user does not
2636:
2637: =cut
2638:
2639: sub nickname {
2640: my ($uname,$udom)=@_;
2641: return if (!defined($uname) || !defined($udom));
2642: my %names=&getnames($uname,$udom);
2643: my $name=$names{'nickname'};
2644: if ($name) {
2645: $name='"'.$name.'"';
2646: } else {
2647: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
2648: $names{'lastname'}.' '.$names{'generation'};
2649: $name=~s/\s+$//;
2650: $name=~s/\s+/ /g;
2651: }
2652: return $name;
2653: }
2654:
2655: sub getnames {
2656: my ($uname,$udom)=@_;
2657: return if (!defined($uname) || !defined($udom));
2658: if ($udom eq 'public' && $uname eq 'public') {
2659: return ('lastname' => &mt('Public'));
2660: }
2661: my $id=$uname.':'.$udom;
2662: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
2663: if ($cached) {
2664: return %{$names};
2665: } else {
2666: my %loadnames=&Apache::lonnet::get('environment',
2667: ['firstname','middlename','lastname','generation','nickname'],
2668: $udom,$uname);
2669: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
2670: return %loadnames;
2671: }
2672: }
2673:
2674: # -------------------------------------------------------------------- getemails
2675:
2676: =pod
2677:
2678: =item * &getemails($uname,$udom)
2679:
2680: Gets a user's email information and returns it as a hash with keys:
2681: notification, critnotification, permanentemail
2682:
2683: For notification and critnotification, values are comma-separated lists
2684: of e-mail addresses; for permanentemail, value is a single e-mail address.
2685:
2686:
2687: =cut
2688:
2689:
2690: sub getemails {
2691: my ($uname,$udom)=@_;
2692: if ($udom eq 'public' && $uname eq 'public') {
2693: return;
2694: }
2695: if (!$udom) { $udom=$env{'user.domain'}; }
2696: if (!$uname) { $uname=$env{'user.name'}; }
2697: my $id=$uname.':'.$udom;
2698: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
2699: if ($cached) {
2700: return %{$names};
2701: } else {
2702: my %loadnames=&Apache::lonnet::get('environment',
2703: ['notification','critnotification',
2704: 'permanentemail'],
2705: $udom,$uname);
2706: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
2707: return %loadnames;
2708: }
2709: }
2710:
2711: sub flush_email_cache {
2712: my ($uname,$udom)=@_;
2713: if (!$udom) { $udom =$env{'user.domain'}; }
2714: if (!$uname) { $uname=$env{'user.name'}; }
2715: return if ($udom eq 'public' && $uname eq 'public');
2716: my $id=$uname.':'.$udom;
2717: &Apache::lonnet::devalidate_cache_new('emailscache',$id);
2718: }
2719:
2720: # ------------------------------------------------------------------ Screenname
2721:
2722: =pod
2723:
2724: =item * &screenname($uname,$udom)
2725:
2726: Gets a users screenname and returns it as a string
2727:
2728: =cut
2729:
2730: sub screenname {
2731: my ($uname,$udom)=@_;
2732: if ($uname eq $env{'user.name'} &&
2733: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
2734: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
2735: return $names{'screenname'};
2736: }
2737:
2738:
2739: # ------------------------------------------------------------- Message Wrapper
2740:
2741: sub messagewrapper {
2742: my ($link,$username,$domain,$subject,$text)=@_;
2743: return
2744: '<a href="/adm/email?compose=individual&'.
2745: 'recname='.$username.'&recdom='.$domain.
2746: '&subject='.&escape($subject).'&text='.&escape($text).'" '.
2747: 'title="'.&mt('Send message').'">'.$link.'</a>';
2748: }
2749: # --------------------------------------------------------------- Notes Wrapper
2750:
2751: sub noteswrapper {
2752: my ($link,$un,$do)=@_;
2753: return
2754: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
2755: }
2756: # ------------------------------------------------------------- Aboutme Wrapper
2757:
2758: sub aboutmewrapper {
2759: my ($link,$username,$domain,$target)=@_;
2760: if (!defined($username) && !defined($domain)) {
2761: return;
2762: }
2763: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
2764: ($target?' target="$target"':'').' title="'.&mt("View this user's personal page").'">'.$link.'</a>';
2765: }
2766:
2767: # ------------------------------------------------------------ Syllabus Wrapper
2768:
2769:
2770: sub syllabuswrapper {
2771: my ($linktext,$coursedir,$domain,$fontcolor)=@_;
2772: if ($fontcolor) {
2773: $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>';
2774: }
2775: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
2776: }
2777:
2778: sub track_student_link {
2779: my ($linktext,$sname,$sdom,$target,$start) = @_;
2780: my $link ="/adm/trackstudent?";
2781: my $title = 'View recent activity';
2782: if (defined($sname) && $sname !~ /^\s*$/ &&
2783: defined($sdom) && $sdom !~ /^\s*$/) {
2784: $link .= "selected_student=$sname:$sdom";
2785: $title .= ' of this student';
2786: }
2787: if (defined($target) && $target !~ /^\s*$/) {
2788: $target = qq{target="$target"};
2789: } else {
2790: $target = '';
2791: }
2792: if ($start) { $link.='&start='.$start; }
2793: $title = &mt($title);
2794: $linktext = &mt($linktext);
2795: return qq{<a href="$link" title="$title" $target>$linktext</a>}.
2796: &help_open_topic('View_recent_activity');
2797: }
2798:
2799: # ===================================================== Display a student photo
2800:
2801:
2802: sub student_image_tag {
2803: my ($domain,$user)=@_;
2804: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
2805: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
2806: return '<img src="'.$imgsrc.'" align="right" />';
2807: } else {
2808: return '';
2809: }
2810: }
2811:
2812: =pod
2813:
2814: =back
2815:
2816: =head1 Access .tab File Data
2817:
2818: =over 4
2819:
2820: =item * &languageids()
2821:
2822: returns list of all language ids
2823:
2824: =cut
2825:
2826: sub languageids {
2827: return sort(keys(%language));
2828: }
2829:
2830: =pod
2831:
2832: =item * &languagedescription()
2833:
2834: returns description of a specified language id
2835:
2836: =cut
2837:
2838: sub languagedescription {
2839: my $code=shift;
2840: return ($supported_language{$code}?'* ':'').
2841: $language{$code}.
2842: ($supported_language{$code}?' ('.&mt('interface available').')':'');
2843: }
2844:
2845: sub plainlanguagedescription {
2846: my $code=shift;
2847: return $language{$code};
2848: }
2849:
2850: sub supportedlanguagecode {
2851: my $code=shift;
2852: return $supported_language{$code};
2853: }
2854:
2855: =pod
2856:
2857: =item * ©rightids()
2858:
2859: returns list of all copyrights
2860:
2861: =cut
2862:
2863: sub copyrightids {
2864: return sort(keys(%cprtag));
2865: }
2866:
2867: =pod
2868:
2869: =item * ©rightdescription()
2870:
2871: returns description of a specified copyright id
2872:
2873: =cut
2874:
2875: sub copyrightdescription {
2876: return &mt($cprtag{shift(@_)});
2877: }
2878:
2879: =pod
2880:
2881: =item * &source_copyrightids()
2882:
2883: returns list of all source copyrights
2884:
2885: =cut
2886:
2887: sub source_copyrightids {
2888: return sort(keys(%scprtag));
2889: }
2890:
2891: =pod
2892:
2893: =item * &source_copyrightdescription()
2894:
2895: returns description of a specified source copyright id
2896:
2897: =cut
2898:
2899: sub source_copyrightdescription {
2900: return &mt($scprtag{shift(@_)});
2901: }
2902:
2903: =pod
2904:
2905: =item * &filecategories()
2906:
2907: returns list of all file categories
2908:
2909: =cut
2910:
2911: sub filecategories {
2912: return sort(keys(%category_extensions));
2913: }
2914:
2915: =pod
2916:
2917: =item * &filecategorytypes()
2918:
2919: returns list of file types belonging to a given file
2920: category
2921:
2922: =cut
2923:
2924: sub filecategorytypes {
2925: my ($cat) = @_;
2926: return @{$category_extensions{lc($cat)}};
2927: }
2928:
2929: =pod
2930:
2931: =item * &fileembstyle()
2932:
2933: returns embedding style for a specified file type
2934:
2935: =cut
2936:
2937: sub fileembstyle {
2938: return $fe{lc(shift(@_))};
2939: }
2940:
2941: sub filemimetype {
2942: return $fm{lc(shift(@_))};
2943: }
2944:
2945:
2946: sub filecategoryselect {
2947: my ($name,$value)=@_;
2948: return &select_form($value,$name,
2949: '' => &mt('Any category'),
2950: map { $_,$_ } sort(keys(%category_extensions)));
2951: }
2952:
2953: =pod
2954:
2955: =item * &filedescription()
2956:
2957: returns description for a specified file type
2958:
2959: =cut
2960:
2961: sub filedescription {
2962: my $file_description = $fd{lc(shift())};
2963: $file_description =~ s:([\[\]]):~$1:g;
2964: return &mt($file_description);
2965: }
2966:
2967: =pod
2968:
2969: =item * &filedescriptionex()
2970:
2971: returns description for a specified file type with
2972: extra formatting
2973:
2974: =cut
2975:
2976: sub filedescriptionex {
2977: my $ex=shift;
2978: my $file_description = $fd{lc($ex)};
2979: $file_description =~ s:([\[\]]):~$1:g;
2980: return '.'.$ex.' '.&mt($file_description);
2981: }
2982:
2983: # End of .tab access
2984: =pod
2985:
2986: =back
2987:
2988: =cut
2989:
2990: # ------------------------------------------------------------------ File Types
2991: sub fileextensions {
2992: return sort(keys(%fe));
2993: }
2994:
2995: # ----------------------------------------------------------- Display Languages
2996: # returns a hash with all desired display languages
2997: #
2998:
2999: sub display_languages {
3000: my %languages=();
3001: foreach my $lang (&preferred_languages()) {
3002: $languages{$lang}=1;
3003: }
3004: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
3005: if ($env{'form.displaylanguage'}) {
3006: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
3007: $languages{$lang}=1;
3008: }
3009: }
3010: return %languages;
3011: }
3012:
3013: sub preferred_languages {
3014: my @languages=();
3015: if (($env{'request.role.adv'}) && ($env{'form.languages'})) {
3016: @languages=(@languages,split(/\s*(\,|\;|\:)\s*/,$env{'form.languages'}));
3017: }
3018: if ($env{'course.'.$env{'request.course.id'}.'.languages'}) {
3019: @languages=(@languages,split(/\s*(\,|\;|\:)\s*/,
3020: $env{'course.'.$env{'request.course.id'}.'.languages'}));
3021: }
3022:
3023: if ($env{'environment.languages'}) {
3024: @languages=(@languages,
3025: split(/\s*(\,|\;|\:)\s*/,$env{'environment.languages'}));
3026: }
3027: my $browser=$ENV{'HTTP_ACCEPT_LANGUAGE'};
3028: if ($browser) {
3029: my @browser =
3030: map { (split(/\s*;\s*/,$_))[0] } (split(/\s*,\s*/,$browser));
3031: push(@languages,@browser);
3032: }
3033:
3034: foreach my $domtype ($env{'user.domain'},$env{'request.role.domain'},
3035: $Apache::lonnet::perlvar{'lonDefDomain'}) {
3036: if ($domtype ne '') {
3037: my %domdefs = &Apache::lonnet::get_domain_defaults($domtype);
3038: if ($domdefs{'lang_def'} ne '') {
3039: push(@languages,$domdefs{'lang_def'});
3040: }
3041: }
3042: }
3043: return &get_genlanguages(@languages);
3044: }
3045:
3046: sub get_genlanguages {
3047: my (@languages) = @_;
3048: # turn "en-ca" into "en-ca,en"
3049: my @genlanguages;
3050: foreach my $lang (@languages) {
3051: unless ($lang=~/\w/) { next; }
3052: push(@genlanguages,$lang);
3053: if ($lang=~/(\-|\_)/) {
3054: push(@genlanguages,(split(/(\-|\_)/,$lang))[0]);
3055: }
3056: }
3057: #uniqueify the languages list
3058: my %count;
3059: @genlanguages = map { $count{$_}++ == 0 ? $_ : () } @genlanguages;
3060: return @genlanguages;
3061: }
3062:
3063: sub languages {
3064: my ($possible_langs) = @_;
3065: my @preferred_langs = &preferred_languages();
3066: if (!ref($possible_langs)) {
3067: if( wantarray ) {
3068: return @preferred_langs;
3069: } else {
3070: return $preferred_langs[0];
3071: }
3072: }
3073: my %possibilities = map { $_ => 1 } (@$possible_langs);
3074: my @preferred_possibilities;
3075: foreach my $preferred_lang (@preferred_langs) {
3076: if (exists($possibilities{$preferred_lang})) {
3077: push(@preferred_possibilities, $preferred_lang);
3078: }
3079: }
3080: if( wantarray ) {
3081: return @preferred_possibilities;
3082: }
3083: return $preferred_possibilities[0];
3084: }
3085:
3086: ###############################################################
3087: ## Student Answer Attempts ##
3088: ###############################################################
3089:
3090: =pod
3091:
3092: =head1 Alternate Problem Views
3093:
3094: =over 4
3095:
3096: =item * &get_previous_attempt($symb, $username, $domain, $course,
3097: $getattempt, $regexp, $gradesub)
3098:
3099: Return string with previous attempt on problem. Arguments:
3100:
3101: =over 4
3102:
3103: =item * $symb: Problem, including path
3104:
3105: =item * $username: username of the desired student
3106:
3107: =item * $domain: domain of the desired student
3108:
3109: =item * $course: Course ID
3110:
3111: =item * $getattempt: Leave blank for all attempts, otherwise put
3112: something
3113:
3114: =item * $regexp: if string matches this regexp, the string will be
3115: sent to $gradesub
3116:
3117: =item * $gradesub: routine that processes the string if it matches $regexp
3118:
3119: =back
3120:
3121: The output string is a table containing all desired attempts, if any.
3122:
3123: =cut
3124:
3125: sub get_previous_attempt {
3126: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
3127: my $prevattempts='';
3128: no strict 'refs';
3129: if ($symb) {
3130: my (%returnhash)=
3131: &Apache::lonnet::restore($symb,$course,$domain,$username);
3132: if ($returnhash{'version'}) {
3133: my %lasthash=();
3134: my $version;
3135: for ($version=1;$version<=$returnhash{'version'};$version++) {
3136: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
3137: $lasthash{$key}=$returnhash{$version.':'.$key};
3138: }
3139: }
3140: $prevattempts=&start_data_table().&start_data_table_header_row();
3141: $prevattempts.='<th>'.&mt('History').'</th>';
3142: foreach my $key (sort(keys(%lasthash))) {
3143: my ($ign,@parts) = split(/\./,$key);
3144: if ($#parts > 0) {
3145: my $data=$parts[-1];
3146: pop(@parts);
3147: $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.' </th>';
3148: } else {
3149: if ($#parts == 0) {
3150: $prevattempts.='<th>'.$parts[0].'</th>';
3151: } else {
3152: $prevattempts.='<th>'.$ign.'</th>';
3153: }
3154: }
3155: }
3156: $prevattempts.=&end_data_table_header_row();
3157: if ($getattempt eq '') {
3158: for ($version=1;$version<=$returnhash{'version'};$version++) {
3159: $prevattempts.=&start_data_table_row().
3160: '<td>'.&mt('Transaction [_1]',$version).'</td>';
3161: foreach my $key (sort(keys(%lasthash))) {
3162: my $value = &format_previous_attempt_value($key,
3163: $returnhash{$version.':'.$key});
3164: $prevattempts.='<td>'.$value.' </td>';
3165: }
3166: $prevattempts.=&end_data_table_row();
3167: }
3168: }
3169: $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
3170: foreach my $key (sort(keys(%lasthash))) {
3171: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3172: if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
3173: $prevattempts.='<td>'.$value.' </td>';
3174: }
3175: $prevattempts.= &end_data_table_row().&end_data_table();
3176: } else {
3177: $prevattempts=
3178: &start_data_table().&start_data_table_row().
3179: '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
3180: &end_data_table_row().&end_data_table();
3181: }
3182: } else {
3183: $prevattempts=
3184: &start_data_table().&start_data_table_row().
3185: '<td>'.&mt('No data.').'</td>'.
3186: &end_data_table_row().&end_data_table();
3187: }
3188: }
3189:
3190: sub format_previous_attempt_value {
3191: my ($key,$value) = @_;
3192: if ($key =~ /timestamp/) {
3193: $value = &Apache::lonlocal::locallocaltime($value);
3194: } elsif (ref($value) eq 'ARRAY') {
3195: $value = '('.join(', ', @{ $value }).')';
3196: } else {
3197: $value = &unescape($value);
3198: }
3199: return $value;
3200: }
3201:
3202:
3203: sub relative_to_absolute {
3204: my ($url,$output)=@_;
3205: my $parser=HTML::TokeParser->new(\$output);
3206: my $token;
3207: my $thisdir=$url;
3208: my @rlinks=();
3209: while ($token=$parser->get_token) {
3210: if ($token->[0] eq 'S') {
3211: if ($token->[1] eq 'a') {
3212: if ($token->[2]->{'href'}) {
3213: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
3214: }
3215: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
3216: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
3217: } elsif ($token->[1] eq 'base') {
3218: $thisdir=$token->[2]->{'href'};
3219: }
3220: }
3221: }
3222: $thisdir=~s-/[^/]*$--;
3223: foreach my $link (@rlinks) {
3224: unless (($link=~/^http:\/\//i) ||
3225: ($link=~/^\//) ||
3226: ($link=~/^javascript:/i) ||
3227: ($link=~/^mailto:/i) ||
3228: ($link=~/^\#/)) {
3229: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
3230: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
3231: }
3232: }
3233: # -------------------------------------------------- Deal with Applet codebases
3234: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
3235: return $output;
3236: }
3237:
3238: =pod
3239:
3240: =item * &get_student_view()
3241:
3242: show a snapshot of what student was looking at
3243:
3244: =cut
3245:
3246: sub get_student_view {
3247: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
3248: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
3249: my (%form);
3250: my @elements=('symb','courseid','domain','username');
3251: foreach my $element (@elements) {
3252: $form{'grade_'.$element}=eval '$'.$element #'
3253: }
3254: if (defined($moreenv)) {
3255: %form=(%form,%{$moreenv});
3256: }
3257: if (defined($target)) { $form{'grade_target'} = $target; }
3258: $feedurl=&Apache::lonnet::clutter($feedurl);
3259: my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
3260: $userview=~s/\<body[^\>]*\>//gi;
3261: $userview=~s/\<\/body\>//gi;
3262: $userview=~s/\<html\>//gi;
3263: $userview=~s/\<\/html\>//gi;
3264: $userview=~s/\<head\>//gi;
3265: $userview=~s/\<\/head\>//gi;
3266: $userview=~s/action\s*\=/would_be_action\=/gi;
3267: $userview=&relative_to_absolute($feedurl,$userview);
3268: if (wantarray) {
3269: return ($userview,$response);
3270: } else {
3271: return $userview;
3272: }
3273: }
3274:
3275: sub get_student_view_with_retries {
3276: my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
3277:
3278: my $ok = 0; # True if we got a good response.
3279: my $content;
3280: my $response;
3281:
3282: # Try to get the student_view done. within the retries count:
3283:
3284: do {
3285: ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
3286: $ok = $response->is_success;
3287: if (!$ok) {
3288: &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
3289: }
3290: $retries--;
3291: } while (!$ok && ($retries > 0));
3292:
3293: if (!$ok) {
3294: $content = ''; # On error return an empty content.
3295: }
3296: if (wantarray) {
3297: return ($content, $response);
3298: } else {
3299: return $content;
3300: }
3301: }
3302:
3303: =pod
3304:
3305: =item * &get_student_answers()
3306:
3307: show a snapshot of how student was answering problem
3308:
3309: =cut
3310:
3311: sub get_student_answers {
3312: my ($symb,$username,$domain,$courseid,%form) = @_;
3313: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
3314: my (%moreenv);
3315: my @elements=('symb','courseid','domain','username');
3316: foreach my $element (@elements) {
3317: $moreenv{'grade_'.$element}=eval '$'.$element #'
3318: }
3319: $moreenv{'grade_target'}='answer';
3320: %moreenv=(%form,%moreenv);
3321: $feedurl = &Apache::lonnet::clutter($feedurl);
3322: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
3323: return $userview;
3324: }
3325:
3326: =pod
3327:
3328: =item * &submlink()
3329:
3330: Inputs: $text $uname $udom $symb $target
3331:
3332: Returns: A link to grades.pm such as to see the SUBM view of a student
3333:
3334: =cut
3335:
3336: ###############################################
3337: sub submlink {
3338: my ($text,$uname,$udom,$symb,$target)=@_;
3339: if (!($uname && $udom)) {
3340: (my $cursymb, my $courseid,$udom,$uname)=
3341: &Apache::lonnet::whichuser($symb);
3342: if (!$symb) { $symb=$cursymb; }
3343: }
3344: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
3345: $symb=&escape($symb);
3346: if ($target) { $target="target=\"$target\""; }
3347: return '<a href="/adm/grades?&command=submission&'.
3348: 'symb='.$symb.'&student='.$uname.
3349: '&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
3350: }
3351: ##############################################
3352:
3353: =pod
3354:
3355: =item * &pgrdlink()
3356:
3357: Inputs: $text $uname $udom $symb $target
3358:
3359: Returns: A link to grades.pm such as to see the PGRD view of a student
3360:
3361: =cut
3362:
3363: ###############################################
3364: sub pgrdlink {
3365: my $link=&submlink(@_);
3366: $link=~s/(&command=submission)/$1&showgrading=yes/;
3367: return $link;
3368: }
3369: ##############################################
3370:
3371: =pod
3372:
3373: =item * &pprmlink()
3374:
3375: Inputs: $text $uname $udom $symb $target
3376:
3377: Returns: A link to parmset.pm such as to see the PPRM view of a
3378: student and a specific resource
3379:
3380: =cut
3381:
3382: ###############################################
3383: sub pprmlink {
3384: my ($text,$uname,$udom,$symb,$target)=@_;
3385: if (!($uname && $udom)) {
3386: (my $cursymb, my $courseid,$udom,$uname)=
3387: &Apache::lonnet::whichuser($symb);
3388: if (!$symb) { $symb=$cursymb; }
3389: }
3390: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
3391: $symb=&escape($symb);
3392: if ($target) { $target="target=\"$target\""; }
3393: return '<a href="/adm/parmset?command=set&'.
3394: 'symb='.$symb.'&uname='.$uname.
3395: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
3396: }
3397: ##############################################
3398:
3399: =pod
3400:
3401: =back
3402:
3403: =cut
3404:
3405: ###############################################
3406:
3407:
3408: sub timehash {
3409: my ($thistime) = @_;
3410: my $timezone = &Apache::lonlocal::gettimezone();
3411: my $dt = DateTime->from_epoch(epoch => $thistime)
3412: ->set_time_zone($timezone);
3413: my $wday = $dt->day_of_week();
3414: if ($wday == 7) { $wday = 0; }
3415: return ( 'second' => $dt->second(),
3416: 'minute' => $dt->minute(),
3417: 'hour' => $dt->hour(),
3418: 'day' => $dt->day_of_month(),
3419: 'month' => $dt->month(),
3420: 'year' => $dt->year(),
3421: 'weekday' => $wday,
3422: 'dayyear' => $dt->day_of_year(),
3423: 'dlsav' => $dt->is_dst() );
3424: }
3425:
3426: sub utc_string {
3427: my ($date)=@_;
3428: return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
3429: }
3430:
3431: sub maketime {
3432: my %th=@_;
3433: my ($epoch_time,$timezone,$dt);
3434: $timezone = &Apache::lonlocal::gettimezone();
3435: eval {
3436: $dt = DateTime->new( year => $th{'year'},
3437: month => $th{'month'},
3438: day => $th{'day'},
3439: hour => $th{'hour'},
3440: minute => $th{'minute'},
3441: second => $th{'second'},
3442: time_zone => $timezone,
3443: );
3444: };
3445: if (!$@) {
3446: $epoch_time = $dt->epoch;
3447: if ($epoch_time) {
3448: return $epoch_time;
3449: }
3450: }
3451: return POSIX::mktime(
3452: ($th{'seconds'},$th{'minutes'},$th{'hours'},
3453: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
3454: }
3455:
3456: #########################################
3457:
3458: sub findallcourses {
3459: my ($roles,$uname,$udom) = @_;
3460: my %roles;
3461: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
3462: my %courses;
3463: my $now=time;
3464: if (!defined($uname)) {
3465: $uname = $env{'user.name'};
3466: }
3467: if (!defined($udom)) {
3468: $udom = $env{'user.domain'};
3469: }
3470: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
3471: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
3472: if (!%roles) {
3473: %roles = (
3474: cc => 1,
3475: in => 1,
3476: ep => 1,
3477: ta => 1,
3478: cr => 1,
3479: st => 1,
3480: );
3481: }
3482: foreach my $entry (keys(%roleshash)) {
3483: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
3484: if ($trole =~ /^cr/) {
3485: next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
3486: } else {
3487: next if (!exists($roles{$trole}));
3488: }
3489: if ($tend) {
3490: next if ($tend < $now);
3491: }
3492: if ($tstart) {
3493: next if ($tstart > $now);
3494: }
3495: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
3496: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
3497: if ($secpart eq '') {
3498: ($cnum,$role) = split(/_/,$cnumpart);
3499: $sec = 'none';
3500: $realsec = '';
3501: } else {
3502: $cnum = $cnumpart;
3503: ($sec,$role) = split(/_/,$secpart);
3504: $realsec = $sec;
3505: }
3506: $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
3507: }
3508: } else {
3509: foreach my $key (keys(%env)) {
3510: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
3511: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
3512: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
3513: next if ($role eq 'ca' || $role eq 'aa');
3514: next if (%roles && !exists($roles{$role}));
3515: my ($starttime,$endtime)=split(/\./,$env{$key});
3516: my $active=1;
3517: if ($starttime) {
3518: if ($now<$starttime) { $active=0; }
3519: }
3520: if ($endtime) {
3521: if ($now>$endtime) { $active=0; }
3522: }
3523: if ($active) {
3524: if ($sec eq '') {
3525: $sec = 'none';
3526: }
3527: $courses{$cdom.'_'.$cnum}{$sec} =
3528: $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
3529: }
3530: }
3531: }
3532: }
3533: return %courses;
3534: }
3535:
3536: ###############################################
3537:
3538: sub blockcheck {
3539: my ($setters,$activity,$uname,$udom) = @_;
3540:
3541: if (!defined($udom)) {
3542: $udom = $env{'user.domain'};
3543: }
3544: if (!defined($uname)) {
3545: $uname = $env{'user.name'};
3546: }
3547:
3548: # If uname and udom are for a course, check for blocks in the course.
3549:
3550: if (&Apache::lonnet::is_course($udom,$uname)) {
3551: my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
3552: my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
3553: return ($startblock,$endblock);
3554: }
3555:
3556: my $startblock = 0;
3557: my $endblock = 0;
3558: my %live_courses = &findallcourses(undef,$uname,$udom);
3559:
3560: # If uname is for a user, and activity is course-specific, i.e.,
3561: # boards, chat or groups, check for blocking in current course only.
3562:
3563: if (($activity eq 'boards' || $activity eq 'chat' ||
3564: $activity eq 'groups') && ($env{'request.course.id'})) {
3565: foreach my $key (keys(%live_courses)) {
3566: if ($key ne $env{'request.course.id'}) {
3567: delete($live_courses{$key});
3568: }
3569: }
3570: }
3571:
3572: my $otheruser = 0;
3573: my %own_courses;
3574: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
3575: # Resource belongs to user other than current user.
3576: $otheruser = 1;
3577: # Gather courses for current user
3578: %own_courses =
3579: &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
3580: }
3581:
3582: # Gather active course roles - course coordinator, instructor,
3583: # exam proctor, ta, student, or custom role.
3584:
3585: foreach my $course (keys(%live_courses)) {
3586: my ($cdom,$cnum);
3587: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
3588: $cdom = $env{'course.'.$course.'.domain'};
3589: $cnum = $env{'course.'.$course.'.num'};
3590: } else {
3591: ($cdom,$cnum) = split(/_/,$course);
3592: }
3593: my $no_ownblock = 0;
3594: my $no_userblock = 0;
3595: if ($otheruser && $activity ne 'com') {
3596: # Check if current user has 'evb' priv for this
3597: if (defined($own_courses{$course})) {
3598: foreach my $sec (keys(%{$own_courses{$course}})) {
3599: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
3600: if ($sec ne 'none') {
3601: $checkrole .= '/'.$sec;
3602: }
3603: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
3604: $no_ownblock = 1;
3605: last;
3606: }
3607: }
3608: }
3609: # if they have 'evb' priv and are currently not playing student
3610: next if (($no_ownblock) &&
3611: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
3612: }
3613: foreach my $sec (keys(%{$live_courses{$course}})) {
3614: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
3615: if ($sec ne 'none') {
3616: $checkrole .= '/'.$sec;
3617: }
3618: if ($otheruser) {
3619: # Resource belongs to user other than current user.
3620: # Assemble privs for that user, and check for 'evb' priv.
3621: my ($trole,$tdom,$tnum,$tsec);
3622: my $entry = $live_courses{$course}{$sec};
3623: if ($entry =~ /^cr/) {
3624: ($trole,$tdom,$tnum,$tsec) =
3625: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
3626: } else {
3627: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
3628: }
3629: my ($spec,$area,$trest,%allroles,%userroles);
3630: $area = '/'.$tdom.'/'.$tnum;
3631: $trest = $tnum;
3632: if ($tsec ne '') {
3633: $area .= '/'.$tsec;
3634: $trest .= '/'.$tsec;
3635: }
3636: $spec = $trole.'.'.$area;
3637: if ($trole =~ /^cr/) {
3638: &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
3639: $tdom,$spec,$trest,$area);
3640: } else {
3641: &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
3642: $tdom,$spec,$trest,$area);
3643: }
3644: my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
3645: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
3646: if ($1) {
3647: $no_userblock = 1;
3648: last;
3649: }
3650: }
3651: } else {
3652: # Resource belongs to current user
3653: # Check for 'evb' priv via lonnet::allowed().
3654: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
3655: $no_ownblock = 1;
3656: last;
3657: }
3658: }
3659: }
3660: # if they have the evb priv and are currently not playing student
3661: next if (($no_ownblock) &&
3662: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
3663: next if ($no_userblock);
3664:
3665: # Retrieve blocking times and identity of blocker for course
3666: # of specified user, unless user has 'evb' privilege.
3667:
3668: my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
3669: if (($start != 0) &&
3670: (($startblock == 0) || ($startblock > $start))) {
3671: $startblock = $start;
3672: }
3673: if (($end != 0) &&
3674: (($endblock == 0) || ($endblock < $end))) {
3675: $endblock = $end;
3676: }
3677: }
3678: return ($startblock,$endblock);
3679: }
3680:
3681: sub get_blocks {
3682: my ($setters,$activity,$cdom,$cnum) = @_;
3683: my $startblock = 0;
3684: my $endblock = 0;
3685: my $course = $cdom.'_'.$cnum;
3686: $setters->{$course} = {};
3687: $setters->{$course}{'staff'} = [];
3688: $setters->{$course}{'times'} = [];
3689: my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
3690: foreach my $record (keys(%records)) {
3691: my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
3692: if ($start <= time && $end >= time) {
3693: my ($staff_name,$staff_dom,$title,$blocks) =
3694: &parse_block_record($records{$record});
3695: if ($blocks->{$activity} eq 'on') {
3696: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
3697: push(@{$$setters{$course}{'times'}}, [$start,$end]);
3698: if ( ($startblock == 0) || ($startblock > $start) ) {
3699: $startblock = $start;
3700: }
3701: if ( ($endblock == 0) || ($endblock < $end) ) {
3702: $endblock = $end;
3703: }
3704: }
3705: }
3706: }
3707: return ($startblock,$endblock);
3708: }
3709:
3710: sub parse_block_record {
3711: my ($record) = @_;
3712: my ($setuname,$setudom,$title,$blocks);
3713: if (ref($record) eq 'HASH') {
3714: ($setuname,$setudom) = split(/:/,$record->{'setter'});
3715: $title = &unescape($record->{'event'});
3716: $blocks = $record->{'blocks'};
3717: } else {
3718: my @data = split(/:/,$record,3);
3719: if (scalar(@data) eq 2) {
3720: $title = $data[1];
3721: ($setuname,$setudom) = split(/@/,$data[0]);
3722: } else {
3723: ($setuname,$setudom,$title) = @data;
3724: }
3725: $blocks = { 'com' => 'on' };
3726: }
3727: return ($setuname,$setudom,$title,$blocks);
3728: }
3729:
3730: sub build_block_table {
3731: my ($startblock,$endblock,$setters) = @_;
3732: my %lt = &Apache::lonlocal::texthash(
3733: 'cacb' => 'Currently active communication blocks',
3734: 'cour' => 'Course',
3735: 'dura' => 'Duration',
3736: 'blse' => 'Block set by'
3737: );
3738: my $output;
3739: $output = '<br />'.$lt{'cacb'}.':<br />';
3740: $output .= &start_data_table();
3741: $output .= '
3742: <tr>
3743: <th>'.$lt{'cour'}.'</th>
3744: <th>'.$lt{'dura'}.'</th>
3745: <th>'.$lt{'blse'}.'</th>
3746: </tr>
3747: ';
3748: foreach my $course (keys(%{$setters})) {
3749: my %courseinfo=&Apache::lonnet::coursedescription($course);
3750: for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
3751: my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
3752: my $fullname = &plainname($uname,$udom);
3753: if (defined($env{'user.name'}) && defined($env{'user.domain'})
3754: && $env{'user.name'} ne 'public'
3755: && $env{'user.domain'} ne 'public') {
3756: $fullname = &aboutmewrapper($fullname,$uname,$udom);
3757: }
3758: my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
3759: $openblock = &Apache::lonlocal::locallocaltime($openblock);
3760: $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
3761: $output .= &Apache::loncommon::start_data_table_row().
3762: '<td>'.$courseinfo{'description'}.'</td>'.
3763: '<td>'.$openblock.' to '.$closeblock.'</td>'.
3764: '<td>'.$fullname.'</td>'.
3765: &Apache::loncommon::end_data_table_row();
3766: }
3767: }
3768: $output .= &end_data_table();
3769: }
3770:
3771: sub blocking_status {
3772: my ($activity,$uname,$udom) = @_;
3773: my %setters;
3774: my ($blocked,$output,$ownitem,$is_course);
3775: my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
3776: if ($startblock && $endblock) {
3777: $blocked = 1;
3778: if (wantarray) {
3779: my $category;
3780: if ($activity eq 'boards') {
3781: $category = 'Discussion posts in this course';
3782: } elsif ($activity eq 'blogs') {
3783: $category = 'Blogs';
3784: } elsif ($activity eq 'port') {
3785: if (defined($uname) && defined($udom)) {
3786: if ($uname eq $env{'user.name'} &&
3787: $udom eq $env{'user.domain'}) {
3788: $ownitem = 1;
3789: }
3790: }
3791: $is_course = &Apache::lonnet::is_course($udom,$uname);
3792: if ($ownitem) {
3793: $category = 'Your portfolio files';
3794: } elsif ($is_course) {
3795: my $coursedesc;
3796: foreach my $course (keys(%setters)) {
3797: my %courseinfo =
3798: &Apache::lonnet::coursedescription($course);
3799: $coursedesc = $courseinfo{'description'};
3800: }
3801: $category = "Group files in the course '$coursedesc'";
3802: } else {
3803: $category = 'Portfolio files belonging to ';
3804: if ($env{'user.name'} eq 'public' &&
3805: $env{'user.domain'} eq 'public') {
3806: $category .= &plainname($uname,$udom);
3807: } else {
3808: $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);
3809: }
3810: }
3811: } elsif ($activity eq 'groups') {
3812: $category = 'Groups in this course';
3813: }
3814: my $showstart = &Apache::lonlocal::locallocaltime($startblock);
3815: my $showend = &Apache::lonlocal::locallocaltime($endblock);
3816: $output = '<br />'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'<br />';
3817: if (!($activity eq 'port' && !($ownitem) && !($is_course))) {
3818: $output .= &build_block_table($startblock,$endblock,\%setters);
3819: }
3820: }
3821: }
3822: if (wantarray) {
3823: return ($blocked,$output);
3824: } else {
3825: return $blocked;
3826: }
3827: }
3828:
3829: ###############################################
3830:
3831: sub check_ip_acc {
3832: my ($acc)=@_;
3833: &Apache::lonxml::debug("acc is $acc");
3834: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
3835: return 1;
3836: }
3837: my $allowed=0;
3838: my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
3839:
3840: my $name;
3841: foreach my $pattern (split(',',$acc)) {
3842: $pattern =~ s/^\s*//;
3843: $pattern =~ s/\s*$//;
3844: if ($pattern =~ /\*$/) {
3845: #35.8.*
3846: $pattern=~s/\*//;
3847: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
3848: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
3849: #35.8.3.[34-56]
3850: my $low=$2;
3851: my $high=$3;
3852: $pattern=$1;
3853: if ($ip =~ /^\Q$pattern\E/) {
3854: my $last=(split(/\./,$ip))[3];
3855: if ($last <=$high && $last >=$low) { $allowed=1; }
3856: }
3857: } elsif ($pattern =~ /^\*/) {
3858: #*.msu.edu
3859: $pattern=~s/\*//;
3860: if (!defined($name)) {
3861: use Socket;
3862: my $netaddr=inet_aton($ip);
3863: ($name)=gethostbyaddr($netaddr,AF_INET);
3864: }
3865: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
3866: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
3867: #127.0.0.1
3868: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
3869: } else {
3870: #some.name.com
3871: if (!defined($name)) {
3872: use Socket;
3873: my $netaddr=inet_aton($ip);
3874: ($name)=gethostbyaddr($netaddr,AF_INET);
3875: }
3876: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
3877: }
3878: if ($allowed) { last; }
3879: }
3880: return $allowed;
3881: }
3882:
3883: ###############################################
3884:
3885: =pod
3886:
3887: =head1 Domain Template Functions
3888:
3889: =over 4
3890:
3891: =item * &determinedomain()
3892:
3893: Inputs: $domain (usually will be undef)
3894:
3895: Returns: Determines which domain should be used for designs
3896:
3897: =cut
3898:
3899: ###############################################
3900: sub determinedomain {
3901: my $domain=shift;
3902: if (! $domain) {
3903: # Determine domain if we have not been given one
3904: $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
3905: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
3906: if ($env{'request.role.domain'}) {
3907: $domain=$env{'request.role.domain'};
3908: }
3909: }
3910: return $domain;
3911: }
3912: ###############################################
3913:
3914: sub devalidate_domconfig_cache {
3915: my ($udom)=@_;
3916: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
3917: }
3918:
3919: # ---------------------- Get domain configuration for a domain
3920: sub get_domainconf {
3921: my ($udom) = @_;
3922: my $cachetime=1800;
3923: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
3924: if (defined($cached)) { return %{$result}; }
3925:
3926: my %domconfig = &Apache::lonnet::get_dom('configuration',
3927: ['login','rolecolors'],$udom);
3928: my (%designhash,%legacy);
3929: if (keys(%domconfig) > 0) {
3930: if (ref($domconfig{'login'}) eq 'HASH') {
3931: if (keys(%{$domconfig{'login'}})) {
3932: foreach my $key (keys(%{$domconfig{'login'}})) {
3933: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
3934: }
3935: } else {
3936: $legacy{'login'} = 1;
3937: }
3938: } else {
3939: $legacy{'login'} = 1;
3940: }
3941: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
3942: if (keys(%{$domconfig{'rolecolors'}})) {
3943: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
3944: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
3945: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
3946: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
3947: }
3948: }
3949: }
3950: } else {
3951: $legacy{'rolecolors'} = 1;
3952: }
3953: } else {
3954: $legacy{'rolecolors'} = 1;
3955: }
3956: if (keys(%legacy) > 0) {
3957: my %legacyhash = &get_legacy_domconf($udom);
3958: foreach my $item (keys(%legacyhash)) {
3959: if ($item =~ /^\Q$udom\E\.login/) {
3960: if ($legacy{'login'}) {
3961: $designhash{$item} = $legacyhash{$item};
3962: }
3963: } else {
3964: if ($legacy{'rolecolors'}) {
3965: $designhash{$item} = $legacyhash{$item};
3966: }
3967: }
3968: }
3969: }
3970: } else {
3971: %designhash = &get_legacy_domconf($udom);
3972: }
3973: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
3974: $cachetime);
3975: return %designhash;
3976: }
3977:
3978: sub get_legacy_domconf {
3979: my ($udom) = @_;
3980: my %legacyhash;
3981: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
3982: my $designfile = $designdir.'/'.$udom.'.tab';
3983: if (-e $designfile) {
3984: if ( open (my $fh,"<$designfile") ) {
3985: while (my $line = <$fh>) {
3986: next if ($line =~ /^\#/);
3987: chomp($line);
3988: my ($key,$val)=(split(/\=/,$line));
3989: if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
3990: }
3991: close($fh);
3992: }
3993: }
3994: if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
3995: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
3996: }
3997: return %legacyhash;
3998: }
3999:
4000: =pod
4001:
4002: =item * &domainlogo()
4003:
4004: Inputs: $domain (usually will be undef)
4005:
4006: Returns: A link to a domain logo, if the domain logo exists.
4007: If the domain logo does not exist, a description of the domain.
4008:
4009: =cut
4010:
4011: ###############################################
4012: sub domainlogo {
4013: my $domain = &determinedomain(shift);
4014: my %designhash = &get_domainconf($domain);
4015: # See if there is a logo
4016: if ($designhash{$domain.'.login.domlogo'} ne '') {
4017: my $imgsrc = $designhash{$domain.'.login.domlogo'};
4018: if ($imgsrc =~ m{^/(adm|res)/}) {
4019: if ($imgsrc =~ m{^/res/}) {
4020: my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
4021: &Apache::lonnet::repcopy($local_name);
4022: }
4023: $imgsrc = &lonhttpdurl($imgsrc);
4024: }
4025: return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
4026: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
4027: return &Apache::lonnet::domain($domain,'description');
4028: } else {
4029: return '';
4030: }
4031: }
4032: ##############################################
4033:
4034: =pod
4035:
4036: =item * &designparm()
4037:
4038: Inputs: $which parameter; $domain (usually will be undef)
4039:
4040: Returns: value of designparamter $which
4041:
4042: =cut
4043:
4044:
4045: ##############################################
4046: sub designparm {
4047: my ($which,$domain)=@_;
4048: if ($env{'browser.blackwhite'} eq 'on') {
4049: if ($which=~/\.(font|alink|vlink|link|textcol)$/) {
4050: return '#000000';
4051: }
4052: if ($which=~/\.(pgbg|sidebg|bgcol)$/) {
4053: return '#FFFFFF';
4054: }
4055: if ($which=~/\.tabbg$/) {
4056: return '#CCCCCC';
4057: }
4058: }
4059: if (exists($env{'environment.color.'.$which})) {
4060: return $env{'environment.color.'.$which};
4061: }
4062: $domain=&determinedomain($domain);
4063: my %domdesign = &get_domainconf($domain);
4064: my $output;
4065: if ($domdesign{$domain.'.'.$which} ne '') {
4066: $output = $domdesign{$domain.'.'.$which};
4067: } else {
4068: $output = $defaultdesign{$which};
4069: }
4070: if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
4071: ($which =~ /login\.(img|logo|domlogo|login)/)) {
4072: if ($output =~ m{^/(adm|res)/}) {
4073: if ($output =~ m{^/res/}) {
4074: my $local_name = &Apache::lonnet::filelocation('',$output);
4075: &Apache::lonnet::repcopy($local_name);
4076: }
4077: $output = &lonhttpdurl($output);
4078: }
4079: }
4080: return $output;
4081: }
4082:
4083: ###############################################
4084: ###############################################
4085:
4086: =pod
4087:
4088: =back
4089:
4090: =head1 HTML Helpers
4091:
4092: =over 4
4093:
4094: =item * &bodytag()
4095:
4096: Returns a uniform header for LON-CAPA web pages.
4097:
4098: Inputs:
4099:
4100: =over 4
4101:
4102: =item * $title, A title to be displayed on the page.
4103:
4104: =item * $function, the current role (can be undef).
4105:
4106: =item * $addentries, extra parameters for the <body> tag.
4107:
4108: =item * $bodyonly, if defined, only return the <body> tag.
4109:
4110: =item * $domain, if defined, force a given domain.
4111:
4112: =item * $forcereg, if page should register as content page (relevant for
4113: text interface only)
4114:
4115: =item * $customtitle, alternate text to use instead of $title
4116: in the title box that appears, this text
4117: is not auto translated like the $title is
4118:
4119: =item * $notopbar, if true, keep the 'what is this' info but remove the
4120: navigational links
4121:
4122: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
4123:
4124: =item * $notitle, if true keep the nav controls, but remove the title bar
4125:
4126: =item * $no_inline_link, if true and in remote mode, don't show the
4127: 'Switch To Inline Menu' link
4128:
4129: =item * $args, optional argument valid values are
4130: no_auto_mt_title -> prevents &mt()ing the title arg
4131: inherit_jsmath -> when creating popup window in a page,
4132: should it have jsmath forced on by the
4133: current page
4134:
4135: =back
4136:
4137: Returns: A uniform header for LON-CAPA web pages.
4138: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
4139: If $bodyonly is undef or zero, an html string containing a <body> tag and
4140: other decorations will be returned.
4141:
4142: =cut
4143:
4144: sub bodytag {
4145: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
4146: $notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
4147:
4148: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
4149:
4150: $function = &get_users_function() if (!$function);
4151: my $img = &designparm($function.'.img',$domain);
4152: my $font = &designparm($function.'.font',$domain);
4153: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
4154:
4155: my %design = ( 'style' => 'margin-top: 0px',
4156: 'bgcolor' => $pgbg,
4157: 'text' => $font,
4158: 'alink' => &designparm($function.'.alink',$domain),
4159: 'vlink' => &designparm($function.'.vlink',$domain),
4160: 'link' => &designparm($function.'.link',$domain),);
4161: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
4162:
4163: # role and realm
4164: my ($role,$realm) = split(/\./,$env{'request.role'},2);
4165: if ($role eq 'ca') {
4166: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
4167: $realm = &plainname($rname,$rdom);
4168: }
4169: # realm
4170: if ($env{'request.course.id'}) {
4171: if ($env{'request.role'} !~ /^cr/) {
4172: $role = &Apache::lonnet::plaintext($role,&course_type());
4173: }
4174: $realm = $env{'course.'.$env{'request.course.id'}.'.description'};
4175: } else {
4176: $role = &Apache::lonnet::plaintext($role);
4177: }
4178:
4179: if (!$realm) { $realm=' '; }
4180: # Set messages
4181: my $messages=&domainlogo($domain);
4182:
4183: my $extra_body_attr = &make_attr_string($forcereg,\%design);
4184:
4185: # construct main body tag
4186: my $bodytag = "<body $extra_body_attr>".
4187: &Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
4188:
4189: if ($bodyonly) {
4190: return $bodytag;
4191: } elsif ($env{'browser.interface'} eq 'textual') {
4192: # Accessibility
4193:
4194: $bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
4195: if (!$notitle) {
4196: $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
4197: }
4198: return $bodytag;
4199: }
4200:
4201: my $name = &plainname($env{'user.name'},$env{'user.domain'});
4202: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4203: undef($role);
4204: } else {
4205: $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
4206: }
4207:
4208: my $roleinfo=(<<ENDROLE);
4209: <td class="LC_title_bar_who">
4210: <div class="LC_title_bar_name">
4211: $name
4212:
4213: </div>
4214: <div class="LC_title_bar_role">
4215: $role
4216: </div>
4217: <div class="LC_title_bar_realm">
4218: $realm
4219: </div>
4220: </td>
4221: ENDROLE
4222:
4223: my $titleinfo = '<span class="LC_title_bar_title">'.$title.'</span>';
4224: if ($customtitle) {
4225: $titleinfo = $customtitle;
4226: }
4227: #
4228: # Extra info if you are the DC
4229: my $dc_info = '';
4230: if ($env{'user.adv'} && exists($env{'user.role.dc./'.
4231: $env{'course.'.$env{'request.course.id'}.
4232: '.domain'}.'/'})) {
4233: my $cid = $env{'request.course.id'};
4234: $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
4235: $dc_info =~ s/\s+$//;
4236: $dc_info = '('.$dc_info.')';
4237: }
4238:
4239: if (($env{'environment.remote'} eq 'off') || ($args->{'suppress_header_logos'})) {
4240: # No Remote
4241: if ($env{'request.state'} eq 'construct') {
4242: $forcereg=1;
4243: }
4244:
4245: if (!$customtitle && $env{'request.state'} eq 'construct') {
4246: # this is for resources; directories have customtitle, and crumbs
4247: # and select recent are created in lonpubdir.pm
4248: my ($uname,$thisdisfn)=
4249: ($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
4250: my $formaction='/priv/'.$uname.'/'.$thisdisfn;
4251: $formaction=~s/\/+/\//g;
4252:
4253: my $parentpath = '';
4254: my $lastitem = '';
4255: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
4256: $parentpath = $1;
4257: $lastitem = $2;
4258: } else {
4259: $lastitem = $thisdisfn;
4260: }
4261: $titleinfo =
4262: &Apache::loncommon::help_open_menu('','',3,'Authoring')
4263: .'<b>'.&mt('Construction Space').'</b>: '
4264: .'<form name="dirs" method="post" action="'.$formaction
4265: .'" target="_top"><tt><b>'
4266: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<font size=\"+1\">$lastitem</font></b></tt><br />"
4267: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
4268: .'</form>'
4269: .&Apache::lonmenu::constspaceform();
4270: }
4271:
4272: my $titletable;
4273: if (!$notitle) {
4274: $titletable =
4275: '<table id="LC_title_bar">'.
4276: "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
4277: '</tr></table>';
4278: }
4279: if ($notopbar) {
4280: $bodytag .= $titletable;
4281: } else {
4282: if ($env{'request.state'} eq 'construct') {
4283: $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
4284: $titletable);
4285: } else {
4286: $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
4287: $titletable;
4288: }
4289: }
4290: return $bodytag;
4291: }
4292:
4293: #
4294: # Top frame rendering, Remote is up
4295: #
4296:
4297: my $imgsrc = $img;
4298: if ($img =~ /^\/adm/) {
4299: $imgsrc = &lonhttpdurl($img);
4300: }
4301: my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
4302:
4303: # Explicit link to get inline menu
4304: my $menu= ($no_inline_link?''
4305: :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
4306: #
4307: if ($notitle) {
4308: return $bodytag;
4309: }
4310: return(<<ENDBODY);
4311: $bodytag
4312: <table id="LC_title_bar" class="LC_with_remote">
4313: <tr><td class="LC_title_bar_role_logo">$upperleft</td>
4314: <td class="LC_title_bar_domain_logo">$messages </td>
4315: </tr>
4316: <tr><td>$titleinfo $dc_info $menu</td>
4317: $roleinfo
4318: </tr>
4319: </table>
4320: ENDBODY
4321: }
4322:
4323: sub make_attr_string {
4324: my ($register,$attr_ref) = @_;
4325:
4326: if ($attr_ref && !ref($attr_ref)) {
4327: die("addentries Must be a hash ref ".
4328: join(':',caller(1))." ".
4329: join(':',caller(0))." ");
4330: }
4331:
4332: if ($register) {
4333: my ($on_load,$on_unload);
4334: foreach my $key (keys(%{$attr_ref})) {
4335: if (lc($key) eq 'onload') {
4336: $on_load.=$attr_ref->{$key}.';';
4337: delete($attr_ref->{$key});
4338:
4339: } elsif (lc($key) eq 'onunload') {
4340: $on_unload.=$attr_ref->{$key}.';';
4341: delete($attr_ref->{$key});
4342: }
4343: }
4344: $attr_ref->{'onload'} =
4345: &Apache::lonmenu::loadevents(). $on_load;
4346: $attr_ref->{'onunload'}=
4347: &Apache::lonmenu::unloadevents().$on_unload;
4348: }
4349:
4350: # Accessibility font enhance
4351: if ($env{'browser.fontenhance'} eq 'on') {
4352: my $style;
4353: foreach my $key (keys(%{$attr_ref})) {
4354: if (lc($key) eq 'style') {
4355: $style.=$attr_ref->{$key}.';';
4356: delete($attr_ref->{$key});
4357: }
4358: }
4359: $attr_ref->{'style'}=$style.'; font-size: x-large;';
4360: }
4361:
4362: if ($env{'browser.blackwhite'} eq 'on') {
4363: delete($attr_ref->{'font'});
4364: delete($attr_ref->{'link'});
4365: delete($attr_ref->{'alink'});
4366: delete($attr_ref->{'vlink'});
4367: delete($attr_ref->{'bgcolor'});
4368: delete($attr_ref->{'background'});
4369: }
4370:
4371: my $attr_string;
4372: foreach my $attr (keys(%$attr_ref)) {
4373: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
4374: }
4375: return $attr_string;
4376: }
4377:
4378:
4379: ###############################################
4380: ###############################################
4381:
4382: =pod
4383:
4384: =item * &endbodytag()
4385:
4386: Returns a uniform footer for LON-CAPA web pages.
4387:
4388: Inputs: 1 - optional reference to an args hash
4389: If in the hash, key for noredirectlink has a value which evaluates to true,
4390: a 'Continue' link is not displayed if the page contains an
4391: internal redirect in the <head></head> section,
4392: i.e., $env{'internal.head.redirect'} exists
4393:
4394: =cut
4395:
4396: sub endbodytag {
4397: my ($args) = @_;
4398: my $endbodytag='</body>';
4399: $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
4400: if ( exists( $env{'internal.head.redirect'} ) ) {
4401: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
4402: $endbodytag=
4403: "<br /><a href=\"$env{'internal.head.redirect'}\">".
4404: &mt('Continue').'</a>'.
4405: $endbodytag;
4406: }
4407: }
4408: return $endbodytag;
4409: }
4410:
4411: =pod
4412:
4413: =item * &standard_css()
4414:
4415: Returns a style sheet
4416:
4417: Inputs: (all optional)
4418: domain -> force to color decorate a page for a specific
4419: domain
4420: function -> force usage of a specific rolish color scheme
4421: bgcolor -> override the default page bgcolor
4422:
4423: =cut
4424:
4425: sub standard_css {
4426: my ($function,$domain,$bgcolor) = @_;
4427: $function = &get_users_function() if (!$function);
4428: my $img = &designparm($function.'.img', $domain);
4429: my $tabbg = &designparm($function.'.tabbg', $domain);
4430: my $font = &designparm($function.'.font', $domain);
4431: my $sidebg = &designparm($function.'.sidebg',$domain);
4432: my $pgbg_or_bgcolor =
4433: $bgcolor ||
4434: &designparm($function.'.pgbg', $domain);
4435: my $pgbg = &designparm($function.'.pgbg', $domain);
4436: my $alink = &designparm($function.'.alink', $domain);
4437: my $vlink = &designparm($function.'.vlink', $domain);
4438: my $link = &designparm($function.'.link', $domain);
4439:
4440: my $sans = 'Verdana,Arial,Helvetica,sans-serif';
4441: my $mono = 'monospace';
4442: my $data_table_head = $tabbg;
4443: my $data_table_light = '#EEEEEE';
4444: my $data_table_dark = '#DDDDDD';
4445: my $data_table_darker = '#CCCCCC';
4446: my $data_table_highlight = '#FFFF00';
4447: my $mail_new = '#FFBB77';
4448: my $mail_new_hover = '#DD9955';
4449: my $mail_read = '#BBBB77';
4450: my $mail_read_hover = '#999944';
4451: my $mail_replied = '#AAAA88';
4452: my $mail_replied_hover = '#888855';
4453: my $mail_other = '#99BBBB';
4454: my $mail_other_hover = '#669999';
4455: my $table_header = '#DDDDDD';
4456: my $feedback_link_bg = '#BBBBBB';
4457:
4458: my $border = ($env{'browser.type'} eq 'explorer' ||
4459: $env{'browser.type'} eq 'safari' ) ? '0px 2px 0px 2px'
4460: : '0px 3px 0px 4px';
4461:
4462:
4463: return <<END;
4464: h1, h2, h3, th { font-family: $sans }
4465: a:focus { color: red; background: yellow }
4466: table.thinborder,
4467:
4468: table.thinborder tr th {
4469: border-style: solid;
4470: border-width: 1px;
4471: background: $tabbg;
4472: }
4473: table.thinborder tr td {
4474: border-style: solid;
4475: border-width: 1px
4476: }
4477:
4478: form, .inline { display: inline; }
4479: .center { text-align: center; }
4480: .LC_filename {font-family: $mono; white-space:pre;}
4481: .LC_error {
4482: color: red;
4483: font-size: larger;
4484: }
4485: .LC_warning,
4486: .LC_diff_removed {
4487: color: red;
4488: }
4489:
4490: .LC_info,
4491: .LC_success,
4492: .LC_diff_added {
4493: color: green;
4494: }
4495: .LC_unknown {
4496: color: yellow;
4497: }
4498:
4499: .LC_icon {
4500: border: 0px;
4501: }
4502: .LC_indexer_icon {
4503: border: 0px;
4504: height: 22px;
4505: }
4506: .LC_docs_spacer {
4507: width: 25px;
4508: height: 1px;
4509: border: 0px;
4510: }
4511:
4512: .LC_internal_info {
4513: color: #999;
4514: }
4515:
4516: table.LC_pastsubmission {
4517: border: 1px solid black;
4518: margin: 2px;
4519: }
4520:
4521: table#LC_top_nav, table#LC_menubuttons,table#LC_nav_location {
4522: width: 100%;
4523: background: $pgbg;
4524: border: 2px;
4525: border-collapse: separate;
4526: padding: 0px;
4527: }
4528:
4529: table#LC_title_bar, table.LC_breadcrumbs,
4530: table#LC_title_bar.LC_with_remote {
4531: width: 100%;
4532: border-color: $pgbg;
4533: border-style: solid;
4534: border-width: $border;
4535:
4536: background: $pgbg;
4537: font-family: $sans;
4538: border-collapse: collapse;
4539: padding: 0px;
4540: }
4541:
4542: table.LC_docs_path {
4543: width: 100%;
4544: border: 0;
4545: background: $pgbg;
4546: font-family: $sans;
4547: border-collapse: collapse;
4548: padding: 0px;
4549: }
4550:
4551: table#LC_title_bar td {
4552: background: $tabbg;
4553: }
4554: table#LC_title_bar td.LC_title_bar_who {
4555: background: $tabbg;
4556: color: $font;
4557: font: small $sans;
4558: text-align: right;
4559: }
4560: span.LC_metadata {
4561: font-family: $sans;
4562: }
4563: span.LC_title_bar_title {
4564: font: bold x-large $sans;
4565: }
4566: table#LC_title_bar td.LC_title_bar_domain_logo {
4567: background: $sidebg;
4568: text-align: right;
4569: padding: 0px;
4570: }
4571: table#LC_title_bar td.LC_title_bar_role_logo {
4572: background: $sidebg;
4573: padding: 0px;
4574: }
4575:
4576: table#LC_menubuttons_mainmenu {
4577: width: 100%;
4578: border: 0px;
4579: border-spacing: 1px;
4580: padding: 0px 1px;
4581: margin: 0px;
4582: border-collapse: separate;
4583: }
4584: table#LC_menubuttons img, table#LC_menubuttons_mainmenu img {
4585: border: 0px;
4586: }
4587: table#LC_top_nav td {
4588: background: $tabbg;
4589: border: 0px;
4590: font-size: small;
4591: }
4592: table#LC_top_nav td a, div#LC_top_nav a {
4593: color: $font;
4594: font-family: $sans;
4595: }
4596: table#LC_top_nav td.LC_top_nav_logo {
4597: background: $tabbg;
4598: text-align: left;
4599: white-space: nowrap;
4600: width: 31px;
4601: }
4602: table#LC_top_nav td.LC_top_nav_logo img {
4603: border: 0px;
4604: vertical-align: bottom;
4605: }
4606: table#LC_top_nav td.LC_top_nav_exit,
4607: table#LC_top_nav td.LC_top_nav_help {
4608: width: 2.0em;
4609: }
4610: table#LC_top_nav td.LC_top_nav_login {
4611: width: 4.0em;
4612: text-align: center;
4613: }
4614: table.LC_breadcrumbs td, table.LC_docs_path td {
4615: background: $tabbg;
4616: color: $font;
4617: font-family: $sans;
4618: font-size: smaller;
4619: }
4620: table.LC_breadcrumbs td.LC_breadcrumbs_component,
4621: table.LC_docs_path td.LC_docs_path_component {
4622: background: $tabbg;
4623: color: $font;
4624: font-family: $sans;
4625: font-size: larger;
4626: text-align: right;
4627: }
4628: td.LC_table_cell_checkbox {
4629: text-align: center;
4630: }
4631: table#LC_mainmenu td.LC_mainmenu_column {
4632: vertical-align: top;
4633: }
4634:
4635: .LC_menubuttons_inline_text {
4636: color: $font;
4637: font-family: $sans;
4638: font-size: smaller;
4639: }
4640:
4641: .LC_menubuttons_link {
4642: text-decoration: none;
4643: }
4644: #2008--9-5: new menu style sheet.Changed category
4645: .LC_menubuttons_category {
4646: color: $font;
4647: background: $pgbg;
4648: font-family: $sans;
4649: font-size: larger;
4650: font-weight: bold;
4651: }
4652:
4653: td.LC_menubuttons_text {
4654: width: 90%;
4655: color: $font;
4656: font-family: $sans;
4657: }
4658:
4659: td.LC_menubuttons_img {
4660: }
4661:
4662: .LC_current_location {
4663: font-family: $sans;
4664: background: $tabbg;
4665: }
4666: .LC_new_mail {
4667: font-family: $sans;
4668: background: $tabbg;
4669: font-weight: bold;
4670: }
4671:
4672: .LC_rolesmenu_is {
4673: font-family: $sans;
4674: }
4675:
4676: .LC_rolesmenu_selected {
4677: font-family: $sans;
4678: }
4679:
4680: .LC_rolesmenu_future {
4681: font-family: $sans;
4682: }
4683:
4684:
4685: .LC_rolesmenu_will {
4686: font-family: $sans;
4687: }
4688:
4689: .LC_rolesmenu_will_not {
4690: font-family: $sans;
4691: }
4692:
4693: .LC_rolesmenu_expired {
4694: font-family: $sans;
4695: }
4696:
4697: .LC_rolesinfo {
4698: font-family: $sans;
4699: }
4700:
4701: .LC_dropadd_labeltext {
4702: font-family: $sans;
4703: text-align: right;
4704: }
4705:
4706: .LC_preferences_labeltext {
4707: font-family: $sans;
4708: text-align: right;
4709: }
4710:
4711: .LC_roleslog_note {
4712: font-size: smaller;
4713: }
4714:
4715: table.LC_aboutme_port {
4716: border: 0px;
4717: border-collapse: collapse;
4718: border-spacing: 0px;
4719: }
4720: table.LC_data_table, table.LC_mail_list {
4721: border: 1px solid #000000;
4722: border-collapse: separate;
4723: border-spacing: 1px;
4724: background: $pgbg;
4725: }
4726: .LC_data_table_dense {
4727: font-size: small;
4728: }
4729: table.LC_nested_outer {
4730: border: 1px solid #000000;
4731: border-collapse: collapse;
4732: border-spacing: 0px;
4733: width: 100%;
4734: }
4735: table.LC_nested {
4736: border: 0px;
4737: border-collapse: collapse;
4738: border-spacing: 0px;
4739: width: 100%;
4740: }
4741: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th,
4742: table.LC_prior_tries tr th {
4743: font-weight: bold;
4744: background-color: $data_table_head;
4745: font-size: smaller;
4746: }
4747: table.LC_data_table tr.LC_odd_row > td,
4748: table.LC_aboutme_port tr td {
4749: background-color: $data_table_light;
4750: padding: 2px;
4751: }
4752: table.LC_data_table tr.LC_even_row > td,
4753: table.LC_aboutme_port tr.LC_even_row td {
4754: background-color: $data_table_dark;
4755: }
4756: table.LC_data_table tr.LC_data_table_highlight td {
4757: background-color: $data_table_darker;
4758: }
4759: table.LC_data_table tr td.LC_leftcol_header {
4760: background-color: $data_table_head;
4761: font-weight: bold;
4762: }
4763: table.LC_data_table tr.LC_empty_row td,
4764: table.LC_nested tr.LC_empty_row td {
4765: background-color: #FFFFFF;
4766: font-weight: bold;
4767: font-style: italic;
4768: text-align: center;
4769: padding: 8px;
4770: }
4771: table.LC_nested tr.LC_empty_row td {
4772: padding: 4ex
4773: }
4774: table.LC_nested_outer tr th {
4775: font-weight: bold;
4776: background-color: $data_table_head;
4777: font-size: smaller;
4778: border-bottom: 1px solid #000000;
4779: }
4780: table.LC_nested_outer tr td.LC_subheader {
4781: background-color: $data_table_head;
4782: font-weight: bold;
4783: font-size: small;
4784: border-bottom: 1px solid #000000;
4785: text-align: right;
4786: }
4787: table.LC_nested tr.LC_info_row td {
4788: background-color: #CCC;
4789: font-weight: bold;
4790: font-size: small;
4791: text-align: center;
4792: }
4793: table.LC_nested tr.LC_info_row td.LC_left_item,
4794: table.LC_nested_outer tr th.LC_left_item {
4795: text-align: left;
4796: }
4797: table.LC_nested td {
4798: background-color: #FFF;
4799: font-size: small;
4800: }
4801: table.LC_nested_outer tr th.LC_right_item,
4802: table.LC_nested tr.LC_info_row td.LC_right_item,
4803: table.LC_nested tr.LC_odd_row td.LC_right_item,
4804: table.LC_nested tr td.LC_right_item {
4805: text-align: right;
4806: }
4807:
4808: table.LC_nested tr.LC_odd_row td {
4809: background-color: #EEE;
4810: }
4811:
4812: table.LC_createuser {
4813: }
4814:
4815: table.LC_createuser tr.LC_section_row td {
4816: font-size: smaller;
4817: }
4818:
4819: table.LC_createuser tr.LC_info_row td {
4820: background-color: #CCC;
4821: font-weight: bold;
4822: text-align: center;
4823: }
4824:
4825: table.LC_calendar {
4826: border: 1px solid #000000;
4827: border-collapse: collapse;
4828: }
4829: table.LC_calendar_pickdate {
4830: font-size: xx-small;
4831: }
4832: table.LC_calendar tr td {
4833: border: 1px solid #000000;
4834: vertical-align: top;
4835: }
4836: table.LC_calendar tr td.LC_calendar_day_empty {
4837: background-color: $data_table_dark;
4838: }
4839: table.LC_calendar tr td.LC_calendar_day_current {
4840: background-color: $data_table_highlight;
4841: }
4842:
4843: table.LC_mail_list tr.LC_mail_new {
4844: background-color: $mail_new;
4845: }
4846: table.LC_mail_list tr.LC_mail_new:hover {
4847: background-color: $mail_new_hover;
4848: }
4849: table.LC_mail_list tr.LC_mail_read {
4850: background-color: $mail_read;
4851: }
4852: table.LC_mail_list tr.LC_mail_read:hover {
4853: background-color: $mail_read_hover;
4854: }
4855: table.LC_mail_list tr.LC_mail_replied {
4856: background-color: $mail_replied;
4857: }
4858: table.LC_mail_list tr.LC_mail_replied:hover {
4859: background-color: $mail_replied_hover;
4860: }
4861: table.LC_mail_list tr.LC_mail_other {
4862: background-color: $mail_other;
4863: }
4864: table.LC_mail_list tr.LC_mail_other:hover {
4865: background-color: $mail_other_hover;
4866: }
4867: table.LC_mail_list tr.LC_mail_even {
4868: }
4869: table.LC_mail_list tr.LC_mail_odd {
4870: }
4871:
4872:
4873: table#LC_portfolio_actions {
4874: width: auto;
4875: background: $pgbg;
4876: border: 0px;
4877: border-spacing: 2px 2px;
4878: padding: 0px;
4879: margin: 0px;
4880: border-collapse: separate;
4881: }
4882: table#LC_portfolio_actions td.LC_label {
4883: background: $tabbg;
4884: text-align: right;
4885: }
4886: table#LC_portfolio_actions td.LC_value {
4887: background: $tabbg;
4888: }
4889:
4890: table#LC_cstr_controls {
4891: width: 100%;
4892: border-collapse: collapse;
4893: }
4894: table#LC_cstr_controls tr td {
4895: border: 4px solid $pgbg;
4896: padding: 4px;
4897: text-align: center;
4898: background: $tabbg;
4899: }
4900: table#LC_cstr_controls tr th {
4901: border: 4px solid $pgbg;
4902: background: $table_header;
4903: text-align: center;
4904: font-family: $sans;
4905: font-size: smaller;
4906: }
4907:
4908: table#LC_browser {
4909:
4910: }
4911: table#LC_browser tr th {
4912: background: $table_header;
4913: }
4914: table#LC_browser tr td {
4915: padding: 2px;
4916: }
4917: table#LC_browser tr.LC_browser_file,
4918: table#LC_browser tr.LC_browser_file_published {
4919: background: #CCFF88;
4920: }
4921: table#LC_browser tr.LC_browser_file_locked,
4922: table#LC_browser tr.LC_browser_file_unpublished {
4923: background: #FFAA99;
4924: }
4925: table#LC_browser tr.LC_browser_file_obsolete {
4926: background: #AAAAAA;
4927: }
4928: table#LC_browser tr.LC_browser_file_modified,
4929: table#LC_browser tr.LC_browser_file_metamodified {
4930: background: #FFFF77;
4931: }
4932: table#LC_browser tr.LC_browser_folder {
4933: background: #CCCCFF;
4934: }
4935: span.LC_current_location {
4936: font-size: x-large;
4937: background: $pgbg;
4938: }
4939:
4940: span.LC_parm_menu_item {
4941: font-size: larger;
4942: font-family: $sans;
4943: }
4944: span.LC_parm_scope_all {
4945: color: red;
4946: }
4947: span.LC_parm_scope_folder {
4948: color: green;
4949: }
4950: span.LC_parm_scope_resource {
4951: color: orange;
4952: }
4953: span.LC_parm_part {
4954: color: blue;
4955: }
4956: span.LC_parm_folder, span.LC_parm_symb {
4957: font-size: x-small;
4958: font-family: $mono;
4959: color: #AAAAAA;
4960: }
4961:
4962: td.LC_parm_overview_level_menu, td.LC_parm_overview_map_menu,
4963: td.LC_parm_overview_parm_selectors, td.LC_parm_overview_parm_restrictions {
4964: border: 1px solid black;
4965: border-collapse: collapse;
4966: }
4967: table.LC_parm_overview_restrictions td {
4968: border-width: 1px 4px 1px 4px;
4969: border-style: solid;
4970: border-color: $pgbg;
4971: text-align: center;
4972: }
4973: table.LC_parm_overview_restrictions th {
4974: background: $tabbg;
4975: border-width: 1px 4px 1px 4px;
4976: border-style: solid;
4977: border-color: $pgbg;
4978: }
4979: table#LC_helpmenu {
4980: border: 0px;
4981: height: 55px;
4982: border-spacing: 0px;
4983: }
4984:
4985: table#LC_helpmenu fieldset legend {
4986: font-size: larger;
4987: font-weight: bold;
4988: }
4989: table#LC_helpmenu_links {
4990: width: 100%;
4991: border: 1px solid black;
4992: background: $pgbg;
4993: padding: 0px;
4994: border-spacing: 1px;
4995: }
4996: table#LC_helpmenu_links tr td {
4997: padding: 1px;
4998: background: $tabbg;
4999: text-align: center;
5000: font-weight: bold;
5001: }
5002:
5003: table#LC_helpmenu_links a:link, table#LC_helpmenu_links a:visited,
5004: table#LC_helpmenu_links a:active {
5005: text-decoration: none;
5006: color: $font;
5007: }
5008: table#LC_helpmenu_links a:hover {
5009: text-decoration: underline;
5010: color: $vlink;
5011: }
5012:
5013: .LC_chrt_popup_exists {
5014: border: 1px solid #339933;
5015: margin: -1px;
5016: }
5017: .LC_chrt_popup_up {
5018: border: 1px solid yellow;
5019: margin: -1px;
5020: }
5021: .LC_chrt_popup {
5022: border: 1px solid #8888FF;
5023: background: #CCCCFF;
5024: }
5025: table.LC_pick_box {
5026: border-collapse: separate;
5027: background: white;
5028: border: 1px solid black;
5029: border-spacing: 1px;
5030: }
5031: table.LC_pick_box td.LC_pick_box_title {
5032: background: $tabbg;
5033: font-weight: bold;
5034: text-align: right;
5035: width: 184px;
5036: padding: 8px;
5037: }
5038: table.LC_pick_box td.LC_selfenroll_pick_box_title {
5039: background: $tabbg;
5040: font-weight: bold;
5041: text-align: right;
5042: width: 350px;
5043: padding: 8px;
5044: }
5045:
5046: table.LC_pick_box td.LC_pick_box_value {
5047: text-align: left;
5048: padding: 8px;
5049: }
5050: table.LC_pick_box td.LC_pick_box_select {
5051: text-align: left;
5052: padding: 8px;
5053: }
5054: table.LC_pick_box td.LC_pick_box_separator {
5055: padding: 0px;
5056: height: 1px;
5057: background: black;
5058: }
5059: table.LC_pick_box td.LC_pick_box_submit {
5060: text-align: right;
5061: }
5062: table.LC_pick_box td.LC_evenrow_value {
5063: text-align: left;
5064: padding: 8px;
5065: background-color: $data_table_light;
5066: }
5067: table.LC_pick_box td.LC_oddrow_value {
5068: text-align: left;
5069: padding: 8px;
5070: background-color: $data_table_light;
5071: }
5072: table.LC_helpform_receipt {
5073: width: 620px;
5074: border-collapse: separate;
5075: background: white;
5076: border: 1px solid black;
5077: border-spacing: 1px;
5078: }
5079: table.LC_helpform_receipt td.LC_pick_box_title {
5080: background: $tabbg;
5081: font-weight: bold;
5082: text-align: right;
5083: width: 184px;
5084: padding: 8px;
5085: }
5086: table.LC_helpform_receipt td.LC_evenrow_value {
5087: text-align: left;
5088: padding: 8px;
5089: background-color: $data_table_light;
5090: }
5091: table.LC_helpform_receipt td.LC_oddrow_value {
5092: text-align: left;
5093: padding: 8px;
5094: background-color: $data_table_light;
5095: }
5096: table.LC_helpform_receipt td.LC_pick_box_separator {
5097: padding: 0px;
5098: height: 1px;
5099: background: black;
5100: }
5101: span.LC_helpform_receipt_cat {
5102: font-weight: bold;
5103: }
5104: table.LC_group_priv_box {
5105: background: white;
5106: border: 1px solid black;
5107: border-spacing: 1px;
5108: }
5109: table.LC_group_priv_box td.LC_pick_box_title {
5110: background: $tabbg;
5111: font-weight: bold;
5112: text-align: right;
5113: width: 184px;
5114: }
5115: table.LC_group_priv_box td.LC_groups_fixed {
5116: background: $data_table_light;
5117: text-align: center;
5118: }
5119: table.LC_group_priv_box td.LC_groups_optional {
5120: background: $data_table_dark;
5121: text-align: center;
5122: }
5123: table.LC_group_priv_box td.LC_groups_functionality {
5124: background: $data_table_darker;
5125: text-align: center;
5126: font-weight: bold;
5127: }
5128: table.LC_group_priv td {
5129: text-align: left;
5130: padding: 0px;
5131: }
5132:
5133: table.LC_notify_front_page {
5134: background: white;
5135: border: 1px solid black;
5136: padding: 8px;
5137: }
5138: table.LC_notify_front_page td {
5139: padding: 8px;
5140: }
5141: .LC_navbuttons {
5142: margin: 2ex 0ex 2ex 0ex;
5143: }
5144: .LC_topic_bar {
5145: font-family: $sans;
5146: font-weight: bold;
5147: width: 100%;
5148: background: $tabbg;
5149: vertical-align: middle;
5150: margin: 2ex 0ex 2ex 0ex;
5151: }
5152: .LC_topic_bar span {
5153: vertical-align: middle;
5154: }
5155: .LC_topic_bar img {
5156: vertical-align: bottom;
5157: }
5158: table.LC_course_group_status {
5159: margin: 20px;
5160: }
5161: table.LC_status_selector td {
5162: vertical-align: top;
5163: text-align: center;
5164: padding: 4px;
5165: }
5166: table.LC_descriptive_input td.LC_description {
5167: vertical-align: top;
5168: text-align: right;
5169: font-weight: bold;
5170: }
5171: div.LC_feedback_link {
5172: clear: both;
5173: background: white;
5174: width: 100%;
5175: }
5176: span.LC_feedback_link {
5177: background: $feedback_link_bg;
5178: font-size: larger;
5179: }
5180: span.LC_message_link {
5181: background: $feedback_link_bg;
5182: font-size: larger;
5183: position: absolute;
5184: right: 1em;
5185: }
5186:
5187: table.LC_prior_tries {
5188: border: 1px solid #000000;
5189: border-collapse: separate;
5190: border-spacing: 1px;
5191: }
5192:
5193: table.LC_prior_tries td {
5194: padding: 2px;
5195: }
5196:
5197: .LC_answer_correct {
5198: background: #AAFFAA;
5199: color: black;
5200: }
5201: .LC_answer_charged_try {
5202: background: #FFAAAA ! important;
5203: color: black;
5204: }
5205: .LC_answer_not_charged_try,
5206: .LC_answer_no_grade,
5207: .LC_answer_late {
5208: background: #FFFFAA;
5209: color: black;
5210: }
5211: .LC_answer_previous {
5212: background: #AAAAFF;
5213: color: black;
5214: }
5215: .LC_answer_no_message {
5216: background: #FFFFFF;
5217: color: black;
5218: }
5219: .LC_answer_unknown {
5220: background: orange;
5221: color: black;
5222: }
5223:
5224:
5225: span.LC_prior_numerical,
5226: span.LC_prior_string,
5227: span.LC_prior_custom,
5228: span.LC_prior_reaction,
5229: span.LC_prior_math {
5230: font-family: monospace;
5231: white-space: pre;
5232: }
5233:
5234: span.LC_prior_string {
5235: font-family: monospace;
5236: white-space: pre;
5237: }
5238:
5239: table.LC_prior_option {
5240: width: 100%;
5241: border-collapse: collapse;
5242: }
5243: table.LC_prior_rank, table.LC_prior_match {
5244: border-collapse: collapse;
5245: }
5246: table.LC_prior_option tr td,
5247: table.LC_prior_rank tr td,
5248: table.LC_prior_match tr td {
5249: border: 1px solid #000000;
5250: }
5251:
5252: span.LC_nobreak {
5253: white-space: nowrap;
5254: }
5255:
5256: span.LC_cusr_emph {
5257: font-style: italic;
5258: }
5259:
5260: span.LC_cusr_subheading {
5261: font-weight: normal;
5262: font-size: 85%;
5263: }
5264:
5265: table.LC_docs_documents {
5266: background: #BBBBBB;
5267: border-width: 0px;
5268: border-collapse: collapse;
5269: }
5270:
5271: table.LC_docs_documents td.LC_docs_document {
5272: border: 2px solid black;
5273: padding: 4px;
5274: }
5275:
5276: .LC_docs_course_commands div {
5277: float: left;
5278: border: 4px solid #AAAAAA;
5279: padding: 4px;
5280: background: #DDDDCC;
5281: }
5282:
5283: .LC_docs_entry_move {
5284: border: 0px;
5285: border-collapse: collapse;
5286: }
5287:
5288: .LC_docs_entry_move td {
5289: border: 2px solid #BBBBBB;
5290: background: #DDDDDD;
5291: }
5292:
5293: .LC_docs_editor td.LC_docs_entry_commands {
5294: background: #DDDDDD;
5295: font-size: x-small;
5296: }
5297: .LC_docs_copy {
5298: color: #000099;
5299: }
5300: .LC_docs_cut {
5301: color: #550044;
5302: }
5303: .LC_docs_rename {
5304: color: #009900;
5305: }
5306: .LC_docs_remove {
5307: color: #990000;
5308: }
5309:
5310: .LC_docs_reinit_warn,
5311: .LC_docs_ext_edit {
5312: font-size: x-small;
5313: }
5314:
5315: .LC_docs_editor td.LC_docs_entry_title,
5316: .LC_docs_editor td.LC_docs_entry_icon {
5317: background: #FFFFBB;
5318: }
5319: .LC_docs_editor td.LC_docs_entry_parameter {
5320: background: #BBBBFF;
5321: font-size: x-small;
5322: white-space: nowrap;
5323: }
5324:
5325: table.LC_docs_adddocs td,
5326: table.LC_docs_adddocs th {
5327: border: 1px solid #BBBBBB;
5328: padding: 4px;
5329: background: #DDDDDD;
5330: }
5331:
5332: table.LC_sty_begin {
5333: background: #BBFFBB;
5334: }
5335: table.LC_sty_end {
5336: background: #FFBBBB;
5337: }
5338:
5339: table.LC_double_column {
5340: border-width: 0px;
5341: border-collapse: collapse;
5342: width: 100%;
5343: padding: 2px;
5344: }
5345:
5346: table.LC_double_column tr td.LC_left_col {
5347: top: 2px;
5348: left: 2px;
5349: width: 47%;
5350: vertical-align: top;
5351: }
5352:
5353: table.LC_double_column tr td.LC_right_col {
5354: top: 2px;
5355: right: 2px;
5356: width: 47%;
5357: vertical-align: top;
5358: }
5359:
5360: span.LC_role_level {
5361: font-weight: bold;
5362: }
5363:
5364: div.LC_left_float {
5365: float: left;
5366: padding-right: 5%;
5367: padding-bottom: 4px;
5368: }
5369:
5370: div.LC_clear_float_header {
5371: padding-bottom: 2px;
5372: }
5373:
5374: div.LC_clear_float_footer {
5375: padding-top: 10px;
5376: clear: both;
5377: }
5378:
5379:
5380: div.LC_grade_select_mode {
5381: font-family: $sans;
5382: }
5383: div.LC_grade_select_mode div div {
5384: margin: 5px;
5385: }
5386: div.LC_grade_select_mode_selector {
5387: margin: 5px;
5388: float: left;
5389: }
5390: div.LC_grade_select_mode_selector_header {
5391: font: bold medium $sans;
5392: }
5393: div.LC_grade_select_mode_type {
5394: clear: left;
5395: }
5396:
5397: div.LC_grade_show_user {
5398: margin-top: 20px;
5399: border: 1px solid black;
5400: }
5401: div.LC_grade_user_name {
5402: background: #DDDDEE;
5403: border-bottom: 1px solid black;
5404: font: bold large $sans;
5405: }
5406: div.LC_grade_show_user_odd_row div.LC_grade_user_name {
5407: background: #DDEEDD;
5408: }
5409:
5410: div.LC_grade_show_problem,
5411: div.LC_grade_submissions,
5412: div.LC_grade_message_center,
5413: div.LC_grade_info_links,
5414: div.LC_grade_assign {
5415: margin: 5px;
5416: width: 99%;
5417: background: #FFFFFF;
5418: }
5419: div.LC_grade_show_problem_header,
5420: div.LC_grade_submissions_header,
5421: div.LC_grade_message_center_header,
5422: div.LC_grade_assign_header {
5423: font: bold large $sans;
5424: }
5425: div.LC_grade_show_problem_problem,
5426: div.LC_grade_submissions_body,
5427: div.LC_grade_message_center_body,
5428: div.LC_grade_assign_body {
5429: border: 1px solid black;
5430: width: 99%;
5431: background: #FFFFFF;
5432: }
5433: span.LC_grade_check_note {
5434: font: normal medium $sans;
5435: display: inline;
5436: position: absolute;
5437: right: 1em;
5438: }
5439:
5440: table.LC_scantron_action {
5441: width: 100%;
5442: }
5443: table.LC_scantron_action tr th {
5444: font: normal bold $sans;
5445: }
5446:
5447: div.LC_edit_problem_header,
5448: div.LC_edit_problem_footer {
5449: font: normal medium $sans;
5450: margin: 2px;
5451: }
5452: div.LC_edit_problem_header,
5453: div.LC_edit_problem_header div,
5454: div.LC_edit_problem_footer,
5455: div.LC_edit_problem_footer div,
5456: div.LC_edit_problem_editxml_header,
5457: div.LC_edit_problem_editxml_header div {
5458: margin-top: 5px;
5459: }
5460: div.LC_edit_problem_header_edit_row {
5461: background: $tabbg;
5462: padding: 3px;
5463: margin-bottom: 5px;
5464: }
5465: div.LC_edit_problem_header_title {
5466: font: larger bold $sans;
5467: background: $tabbg;
5468: padding: 3px;
5469: }
5470: table.LC_edit_problem_header_title {
5471: font: larger bold $sans;
5472: width: 100%;
5473: border-color: $pgbg;
5474: border-style: solid;
5475: border-width: $border;
5476:
5477: background: $tabbg;
5478: border-collapse: collapse;
5479: padding: 0px
5480: }
5481:
5482: div.LC_edit_problem_discards {
5483: float: left;
5484: padding-bottom: 5px;
5485: }
5486: div.LC_edit_problem_saves {
5487: float: right;
5488: padding-bottom: 5px;
5489: }
5490: hr.LC_edit_problem_divide {
5491: clear: both;
5492: color: $tabbg;
5493: background-color: $tabbg;
5494: height: 3px;
5495: border: 0px;
5496: }
5497: img.stift{
5498: border-width:0;
5499: vertical-align:middle;
5500: }
5501:
5502: table#LC_mainmenu{
5503: margin-top:10px;
5504: width:80%;
5505:
5506: }
5507:
5508: table#LC_mainmenu td.LC_mainmenu_col_fieldset{
5509: vertical-align: top;
5510: width: 45%;
5511: }
5512: .LC_mainmenu_fieldset_category {
5513: color: $font;
5514: background: $pgbg;
5515: font-family: $sans;
5516: font-size: small;
5517: font-weight: bold;
5518: }
5519: fieldset#LC_mainmenu_fieldset {
5520: margin:0px 10px 10px 0px;
5521:
5522: }
5523: /* ---- Remove when done ----
5524: # The following styles is part of the redesign of LON-CAPA and are
5525: # subject to change during this project.
5526: # Don't rely on their current functionality as they might be
5527: # changed or removed.
5528: # --------------------------*/
5529:
5530:
5531: body {
5532: font-family: Tahoma, Arial,Helvetica,sans-serif;
5533: font-size: 0.85em;
5534: line-height: 130%;
5535: color: RGB(45, 45, 45);
5536: }
5537:
5538: a:link,a:visited {
5539: /*color: RGB(0, 118, 127);*/
5540: /*text-decoration: underline;*/
5541: }
5542:
5543: a:hover{
5544: text-decoration:none;
5545: }
5546: /*a:hover,
5547: UL.smallMenu A:hover,
5548: UL.MenuBreadcrumbs A:hover,
5549: UL#TabMainMenuContent A:hover{
5550: color: rgb(200, 10, 50);
5551: }*/
5552:
5553: h1 {
5554: padding:5px 10px 5px 20px;
5555: line-height:130%;
5556: }
5557: h2,h4,h6 {
5558: /*color: RGB(0, 118, 127);*/
5559: }
5560: h2,h3,h4,h5,h6
5561: {
5562: margin:5px 0px 5px 0px;
5563: line-height:130%;
5564: }
5565:
5566: .right {
5567: text-align: right;
5568: }
5569:
5570: .center {
5571: text-align: center;
5572: }
5573:
5574: .left {
5575: text-align: left;
5576: }
5577:
5578:
5579: .HeadRight {
5580: text-align: right;
5581: float: right;
5582: margin: 0px;
5583: padding: 0px;
5584: right:0;
5585: position:absolute;
5586: }
5587:
5588: img {
5589: /* border: 0px; */
5590: }
5591:
5592: .personalBgColor {
5593: background: RGB(237, 239, 0) url(images/headHighlight.png) repeat-y left top;
5594: }
5595:
5596: p {
5597: padding: 10px;
5598: }
5599: DL,UL,Div,Fieldset {
5600: /*margin: 10px;*/
5601: overflow:hidden;
5602: }
5603: OL.smallMenu {
5604: margin: 0px 0px 0px 0px;
5605: }
5606:
5607: OL.smallMenu li {
5608: display: inline;
5609: padding: 5px 5px 0px 10px;
5610: vertical-align: top;
5611: }
5612:
5613: OL.smallMenu li img {
5614: vertical-align: bottom;
5615: }
5616:
5617: OL.smallMenu A {
5618: font-size: 90%;
5619: color: RGB(80, 80, 80);
5620: text-decoration: none;
5621: }
5622:
5623: OL#TabMainMenuContent {
5624:
5625: margin: 0px 0px 10px 0px;
5626: padding: 0px;
5627: }
5628:
5629: OL#TabMainMenuContent LI {
5630: display: inline;
5631: vertical-align: bottom;
5632: border-bottom: solid 1px RGB(175, 175, 175);
5633: border-right: solid 1px RGB(175, 175, 175);
5634: padding: 5px 15px 5px 15px;
5635: margin-right:4px;
5636: line-height: 140%;
5637: font-weight: bold;
5638: overflow:hidden;
5639: background: RGB(211, 206, 205) URL(images/TabMenuBG.png) repeat-x left top;
5640: }
5641:
5642: OL#TabMainMenuContent LI A {
5643: color: RGB(47, 47, 47);
5644: text-decoration: none;
5645: }
5646:
5647: OL#TabMainMenuContent DIV.columnSection {
5648: margin-bottom: 0px;
5649: }
5650:
5651: OL#MenuBreadcrumbs {
5652: border-top: solid 1px RGB(255, 255, 255);
5653: height: 20px;
5654: line-height: 20px;
5655: vertical-align: bottom;
5656: margin: 0px 0px 30px 0px;
5657: padding-left: 10px;
5658: list-style-position: inside;
5659: background: RGB(211, 206, 205) URL(images/TabMenuBG.png) repeat-x left
5660: top;
5661: }
5662:
5663: OL#MenuBreadcrumbs li {
5664: background: url(images/pfeil_white.png) no-repeat left center;
5665: display: inline;
5666: padding: 0px 0px 0px 10px;
5667: vertical-align: bottom;
5668: overflow:hidden;
5669: }
5670:
5671: OL#MenuBreadcrumbs LI A {
5672: text-decoration: none;
5673: font-size:90%;
5674: }
5675:
5676: h4.hcell {
5677: padding: 3px 10px 3px 10px;
5678: margin: 0px;
5679: background: RGB(0, 118, 127);
5680: color: white;
5681: border: outset 1px;
5682: }
5683:
5684: DIV.DivContentBoxSpecial
5685: {
5686: border: solid 1px RGB(100, 100, 100);
5687: }
5688:
5689: FIELDSET
5690: {
5691: /*width:78%;*/
5692: }
5693: DIV.DivContentBox,
5694: DIV.DivContentBoxSpecial {
5695: width: 80%;
5696: margin:10px;
5697: }
5698:
5699: FIELDSET legend,DL DT {
5700: font-weight: bold;
5701: font-size: 110%;
5702: /*padding-left: 0px;*/
5703: /* margin-left: 0px;*/
5704: }
5705:
5706: DIV.DivImportant {
5707: background: url(images/important.png) no-repeat center top;
5708: padding: 100px 10px 10px 10px;
5709: width: 200px;
5710: border: double 4px RGB(200, 200, 200);
5711: }
5712:
5713:
5714:
5715: DL.ListStyleClean DT {
5716: padding-right: 5px;
5717: display: table-header-group;
5718: }
5719:
5720: DL.ListStyleClean DD {
5721: display: table-row;
5722: }
5723:
5724: .ListStyleClean,
5725: .ListStyleSimple,
5726: .ListStyleNormal,
5727: .ListStyleNormal_Border,
5728: .ListStyleSpecial
5729: {
5730: /*display:block; */
5731: width: 400px;
5732: list-style-position: inside;
5733: list-style-type: none;
5734: overflow: hidden;
5735: padding: 0px;
5736: }
5737:
5738: .ListStyleClean li,
5739: .ListStyleSimple li,
5740: .ListStyleSimple DD,
5741: .ListStyleNormal li,
5742: .ListStyleNormal DD,
5743: .ListStyleSpecial li,
5744: .ListStyleSpecial DD
5745: {
5746: margin: 0px;
5747: padding: 5px 5px 5px 10px;
5748: clear: both;
5749: /*display:block;*/
5750: }
5751:
5752: .ListStyleClean LI,
5753: .ListStyleClean DD {
5754: padding-top: 0px;
5755: padding-bottom: 0px;
5756: }
5757:
5758: .ListStyleSimple DD,
5759: .ListStyleSimple LI{
5760: border-bottom: solid 1px RGB(150, 150, 150);
5761: }
5762:
5763: .ListStyleSpecial LI,
5764: .ListStyleSpecial DD {
5765: list-style-type: none;
5766: background-color: RGB(220, 220, 220);
5767: margin-bottom: 4px;
5768: }
5769:
5770: table.SimpleTable *{
5771: padding:10px;
5772: }
5773:
5774: table.SimpleTable td {
5775: vertical-align:top;
5776: border:solid 1px RGB(210,210,210);
5777: }
5778: table.SimpleTable thead{
5779: background:rgb(210,210,210);
5780: }
5781:
5782: DIV.columnSection {
5783: display: block;
5784: clear: both;
5785: overflow: hidden;
5786: margin:0px;
5787: }
5788:
5789: DIV.columnSection>* {
5790: float: left;
5791: margin: 10px 20px 10px 0px;
5792: overflow:hidden;
5793: }
5794:
5795: DIV.columnSection>FIELDSET,
5796: DIV.columnSection>DIV.DivContentBox,
5797: DIV.columnSection>DIV.DivContentBoxSpecial
5798: {
5799: width: 480px;
5800:
5801: }
5802:
5803:
5804: END
5805: }
5806:
5807: =pod
5808:
5809: =item * &headtag()
5810:
5811: Returns a uniform footer for LON-CAPA web pages.
5812:
5813: Inputs: $title - optional title for the head
5814: $head_extra - optional extra HTML to put inside the <head>
5815: $args - optional arguments
5816: force_register - if is true call registerurl so the remote is
5817: informed
5818: redirect -> array ref of
5819: 1- seconds before redirect occurs
5820: 2- url to redirect to
5821: 3- whether the side effect should occur
5822: (side effect of setting
5823: $env{'internal.head.redirect'} to the url
5824: redirected too)
5825: domain -> force to color decorate a page for a specific
5826: domain
5827: function -> force usage of a specific rolish color scheme
5828: bgcolor -> override the default page bgcolor
5829: no_auto_mt_title
5830: -> prevent &mt()ing the title arg
5831:
5832: =cut
5833:
5834: sub headtag {
5835: my ($title,$head_extra,$args) = @_;
5836:
5837: my $function = $args->{'function'} || &get_users_function();
5838: my $domain = $args->{'domain'} || &determinedomain();
5839: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
5840: my $url = join(':',$env{'user.name'},$env{'user.domain'},
5841: $Apache::lonnet::perlvar{'lonVersion'},
5842: #time(),
5843: $env{'environment.color.timestamp'},
5844: $function,$domain,$bgcolor);
5845:
5846: $url = '/adm/css/'.&escape($url).'.css';
5847:
5848: my $result =
5849: '<head>'.
5850: &font_settings();
5851:
5852: if (!$args->{'frameset'}) {
5853: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
5854: }
5855: if ($args->{'force_register'}) {
5856: $result .= &Apache::lonmenu::registerurl(1);
5857: }
5858: if (!$args->{'no_nav_bar'}
5859: && !$args->{'only_body'}
5860: && !$args->{'frameset'}) {
5861: $result .= &help_menu_js();
5862: }
5863:
5864: if (ref($args->{'redirect'})) {
5865: my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
5866: $url = &Apache::lonenc::check_encrypt($url);
5867: if (!$inhibit_continue) {
5868: $env{'internal.head.redirect'} = $url;
5869: }
5870: $result.=<<ADDMETA
5871: <meta http-equiv="pragma" content="no-cache" />
5872: <meta http-equiv="Refresh" content="$time; url=$url" />
5873: ADDMETA
5874: }
5875: if (!defined($title)) {
5876: $title = 'The LearningOnline Network with CAPA';
5877: }
5878: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
5879: $result .= '<title> LON-CAPA '.$title.'</title>'
5880: .'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
5881: .$head_extra;
5882: return $result;
5883: }
5884:
5885: =pod
5886:
5887: =item * &font_settings()
5888:
5889: Returns neccessary <meta> to set the proper encoding
5890:
5891: Inputs: none
5892:
5893: =cut
5894:
5895: sub font_settings {
5896: my $headerstring='';
5897: if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
5898: $headerstring.=
5899: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
5900: }
5901: return $headerstring;
5902: }
5903:
5904: =pod
5905:
5906: =item * &xml_begin()
5907:
5908: Returns the needed doctype and <html>
5909:
5910: Inputs: none
5911:
5912: =cut
5913:
5914: sub xml_begin {
5915: my $output='';
5916:
5917: if ($env{'internal.start_page'}==1) {
5918: &Apache::lonhtmlcommon::init_htmlareafields();
5919: }
5920:
5921: if ($env{'browser.mathml'}) {
5922: $output='<?xml version="1.0"?>'
5923: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
5924: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
5925:
5926: # .'<!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">] >'
5927: .'<!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">'
5928: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
5929: .'xmlns="http://www.w3.org/1999/xhtml">';
5930: } else {
5931: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
5932: }
5933: return $output;
5934: }
5935:
5936: =pod
5937:
5938: =item * &endheadtag()
5939:
5940: Returns a uniform </head> for LON-CAPA web pages.
5941:
5942: Inputs: none
5943:
5944: =cut
5945:
5946: sub endheadtag {
5947: return '</head>';
5948: }
5949:
5950: =pod
5951:
5952: =item * &head()
5953:
5954: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
5955:
5956: Inputs:
5957:
5958: =over 4
5959:
5960: $title - optional title for the page
5961:
5962: $head_extra - optional extra HTML to put inside the <head>
5963:
5964: =back
5965:
5966: =cut
5967:
5968: sub head {
5969: my ($title,$head_extra,$args) = @_;
5970: return &headtag($title,$head_extra,$args).&endheadtag();
5971: }
5972:
5973: =pod
5974:
5975: =item * &start_page()
5976:
5977: Returns a complete <html> .. <body> section for LON-CAPA web pages.
5978:
5979: Inputs:
5980:
5981: =over 4
5982:
5983: $title - optional title for the page
5984:
5985: $head_extra - optional extra HTML to incude inside the <head>
5986:
5987: $args - additional optional args supported are:
5988:
5989: =over 8
5990:
5991: only_body -> is true will set &bodytag() onlybodytag
5992: arg on
5993: no_nav_bar -> is true will set &bodytag() notopbar arg on
5994: add_entries -> additional attributes to add to the <body>
5995: domain -> force to color decorate a page for a
5996: specific domain
5997: function -> force usage of a specific rolish color
5998: scheme
5999: redirect -> see &headtag()
6000: bgcolor -> override the default page bg color
6001: js_ready -> return a string ready for being used in
6002: a javascript writeln
6003: html_encode -> return a string ready for being used in
6004: a html attribute
6005: force_register -> if is true will turn on the &bodytag()
6006: $forcereg arg
6007: body_title -> alternate text to use instead of $title
6008: in the title box that appears, this text
6009: is not auto translated like the $title is
6010: frameset -> if true will start with a <frameset>
6011: rather than <body>
6012: no_title -> if true the title bar won't be shown
6013: skip_phases -> hash ref of
6014: head -> skip the <html><head> generation
6015: body -> skip all <body> generation
6016: no_inline_link -> if true and in remote mode, don't show the
6017: 'Switch To Inline Menu' link
6018: no_auto_mt_title -> prevent &mt()ing the title arg
6019: inherit_jsmath -> when creating popup window in a page,
6020: should it have jsmath forced on by the
6021: current page
6022:
6023: =back
6024:
6025: =back
6026:
6027: =cut
6028:
6029: sub start_page {
6030: my ($title,$head_extra,$args) = @_;
6031: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
6032: my %head_args;
6033: foreach my $arg ('redirect','force_register','domain','function',
6034: 'bgcolor','frameset','no_nav_bar','only_body',
6035: 'no_auto_mt_title') {
6036: if (defined($args->{$arg})) {
6037: $head_args{$arg} = $args->{$arg};
6038: }
6039: }
6040:
6041: $env{'internal.start_page'}++;
6042: my $result;
6043: if (! exists($args->{'skip_phases'}{'head'}) ) {
6044: $result.=
6045: &xml_begin().
6046: &headtag($title,$head_extra,\%head_args).&endheadtag();
6047: }
6048:
6049: if (! exists($args->{'skip_phases'}{'body'}) ) {
6050: if ($args->{'frameset'}) {
6051: my $attr_string = &make_attr_string($args->{'force_register'},
6052: $args->{'add_entries'});
6053: $result .= "\n<frameset $attr_string>\n";
6054: } else {
6055: $result .=
6056: &bodytag($title,
6057: $args->{'function'}, $args->{'add_entries'},
6058: $args->{'only_body'}, $args->{'domain'},
6059: $args->{'force_register'}, $args->{'body_title'},
6060: $args->{'no_nav_bar'}, $args->{'bgcolor'},
6061: $args->{'no_title'}, $args->{'no_inline_link'},
6062: $args);
6063: }
6064: }
6065:
6066: if ($args->{'js_ready'}) {
6067: $result = &js_ready($result);
6068: }
6069: if ($args->{'html_encode'}) {
6070: $result = &html_encode($result);
6071: }
6072: return $result;
6073: }
6074:
6075:
6076: =pod
6077:
6078: =item * &head()
6079:
6080: Returns a complete </body></html> section for LON-CAPA web pages.
6081:
6082: Inputs: $args - additional optional args supported are:
6083: js_ready -> return a string ready for being used in
6084: a javascript writeln
6085: html_encode -> return a string ready for being used in
6086: a html attribute
6087: frameset -> if true will start with a <frameset>
6088: rather than <body>
6089: dicsussion -> if true will get discussion from
6090: lonxml::xmlend
6091: (you can pass the target and parser arguments
6092: through optional 'target' and 'parser' args
6093: to this routine)
6094:
6095: =cut
6096:
6097: sub end_page {
6098: my ($args) = @_;
6099: $env{'internal.end_page'}++;
6100: my $result;
6101: if ($args->{'discussion'}) {
6102: my ($target,$parser);
6103: if (ref($args->{'discussion'})) {
6104: ($target,$parser) =($args->{'discussion'}{'target'},
6105: $args->{'discussion'}{'parser'});
6106: }
6107: $result .= &Apache::lonxml::xmlend($target,$parser);
6108: }
6109:
6110: if ($args->{'frameset'}) {
6111: $result .= '</frameset>';
6112: } else {
6113: $result .= &endbodytag($args);
6114: }
6115: $result .= "\n</html>";
6116:
6117: if ($args->{'js_ready'}) {
6118: $result = &js_ready($result);
6119: }
6120:
6121: if ($args->{'html_encode'}) {
6122: $result = &html_encode($result);
6123: }
6124:
6125: return $result;
6126: }
6127:
6128: sub html_encode {
6129: my ($result) = @_;
6130:
6131: $result = &HTML::Entities::encode($result,'<>&"');
6132:
6133: return $result;
6134: }
6135: sub js_ready {
6136: my ($result) = @_;
6137:
6138: $result =~ s/[\n\r]/ /xmsg;
6139: $result =~ s/\\/\\\\/xmsg;
6140: $result =~ s/'/\\'/xmsg;
6141: $result =~ s{</}{<\\/}xmsg;
6142:
6143: return $result;
6144: }
6145:
6146: sub validate_page {
6147: if ( exists($env{'internal.start_page'})
6148: && $env{'internal.start_page'} > 1) {
6149: &Apache::lonnet::logthis('start_page called multiple times '.
6150: $env{'internal.start_page'}.' '.
6151: $ENV{'request.filename'});
6152: }
6153: if ( exists($env{'internal.end_page'})
6154: && $env{'internal.end_page'} > 1) {
6155: &Apache::lonnet::logthis('end_page called multiple times '.
6156: $env{'internal.end_page'}.' '.
6157: $env{'request.filename'});
6158: }
6159: if ( exists($env{'internal.start_page'})
6160: && ! exists($env{'internal.end_page'})) {
6161: &Apache::lonnet::logthis('start_page called without end_page '.
6162: $env{'request.filename'});
6163: }
6164: if ( ! exists($env{'internal.start_page'})
6165: && exists($env{'internal.end_page'})) {
6166: &Apache::lonnet::logthis('end_page called without start_page'.
6167: $env{'request.filename'});
6168: }
6169: }
6170:
6171: sub simple_error_page {
6172: my ($r,$title,$msg) = @_;
6173: my $page =
6174: &Apache::loncommon::start_page($title).
6175: &mt($msg).
6176: &Apache::loncommon::end_page();
6177: if (ref($r)) {
6178: $r->print($page);
6179: return;
6180: }
6181: return $page;
6182: }
6183:
6184: {
6185: my @row_count;
6186: sub start_data_table {
6187: my ($add_class) = @_;
6188: my $css_class = (join(' ','LC_data_table',$add_class));
6189: unshift(@row_count,0);
6190: return '<table class="'.$css_class.'">'."\n";
6191: }
6192:
6193: sub end_data_table {
6194: shift(@row_count);
6195: return '</table>'."\n";;
6196: }
6197:
6198: sub start_data_table_row {
6199: my ($add_class) = @_;
6200: $row_count[0]++;
6201: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
6202: $css_class = (join(' ',$css_class,$add_class));
6203: return '<tr class="'.$css_class.'">'."\n";;
6204: }
6205:
6206: sub continue_data_table_row {
6207: my ($add_class) = @_;
6208: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
6209: $css_class = (join(' ',$css_class,$add_class));
6210: return '<tr class="'.$css_class.'">'."\n";;
6211: }
6212:
6213: sub end_data_table_row {
6214: return '</tr>'."\n";;
6215: }
6216:
6217: sub start_data_table_empty_row {
6218: $row_count[0]++;
6219: return '<tr class="LC_empty_row" >'."\n";;
6220: }
6221:
6222: sub end_data_table_empty_row {
6223: return '</tr>'."\n";;
6224: }
6225:
6226: sub start_data_table_header_row {
6227: return '<tr class="LC_header_row">'."\n";;
6228: }
6229:
6230: sub end_data_table_header_row {
6231: return '</tr>'."\n";;
6232: }
6233: }
6234:
6235: =pod
6236:
6237: =item * &inhibit_menu_check($arg)
6238:
6239: Checks for a inhibitmenu state and generates output to preserve it
6240:
6241: Inputs: $arg - can be any of
6242: - undef - in which case the return value is a string
6243: to add into arguments list of a uri
6244: - 'input' - in which case the return value is a HTML
6245: <form> <input> field of type hidden to
6246: preserve the value
6247: - a url - in which case the return value is the url with
6248: the neccesary cgi args added to preserve the
6249: inhibitmenu state
6250: - a ref to a url - no return value, but the string is
6251: updated to include the neccessary cgi
6252: args to preserve the inhibitmenu state
6253:
6254: =cut
6255:
6256: sub inhibit_menu_check {
6257: my ($arg) = @_;
6258: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
6259: if ($arg eq 'input') {
6260: if ($env{'form.inhibitmenu'}) {
6261: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
6262: } else {
6263: return
6264: }
6265: }
6266: if ($env{'form.inhibitmenu'}) {
6267: if (ref($arg)) {
6268: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
6269: } elsif ($arg eq '') {
6270: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
6271: } else {
6272: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
6273: }
6274: }
6275: if (!ref($arg)) {
6276: return $arg;
6277: }
6278: }
6279:
6280: ###############################################
6281:
6282: =pod
6283:
6284: =back
6285:
6286: =head1 User Information Routines
6287:
6288: =over 4
6289:
6290: =item * &get_users_function()
6291:
6292: Used by &bodytag to determine the current users primary role.
6293: Returns either 'student','coordinator','admin', or 'author'.
6294:
6295: =cut
6296:
6297: ###############################################
6298: sub get_users_function {
6299: my $function = 'student';
6300: if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
6301: $function='coordinator';
6302: }
6303: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
6304: $function='admin';
6305: }
6306: if (($env{'request.role'}=~/^(au|ca)/) ||
6307: ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
6308: $function='author';
6309: }
6310: return $function;
6311: }
6312:
6313: ###############################################
6314:
6315: =pod
6316:
6317: =item * &check_user_status()
6318:
6319: Determines current status of supplied role for a
6320: specific user. Roles can be active, previous or future.
6321:
6322: Inputs:
6323: user's domain, user's username, course's domain,
6324: course's number, optional section ID.
6325:
6326: Outputs:
6327: role status: active, previous or future.
6328:
6329: =cut
6330:
6331: sub check_user_status {
6332: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
6333: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
6334: my @uroles = keys %userinfo;
6335: my $srchstr;
6336: my $active_chk = 'none';
6337: my $now = time;
6338: if (@uroles > 0) {
6339: if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
6340: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
6341: } else {
6342: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
6343: }
6344: if (grep/^\Q$srchstr\E$/,@uroles) {
6345: my $role_end = 0;
6346: my $role_start = 0;
6347: $active_chk = 'active';
6348: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
6349: $role_end = $1;
6350: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
6351: $role_start = $1;
6352: }
6353: }
6354: if ($role_start > 0) {
6355: if ($now < $role_start) {
6356: $active_chk = 'future';
6357: }
6358: }
6359: if ($role_end > 0) {
6360: if ($now > $role_end) {
6361: $active_chk = 'previous';
6362: }
6363: }
6364: }
6365: }
6366: return $active_chk;
6367: }
6368:
6369: ###############################################
6370:
6371: =pod
6372:
6373: =item * &get_sections()
6374:
6375: Determines all the sections for a course including
6376: sections with students and sections containing other roles.
6377: Incoming parameters:
6378:
6379: 1. domain
6380: 2. course number
6381: 3. reference to array containing roles for which sections should
6382: be gathered (optional).
6383: 4. reference to array containing status types for which sections
6384: should be gathered (optional).
6385:
6386: If the third argument is undefined, sections are gathered for any role.
6387: If the fourth argument is undefined, sections are gathered for any status.
6388: Permissible values are 'active' or 'future' or 'previous'.
6389:
6390: Returns section hash (keys are section IDs, values are
6391: number of users in each section), subject to the
6392: optional roles filter, optional status filter
6393:
6394: =cut
6395:
6396: ###############################################
6397: sub get_sections {
6398: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
6399: if (!defined($cdom) || !defined($cnum)) {
6400: my $cid = $env{'request.course.id'};
6401:
6402: return if (!defined($cid));
6403:
6404: $cdom = $env{'course.'.$cid.'.domain'};
6405: $cnum = $env{'course.'.$cid.'.num'};
6406: }
6407:
6408: my %sectioncount;
6409: my $now = time;
6410:
6411: if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
6412: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
6413: my $sec_index = &Apache::loncoursedata::CL_SECTION();
6414: my $status_index = &Apache::loncoursedata::CL_STATUS();
6415: my $start_index = &Apache::loncoursedata::CL_START();
6416: my $end_index = &Apache::loncoursedata::CL_END();
6417: my $status;
6418: while (my ($student,$data) = each(%$classlist)) {
6419: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
6420: $data->[$status_index],
6421: $data->[$start_index],
6422: $data->[$end_index]);
6423: if ($stu_status eq 'Active') {
6424: $status = 'active';
6425: } elsif ($end < $now) {
6426: $status = 'previous';
6427: } elsif ($start > $now) {
6428: $status = 'future';
6429: }
6430: if ($section ne '-1' && $section !~ /^\s*$/) {
6431: if ((!defined($possible_status)) || (($status ne '') &&
6432: (grep/^\Q$status\E$/,@{$possible_status}))) {
6433: $sectioncount{$section}++;
6434: }
6435: }
6436: }
6437: }
6438: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
6439: foreach my $user (sort(keys(%courseroles))) {
6440: if ($user !~ /^(\w{2})/) { next; }
6441: my ($role) = ($user =~ /^(\w{2})/);
6442: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
6443: my ($section,$status);
6444: if ($role eq 'cr' &&
6445: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
6446: $section=$1;
6447: }
6448: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
6449: if (!defined($section) || $section eq '-1') { next; }
6450: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
6451: if ($end == -1 && $start == -1) {
6452: next; #deleted role
6453: }
6454: if (!defined($possible_status)) {
6455: $sectioncount{$section}++;
6456: } else {
6457: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
6458: $status = 'active';
6459: } elsif ($end < $now) {
6460: $status = 'future';
6461: } elsif ($start > $now) {
6462: $status = 'previous';
6463: }
6464: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
6465: $sectioncount{$section}++;
6466: }
6467: }
6468: }
6469: return %sectioncount;
6470: }
6471:
6472: ###############################################
6473:
6474: =pod
6475:
6476: =item * &get_course_users()
6477:
6478: Retrieves usernames:domains for users in the specified course
6479: with specific role(s), and access status.
6480:
6481: Incoming parameters:
6482: 1. course domain
6483: 2. course number
6484: 3. access status: users must have - either active,
6485: previous, future, or all.
6486: 4. reference to array of permissible roles
6487: 5. reference to array of section restrictions (optional)
6488: 6. reference to results object (hash of hashes).
6489: 7. reference to optional userdata hash
6490: 8. reference to optional statushash
6491: 9. flag if privileged users (except those set to unhide in
6492: course settings) should be excluded
6493: Keys of top level results hash are roles.
6494: Keys of inner hashes are username:domain, with
6495: values set to access type.
6496: Optional userdata hash returns an array with arguments in the
6497: same order as loncoursedata::get_classlist() for student data.
6498:
6499: Optional statushash returns
6500:
6501: Entries for end, start, section and status are blank because
6502: of the possibility of multiple values for non-student roles.
6503:
6504: =cut
6505:
6506: ###############################################
6507:
6508: sub get_course_users {
6509: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
6510: my %idx = ();
6511: my %seclists;
6512:
6513: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
6514: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
6515: $idx{end} = &Apache::loncoursedata::CL_END();
6516: $idx{start} = &Apache::loncoursedata::CL_START();
6517: $idx{id} = &Apache::loncoursedata::CL_ID();
6518: $idx{section} = &Apache::loncoursedata::CL_SECTION();
6519: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
6520: $idx{status} = &Apache::loncoursedata::CL_STATUS();
6521:
6522: if (grep(/^st$/,@{$roles})) {
6523: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
6524: my $now = time;
6525: foreach my $student (keys(%{$classlist})) {
6526: my $match = 0;
6527: my $secmatch = 0;
6528: my $section = $$classlist{$student}[$idx{section}];
6529: my $status = $$classlist{$student}[$idx{status}];
6530: if ($section eq '') {
6531: $section = 'none';
6532: }
6533: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
6534: if (grep(/^all$/,@{$sections})) {
6535: $secmatch = 1;
6536: } elsif ($$classlist{$student}[$idx{section}] eq '') {
6537: if (grep(/^none$/,@{$sections})) {
6538: $secmatch = 1;
6539: }
6540: } else {
6541: if (grep(/^\Q$section\E$/,@{$sections})) {
6542: $secmatch = 1;
6543: }
6544: }
6545: if (!$secmatch) {
6546: next;
6547: }
6548: }
6549: if (defined($$types{'active'})) {
6550: if ($$classlist{$student}[$idx{status}] eq 'Active') {
6551: push(@{$$users{st}{$student}},'active');
6552: $match = 1;
6553: }
6554: }
6555: if (defined($$types{'previous'})) {
6556: if ($$classlist{$student}[$idx{status}] eq 'Expired') {
6557: push(@{$$users{st}{$student}},'previous');
6558: $match = 1;
6559: }
6560: }
6561: if (defined($$types{'future'})) {
6562: if ($$classlist{$student}[$idx{status}] eq 'Future') {
6563: push(@{$$users{st}{$student}},'future');
6564: $match = 1;
6565: }
6566: }
6567: if ($match) {
6568: push(@{$seclists{$student}},$section);
6569: if (ref($userdata) eq 'HASH') {
6570: $$userdata{$student} = $$classlist{$student};
6571: }
6572: if (ref($statushash) eq 'HASH') {
6573: $statushash->{$student}{'st'}{$section} = $status;
6574: }
6575: }
6576: }
6577: }
6578: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
6579: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
6580: my $now = time;
6581: my %displaystatus = ( previous => 'Expired',
6582: active => 'Active',
6583: future => 'Future',
6584: );
6585: my %nothide;
6586: if ($hidepriv) {
6587: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
6588: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
6589: if ($user !~ /:/) {
6590: $nothide{join(':',split(/[\@]/,$user))}=1;
6591: } else {
6592: $nothide{$user} = 1;
6593: }
6594: }
6595: }
6596: foreach my $person (sort(keys(%coursepersonnel))) {
6597: my $match = 0;
6598: my $secmatch = 0;
6599: my $status;
6600: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
6601: $user =~ s/:$//;
6602: my ($end,$start) = split(/:/,$coursepersonnel{$person});
6603: if ($end == -1 || $start == -1) {
6604: next;
6605: }
6606: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
6607: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
6608: my ($uname,$udom) = split(/:/,$user);
6609: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
6610: if (grep(/^all$/,@{$sections})) {
6611: $secmatch = 1;
6612: } elsif ($usec eq '') {
6613: if (grep(/^none$/,@{$sections})) {
6614: $secmatch = 1;
6615: }
6616: } else {
6617: if (grep(/^\Q$usec\E$/,@{$sections})) {
6618: $secmatch = 1;
6619: }
6620: }
6621: if (!$secmatch) {
6622: next;
6623: }
6624: }
6625: if ($usec eq '') {
6626: $usec = 'none';
6627: }
6628: if ($uname ne '' && $udom ne '') {
6629: if ($hidepriv) {
6630: if ((&Apache::lonnet::privileged($uname,$udom)) &&
6631: (!$nothide{$uname.':'.$udom})) {
6632: next;
6633: }
6634: }
6635: if ($end > 0 && $end < $now) {
6636: $status = 'previous';
6637: } elsif ($start > $now) {
6638: $status = 'future';
6639: } else {
6640: $status = 'active';
6641: }
6642: foreach my $type (keys(%{$types})) {
6643: if ($status eq $type) {
6644: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
6645: push(@{$$users{$role}{$user}},$type);
6646: }
6647: $match = 1;
6648: }
6649: }
6650: if (($match) && (ref($userdata) eq 'HASH')) {
6651: if (!exists($$userdata{$uname.':'.$udom})) {
6652: &get_user_info($udom,$uname,\%idx,$userdata);
6653: }
6654: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
6655: push(@{$seclists{$uname.':'.$udom}},$usec);
6656: }
6657: if (ref($statushash) eq 'HASH') {
6658: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
6659: }
6660: }
6661: }
6662: }
6663: }
6664: if (grep(/^ow$/,@{$roles})) {
6665: if ((defined($cdom)) && (defined($cnum))) {
6666: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
6667: if ( defined($csettings{'internal.courseowner'}) ) {
6668: my $owner = $csettings{'internal.courseowner'};
6669: next if ($owner eq '');
6670: my ($ownername,$ownerdom);
6671: if ($owner =~ /^([^:]+):([^:]+)$/) {
6672: $ownername = $1;
6673: $ownerdom = $2;
6674: } else {
6675: $ownername = $owner;
6676: $ownerdom = $cdom;
6677: $owner = $ownername.':'.$ownerdom;
6678: }
6679: @{$$users{'ow'}{$owner}} = 'any';
6680: if (defined($userdata) &&
6681: !exists($$userdata{$owner})) {
6682: &get_user_info($ownerdom,$ownername,\%idx,$userdata);
6683: if (!grep(/^none$/,@{$seclists{$owner}})) {
6684: push(@{$seclists{$owner}},'none');
6685: }
6686: if (ref($statushash) eq 'HASH') {
6687: $statushash->{$owner}{'ow'}{'none'} = 'Any';
6688: }
6689: }
6690: }
6691: }
6692: }
6693: foreach my $user (keys(%seclists)) {
6694: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
6695: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
6696: }
6697: }
6698: return;
6699: }
6700:
6701: sub get_user_info {
6702: my ($udom,$uname,$idx,$userdata) = @_;
6703: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
6704: &plainname($uname,$udom,'lastname');
6705: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
6706: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
6707: my %idhash = &Apache::lonnet::idrget($udom,($uname));
6708: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname};
6709: return;
6710: }
6711:
6712: ###############################################
6713:
6714: =pod
6715:
6716: =item * &get_user_quota()
6717:
6718: Retrieves quota assigned for storage of portfolio files for a user
6719:
6720: Incoming parameters:
6721: 1. user's username
6722: 2. user's domain
6723:
6724: Returns:
6725: 1. Disk quota (in Mb) assigned to student.
6726: 2. (Optional) Type of setting: custom or default
6727: (individually assigned or default for user's
6728: institutional status).
6729: 3. (Optional) - User's institutional status (e.g., faculty, staff
6730: or student - types as defined in localenroll::inst_usertypes
6731: for user's domain, which determines default quota for user.
6732: 4. (Optional) - Default quota which would apply to the user.
6733:
6734: If a value has been stored in the user's environment,
6735: it will return that, otherwise it returns the maximal default
6736: defined for the user's instituional status(es) in the domain.
6737:
6738: =cut
6739:
6740: ###############################################
6741:
6742:
6743: sub get_user_quota {
6744: my ($uname,$udom) = @_;
6745: my ($quota,$quotatype,$settingstatus,$defquota);
6746: if (!defined($udom)) {
6747: $udom = $env{'user.domain'};
6748: }
6749: if (!defined($uname)) {
6750: $uname = $env{'user.name'};
6751: }
6752: if (($udom eq '' || $uname eq '') ||
6753: ($udom eq 'public') && ($uname eq 'public')) {
6754: $quota = 0;
6755: $quotatype = 'default';
6756: $defquota = 0;
6757: } else {
6758: my $inststatus;
6759: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
6760: $quota = $env{'environment.portfolioquota'};
6761: $inststatus = $env{'environment.inststatus'};
6762: } else {
6763: my %userenv =
6764: &Apache::lonnet::get('environment',['portfolioquota',
6765: 'inststatus'],$udom,$uname);
6766: my ($tmp) = keys(%userenv);
6767: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
6768: $quota = $userenv{'portfolioquota'};
6769: $inststatus = $userenv{'inststatus'};
6770: } else {
6771: undef(%userenv);
6772: }
6773: }
6774: ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
6775: if ($quota eq '') {
6776: $quota = $defquota;
6777: $quotatype = 'default';
6778: } else {
6779: $quotatype = 'custom';
6780: }
6781: }
6782: if (wantarray) {
6783: return ($quota,$quotatype,$settingstatus,$defquota);
6784: } else {
6785: return $quota;
6786: }
6787: }
6788:
6789: ###############################################
6790:
6791: =pod
6792:
6793: =item * &default_quota()
6794:
6795: Retrieves default quota assigned for storage of user portfolio files,
6796: given an (optional) user's institutional status.
6797:
6798: Incoming parameters:
6799: 1. domain
6800: 2. (Optional) institutional status(es). This is a : separated list of
6801: status types (e.g., faculty, staff, student etc.)
6802: which apply to the user for whom the default is being retrieved.
6803: If the institutional status string in undefined, the domain
6804: default quota will be returned.
6805:
6806: Returns:
6807: 1. Default disk quota (in Mb) for user portfolios in the domain.
6808: 2. (Optional) institutional type which determined the value of the
6809: default quota.
6810:
6811: If a value has been stored in the domain's configuration db,
6812: it will return that, otherwise it returns 20 (for backwards
6813: compatibility with domains which have not set up a configuration
6814: db file; the original statically defined portfolio quota was 20 Mb).
6815:
6816: If the user's status includes multiple types (e.g., staff and student),
6817: the largest default quota which applies to the user determines the
6818: default quota returned.
6819:
6820: =cut
6821:
6822: ###############################################
6823:
6824:
6825: sub default_quota {
6826: my ($udom,$inststatus) = @_;
6827: my ($defquota,$settingstatus);
6828: my %quotahash = &Apache::lonnet::get_dom('configuration',
6829: ['quotas'],$udom);
6830: if (ref($quotahash{'quotas'}) eq 'HASH') {
6831: if ($inststatus ne '') {
6832: my @statuses = split(/:/,$inststatus);
6833: foreach my $item (@statuses) {
6834: if ($quotahash{'quotas'}{$item} ne '') {
6835: if ($defquota eq '') {
6836: $defquota = $quotahash{'quotas'}{$item};
6837: $settingstatus = $item;
6838: } elsif ($quotahash{'quotas'}{$item} > $defquota) {
6839: $defquota = $quotahash{'quotas'}{$item};
6840: $settingstatus = $item;
6841: }
6842: }
6843: }
6844: }
6845: if ($defquota eq '') {
6846: $defquota = $quotahash{'quotas'}{'default'};
6847: $settingstatus = 'default';
6848: }
6849: } else {
6850: $settingstatus = 'default';
6851: $defquota = 20;
6852: }
6853: if (wantarray) {
6854: return ($defquota,$settingstatus);
6855: } else {
6856: return $defquota;
6857: }
6858: }
6859:
6860: sub get_secgrprole_info {
6861: my ($cdom,$cnum,$needroles,$type) = @_;
6862: my %sections_count = &get_sections($cdom,$cnum);
6863: my @sections = (sort {$a <=> $b} keys(%sections_count));
6864: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
6865: my @groups = sort(keys(%curr_groups));
6866: my $allroles = [];
6867: my $rolehash;
6868: my $accesshash = {
6869: active => 'Currently has access',
6870: future => 'Will have future access',
6871: previous => 'Previously had access',
6872: };
6873: if ($needroles) {
6874: $rolehash = {'all' => 'all'};
6875: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
6876: if (&Apache::lonnet::error(%user_roles)) {
6877: undef(%user_roles);
6878: }
6879: foreach my $item (keys(%user_roles)) {
6880: my ($role)=split(/\:/,$item,2);
6881: if ($role eq 'cr') { next; }
6882: if ($role =~ /^cr/) {
6883: $$rolehash{$role} = (split('/',$role))[3];
6884: } else {
6885: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
6886: }
6887: }
6888: foreach my $key (sort(keys(%{$rolehash}))) {
6889: push(@{$allroles},$key);
6890: }
6891: push (@{$allroles},'st');
6892: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
6893: }
6894: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
6895: }
6896:
6897: sub user_picker {
6898: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
6899: my $currdom = $dom;
6900: my %curr_selected = (
6901: srchin => 'dom',
6902: srchby => 'lastname',
6903: );
6904: my $srchterm;
6905: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
6906: if ($srch->{'srchby'} ne '') {
6907: $curr_selected{'srchby'} = $srch->{'srchby'};
6908: }
6909: if ($srch->{'srchin'} ne '') {
6910: $curr_selected{'srchin'} = $srch->{'srchin'};
6911: }
6912: if ($srch->{'srchtype'} ne '') {
6913: $curr_selected{'srchtype'} = $srch->{'srchtype'};
6914: }
6915: if ($srch->{'srchdomain'} ne '') {
6916: $currdom = $srch->{'srchdomain'};
6917: }
6918: $srchterm = $srch->{'srchterm'};
6919: }
6920: my %lt=&Apache::lonlocal::texthash(
6921: 'usr' => 'Search criteria',
6922: 'doma' => 'Domain/institution to search',
6923: 'uname' => 'username',
6924: 'lastname' => 'last name',
6925: 'lastfirst' => 'last name, first name',
6926: 'crs' => 'in this course',
6927: 'dom' => 'in selected LON-CAPA domain',
6928: 'alc' => 'all LON-CAPA',
6929: 'instd' => 'in institutional directory for selected domain',
6930: 'exact' => 'is',
6931: 'contains' => 'contains',
6932: 'begins' => 'begins with',
6933: 'youm' => "You must include some text to search for.",
6934: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
6935: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
6936: 'yomc' => "You must choose a domain when using an institutional directory search.",
6937: 'ymcd' => "You must choose a domain when using a domain search.",
6938: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.",
6939: 'whse' => "When searching by last,first you must include at least one character in the first name.",
6940: 'thfo' => "The following need to be corrected before the search can be run:",
6941: );
6942: my $domform = &select_dom_form($currdom,'srchdomain',1,1);
6943: my $srchinsel = ' <select name="srchin">';
6944:
6945: my @srchins = ('crs','dom','alc','instd');
6946:
6947: foreach my $option (@srchins) {
6948: # FIXME 'alc' option unavailable until
6949: # loncreateuser::print_user_query_page()
6950: # has been completed.
6951: next if ($option eq 'alc');
6952: next if ($option eq 'crs' && !$env{'request.course.id'});
6953: if ($curr_selected{'srchin'} eq $option) {
6954: $srchinsel .= '
6955: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
6956: } else {
6957: $srchinsel .= '
6958: <option value="'.$option.'">'.$lt{$option}.'</option>';
6959: }
6960: }
6961: $srchinsel .= "\n </select>\n";
6962:
6963: my $srchbysel = ' <select name="srchby">';
6964: foreach my $option ('lastname','lastfirst','uname') {
6965: if ($curr_selected{'srchby'} eq $option) {
6966: $srchbysel .= '
6967: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
6968: } else {
6969: $srchbysel .= '
6970: <option value="'.$option.'">'.$lt{$option}.'</option>';
6971: }
6972: }
6973: $srchbysel .= "\n </select>\n";
6974:
6975: my $srchtypesel = ' <select name="srchtype">';
6976: foreach my $option ('begins','contains','exact') {
6977: if ($curr_selected{'srchtype'} eq $option) {
6978: $srchtypesel .= '
6979: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
6980: } else {
6981: $srchtypesel .= '
6982: <option value="'.$option.'">'.$lt{$option}.'</option>';
6983: }
6984: }
6985: $srchtypesel .= "\n </select>\n";
6986:
6987: my ($newuserscript,$new_user_create);
6988:
6989: if ($forcenewuser) {
6990: if (ref($srch) eq 'HASH') {
6991: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
6992: if ($cancreate) {
6993: $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>';
6994: } else {
6995: my $helplink = ' href="javascript:helpMenu('."'display'".')"';
6996: my %usertypetext = (
6997: official => 'institutional',
6998: unofficial => 'non-institutional',
6999: );
7000: $new_user_create = '<br /><span class="LC_warning">'.&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.").' '.&mt('Contact the <a[_1]>helpdesk</a> for assistance.',$helplink).'</span><br /><br />';
7001: }
7002: }
7003: }
7004:
7005: $newuserscript = <<"ENDSCRIPT";
7006:
7007: function setSearch(createnew,callingForm) {
7008: if (createnew == 1) {
7009: for (var i=0; i<callingForm.srchby.length; i++) {
7010: if (callingForm.srchby.options[i].value == 'uname') {
7011: callingForm.srchby.selectedIndex = i;
7012: }
7013: }
7014: for (var i=0; i<callingForm.srchin.length; i++) {
7015: if ( callingForm.srchin.options[i].value == 'dom') {
7016: callingForm.srchin.selectedIndex = i;
7017: }
7018: }
7019: for (var i=0; i<callingForm.srchtype.length; i++) {
7020: if (callingForm.srchtype.options[i].value == 'exact') {
7021: callingForm.srchtype.selectedIndex = i;
7022: }
7023: }
7024: for (var i=0; i<callingForm.srchdomain.length; i++) {
7025: if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
7026: callingForm.srchdomain.selectedIndex = i;
7027: }
7028: }
7029: }
7030: }
7031: ENDSCRIPT
7032:
7033: }
7034:
7035: my $output = <<"END_BLOCK";
7036: <script type="text/javascript">
7037: function validateEntry(callingForm) {
7038:
7039: var checkok = 1;
7040: var srchin;
7041: for (var i=0; i<callingForm.srchin.length; i++) {
7042: if ( callingForm.srchin[i].checked ) {
7043: srchin = callingForm.srchin[i].value;
7044: }
7045: }
7046:
7047: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
7048: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
7049: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
7050: var srchterm = callingForm.srchterm.value;
7051: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
7052: var msg = "";
7053:
7054: if (srchterm == "") {
7055: checkok = 0;
7056: msg += "$lt{'youm'}\\n";
7057: }
7058:
7059: if (srchtype== 'begins') {
7060: if (srchterm.length < 2) {
7061: checkok = 0;
7062: msg += "$lt{'thte'}\\n";
7063: }
7064: }
7065:
7066: if (srchtype== 'contains') {
7067: if (srchterm.length < 3) {
7068: checkok = 0;
7069: msg += "$lt{'thet'}\\n";
7070: }
7071: }
7072: if (srchin == 'instd') {
7073: if (srchdomain == '') {
7074: checkok = 0;
7075: msg += "$lt{'yomc'}\\n";
7076: }
7077: }
7078: if (srchin == 'dom') {
7079: if (srchdomain == '') {
7080: checkok = 0;
7081: msg += "$lt{'ymcd'}\\n";
7082: }
7083: }
7084: if (srchby == 'lastfirst') {
7085: if (srchterm.indexOf(",") == -1) {
7086: checkok = 0;
7087: msg += "$lt{'whus'}\\n";
7088: }
7089: if (srchterm.indexOf(",") == srchterm.length -1) {
7090: checkok = 0;
7091: msg += "$lt{'whse'}\\n";
7092: }
7093: }
7094: if (checkok == 0) {
7095: alert("$lt{'thfo'}\\n"+msg);
7096: return;
7097: }
7098: if (checkok == 1) {
7099: callingForm.submit();
7100: }
7101: }
7102:
7103: $newuserscript
7104:
7105: </script>
7106:
7107: $new_user_create
7108:
7109: <table>
7110: <tr>
7111: <td>$lt{'doma'}:</td>
7112: <td>$domform</td>
7113: </td>
7114: </tr>
7115: <tr>
7116: <td>$lt{'usr'}:</td>
7117: <td>$srchbysel
7118: $srchtypesel
7119: <input type="text" size="15" name="srchterm" value="$srchterm" />
7120: $srchinsel
7121: </td>
7122: </tr>
7123: </table>
7124: <br />
7125: END_BLOCK
7126:
7127: return $output;
7128: }
7129:
7130: sub user_rule_check {
7131: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
7132: my $response;
7133: if (ref($usershash) eq 'HASH') {
7134: foreach my $user (keys(%{$usershash})) {
7135: my ($uname,$udom) = split(/:/,$user);
7136: next if ($udom eq '' || $uname eq '');
7137: my ($id,$newuser);
7138: if (ref($usershash->{$user}) eq 'HASH') {
7139: $newuser = $usershash->{$user}->{'newuser'};
7140: $id = $usershash->{$user}->{'id'};
7141: }
7142: my $inst_response;
7143: if (ref($checks) eq 'HASH') {
7144: if (defined($checks->{'username'})) {
7145: ($inst_response,%{$inst_results->{$user}}) =
7146: &Apache::lonnet::get_instuser($udom,$uname);
7147: } elsif (defined($checks->{'id'})) {
7148: ($inst_response,%{$inst_results->{$user}}) =
7149: &Apache::lonnet::get_instuser($udom,undef,$id);
7150: }
7151: } else {
7152: ($inst_response,%{$inst_results->{$user}}) =
7153: &Apache::lonnet::get_instuser($udom,$uname);
7154: return;
7155: }
7156: if (!$got_rules->{$udom}) {
7157: my %domconfig = &Apache::lonnet::get_dom('configuration',
7158: ['usercreation'],$udom);
7159: if (ref($domconfig{'usercreation'}) eq 'HASH') {
7160: foreach my $item ('username','id') {
7161: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
7162: $$curr_rules{$udom}{$item} =
7163: $domconfig{'usercreation'}{$item.'_rule'};
7164: }
7165: }
7166: }
7167: $got_rules->{$udom} = 1;
7168: }
7169: foreach my $item (keys(%{$checks})) {
7170: if (ref($$curr_rules{$udom}) eq 'HASH') {
7171: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
7172: if (@{$$curr_rules{$udom}{$item}} > 0) {
7173: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
7174: foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
7175: if ($rule_check{$rule}) {
7176: $$rulematch{$user}{$item} = $rule;
7177: if ($inst_response eq 'ok') {
7178: if (ref($inst_results) eq 'HASH') {
7179: if (ref($inst_results->{$user}) eq 'HASH') {
7180: if (keys(%{$inst_results->{$user}}) == 0) {
7181: $$alerts{$item}{$udom}{$uname} = 1;
7182: }
7183: }
7184: }
7185: }
7186: last;
7187: }
7188: }
7189: }
7190: }
7191: }
7192: }
7193: }
7194: }
7195: return;
7196: }
7197:
7198: sub user_rule_formats {
7199: my ($domain,$domdesc,$curr_rules,$check) = @_;
7200: my %text = (
7201: 'username' => 'Usernames',
7202: 'id' => 'IDs',
7203: );
7204: my $output;
7205: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
7206: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
7207: if (@{$ruleorder} > 0) {
7208: $output = '<br />'.&mt("$text{$check} with the following format(s) may <span class=\"LC_cusr_emph\">only</span> be used for verified users at [_1]:",$domdesc).' <ul>';
7209: foreach my $rule (@{$ruleorder}) {
7210: if (ref($curr_rules) eq 'ARRAY') {
7211: if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
7212: if (ref($rules->{$rule}) eq 'HASH') {
7213: $output .= '<li>'.$rules->{$rule}{'name'}.': '.
7214: $rules->{$rule}{'desc'}.'</li>';
7215: }
7216: }
7217: }
7218: }
7219: $output .= '</ul>';
7220: }
7221: }
7222: return $output;
7223: }
7224:
7225: sub instrule_disallow_msg {
7226: my ($checkitem,$domdesc,$count,$mode) = @_;
7227: my $response;
7228: my %text = (
7229: item => 'username',
7230: items => 'usernames',
7231: match => 'matches',
7232: do => 'does',
7233: action => 'a username',
7234: one => 'one',
7235: );
7236: if ($count > 1) {
7237: $text{'item'} = 'usernames';
7238: $text{'match'} ='match';
7239: $text{'do'} = 'do';
7240: $text{'action'} = 'usernames',
7241: $text{'one'} = 'ones';
7242: }
7243: if ($checkitem eq 'id') {
7244: $text{'items'} = 'IDs';
7245: $text{'item'} = 'ID';
7246: $text{'action'} = 'an ID';
7247: if ($count > 1) {
7248: $text{'item'} = 'IDs';
7249: $text{'action'} = 'IDs';
7250: }
7251: }
7252: $response = &mt("The $text{'item'} you chose $text{'match'} the format of $text{'items'} defined for [_1], but the $text{'item'} $text{'do'} not exist in the institutional directory.",'<span class="LC_cusr_emph">'.$domdesc.'</span>').'<br />';
7253: if ($mode eq 'upload') {
7254: if ($checkitem eq 'username') {
7255: $response .= &mt("You will need to modify your upload file so it will include $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
7256: } elsif ($checkitem eq 'id') {
7257: $response .= &mt("Either upload a file which includes $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or when associating fields with data columns, omit an association for the Student/Employee ID field.");
7258: }
7259: } elsif ($mode eq 'selfcreate') {
7260: if ($checkitem eq 'id') {
7261: $response .= &mt("You must either choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or leave the ID field blank.");
7262: }
7263: } else {
7264: if ($checkitem eq 'username') {
7265: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
7266: } elsif ($checkitem eq 'id') {
7267: $response .= &mt("You must either choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or leave the ID field blank.");
7268: }
7269: }
7270: return $response;
7271: }
7272:
7273: sub personal_data_fieldtitles {
7274: my %fieldtitles = &Apache::lonlocal::texthash (
7275: id => 'Student/Employee ID',
7276: permanentemail => 'E-mail address',
7277: lastname => 'Last Name',
7278: firstname => 'First Name',
7279: middlename => 'Middle Name',
7280: generation => 'Generation',
7281: gen => 'Generation',
7282: );
7283: return %fieldtitles;
7284: }
7285:
7286: sub sorted_inst_types {
7287: my ($dom) = @_;
7288: my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
7289: my $othertitle = &mt('All users');
7290: if ($env{'request.course.id'}) {
7291: $othertitle = &mt('Any users');
7292: }
7293: my @types;
7294: if (ref($order) eq 'ARRAY') {
7295: @types = @{$order};
7296: }
7297: if (@types == 0) {
7298: if (ref($usertypes) eq 'HASH') {
7299: @types = sort(keys(%{$usertypes}));
7300: }
7301: }
7302: if (keys(%{$usertypes}) > 0) {
7303: $othertitle = &mt('Other users');
7304: }
7305: return ($othertitle,$usertypes,\@types);
7306: }
7307:
7308: sub get_institutional_codes {
7309: my ($settings,$allcourses,$LC_code) = @_;
7310: # Get complete list of course sections to update
7311: my @currsections = ();
7312: my @currxlists = ();
7313: my $coursecode = $$settings{'internal.coursecode'};
7314:
7315: if ($$settings{'internal.sectionnums'} ne '') {
7316: @currsections = split(/,/,$$settings{'internal.sectionnums'});
7317: }
7318:
7319: if ($$settings{'internal.crosslistings'} ne '') {
7320: @currxlists = split(/,/,$$settings{'internal.crosslistings'});
7321: }
7322:
7323: if (@currxlists > 0) {
7324: foreach (@currxlists) {
7325: if (m/^([^:]+):(\w*)$/) {
7326: unless (grep/^$1$/,@{$allcourses}) {
7327: push @{$allcourses},$1;
7328: $$LC_code{$1} = $2;
7329: }
7330: }
7331: }
7332: }
7333:
7334: if (@currsections > 0) {
7335: foreach (@currsections) {
7336: if (m/^(\w+):(\w*)$/) {
7337: my $sec = $coursecode.$1;
7338: my $lc_sec = $2;
7339: unless (grep/^$sec$/,@{$allcourses}) {
7340: push @{$allcourses},$sec;
7341: $$LC_code{$sec} = $lc_sec;
7342: }
7343: }
7344: }
7345: }
7346: return;
7347: }
7348:
7349: =pod
7350:
7351: =back
7352:
7353: =head1 HTTP Helpers
7354:
7355: =over 4
7356:
7357: =item * &get_unprocessed_cgi($query,$possible_names)
7358:
7359: Modify the %env hash to contain unprocessed CGI form parameters held in
7360: $query. The parameters listed in $possible_names (an array reference),
7361: will be set in $env{'form.name'} if they do not already exist.
7362:
7363: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
7364: $possible_names is an ref to an array of form element names. As an example:
7365: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
7366: will result in $env{'form.uname'} and $env{'form.udom'} being set.
7367:
7368: =cut
7369:
7370: sub get_unprocessed_cgi {
7371: my ($query,$possible_names)= @_;
7372: # $Apache::lonxml::debug=1;
7373: foreach my $pair (split(/&/,$query)) {
7374: my ($name, $value) = split(/=/,$pair);
7375: $name = &unescape($name);
7376: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
7377: $value =~ tr/+/ /;
7378: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
7379: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
7380: }
7381: }
7382: }
7383:
7384: =pod
7385:
7386: =item * &cacheheader()
7387:
7388: returns cache-controlling header code
7389:
7390: =cut
7391:
7392: sub cacheheader {
7393: unless ($env{'request.method'} eq 'GET') { return ''; }
7394: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
7395: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
7396: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
7397: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
7398: return $output;
7399: }
7400:
7401: =pod
7402:
7403: =item * &no_cache($r)
7404:
7405: specifies header code to not have cache
7406:
7407: =cut
7408:
7409: sub no_cache {
7410: my ($r) = @_;
7411: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
7412: $env{'request.method'} ne 'GET') { return ''; }
7413: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
7414: $r->no_cache(1);
7415: $r->header_out("Expires" => $date);
7416: $r->header_out("Pragma" => "no-cache");
7417: }
7418:
7419: sub content_type {
7420: my ($r,$type,$charset) = @_;
7421: if ($r) {
7422: # Note that printout.pl calls this with undef for $r.
7423: &no_cache($r);
7424: }
7425: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
7426: unless ($charset) {
7427: $charset=&Apache::lonlocal::current_encoding;
7428: }
7429: if ($charset) { $type.='; charset='.$charset; }
7430: if ($r) {
7431: $r->content_type($type);
7432: } else {
7433: print("Content-type: $type\n\n");
7434: }
7435: }
7436:
7437: =pod
7438:
7439: =item * &add_to_env($name,$value)
7440:
7441: adds $name to the %env hash with value
7442: $value, if $name already exists, the entry is converted to an array
7443: reference and $value is added to the array.
7444:
7445: =cut
7446:
7447: sub add_to_env {
7448: my ($name,$value)=@_;
7449: if (defined($env{$name})) {
7450: if (ref($env{$name})) {
7451: #already have multiple values
7452: push(@{ $env{$name} },$value);
7453: } else {
7454: #first time seeing multiple values, convert hash entry to an arrayref
7455: my $first=$env{$name};
7456: undef($env{$name});
7457: push(@{ $env{$name} },$first,$value);
7458: }
7459: } else {
7460: $env{$name}=$value;
7461: }
7462: }
7463:
7464: =pod
7465:
7466: =item * &get_env_multiple($name)
7467:
7468: gets $name from the %env hash, it seemlessly handles the cases where multiple
7469: values may be defined and end up as an array ref.
7470:
7471: returns an array of values
7472:
7473: =cut
7474:
7475: sub get_env_multiple {
7476: my ($name) = @_;
7477: my @values;
7478: if (defined($env{$name})) {
7479: # exists is it an array
7480: if (ref($env{$name})) {
7481: @values=@{ $env{$name} };
7482: } else {
7483: $values[0]=$env{$name};
7484: }
7485: }
7486: return(@values);
7487: }
7488:
7489: sub ask_for_embedded_content {
7490: my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
7491: my $upload_output = '
7492: <form name="upload_embedded" action="'.$actionurl.'"
7493: method="post" enctype="multipart/form-data">';
7494: $upload_output .= $state;
7495: $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
7496:
7497: my $num = 0;
7498: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
7499: $upload_output .= &start_data_table_row().
7500: '<td>'.$embed_file.'</td><td>';
7501: if ($args->{'ignore_remote_references'}
7502: && $embed_file =~ m{^\w+://}) {
7503: $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
7504: } elsif ($args->{'error_on_invalid_names'}
7505: && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
7506:
7507: $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
7508:
7509: } else {
7510: $upload_output .='
7511: <input name="embedded_item_'.$num.'" type="file" value="" />
7512: <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
7513: my $attrib = join(':',@{$$allfiles{$embed_file}});
7514: $upload_output .=
7515: "\n\t\t".
7516: '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
7517: $attrib.'" />';
7518: if (exists($$codebase{$embed_file})) {
7519: $upload_output .=
7520: "\n\t\t".
7521: '<input name="codebase_'.$num.'" type="hidden" value="'.
7522: &escape($$codebase{$embed_file}).'" />';
7523: }
7524: }
7525: $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
7526: $num++;
7527: }
7528: $upload_output .= &Apache::loncommon::end_data_table().'<br />
7529: <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
7530: <input type ="submit" value="'.&mt('Upload Listed Files').'" />
7531: '.&mt('(only files for which a location has been provided will be uploaded)').'
7532: </form>';
7533: return $upload_output;
7534: }
7535:
7536: sub upload_embedded {
7537: my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
7538: $current_disk_usage) = @_;
7539: my $output;
7540: for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
7541: next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
7542: my $orig_uploaded_filename =
7543: $env{'form.embedded_item_'.$i.'.filename'};
7544:
7545: $env{'form.embedded_orig_'.$i} =
7546: &unescape($env{'form.embedded_orig_'.$i});
7547: my ($path,$fname) =
7548: ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
7549: # no path, whole string is fname
7550: if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
7551:
7552: $path = $env{'form.currentpath'}.$path;
7553: $fname = &Apache::lonnet::clean_filename($fname);
7554: # See if there is anything left
7555: next if ($fname eq '');
7556:
7557: # Check if file already exists as a file or directory.
7558: my ($state,$msg);
7559: if ($context eq 'portfolio') {
7560: my $port_path = $dirpath;
7561: if ($group ne '') {
7562: $port_path = "groups/$group/$port_path";
7563: }
7564: ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
7565: $dir_root,$port_path,$disk_quota,
7566: $current_disk_usage,$uname,$udom);
7567: if ($state eq 'will_exceed_quota'
7568: || $state eq 'file_locked'
7569: || $state eq 'file_exists' ) {
7570: $output .= $msg;
7571: next;
7572: }
7573: } elsif (($context eq 'author') || ($context eq 'testbank')) {
7574: ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
7575: if ($state eq 'exists') {
7576: $output .= $msg;
7577: next;
7578: }
7579: }
7580: # Check if extension is valid
7581: if (($fname =~ /\.(\w+)$/) &&
7582: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
7583: $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
7584: next;
7585: } elsif (($fname =~ /\.(\w+)$/) &&
7586: (!defined(&Apache::loncommon::fileembstyle($1)))) {
7587: $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
7588: next;
7589: } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
7590: $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
7591: next;
7592: }
7593:
7594: $env{'form.embedded_item_'.$i.'.filename'}=$fname;
7595: if ($context eq 'portfolio') {
7596: my $result=
7597: &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
7598: $dirpath.$path);
7599: if ($result !~ m|^/uploaded/|) {
7600: $output .= '<span class="LC_error">'
7601: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
7602: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
7603: .'</span><br />';
7604: next;
7605: } else {
7606: $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
7607: $path.$fname.'</span>').'</p>';
7608: }
7609: } else {
7610: # Save the file
7611: my $target = $env{'form.embedded_item_'.$i};
7612: my $fullpath = $dir_root.$dirpath.'/'.$path;
7613: my $dest = $fullpath.$fname;
7614: my $url = $url_root.$dirpath.'/'.$path.$fname;
7615: my @parts=split(/\//,$fullpath);
7616: my $count;
7617: my $filepath = $dir_root;
7618: for ($count=4;$count<=$#parts;$count++) {
7619: $filepath .= "/$parts[$count]";
7620: if ((-e $filepath)!=1) {
7621: mkdir($filepath,0770);
7622: }
7623: }
7624: my $fh;
7625: if (!open($fh,'>'.$dest)) {
7626: &Apache::lonnet::logthis('Failed to create '.$dest);
7627: $output .= '<span class="LC_error">'.
7628: &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
7629: '</span><br />';
7630: } else {
7631: if (!print $fh $env{'form.embedded_item_'.$i}) {
7632: &Apache::lonnet::logthis('Failed to write to '.$dest);
7633: $output .= '<span class="LC_error">'.
7634: &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
7635: '</span><br />';
7636: } else {
7637: if ($context eq 'testbank') {
7638: $output .= &mt('Embedded file uploaded successfully:').
7639: ' <a href="'.$url.'">'.
7640: $orig_uploaded_filename.'</a><br />';
7641: } else {
7642: $output .= '<font size="+2">'.
7643: &mt('View embedded file: [_1]','<a href="'.$url.'">'.
7644: $orig_uploaded_filename.'</a>').'</font><br />';
7645: }
7646: }
7647: close($fh);
7648: }
7649: }
7650: }
7651: return $output;
7652: }
7653:
7654: sub check_for_existing {
7655: my ($path,$fname,$element) = @_;
7656: my ($state,$msg);
7657: if (-d $path.'/'.$fname) {
7658: $state = 'exists';
7659: $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
7660: } elsif (-e $path.'/'.$fname) {
7661: $state = 'exists';
7662: $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
7663: }
7664: if ($state eq 'exists') {
7665: $msg = '<span class="LC_error">'.$msg.'</span><br />';
7666: }
7667: return ($state,$msg);
7668: }
7669:
7670: sub check_for_upload {
7671: my ($path,$fname,$group,$element,$portfolio_root,$port_path,
7672: $disk_quota,$current_disk_usage,$uname,$udom) = @_;
7673: my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
7674: my $getpropath = 1;
7675: my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
7676: $getpropath);
7677: my $found_file = 0;
7678: my $locked_file = 0;
7679: foreach my $line (@dir_list) {
7680: my ($file_name)=split(/\&/,$line,2);
7681: if ($file_name eq $fname){
7682: $file_name = $path.$file_name;
7683: if ($group ne '') {
7684: $file_name = $group.$file_name;
7685: }
7686: $found_file = 1;
7687: if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
7688: $locked_file = 1;
7689: }
7690: }
7691: }
7692: if (($current_disk_usage + $filesize) > $disk_quota){
7693: my $msg = '<span class="LC_error">'.
7694: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
7695: '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
7696: return ('will_exceed_quota',$msg);
7697: } elsif ($found_file) {
7698: if ($locked_file) {
7699: my $msg = '<span class="LC_error">';
7700: $msg .= &mt('Unable to upload [_1]. A locked file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>','<span class="LC_filename">'.$port_path.$env{'form.currentpath'}.'</span>');
7701: $msg .= '</span><br />';
7702: $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
7703: return ('file_locked',$msg);
7704: } else {
7705: my $msg = '<span class="LC_error">';
7706: $msg .= &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
7707: $msg .= '</span>';
7708: $msg .= '<br />';
7709: $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
7710: return ('file_exists',$msg);
7711: }
7712: }
7713: }
7714:
7715:
7716: =pod
7717:
7718: =back
7719:
7720: =head1 CSV Upload/Handling functions
7721:
7722: =over 4
7723:
7724: =item * &upfile_store($r)
7725:
7726: Store uploaded file, $r should be the HTTP Request object,
7727: needs $env{'form.upfile'}
7728: returns $datatoken to be put into hidden field
7729:
7730: =cut
7731:
7732: sub upfile_store {
7733: my $r=shift;
7734: $env{'form.upfile'}=~s/\r/\n/gs;
7735: $env{'form.upfile'}=~s/\f/\n/gs;
7736: $env{'form.upfile'}=~s/\n+/\n/gs;
7737: $env{'form.upfile'}=~s/\n+$//gs;
7738:
7739: my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
7740: '_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
7741: {
7742: my $datafile = $r->dir_config('lonDaemons').
7743: '/tmp/'.$datatoken.'.tmp';
7744: if ( open(my $fh,">$datafile") ) {
7745: print $fh $env{'form.upfile'};
7746: close($fh);
7747: }
7748: }
7749: return $datatoken;
7750: }
7751:
7752: =pod
7753:
7754: =item * &load_tmp_file($r)
7755:
7756: Load uploaded file from tmp, $r should be the HTTP Request object,
7757: needs $env{'form.datatoken'},
7758: sets $env{'form.upfile'} to the contents of the file
7759:
7760: =cut
7761:
7762: sub load_tmp_file {
7763: my $r=shift;
7764: my @studentdata=();
7765: {
7766: my $studentfile = $r->dir_config('lonDaemons').
7767: '/tmp/'.$env{'form.datatoken'}.'.tmp';
7768: if ( open(my $fh,"<$studentfile") ) {
7769: @studentdata=<$fh>;
7770: close($fh);
7771: }
7772: }
7773: $env{'form.upfile'}=join('',@studentdata);
7774: }
7775:
7776: =pod
7777:
7778: =item * &upfile_record_sep()
7779:
7780: Separate uploaded file into records
7781: returns array of records,
7782: needs $env{'form.upfile'} and $env{'form.upfiletype'}
7783:
7784: =cut
7785:
7786: sub upfile_record_sep {
7787: if ($env{'form.upfiletype'} eq 'xml') {
7788: } else {
7789: my @records;
7790: foreach my $line (split(/\n/,$env{'form.upfile'})) {
7791: if ($line=~/^\s*$/) { next; }
7792: push(@records,$line);
7793: }
7794: return @records;
7795: }
7796: }
7797:
7798: =pod
7799:
7800: =item * &record_sep($record)
7801:
7802: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
7803:
7804: =cut
7805:
7806: sub takeleft {
7807: my $index=shift;
7808: return substr('0000'.$index,-4,4);
7809: }
7810:
7811: sub record_sep {
7812: my $record=shift;
7813: my %components=();
7814: if ($env{'form.upfiletype'} eq 'xml') {
7815: } elsif ($env{'form.upfiletype'} eq 'space') {
7816: my $i=0;
7817: foreach my $field (split(/\s+/,$record)) {
7818: $field=~s/^(\"|\')//;
7819: $field=~s/(\"|\')$//;
7820: $components{&takeleft($i)}=$field;
7821: $i++;
7822: }
7823: } elsif ($env{'form.upfiletype'} eq 'tab') {
7824: my $i=0;
7825: foreach my $field (split(/\t/,$record)) {
7826: $field=~s/^(\"|\')//;
7827: $field=~s/(\"|\')$//;
7828: $components{&takeleft($i)}=$field;
7829: $i++;
7830: }
7831: } else {
7832: my $separator=',';
7833: if ($env{'form.upfiletype'} eq 'semisv') {
7834: $separator=';';
7835: }
7836: my $i=0;
7837: # the character we are looking for to indicate the end of a quote or a record
7838: my $looking_for=$separator;
7839: # do not add the characters to the fields
7840: my $ignore=0;
7841: # we just encountered a separator (or the beginning of the record)
7842: my $just_found_separator=1;
7843: # store the field we are working on here
7844: my $field='';
7845: # work our way through all characters in record
7846: foreach my $character ($record=~/(.)/g) {
7847: if ($character eq $looking_for) {
7848: if ($character ne $separator) {
7849: # Found the end of a quote, again looking for separator
7850: $looking_for=$separator;
7851: $ignore=1;
7852: } else {
7853: # Found a separator, store away what we got
7854: $components{&takeleft($i)}=$field;
7855: $i++;
7856: $just_found_separator=1;
7857: $ignore=0;
7858: $field='';
7859: }
7860: next;
7861: }
7862: # single or double quotation marks after a separator indicate beginning of a quote
7863: # we are now looking for the end of the quote and need to ignore separators
7864: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) {
7865: $looking_for=$character;
7866: next;
7867: }
7868: # ignore would be true after we reached the end of a quote
7869: if ($ignore) { next; }
7870: if (($just_found_separator) && ($character=~/\s/)) { next; }
7871: $field.=$character;
7872: $just_found_separator=0;
7873: }
7874: # catch the very last entry, since we never encountered the separator
7875: $components{&takeleft($i)}=$field;
7876: }
7877: return %components;
7878: }
7879:
7880: ######################################################
7881: ######################################################
7882:
7883: =pod
7884:
7885: =item * &upfile_select_html()
7886:
7887: Return HTML code to select a file from the users machine and specify
7888: the file type.
7889:
7890: =cut
7891:
7892: ######################################################
7893: ######################################################
7894: sub upfile_select_html {
7895: my %Types = (
7896: csv => &mt('CSV (comma separated values, spreadsheet)'),
7897: semisv => &mt('Semicolon separated values'),
7898: space => &mt('Space separated'),
7899: tab => &mt('Tabulator separated'),
7900: # xml => &mt('HTML/XML'),
7901: );
7902: my $Str = '<input type="file" name="upfile" size="50" />'.
7903: '<br />Type: <select name="upfiletype">';
7904: foreach my $type (sort(keys(%Types))) {
7905: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
7906: }
7907: $Str .= "</select>\n";
7908: return $Str;
7909: }
7910:
7911: sub get_samples {
7912: my ($records,$toget) = @_;
7913: my @samples=({});
7914: my $got=0;
7915: foreach my $rec (@$records) {
7916: my %temp = &record_sep($rec);
7917: if (! grep(/\S/, values(%temp))) { next; }
7918: if (%temp) {
7919: $samples[$got]=\%temp;
7920: $got++;
7921: if ($got == $toget) { last; }
7922: }
7923: }
7924: return \@samples;
7925: }
7926:
7927: ######################################################
7928: ######################################################
7929:
7930: =pod
7931:
7932: =item * &csv_print_samples($r,$records)
7933:
7934: Prints a table of sample values from each column uploaded $r is an
7935: Apache Request ref, $records is an arrayref from
7936: &Apache::loncommon::upfile_record_sep
7937:
7938: =cut
7939:
7940: ######################################################
7941: ######################################################
7942: sub csv_print_samples {
7943: my ($r,$records) = @_;
7944: my $samples = &get_samples($records,5);
7945:
7946: $r->print(&mt('Samples').'<br />'.&start_data_table().
7947: &start_data_table_header_row());
7948: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
7949: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
7950: $r->print(&end_data_table_header_row());
7951: foreach my $hash (@$samples) {
7952: $r->print(&start_data_table_row());
7953: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
7954: $r->print('<td>');
7955: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
7956: $r->print('</td>');
7957: }
7958: $r->print(&end_data_table_row());
7959: }
7960: $r->print(&end_data_table().'<br />'."\n");
7961: }
7962:
7963: ######################################################
7964: ######################################################
7965:
7966: =pod
7967:
7968: =item * &csv_print_select_table($r,$records,$d)
7969:
7970: Prints a table to create associations between values and table columns.
7971:
7972: $r is an Apache Request ref,
7973: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
7974: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
7975:
7976: =cut
7977:
7978: ######################################################
7979: ######################################################
7980: sub csv_print_select_table {
7981: my ($r,$records,$d) = @_;
7982: my $i=0;
7983: my $samples = &get_samples($records,1);
7984: $r->print(&mt('Associate columns with student attributes.')."\n".
7985: &start_data_table().&start_data_table_header_row().
7986: '<th>'.&mt('Attribute').'</th>'.
7987: '<th>'.&mt('Column').'</th>'.
7988: &end_data_table_header_row()."\n");
7989: foreach my $array_ref (@$d) {
7990: my ($value,$display,$defaultcol)=@{ $array_ref };
7991: $r->print(&start_data_table_row().'<td>'.$display.'</td>');
7992:
7993: $r->print('<td><select name=f'.$i.
7994: ' onchange="javascript:flip(this.form,'.$i.');">');
7995: $r->print('<option value="none"></option>');
7996: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
7997: $r->print('<option value="'.$sample.'"'.
7998: ($sample eq $defaultcol ? ' selected="selected" ' : '').
7999: '>'.&mt('Column [_1]',($sample+1)).'</option>');
8000: }
8001: $r->print('</select></td>'.&end_data_table_row()."\n");
8002: $i++;
8003: }
8004: $r->print(&end_data_table());
8005: $i--;
8006: return $i;
8007: }
8008:
8009: ######################################################
8010: ######################################################
8011:
8012: =pod
8013:
8014: =item * &csv_samples_select_table($r,$records,$d)
8015:
8016: Prints a table of sample values from the upload and can make associate samples to internal names.
8017:
8018: $r is an Apache Request ref,
8019: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
8020: $d is an array of 2 element arrays (internal name, displayed name)
8021:
8022: =cut
8023:
8024: ######################################################
8025: ######################################################
8026: sub csv_samples_select_table {
8027: my ($r,$records,$d) = @_;
8028: my $i=0;
8029: #
8030: my $max_samples = 5;
8031: my $samples = &get_samples($records,$max_samples);
8032: $r->print(&start_data_table().
8033: &start_data_table_header_row().'<th>'.
8034: &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
8035: &end_data_table_header_row());
8036:
8037: foreach my $key (sort(keys(%{ $samples->[0] }))) {
8038: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
8039: ' onchange="javascript:flip(this.form,'.$i.');">');
8040: foreach my $option (@$d) {
8041: my ($value,$display,$defaultcol)=@{ $option };
8042: $r->print('<option value="'.$value.'"'.
8043: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
8044: $display.'</option>');
8045: }
8046: $r->print('</select></td><td>');
8047: foreach my $line (0..($max_samples-1)) {
8048: if (defined($samples->[$line]{$key})) {
8049: $r->print($samples->[$line]{$key}."<br />\n");
8050: }
8051: }
8052: $r->print('</td>'.&end_data_table_row());
8053: $i++;
8054: }
8055: $r->print(&end_data_table());
8056: $i--;
8057: return($i);
8058: }
8059:
8060: ######################################################
8061: ######################################################
8062:
8063: =pod
8064:
8065: =item * &clean_excel_name($name)
8066:
8067: Returns a replacement for $name which does not contain any illegal characters.
8068:
8069: =cut
8070:
8071: ######################################################
8072: ######################################################
8073: sub clean_excel_name {
8074: my ($name) = @_;
8075: $name =~ s/[:\*\?\/\\]//g;
8076: if (length($name) > 31) {
8077: $name = substr($name,0,31);
8078: }
8079: return $name;
8080: }
8081:
8082: =pod
8083:
8084: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
8085:
8086: Returns either 1 or undef
8087:
8088: 1 if the part is to be hidden, undef if it is to be shown
8089:
8090: Arguments are:
8091:
8092: $id the id of the part to be checked
8093: $symb, optional the symb of the resource to check
8094: $udom, optional the domain of the user to check for
8095: $uname, optional the username of the user to check for
8096:
8097: =cut
8098:
8099: sub check_if_partid_hidden {
8100: my ($id,$symb,$udom,$uname) = @_;
8101: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
8102: $symb,$udom,$uname);
8103: my $truth=1;
8104: #if the string starts with !, then the list is the list to show not hide
8105: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
8106: my @hiddenlist=split(/,/,$hiddenparts);
8107: foreach my $checkid (@hiddenlist) {
8108: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
8109: }
8110: return !$truth;
8111: }
8112:
8113:
8114: ############################################################
8115: ############################################################
8116:
8117: =pod
8118:
8119: =back
8120:
8121: =head1 cgi-bin script and graphing routines
8122:
8123: =over 4
8124:
8125: =item * &get_cgi_id()
8126:
8127: Inputs: none
8128:
8129: Returns an id which can be used to pass environment variables
8130: to various cgi-bin scripts. These environment variables will
8131: be removed from the users environment after a given time by
8132: the routine &Apache::lonnet::transfer_profile_to_env.
8133:
8134: =cut
8135:
8136: ############################################################
8137: ############################################################
8138: my $uniq=0;
8139: sub get_cgi_id {
8140: $uniq=($uniq+1)%100000;
8141: return (time.'_'.$$.'_'.$uniq);
8142: }
8143:
8144: ############################################################
8145: ############################################################
8146:
8147: =pod
8148:
8149: =item * &DrawBarGraph()
8150:
8151: Facilitates the plotting of data in a (stacked) bar graph.
8152: Puts plot definition data into the users environment in order for
8153: graph.png to plot it. Returns an <img> tag for the plot.
8154: The bars on the plot are labeled '1','2',...,'n'.
8155:
8156: Inputs:
8157:
8158: =over 4
8159:
8160: =item $Title: string, the title of the plot
8161:
8162: =item $xlabel: string, text describing the X-axis of the plot
8163:
8164: =item $ylabel: string, text describing the Y-axis of the plot
8165:
8166: =item $Max: scalar, the maximum Y value to use in the plot
8167: If $Max is < any data point, the graph will not be rendered.
8168:
8169: =item $colors: array ref holding the colors to be used for the data sets when
8170: they are plotted. If undefined, default values will be used.
8171:
8172: =item $labels: array ref holding the labels to use on the x-axis for the bars.
8173:
8174: =item @Values: An array of array references. Each array reference holds data
8175: to be plotted in a stacked bar chart.
8176:
8177: =item If the final element of @Values is a hash reference the key/value
8178: pairs will be added to the graph definition.
8179:
8180: =back
8181:
8182: Returns:
8183:
8184: An <img> tag which references graph.png and the appropriate identifying
8185: information for the plot.
8186:
8187: =cut
8188:
8189: ############################################################
8190: ############################################################
8191: sub DrawBarGraph {
8192: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
8193: #
8194: if (! defined($colors)) {
8195: $colors = ['#33ff00',
8196: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
8197: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
8198: ];
8199: }
8200: my $extra_settings = {};
8201: if (ref($Values[-1]) eq 'HASH') {
8202: $extra_settings = pop(@Values);
8203: }
8204: #
8205: my $identifier = &get_cgi_id();
8206: my $id = 'cgi.'.$identifier;
8207: if (! @Values || ref($Values[0]) ne 'ARRAY') {
8208: return '';
8209: }
8210: #
8211: my @Labels;
8212: if (defined($labels)) {
8213: @Labels = @$labels;
8214: } else {
8215: for (my $i=0;$i<@{$Values[0]};$i++) {
8216: push (@Labels,$i+1);
8217: }
8218: }
8219: #
8220: my $NumBars = scalar(@{$Values[0]});
8221: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
8222: my %ValuesHash;
8223: my $NumSets=1;
8224: foreach my $array (@Values) {
8225: next if (! ref($array));
8226: $ValuesHash{$id.'.data.'.$NumSets++} =
8227: join(',',@$array);
8228: }
8229: #
8230: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
8231: if ($NumBars < 3) {
8232: $width = 120+$NumBars*32;
8233: $xskip = 1;
8234: $bar_width = 30;
8235: } elsif ($NumBars < 5) {
8236: $width = 120+$NumBars*20;
8237: $xskip = 1;
8238: $bar_width = 20;
8239: } elsif ($NumBars < 10) {
8240: $width = 120+$NumBars*15;
8241: $xskip = 1;
8242: $bar_width = 15;
8243: } elsif ($NumBars <= 25) {
8244: $width = 120+$NumBars*11;
8245: $xskip = 5;
8246: $bar_width = 8;
8247: } elsif ($NumBars <= 50) {
8248: $width = 120+$NumBars*8;
8249: $xskip = 5;
8250: $bar_width = 4;
8251: } else {
8252: $width = 120+$NumBars*8;
8253: $xskip = 5;
8254: $bar_width = 4;
8255: }
8256: #
8257: $Max = 1 if ($Max < 1);
8258: if ( int($Max) < $Max ) {
8259: $Max++;
8260: $Max = int($Max);
8261: }
8262: $Title = '' if (! defined($Title));
8263: $xlabel = '' if (! defined($xlabel));
8264: $ylabel = '' if (! defined($ylabel));
8265: $ValuesHash{$id.'.title'} = &escape($Title);
8266: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
8267: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
8268: $ValuesHash{$id.'.y_max_value'} = $Max;
8269: $ValuesHash{$id.'.NumBars'} = $NumBars;
8270: $ValuesHash{$id.'.NumSets'} = $NumSets;
8271: $ValuesHash{$id.'.PlotType'} = 'bar';
8272: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
8273: $ValuesHash{$id.'.height'} = $height;
8274: $ValuesHash{$id.'.width'} = $width;
8275: $ValuesHash{$id.'.xskip'} = $xskip;
8276: $ValuesHash{$id.'.bar_width'} = $bar_width;
8277: $ValuesHash{$id.'.labels'} = join(',',@Labels);
8278: #
8279: # Deal with other parameters
8280: while (my ($key,$value) = each(%$extra_settings)) {
8281: $ValuesHash{$id.'.'.$key} = $value;
8282: }
8283: #
8284: &Apache::lonnet::appenv(\%ValuesHash);
8285: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
8286: }
8287:
8288: ############################################################
8289: ############################################################
8290:
8291: =pod
8292:
8293: =item * &DrawXYGraph()
8294:
8295: Facilitates the plotting of data in an XY graph.
8296: Puts plot definition data into the users environment in order for
8297: graph.png to plot it. Returns an <img> tag for the plot.
8298:
8299: Inputs:
8300:
8301: =over 4
8302:
8303: =item $Title: string, the title of the plot
8304:
8305: =item $xlabel: string, text describing the X-axis of the plot
8306:
8307: =item $ylabel: string, text describing the Y-axis of the plot
8308:
8309: =item $Max: scalar, the maximum Y value to use in the plot
8310: If $Max is < any data point, the graph will not be rendered.
8311:
8312: =item $colors: Array ref containing the hex color codes for the data to be
8313: plotted in. If undefined, default values will be used.
8314:
8315: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
8316:
8317: =item $Ydata: Array ref containing Array refs.
8318: Each of the contained arrays will be plotted as a separate curve.
8319:
8320: =item %Values: hash indicating or overriding any default values which are
8321: passed to graph.png.
8322: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
8323:
8324: =back
8325:
8326: Returns:
8327:
8328: An <img> tag which references graph.png and the appropriate identifying
8329: information for the plot.
8330:
8331: =cut
8332:
8333: ############################################################
8334: ############################################################
8335: sub DrawXYGraph {
8336: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
8337: #
8338: # Create the identifier for the graph
8339: my $identifier = &get_cgi_id();
8340: my $id = 'cgi.'.$identifier;
8341: #
8342: $Title = '' if (! defined($Title));
8343: $xlabel = '' if (! defined($xlabel));
8344: $ylabel = '' if (! defined($ylabel));
8345: my %ValuesHash =
8346: (
8347: $id.'.title' => &escape($Title),
8348: $id.'.xlabel' => &escape($xlabel),
8349: $id.'.ylabel' => &escape($ylabel),
8350: $id.'.y_max_value'=> $Max,
8351: $id.'.labels' => join(',',@$Xlabels),
8352: $id.'.PlotType' => 'XY',
8353: );
8354: #
8355: if (defined($colors) && ref($colors) eq 'ARRAY') {
8356: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
8357: }
8358: #
8359: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
8360: return '';
8361: }
8362: my $NumSets=1;
8363: foreach my $array (@{$Ydata}){
8364: next if (! ref($array));
8365: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
8366: }
8367: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
8368: #
8369: # Deal with other parameters
8370: while (my ($key,$value) = each(%Values)) {
8371: $ValuesHash{$id.'.'.$key} = $value;
8372: }
8373: #
8374: &Apache::lonnet::appenv(\%ValuesHash);
8375: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
8376: }
8377:
8378: ############################################################
8379: ############################################################
8380:
8381: =pod
8382:
8383: =item * &DrawXYYGraph()
8384:
8385: Facilitates the plotting of data in an XY graph with two Y axes.
8386: Puts plot definition data into the users environment in order for
8387: graph.png to plot it. Returns an <img> tag for the plot.
8388:
8389: Inputs:
8390:
8391: =over 4
8392:
8393: =item $Title: string, the title of the plot
8394:
8395: =item $xlabel: string, text describing the X-axis of the plot
8396:
8397: =item $ylabel: string, text describing the Y-axis of the plot
8398:
8399: =item $colors: Array ref containing the hex color codes for the data to be
8400: plotted in. If undefined, default values will be used.
8401:
8402: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
8403:
8404: =item $Ydata1: The first data set
8405:
8406: =item $Min1: The minimum value of the left Y-axis
8407:
8408: =item $Max1: The maximum value of the left Y-axis
8409:
8410: =item $Ydata2: The second data set
8411:
8412: =item $Min2: The minimum value of the right Y-axis
8413:
8414: =item $Max2: The maximum value of the left Y-axis
8415:
8416: =item %Values: hash indicating or overriding any default values which are
8417: passed to graph.png.
8418: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
8419:
8420: =back
8421:
8422: Returns:
8423:
8424: An <img> tag which references graph.png and the appropriate identifying
8425: information for the plot.
8426:
8427: =cut
8428:
8429: ############################################################
8430: ############################################################
8431: sub DrawXYYGraph {
8432: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
8433: $Ydata2,$Min2,$Max2,%Values)=@_;
8434: #
8435: # Create the identifier for the graph
8436: my $identifier = &get_cgi_id();
8437: my $id = 'cgi.'.$identifier;
8438: #
8439: $Title = '' if (! defined($Title));
8440: $xlabel = '' if (! defined($xlabel));
8441: $ylabel = '' if (! defined($ylabel));
8442: my %ValuesHash =
8443: (
8444: $id.'.title' => &escape($Title),
8445: $id.'.xlabel' => &escape($xlabel),
8446: $id.'.ylabel' => &escape($ylabel),
8447: $id.'.labels' => join(',',@$Xlabels),
8448: $id.'.PlotType' => 'XY',
8449: $id.'.NumSets' => 2,
8450: $id.'.two_axes' => 1,
8451: $id.'.y1_max_value' => $Max1,
8452: $id.'.y1_min_value' => $Min1,
8453: $id.'.y2_max_value' => $Max2,
8454: $id.'.y2_min_value' => $Min2,
8455: );
8456: #
8457: if (defined($colors) && ref($colors) eq 'ARRAY') {
8458: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
8459: }
8460: #
8461: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
8462: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
8463: return '';
8464: }
8465: my $NumSets=1;
8466: foreach my $array ($Ydata1,$Ydata2){
8467: next if (! ref($array));
8468: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
8469: }
8470: #
8471: # Deal with other parameters
8472: while (my ($key,$value) = each(%Values)) {
8473: $ValuesHash{$id.'.'.$key} = $value;
8474: }
8475: #
8476: &Apache::lonnet::appenv(\%ValuesHash);
8477: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
8478: }
8479:
8480: ############################################################
8481: ############################################################
8482:
8483: =pod
8484:
8485: =back
8486:
8487: =head1 Statistics helper routines?
8488:
8489: Bad place for them but what the hell.
8490:
8491: =over 4
8492:
8493: =item * &chartlink()
8494:
8495: Returns a link to the chart for a specific student.
8496:
8497: Inputs:
8498:
8499: =over 4
8500:
8501: =item $linktext: The text of the link
8502:
8503: =item $sname: The students username
8504:
8505: =item $sdomain: The students domain
8506:
8507: =back
8508:
8509: =back
8510:
8511: =cut
8512:
8513: ############################################################
8514: ############################################################
8515: sub chartlink {
8516: my ($linktext, $sname, $sdomain) = @_;
8517: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
8518: '&SelectedStudent='.&escape($sname.':'.$sdomain).
8519: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
8520: '">'.$linktext.'</a>';
8521: }
8522:
8523: #######################################################
8524: #######################################################
8525:
8526: =pod
8527:
8528: =head1 Course Environment Routines
8529:
8530: =over 4
8531:
8532: =item * &restore_course_settings()
8533:
8534: =item * &store_course_settings()
8535:
8536: Restores/Store indicated form parameters from the course environment.
8537: Will not overwrite existing values of the form parameters.
8538:
8539: Inputs:
8540: a scalar describing the data (e.g. 'chart', 'problem_analysis')
8541:
8542: a hash ref describing the data to be stored. For example:
8543:
8544: %Save_Parameters = ('Status' => 'scalar',
8545: 'chartoutputmode' => 'scalar',
8546: 'chartoutputdata' => 'scalar',
8547: 'Section' => 'array',
8548: 'Group' => 'array',
8549: 'StudentData' => 'array',
8550: 'Maps' => 'array');
8551:
8552: Returns: both routines return nothing
8553:
8554: =back
8555:
8556: =cut
8557:
8558: #######################################################
8559: #######################################################
8560: sub store_course_settings {
8561: return &store_settings($env{'request.course.id'},@_);
8562: }
8563:
8564: sub store_settings {
8565: # save to the environment
8566: # appenv the same items, just to be safe
8567: my $udom = $env{'user.domain'};
8568: my $uname = $env{'user.name'};
8569: my ($context,$prefix,$Settings) = @_;
8570: my %SaveHash;
8571: my %AppHash;
8572: while (my ($setting,$type) = each(%$Settings)) {
8573: my $basename = join('.','internal',$context,$prefix,$setting);
8574: my $envname = 'environment.'.$basename;
8575: if (exists($env{'form.'.$setting})) {
8576: # Save this value away
8577: if ($type eq 'scalar' &&
8578: (! exists($env{$envname}) ||
8579: $env{$envname} ne $env{'form.'.$setting})) {
8580: $SaveHash{$basename} = $env{'form.'.$setting};
8581: $AppHash{$envname} = $env{'form.'.$setting};
8582: } elsif ($type eq 'array') {
8583: my $stored_form;
8584: if (ref($env{'form.'.$setting})) {
8585: $stored_form = join(',',
8586: map {
8587: &escape($_);
8588: } sort(@{$env{'form.'.$setting}}));
8589: } else {
8590: $stored_form =
8591: &escape($env{'form.'.$setting});
8592: }
8593: # Determine if the array contents are the same.
8594: if ($stored_form ne $env{$envname}) {
8595: $SaveHash{$basename} = $stored_form;
8596: $AppHash{$envname} = $stored_form;
8597: }
8598: }
8599: }
8600: }
8601: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
8602: $udom,$uname);
8603: if ($put_result !~ /^(ok|delayed)/) {
8604: &Apache::lonnet::logthis('unable to save form parameters, '.
8605: 'got error:'.$put_result);
8606: }
8607: # Make sure these settings stick around in this session, too
8608: &Apache::lonnet::appenv(\%AppHash);
8609: return;
8610: }
8611:
8612: sub restore_course_settings {
8613: return &restore_settings($env{'request.course.id'},@_);
8614: }
8615:
8616: sub restore_settings {
8617: my ($context,$prefix,$Settings) = @_;
8618: while (my ($setting,$type) = each(%$Settings)) {
8619: next if (exists($env{'form.'.$setting}));
8620: my $envname = 'environment.internal.'.$context.'.'.$prefix.
8621: '.'.$setting;
8622: if (exists($env{$envname})) {
8623: if ($type eq 'scalar') {
8624: $env{'form.'.$setting} = $env{$envname};
8625: } elsif ($type eq 'array') {
8626: $env{'form.'.$setting} = [
8627: map {
8628: &unescape($_);
8629: } split(',',$env{$envname})
8630: ];
8631: }
8632: }
8633: }
8634: }
8635:
8636: #######################################################
8637: #######################################################
8638:
8639: =pod
8640:
8641: =head1 Domain E-mail Routines
8642:
8643: =over 4
8644:
8645: =item * &build_recipient_list()
8646:
8647: Build recipient lists for three types of e-mail:
8648: (a) Error Reports, (b) Package Updates, (c) Help requests, generated by
8649: lonerrorhandler.pm, CHECKRPMS and lonsupportreq.pm respectively.
8650:
8651: Inputs:
8652: defmail (scalar - email address of default recipient),
8653: mailing type (scalar - errormail, packagesmail, or helpdeskmail),
8654: defdom (domain for which to retrieve configuration settings),
8655: origmail (scalar - email address of recipient from loncapa.conf,
8656: i.e., predates configuration by DC via domainprefs.pm
8657:
8658: Returns: comma separated list of addresses to which to send e-mail.
8659:
8660: =back
8661:
8662: =cut
8663:
8664: ############################################################
8665: ############################################################
8666: sub build_recipient_list {
8667: my ($defmail,$mailing,$defdom,$origmail) = @_;
8668: my @recipients;
8669: my $otheremails;
8670: my %domconfig =
8671: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
8672: if (ref($domconfig{'contacts'}) eq 'HASH') {
8673: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
8674: my @contacts = ('adminemail','supportemail');
8675: foreach my $item (@contacts) {
8676: if ($domconfig{'contacts'}{$mailing}{$item}) {
8677: my $addr = $domconfig{'contacts'}{$item};
8678: if (!grep(/^\Q$addr\E$/,@recipients)) {
8679: push(@recipients,$addr);
8680: }
8681: }
8682: $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
8683: }
8684: }
8685: } elsif ($origmail ne '') {
8686: push(@recipients,$origmail);
8687: }
8688: if (defined($defmail)) {
8689: if ($defmail ne '') {
8690: push(@recipients,$defmail);
8691: }
8692: }
8693: if ($otheremails) {
8694: my @others;
8695: if ($otheremails =~ /,/) {
8696: @others = split(/,/,$otheremails);
8697: } else {
8698: push(@others,$otheremails);
8699: }
8700: foreach my $addr (@others) {
8701: if (!grep(/^\Q$addr\E$/,@recipients)) {
8702: push(@recipients,$addr);
8703: }
8704: }
8705: }
8706: my $recipientlist = join(',',@recipients);
8707: return $recipientlist;
8708: }
8709:
8710: ############################################################
8711: ############################################################
8712:
8713: =pod
8714:
8715: =head1 Course Catalog Routines
8716:
8717: =over 4
8718:
8719: =item * &gather_categories()
8720:
8721: Converts category definitions - keys of categories hash stored in
8722: coursecategories in configuration.db on the primary library server in a
8723: domain - to an array. Also generates javascript and idx hash used to
8724: generate Domain Coordinator interface for editing Course Categories.
8725:
8726: Inputs:
8727:
8728: categories (reference to hash of category definitions).
8729:
8730: cats (reference to array of arrays/hashes which encapsulates hierarchy of
8731: categories and subcategories).
8732:
8733: idx (reference to hash of counters used in Domain Coordinator interface for
8734: editing Course Categories).
8735:
8736: jsarray (reference to array of categories used to create Javascript arrays for
8737: Domain Coordinator interface for editing Course Categories).
8738:
8739: Returns: nothing
8740:
8741: Side effects: populates cats, idx and jsarray.
8742:
8743: =cut
8744:
8745: sub gather_categories {
8746: my ($categories,$cats,$idx,$jsarray) = @_;
8747: my %counters;
8748: my $num = 0;
8749: foreach my $item (keys(%{$categories})) {
8750: my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
8751: if ($container eq '' && $depth == 0) {
8752: $cats->[$depth][$categories->{$item}] = $cat;
8753: } else {
8754: $cats->[$depth]{$container}[$categories->{$item}] = $cat;
8755: }
8756: my ($escitem,$tail) = split(/:/,$item,2);
8757: if ($counters{$tail} eq '') {
8758: $counters{$tail} = $num;
8759: $num ++;
8760: }
8761: if (ref($idx) eq 'HASH') {
8762: $idx->{$item} = $counters{$tail};
8763: }
8764: if (ref($jsarray) eq 'ARRAY') {
8765: push(@{$jsarray->[$counters{$tail}]},$item);
8766: }
8767: }
8768: return;
8769: }
8770:
8771: =pod
8772:
8773: =item * &extract_categories()
8774:
8775: Used to generate breadcrumb trails for course categories.
8776:
8777: Inputs:
8778:
8779: categories (reference to hash of category definitions).
8780:
8781: cats (reference to array of arrays/hashes which encapsulates hierarchy of
8782: categories and subcategories).
8783:
8784: trails (reference to array of breacrumb trails for each category).
8785:
8786: allitems (reference to hash - key is category key
8787: (format: escaped(name):escaped(parent category):depth in hierarchy).
8788:
8789: idx (reference to hash of counters used in Domain Coordinator interface for
8790: editing Course Categories).
8791:
8792: jsarray (reference to array of categories used to create Javascript arrays for
8793: Domain Coordinator interface for editing Course Categories).
8794:
8795: subcats (reference to hash of arrays containing all subcategories within each
8796: category, -recursive)
8797:
8798: Returns: nothing
8799:
8800: Side effects: populates trails and allitems hash references.
8801:
8802: =cut
8803:
8804: sub extract_categories {
8805: my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
8806: if (ref($categories) eq 'HASH') {
8807: &gather_categories($categories,$cats,$idx,$jsarray);
8808: if (ref($cats->[0]) eq 'ARRAY') {
8809: for (my $i=0; $i<@{$cats->[0]}; $i++) {
8810: my $name = $cats->[0][$i];
8811: my $item = &escape($name).'::0';
8812: my $trailstr;
8813: if ($name eq 'instcode') {
8814: $trailstr = &mt('Official courses (with institutional codes)');
8815: } else {
8816: $trailstr = $name;
8817: }
8818: if ($allitems->{$item} eq '') {
8819: push(@{$trails},$trailstr);
8820: $allitems->{$item} = scalar(@{$trails})-1;
8821: }
8822: my @parents = ($name);
8823: if (ref($cats->[1]{$name}) eq 'ARRAY') {
8824: for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
8825: my $category = $cats->[1]{$name}[$j];
8826: if (ref($subcats) eq 'HASH') {
8827: push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
8828: }
8829: &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
8830: }
8831: } else {
8832: if (ref($subcats) eq 'HASH') {
8833: $subcats->{$item} = [];
8834: }
8835: }
8836: }
8837: }
8838: }
8839: return;
8840: }
8841:
8842: =pod
8843:
8844: =item *&recurse_categories()
8845:
8846: Recursively used to generate breadcrumb trails for course categories.
8847:
8848: Inputs:
8849:
8850: cats (reference to array of arrays/hashes which encapsulates hierarchy of
8851: categories and subcategories).
8852:
8853: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
8854:
8855: category (current course category, for which breadcrumb trail is being generated).
8856:
8857: trails (reference to array of breadcrumb trails for each category).
8858:
8859: allitems (reference to hash - key is category key
8860: (format: escaped(name):escaped(parent category):depth in hierarchy).
8861:
8862: parents (array containing containers directories for current category,
8863: back to top level).
8864:
8865: Returns: nothing
8866:
8867: Side effects: populates trails and allitems hash references
8868:
8869: =cut
8870:
8871: sub recurse_categories {
8872: my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
8873: my $shallower = $depth - 1;
8874: if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
8875: for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
8876: my $name = $cats->[$depth]{$category}[$k];
8877: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
8878: my $trailstr = join(' -> ',(@{$parents},$category));
8879: if ($allitems->{$item} eq '') {
8880: push(@{$trails},$trailstr);
8881: $allitems->{$item} = scalar(@{$trails})-1;
8882: }
8883: my $deeper = $depth+1;
8884: push(@{$parents},$category);
8885: if (ref($subcats) eq 'HASH') {
8886: my $subcat = &escape($name).':'.$category.':'.$depth;
8887: for (my $j=@{$parents}; $j>=0; $j--) {
8888: my $higher;
8889: if ($j > 0) {
8890: $higher = &escape($parents->[$j]).':'.
8891: &escape($parents->[$j-1]).':'.$j;
8892: } else {
8893: $higher = &escape($parents->[$j]).'::'.$j;
8894: }
8895: push(@{$subcats->{$higher}},$subcat);
8896: }
8897: }
8898: &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
8899: $subcats);
8900: pop(@{$parents});
8901: }
8902: } else {
8903: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
8904: my $trailstr = join(' -> ',(@{$parents},$category));
8905: if ($allitems->{$item} eq '') {
8906: push(@{$trails},$trailstr);
8907: $allitems->{$item} = scalar(@{$trails})-1;
8908: }
8909: }
8910: return;
8911: }
8912:
8913: =pod
8914:
8915: =item *&assign_categories_table()
8916:
8917: Create a datatable for display of hierarchical categories in a domain,
8918: with checkboxes to allow a course to be categorized.
8919:
8920: Inputs:
8921:
8922: cathash - reference to hash of categories defined for the domain (from
8923: configuration.db)
8924:
8925: currcat - scalar with an & separated list of categories assigned to a course.
8926:
8927: Returns: $output (markup to be displayed)
8928:
8929: =cut
8930:
8931: sub assign_categories_table {
8932: my ($cathash,$currcat) = @_;
8933: my $output;
8934: if (ref($cathash) eq 'HASH') {
8935: my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
8936: &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
8937: $maxdepth = scalar(@cats);
8938: if (@cats > 0) {
8939: my $itemcount = 0;
8940: if (ref($cats[0]) eq 'ARRAY') {
8941: $output = &Apache::loncommon::start_data_table();
8942: my @currcategories;
8943: if ($currcat ne '') {
8944: @currcategories = split('&',$currcat);
8945: }
8946: for (my $i=0; $i<@{$cats[0]}; $i++) {
8947: my $parent = $cats[0][$i];
8948: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
8949: next if ($parent eq 'instcode');
8950: my $item = &escape($parent).'::0';
8951: my $checked = '';
8952: if (@currcategories > 0) {
8953: if (grep(/^\Q$item\E$/,@currcategories)) {
8954: $checked = ' checked="checked" ';
8955: }
8956: }
8957: $output .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
8958: '<input type="checkbox" name="usecategory" value="'.
8959: $item.'"'.$checked.' />'.$parent.'</span>'.
8960: '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
8961: my $depth = 1;
8962: push(@path,$parent);
8963: $output .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
8964: pop(@path);
8965: $output .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
8966: $itemcount ++;
8967: }
8968: $output .= &Apache::loncommon::end_data_table();
8969: }
8970: }
8971: }
8972: return $output;
8973: }
8974:
8975: =pod
8976:
8977: =item *&assign_category_rows()
8978:
8979: Create a datatable row for display of nested categories in a domain,
8980: with checkboxes to allow a course to be categorized,called recursively.
8981:
8982: Inputs:
8983:
8984: itemcount - track row number for alternating colors
8985:
8986: cats - reference to array of arrays/hashes which encapsulates hierarchy of
8987: categories and subcategories.
8988:
8989: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
8990:
8991: parent - parent of current category item
8992:
8993: path - Array containing all categories back up through the hierarchy from the
8994: current category to the top level.
8995:
8996: currcategories - reference to array of current categories assigned to the course
8997:
8998: Returns: $output (markup to be displayed).
8999:
9000: =cut
9001:
9002: sub assign_category_rows {
9003: my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
9004: my ($text,$name,$item,$chgstr);
9005: if (ref($cats) eq 'ARRAY') {
9006: my $maxdepth = scalar(@{$cats});
9007: if (ref($cats->[$depth]) eq 'HASH') {
9008: if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
9009: my $numchildren = @{$cats->[$depth]{$parent}};
9010: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
9011: $text .= '<td><table class="LC_datatable">';
9012: for (my $j=0; $j<$numchildren; $j++) {
9013: $name = $cats->[$depth]{$parent}[$j];
9014: $item = &escape($name).':'.&escape($parent).':'.$depth;
9015: my $deeper = $depth+1;
9016: my $checked = '';
9017: if (ref($currcategories) eq 'ARRAY') {
9018: if (@{$currcategories} > 0) {
9019: if (grep(/^\Q$item\E$/,@{$currcategories})) {
9020: $checked = ' checked="checked" ';
9021: }
9022: }
9023: }
9024: $text .= '<tr><td><span class="LC_nobreak"><label>'.
9025: '<input type="checkbox" name="usecategory" value="'.
9026: $item.'"'.$checked.' />'.$name.'</label></span>'.
9027: '<input type="hidden" name="catname" value="'.$name.'" />'.
9028: '</td><td>';
9029: if (ref($path) eq 'ARRAY') {
9030: push(@{$path},$name);
9031: $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
9032: pop(@{$path});
9033: }
9034: $text .= '</td></tr>';
9035: }
9036: $text .= '</table></td>';
9037: }
9038: }
9039: }
9040: return $text;
9041: }
9042:
9043: ############################################################
9044: ############################################################
9045:
9046:
9047: sub commit_customrole {
9048: my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
9049: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
9050: ($start?', '.&mt('starting').' '.localtime($start):'').
9051: ($end?', ending '.localtime($end):'').': <b>'.
9052: &Apache::lonnet::assigncustomrole(
9053: $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
9054: '</b><br />';
9055: return $output;
9056: }
9057:
9058: sub commit_standardrole {
9059: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
9060: my ($output,$logmsg,$linefeed);
9061: if ($context eq 'auto') {
9062: $linefeed = "\n";
9063: } else {
9064: $linefeed = "<br />\n";
9065: }
9066: if ($three eq 'st') {
9067: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
9068: $one,$two,$sec,$context);
9069: if (($result =~ /^error/) || ($result eq 'not_in_class') ||
9070: ($result eq 'unknown_course') || ($result eq 'refused')) {
9071: $output = $logmsg.' '.&mt('Error: ').$result."\n";
9072: } else {
9073: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
9074: ($start?', '.&mt('starting').' '.localtime($start):'').
9075: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
9076: if ($context eq 'auto') {
9077: $output .= $result.$linefeed.&mt('Add to classlist').': ok';
9078: } else {
9079: $output .= '<b>'.$result.'</b>'.$linefeed.
9080: &mt('Add to classlist').': <b>ok</b>';
9081: }
9082: $output .= $linefeed;
9083: }
9084: } else {
9085: $output = &mt('Assigning').' '.$three.' in '.$url.
9086: ($start?', '.&mt('starting').' '.localtime($start):'').
9087: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
9088: my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
9089: if ($context eq 'auto') {
9090: $output .= $result.$linefeed;
9091: } else {
9092: $output .= '<b>'.$result.'</b>'.$linefeed;
9093: }
9094: }
9095: return $output;
9096: }
9097:
9098: sub commit_studentrole {
9099: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
9100: my ($result,$linefeed,$oldsecurl,$newsecurl);
9101: if ($context eq 'auto') {
9102: $linefeed = "\n";
9103: } else {
9104: $linefeed = '<br />'."\n";
9105: }
9106: if (defined($one) && defined($two)) {
9107: my $cid=$one.'_'.$two;
9108: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
9109: my $secchange = 0;
9110: my $expire_role_result;
9111: my $modify_section_result;
9112: if ($oldsec ne '-1') {
9113: if ($oldsec ne $sec) {
9114: $secchange = 1;
9115: my $now = time;
9116: my $uurl='/'.$cid;
9117: $uurl=~s/\_/\//g;
9118: if ($oldsec) {
9119: $uurl.='/'.$oldsec;
9120: }
9121: $oldsecurl = $uurl;
9122: $expire_role_result =
9123: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
9124: if ($env{'request.course.sec'} ne '') {
9125: if ($expire_role_result eq 'refused') {
9126: my @roles = ('st');
9127: my @statuses = ('previous');
9128: my @roledoms = ($one);
9129: my $withsec = 1;
9130: my %roleshash =
9131: &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
9132: \@statuses,\@roles,\@roledoms,$withsec);
9133: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
9134: my ($oldstart,$oldend) =
9135: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
9136: if ($oldend > 0 && $oldend <= $now) {
9137: $expire_role_result = 'ok';
9138: }
9139: }
9140: }
9141: }
9142: $result = $expire_role_result;
9143: }
9144: }
9145: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
9146: $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
9147: if ($modify_section_result =~ /^ok/) {
9148: if ($secchange == 1) {
9149: if ($sec eq '') {
9150: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
9151: } else {
9152: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
9153: }
9154: } elsif ($oldsec eq '-1') {
9155: if ($sec eq '') {
9156: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
9157: } else {
9158: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
9159: }
9160: } else {
9161: if ($sec eq '') {
9162: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
9163: } else {
9164: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
9165: }
9166: }
9167: } else {
9168: if ($secchange) {
9169: $$logmsg .= &mt('Error when attempting section change for [_1] from old section "[_2]" to new section: "[_3]" in course [_4] -error:',$uname,$oldsec,$sec,$cid).' '.$modify_section_result.$linefeed;
9170: } else {
9171: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
9172: }
9173: }
9174: $result = $modify_section_result;
9175: } elsif ($secchange == 1) {
9176: if ($oldsec eq '') {
9177: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
9178: } else {
9179: $$logmsg .= &mt('Error when attempting to expire existing role for [_1] in section [_2] in course [_3] -error: ',$uname,$oldsec,$cid).' '.$expire_role_result.$linefeed;
9180: }
9181: if ($expire_role_result eq 'refused') {
9182: my $newsecurl = '/'.$cid;
9183: $newsecurl =~ s/\_/\//g;
9184: if ($sec ne '') {
9185: $newsecurl.='/'.$sec;
9186: }
9187: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
9188: if ($sec eq '') {
9189: $$logmsg .= &mt('Although your current role has privileges to add students to section "[_1]", you do not have privileges to modify existing enrollments unaffiliated with any section.',$sec).$linefeed;
9190: } else {
9191: $$logmsg .= &mt('Although your current role has privileges to add students to section "[_1]", you do not have privileges to modify existing enrollments in other sections.',$sec).$linefeed;
9192: }
9193: }
9194: }
9195: }
9196: } else {
9197: $$logmsg .= &mt('Incomplete course id defined.').$linefeed.&mt('Addition of user [_1] from domain [_2] to course [_3], section [_4] not completed.',$uname,$udom,$one.'_'.$two,$sec).$linefeed;
9198: $result = "error: incomplete course id\n";
9199: }
9200: return $result;
9201: }
9202:
9203: ############################################################
9204: ############################################################
9205:
9206: sub check_clone {
9207: my ($args,$linefeed) = @_;
9208: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
9209: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
9210: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
9211: my $clonemsg;
9212: my $can_clone = 0;
9213:
9214: if ($clonehome eq 'no_host') {
9215: $clonemsg = &mt('No new course created.').$linefeed.&mt('A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
9216: } else {
9217: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
9218: if ($env{'request.role.domain'} eq $args->{'clonedomain'}) {
9219: $can_clone = 1;
9220: } else {
9221: my %clonehash = &Apache::lonnet::get('environment',['cloners'],
9222: $args->{'clonedomain'},$args->{'clonecourse'});
9223: my @cloners = split(/,/,$clonehash{'cloners'});
9224: if (grep(/^\*$/,@cloners)) {
9225: $can_clone = 1;
9226: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
9227: $can_clone = 1;
9228: } else {
9229: my %roleshash =
9230: &Apache::lonnet::get_my_roles($args->{'ccuname'},
9231: $args->{'ccdomain'},
9232: 'userroles',['active'],['cc'],
9233: [$args->{'clonedomain'}]);
9234: if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
9235: $can_clone = 1;
9236: } else {
9237: $clonemsg = &mt('No new course created.').$linefeed.&mt('The new course could not be cloned from the existing course because the new course owner ([_1]) does not have cloning rights in the existing course ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
9238: }
9239: }
9240: }
9241: }
9242: return ($can_clone, $clonemsg, $cloneid, $clonehome);
9243: }
9244:
9245: sub construct_course {
9246: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context) = @_;
9247: my $outcome;
9248: my $linefeed = '<br />'."\n";
9249: if ($context eq 'auto') {
9250: $linefeed = "\n";
9251: }
9252:
9253: #
9254: # Are we cloning?
9255: #
9256: my ($can_clone, $clonemsg, $cloneid, $clonehome);
9257: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
9258: ($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
9259: if ($context ne 'auto') {
9260: if ($clonemsg ne '') {
9261: $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
9262: }
9263: }
9264: $outcome .= $clonemsg.$linefeed;
9265:
9266: if (!$can_clone) {
9267: return (0,$outcome);
9268: }
9269: }
9270:
9271: #
9272: # Open course
9273: #
9274: my $crstype = lc($args->{'crstype'});
9275: my %cenv=();
9276: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
9277: $args->{'cdescr'},
9278: $args->{'curl'},
9279: $args->{'course_home'},
9280: $args->{'nonstandard'},
9281: $args->{'crscode'},
9282: $args->{'ccuname'}.':'.
9283: $args->{'ccdomain'},
9284: $args->{'crstype'});
9285:
9286: # Note: The testing routines depend on this being output; see
9287: # Utils::Course. This needs to at least be output as a comment
9288: # if anyone ever decides to not show this, and Utils::Course::new
9289: # will need to be suitably modified.
9290: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
9291: #
9292: # Check if created correctly
9293: #
9294: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
9295: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
9296: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
9297:
9298: #
9299: # Do the cloning
9300: #
9301: if ($can_clone && $cloneid) {
9302: $clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
9303: if ($context ne 'auto') {
9304: $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
9305: }
9306: $outcome .= $clonemsg.$linefeed;
9307: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
9308: # Copy all files
9309: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
9310: # Restore URL
9311: $cenv{'url'}=$oldcenv{'url'};
9312: # Restore title
9313: $cenv{'description'}=$oldcenv{'description'};
9314: # Mark as cloned
9315: $cenv{'clonedfrom'}=$cloneid;
9316: # Need to clone grading mode
9317: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
9318: $cenv{'grading'}=$newenv{'grading'};
9319: # Do not clone these environment entries
9320: &Apache::lonnet::del('environment',
9321: ['default_enrollment_start_date',
9322: 'default_enrollment_end_date',
9323: 'question.email',
9324: 'policy.email',
9325: 'comment.email',
9326: 'pch.users.denied',
9327: 'plc.users.denied'],
9328: $$crsudom,$$crsunum);
9329: }
9330:
9331: #
9332: # Set environment (will override cloned, if existing)
9333: #
9334: my @sections = ();
9335: my @xlists = ();
9336: if ($args->{'crstype'}) {
9337: $cenv{'type'}=$args->{'crstype'};
9338: }
9339: if ($args->{'crsid'}) {
9340: $cenv{'courseid'}=$args->{'crsid'};
9341: }
9342: if ($args->{'crscode'}) {
9343: $cenv{'internal.coursecode'}=$args->{'crscode'};
9344: }
9345: if ($args->{'crsquota'} ne '') {
9346: $cenv{'internal.coursequota'}=$args->{'crsquota'};
9347: } else {
9348: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
9349: }
9350: if ($args->{'ccuname'}) {
9351: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
9352: ':'.$args->{'ccdomain'};
9353: } else {
9354: $cenv{'internal.courseowner'} = $args->{'curruser'};
9355: }
9356: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
9357: if ($args->{'crssections'}) {
9358: $cenv{'internal.sectionnums'} = '';
9359: if ($args->{'crssections'} =~ m/,/) {
9360: @sections = split/,/,$args->{'crssections'};
9361: } else {
9362: $sections[0] = $args->{'crssections'};
9363: }
9364: if (@sections > 0) {
9365: foreach my $item (@sections) {
9366: my ($sec,$gp) = split/:/,$item;
9367: my $class = $args->{'crscode'}.$sec;
9368: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
9369: $cenv{'internal.sectionnums'} .= $item.',';
9370: unless ($addcheck eq 'ok') {
9371: push @badclasses, $class;
9372: }
9373: }
9374: $cenv{'internal.sectionnums'} =~ s/,$//;
9375: }
9376: }
9377: # do not hide course coordinator from staff listing,
9378: # even if privileged
9379: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
9380: # add crosslistings
9381: if ($args->{'crsxlist'}) {
9382: $cenv{'internal.crosslistings'}='';
9383: if ($args->{'crsxlist'} =~ m/,/) {
9384: @xlists = split/,/,$args->{'crsxlist'};
9385: } else {
9386: $xlists[0] = $args->{'crsxlist'};
9387: }
9388: if (@xlists > 0) {
9389: foreach my $item (@xlists) {
9390: my ($xl,$gp) = split/:/,$item;
9391: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
9392: $cenv{'internal.crosslistings'} .= $item.',';
9393: unless ($addcheck eq 'ok') {
9394: push @badclasses, $xl;
9395: }
9396: }
9397: $cenv{'internal.crosslistings'} =~ s/,$//;
9398: }
9399: }
9400: if ($args->{'autoadds'}) {
9401: $cenv{'internal.autoadds'}=$args->{'autoadds'};
9402: }
9403: if ($args->{'autodrops'}) {
9404: $cenv{'internal.autodrops'}=$args->{'autodrops'};
9405: }
9406: # check for notification of enrollment changes
9407: my @notified = ();
9408: if ($args->{'notify_owner'}) {
9409: if ($args->{'ccuname'} ne '') {
9410: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
9411: }
9412: }
9413: if ($args->{'notify_dc'}) {
9414: if ($uname ne '') {
9415: push(@notified,$uname.':'.$udom);
9416: }
9417: }
9418: if (@notified > 0) {
9419: my $notifylist;
9420: if (@notified > 1) {
9421: $notifylist = join(',',@notified);
9422: } else {
9423: $notifylist = $notified[0];
9424: }
9425: $cenv{'internal.notifylist'} = $notifylist;
9426: }
9427: if (@badclasses > 0) {
9428: my %lt=&Apache::lonlocal::texthash(
9429: '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',
9430: 'dnhr' => 'does not have rights to access enrollment in these classes',
9431: 'adby' => 'as determined by the policies of your institution on access to official classlists'
9432: );
9433: my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
9434: ' ('.$lt{'adby'}.')';
9435: if ($context eq 'auto') {
9436: $outcome .= $badclass_msg.$linefeed;
9437: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
9438: foreach my $item (@badclasses) {
9439: if ($context eq 'auto') {
9440: $outcome .= " - $item\n";
9441: } else {
9442: $outcome .= "<li>$item</li>\n";
9443: }
9444: }
9445: if ($context eq 'auto') {
9446: $outcome .= $linefeed;
9447: } else {
9448: $outcome .= "</ul><br /><br /></div>\n";
9449: }
9450: }
9451: }
9452: if ($args->{'no_end_date'}) {
9453: $args->{'endaccess'} = 0;
9454: }
9455: $cenv{'internal.autostart'}=$args->{'enrollstart'};
9456: $cenv{'internal.autoend'}=$args->{'enrollend'};
9457: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
9458: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
9459: if ($args->{'showphotos'}) {
9460: $cenv{'internal.showphotos'}=$args->{'showphotos'};
9461: }
9462: $cenv{'internal.authtype'} = $args->{'authtype'};
9463: $cenv{'internal.autharg'} = $args->{'autharg'};
9464: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
9465: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
9466: 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');
9467: if ($context eq 'auto') {
9468: $outcome .= $krb_msg;
9469: } else {
9470: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
9471: }
9472: $outcome .= $linefeed;
9473: }
9474: }
9475: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
9476: if ($args->{'setpolicy'}) {
9477: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
9478: }
9479: if ($args->{'setcontent'}) {
9480: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
9481: }
9482: }
9483: if ($args->{'reshome'}) {
9484: $cenv{'reshome'}=$args->{'reshome'}.'/';
9485: $cenv{'reshome'}=~s/\/+$/\//;
9486: }
9487: #
9488: # course has keyed access
9489: #
9490: if ($args->{'setkeys'}) {
9491: $cenv{'keyaccess'}='yes';
9492: }
9493: # if specified, key authority is not course, but user
9494: # only active if keyaccess is yes
9495: if ($args->{'keyauth'}) {
9496: my ($user,$domain) = split(':',$args->{'keyauth'});
9497: $user = &LONCAPA::clean_username($user);
9498: $domain = &LONCAPA::clean_username($domain);
9499: if ($user ne '' && $domain ne '') {
9500: $cenv{'keyauth'}=$user.':'.$domain;
9501: }
9502: }
9503:
9504: if ($args->{'disresdis'}) {
9505: $cenv{'pch.roles.denied'}='st';
9506: }
9507: if ($args->{'disablechat'}) {
9508: $cenv{'plc.roles.denied'}='st';
9509: }
9510:
9511: # Record we've not yet viewed the Course Initialization Helper for this
9512: # course
9513: $cenv{'course.helper.not.run'} = 1;
9514: #
9515: # Use new Randomseed
9516: #
9517: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
9518: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
9519: #
9520: # The encryption code and receipt prefix for this course
9521: #
9522: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
9523: $cenv{'internal.encpref'}=100+int(9*rand(99));
9524: #
9525: # By default, use standard grading
9526: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
9527:
9528: $outcome .= $linefeed.&mt('Setting environment').': '.
9529: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
9530: #
9531: # Open all assignments
9532: #
9533: if ($args->{'openall'}) {
9534: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
9535: my %storecontent = ($storeunder => time,
9536: $storeunder.'.type' => 'date_start');
9537:
9538: $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
9539: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
9540: }
9541: #
9542: # Set first page
9543: #
9544: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
9545: || ($cloneid)) {
9546: use LONCAPA::map;
9547: $outcome .= &mt('Setting first resource').': ';
9548:
9549: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
9550: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
9551:
9552: $outcome .= ($fatal?$errtext:'read ok').' - ';
9553: my $title; my $url;
9554: if ($args->{'firstres'} eq 'syl') {
9555: $title=&mt('Syllabus');
9556: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
9557: } else {
9558: $title=&mt('Navigate Contents');
9559: $url='/adm/navmaps';
9560: }
9561:
9562: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
9563: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
9564:
9565: if ($errtext) { $fatal=2; }
9566: $outcome .= ($fatal?$errtext:'write ok').$linefeed;
9567: }
9568:
9569: return (1,$outcome);
9570: }
9571:
9572: ############################################################
9573: ############################################################
9574:
9575: sub course_type {
9576: my ($cid) = @_;
9577: if (!defined($cid)) {
9578: $cid = $env{'request.course.id'};
9579: }
9580: if (defined($env{'course.'.$cid.'.type'})) {
9581: return $env{'course.'.$cid.'.type'};
9582: } else {
9583: return 'Course';
9584: }
9585: }
9586:
9587: sub group_term {
9588: my $crstype = &course_type();
9589: my %names = (
9590: 'Course' => 'group',
9591: 'Group' => 'team',
9592: );
9593: return $names{$crstype};
9594: }
9595:
9596: sub icon {
9597: my ($file)=@_;
9598: my $curfext = lc((split(/\./,$file))[-1]);
9599: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
9600: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
9601: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
9602: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
9603: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
9604: $curfext.".gif") {
9605: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
9606: $curfext.".gif";
9607: }
9608: }
9609: return &lonhttpdurl($iconname);
9610: }
9611:
9612: sub lonhttpdurl {
9613: #
9614: # Had been used for "small fry" static images on separate port 8080.
9615: # Modify here if lightweight http functionality desired again.
9616: # Currently eliminated due to increasing firewall issues.
9617: #
9618: my ($url)=@_;
9619: return $url;
9620: }
9621:
9622: sub connection_aborted {
9623: my ($r)=@_;
9624: $r->print(" ");$r->rflush();
9625: my $c = $r->connection;
9626: return $c->aborted();
9627: }
9628:
9629: # Escapes strings that may have embedded 's that will be put into
9630: # strings as 'strings'.
9631: sub escape_single {
9632: my ($input) = @_;
9633: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
9634: $input =~ s/\'/\\\'/g; # Esacpe the 's....
9635: return $input;
9636: }
9637:
9638: # Same as escape_single, but escape's "'s This
9639: # can be used for "strings"
9640: sub escape_double {
9641: my ($input) = @_;
9642: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
9643: $input =~ s/\"/\\\"/g; # Esacpe the "s....
9644: return $input;
9645: }
9646:
9647: # Escapes the last element of a full URL.
9648: sub escape_url {
9649: my ($url) = @_;
9650: my @urlslices = split(/\//, $url,-1);
9651: my $lastitem = &escape(pop(@urlslices));
9652: return join('/',@urlslices).'/'.$lastitem;
9653: }
9654:
9655: # -------------------------------------------------------- Initliaze user login
9656: sub init_user_environment {
9657: my ($r, $username, $domain, $authhost, $form, $args) = @_;
9658: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
9659:
9660: my $public=($username eq 'public' && $domain eq 'public');
9661:
9662: # See if old ID present, if so, remove
9663:
9664: my ($filename,$cookie,$userroles);
9665: my $now=time;
9666:
9667: if ($public) {
9668: my $max_public=100;
9669: my $oldest;
9670: my $oldest_time=0;
9671: for(my $next=1;$next<=$max_public;$next++) {
9672: if (-e $lonids."/publicuser_$next.id") {
9673: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
9674: if ($mtime<$oldest_time || !$oldest_time) {
9675: $oldest_time=$mtime;
9676: $oldest=$next;
9677: }
9678: } else {
9679: $cookie="publicuser_$next";
9680: last;
9681: }
9682: }
9683: if (!$cookie) { $cookie="publicuser_$oldest"; }
9684: } else {
9685: # if this isn't a robot, kill any existing non-robot sessions
9686: if (!$args->{'robot'}) {
9687: opendir(DIR,$lonids);
9688: while ($filename=readdir(DIR)) {
9689: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
9690: unlink($lonids.'/'.$filename);
9691: }
9692: }
9693: closedir(DIR);
9694: }
9695: # Give them a new cookie
9696: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
9697: : $now.$$.int(rand(10000)));
9698: $cookie="$username\_$id\_$domain\_$authhost";
9699:
9700: # Initialize roles
9701:
9702: $userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
9703: }
9704: # ------------------------------------ Check browser type and MathML capability
9705:
9706: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
9707: $clientunicode,$clientos) = &decode_user_agent($r);
9708:
9709: # -------------------------------------- Any accessibility options to remember?
9710: if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
9711: foreach my $option ('imagesuppress','appletsuppress',
9712: 'embedsuppress','fontenhance','blackwhite') {
9713: if ($form->{$option} eq 'true') {
9714: &Apache::lonnet::put('environment',{$option => 'on'},
9715: $domain,$username);
9716: } else {
9717: &Apache::lonnet::del('environment',[$option],
9718: $domain,$username);
9719: }
9720: }
9721: }
9722: # ------------------------------------------------------------- Get environment
9723:
9724: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
9725: my ($tmp) = keys(%userenv);
9726: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9727: # default remote control to off
9728: if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
9729: } else {
9730: undef(%userenv);
9731: }
9732: if (($userenv{'interface'}) && (!$form->{'interface'})) {
9733: $form->{'interface'}=$userenv{'interface'};
9734: }
9735: $env{'environment.remote'}=$userenv{'remote'};
9736: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
9737:
9738: # --------------- Do not trust query string to be put directly into environment
9739: foreach my $option ('imagesuppress','appletsuppress',
9740: 'embedsuppress','fontenhance','blackwhite',
9741: 'interface','localpath','localres') {
9742: $form->{$option}=~s/[\n\r\=]//gs;
9743: }
9744: # --------------------------------------------------------- Write first profile
9745:
9746: {
9747: my %initial_env =
9748: ("user.name" => $username,
9749: "user.domain" => $domain,
9750: "user.home" => $authhost,
9751: "browser.type" => $clientbrowser,
9752: "browser.version" => $clientversion,
9753: "browser.mathml" => $clientmathml,
9754: "browser.unicode" => $clientunicode,
9755: "browser.os" => $clientos,
9756: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
9757: "request.course.fn" => '',
9758: "request.course.uri" => '',
9759: "request.course.sec" => '',
9760: "request.role" => 'cm',
9761: "request.role.adv" => $env{'user.adv'},
9762: "request.host" => $ENV{'REMOTE_ADDR'},);
9763:
9764: if ($form->{'localpath'}) {
9765: $initial_env{"browser.localpath"} = $form->{'localpath'};
9766: $initial_env{"browser.localres"} = $form->{'localres'};
9767: }
9768:
9769: if ($public) {
9770: $initial_env{"environment.remote"} = "off";
9771: }
9772: if ($form->{'interface'}) {
9773: $form->{'interface'}=~s/\W//gs;
9774: $initial_env{"browser.interface"} = $form->{'interface'};
9775: $env{'browser.interface'}=$form->{'interface'};
9776: foreach my $option ('imagesuppress','appletsuppress',
9777: 'embedsuppress','fontenhance','blackwhite') {
9778: if (($form->{$option} eq 'true') ||
9779: ($userenv{$option} eq 'on')) {
9780: $initial_env{"browser.$option"} = "on";
9781: }
9782: }
9783: }
9784:
9785: $env{'user.environment'} = "$lonids/$cookie.id";
9786:
9787: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
9788: &GDBM_WRCREAT(),0640)) {
9789: &_add_to_env(\%disk_env,\%initial_env);
9790: &_add_to_env(\%disk_env,\%userenv,'environment.');
9791: &_add_to_env(\%disk_env,$userroles);
9792: if (ref($args->{'extra_env'})) {
9793: &_add_to_env(\%disk_env,$args->{'extra_env'});
9794: }
9795: untie(%disk_env);
9796: } else {
9797: &Apache::lonnet::logthis("<font color=\"blue\">WARNING: ".
9798: 'Could not create environment storage in lonauth: '.$!.'</font>');
9799: return 'error: '.$!;
9800: }
9801: }
9802: $env{'request.role'}='cm';
9803: $env{'request.role.adv'}=$env{'user.adv'};
9804: $env{'browser.type'}=$clientbrowser;
9805:
9806: return $cookie;
9807:
9808: }
9809:
9810: sub _add_to_env {
9811: my ($idf,$env_data,$prefix) = @_;
9812: if (ref($env_data) eq 'HASH') {
9813: while (my ($key,$value) = each(%$env_data)) {
9814: $idf->{$prefix.$key} = $value;
9815: $env{$prefix.$key} = $value;
9816: }
9817: }
9818: }
9819:
9820: # --- Get the symbolic name of a problem and the url
9821: sub get_symb {
9822: my ($request,$silent) = @_;
9823: (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
9824: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
9825: if ($symb eq '') {
9826: if (!$silent) {
9827: $request->print("Unable to handle ambiguous references:$url:.");
9828: return ();
9829: }
9830: }
9831: &Apache::lonenc::check_decrypt(\$symb);
9832: return ($symb);
9833: }
9834:
9835: # --------------------------------------------------------------Get annotation
9836:
9837: sub get_annotation {
9838: my ($symb,$enc) = @_;
9839:
9840: my $key = $symb;
9841: if (!$enc) {
9842: $key =
9843: &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
9844: }
9845: my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
9846: return $annotation{$key};
9847: }
9848:
9849: sub clean_symb {
9850: my ($symb) = @_;
9851:
9852: &Apache::lonenc::check_decrypt(\$symb);
9853: my $enc = $env{'request.enc'};
9854: delete($env{'request.enc'});
9855:
9856: return ($symb,$enc);
9857: }
9858:
9859: =pod
9860:
9861: =back
9862:
9863: =cut
9864:
9865: 1;
9866: __END__;
9867:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>