File:
[LON-CAPA] /
loncom /
interface /
loncommon.pm
Revision
1.875:
download - view:
text,
annotated -
select for diffs
Mon Aug 3 16:47:53 2009 UTC (15 years, 2 months ago) by
bisitz
Branches:
MAIN
CVS tags:
HEAD
- XHTML: Added missing quotation marks to HTML attribute (Selection list generated by &csv_print_select_table)
- Removed now unused style "LC_role_level" (only occurrence has been removed in lonuserutils.pm 1.95)
1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.875 2009/08/03 16:47:53 bisitz Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29: # Makes a table out of the previous attempts
30: # Inputs result_from_symbread, user, domain, course_id
31: # Reads in non-network-related .tab files
32:
33: # POD header:
34:
35: =pod
36:
37: =head1 NAME
38:
39: Apache::loncommon - pile of common routines
40:
41: =head1 SYNOPSIS
42:
43: Common routines for manipulating connections, student answers,
44: domains, common Javascript fragments, etc.
45:
46: =head1 OVERVIEW
47:
48: A collection of commonly used subroutines that don't have a natural
49: home anywhere else. This collection helps remove
50: redundancy from other modules and increase efficiency of memory usage.
51:
52: =cut
53:
54: # End of POD header
55: package Apache::loncommon;
56:
57: use strict;
58: use Apache::lonnet;
59: use GDBM_File;
60: use POSIX qw(strftime mktime);
61: use Apache::lonmenu();
62: use Apache::lonenc();
63: use Apache::lonlocal;
64: use Apache::lonnet();
65: use HTML::Entities;
66: use Apache::lonhtmlcommon();
67: use Apache::loncoursedata();
68: use Apache::lontexconvert();
69: use Apache::lonclonecourse();
70: use LONCAPA qw(:DEFAULT :match);
71: use DateTime::TimeZone;
72: use DateTime::Locale::Catalog;
73:
74: # ---------------------------------------------- Designs
75: use vars qw(%defaultdesign);
76:
77: my $readit;
78:
79:
80: ##
81: ## Global Variables
82: ##
83:
84:
85: # ----------------------------------------------- SSI with retries:
86: #
87:
88: =pod
89:
90: =head1 Server Side include with retries:
91:
92: =over 4
93:
94: =item * &ssi_with_retries(resource,retries form)
95:
96: Performs an ssi with some number of retries. Retries continue either
97: until the result is ok or until the retry count supplied by the
98: caller is exhausted.
99:
100: Inputs:
101:
102: =over 4
103:
104: resource - Identifies the resource to insert.
105:
106: retries - Count of the number of retries allowed.
107:
108: form - Hash that identifies the rendering options.
109:
110: =back
111:
112: Returns:
113:
114: =over 4
115:
116: content - The content of the response. If retries were exhausted this is empty.
117:
118: response - The response from the last attempt (which may or may not have been successful.
119:
120: =back
121:
122: =back
123:
124: =cut
125:
126: sub ssi_with_retries {
127: my ($resource, $retries, %form) = @_;
128:
129:
130: my $ok = 0; # True if we got a good response.
131: my $content;
132: my $response;
133:
134: # Try to get the ssi done. within the retries count:
135:
136: do {
137: ($content, $response) = &Apache::lonnet::ssi($resource, %form);
138: $ok = $response->is_success;
139: if (!$ok) {
140: &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
141: }
142: $retries--;
143: } while (!$ok && ($retries > 0));
144:
145: if (!$ok) {
146: $content = ''; # On error return an empty content.
147: }
148: return ($content, $response);
149:
150: }
151:
152:
153:
154: # ----------------------------------------------- Filetypes/Languages/Copyright
155: my %language;
156: my %supported_language;
157: my %cprtag;
158: my %scprtag;
159: my %fe; my %fd; my %fm;
160: my %category_extensions;
161:
162: # ---------------------------------------------- Thesaurus variables
163: #
164: # %Keywords:
165: # A hash used by &keyword to determine if a word is considered a keyword.
166: # $thesaurus_db_file
167: # Scalar containing the full path to the thesaurus database.
168:
169: my %Keywords;
170: my $thesaurus_db_file;
171:
172: #
173: # Initialize values from language.tab, copyright.tab, filetypes.tab,
174: # thesaurus.tab, and filecategories.tab.
175: #
176: BEGIN {
177: # Variable initialization
178: $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
179: #
180: unless ($readit) {
181: # ------------------------------------------------------------------- languages
182: {
183: my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
184: '/language.tab';
185: if ( open(my $fh,"<$langtabfile") ) {
186: while (my $line = <$fh>) {
187: next if ($line=~/^\#/);
188: chomp($line);
189: my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
190: $language{$key}=$val.' - '.$enc;
191: if ($sup) {
192: $supported_language{$key}=$sup;
193: }
194: }
195: close($fh);
196: }
197: }
198: # ------------------------------------------------------------------ copyrights
199: {
200: my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
201: '/copyright.tab';
202: if ( open (my $fh,"<$copyrightfile") ) {
203: while (my $line = <$fh>) {
204: next if ($line=~/^\#/);
205: chomp($line);
206: my ($key,$val)=(split(/\s+/,$line,2));
207: $cprtag{$key}=$val;
208: }
209: close($fh);
210: }
211: }
212: # ----------------------------------------------------------- source copyrights
213: {
214: my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
215: '/source_copyright.tab';
216: if ( open (my $fh,"<$sourcecopyrightfile") ) {
217: while (my $line = <$fh>) {
218: next if ($line =~ /^\#/);
219: chomp($line);
220: my ($key,$val)=(split(/\s+/,$line,2));
221: $scprtag{$key}=$val;
222: }
223: close($fh);
224: }
225: }
226:
227: # -------------------------------------------------------------- default domain designs
228: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
229: my $designfile = $designdir.'/default.tab';
230: if ( open (my $fh,"<$designfile") ) {
231: while (my $line = <$fh>) {
232: next if ($line =~ /^\#/);
233: chomp($line);
234: my ($key,$val)=(split(/\=/,$line));
235: if ($val) { $defaultdesign{$key}=$val; }
236: }
237: close($fh);
238: }
239:
240: # ------------------------------------------------------------- file categories
241: {
242: my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
243: '/filecategories.tab';
244: if ( open (my $fh,"<$categoryfile") ) {
245: while (my $line = <$fh>) {
246: next if ($line =~ /^\#/);
247: chomp($line);
248: my ($extension,$category)=(split(/\s+/,$line,2));
249: push @{$category_extensions{lc($category)}},$extension;
250: }
251: close($fh);
252: }
253:
254: }
255: # ------------------------------------------------------------------ file types
256: {
257: my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
258: '/filetypes.tab';
259: if ( open (my $fh,"<$typesfile") ) {
260: while (my $line = <$fh>) {
261: next if ($line =~ /^\#/);
262: chomp($line);
263: my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
264: if ($descr ne '') {
265: $fe{$ending}=lc($emb);
266: $fd{$ending}=$descr;
267: if ($mime ne 'unk') { $fm{$ending}=$mime; }
268: }
269: }
270: close($fh);
271: }
272: }
273: &Apache::lonnet::logthis(
274: "<span style='color:yellow;'>INFO: Read file types</span>");
275: $readit=1;
276: } # end of unless($readit)
277:
278: }
279:
280: ###############################################################
281: ## HTML and Javascript Helper Functions ##
282: ###############################################################
283:
284: =pod
285:
286: =head1 HTML and Javascript Functions
287:
288: =over 4
289:
290: =item * &browser_and_searcher_javascript()
291:
292: X<browsing, javascript>X<searching, javascript>Returns a string
293: containing javascript with two functions, C<openbrowser> and
294: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
295: tags.
296:
297: =item * &openbrowser(formname,elementname,only,omit) [javascript]
298:
299: inputs: formname, elementname, only, omit
300:
301: formname and elementname indicate the name of the html form and name of
302: the element that the results of the browsing selection are to be placed in.
303:
304: Specifying 'only' will restrict the browser to displaying only files
305: with the given extension. Can be a comma separated list.
306:
307: Specifying 'omit' will restrict the browser to NOT displaying files
308: with the given extension. Can be a comma separated list.
309:
310: =item * &opensearcher(formname,elementname) [javascript]
311:
312: Inputs: formname, elementname
313:
314: formname and elementname specify the name of the html form and the name
315: of the element the selection from the search results will be placed in.
316:
317: =cut
318:
319: sub browser_and_searcher_javascript {
320: my ($mode)=@_;
321: if (!defined($mode)) { $mode='edit'; }
322: my $resurl=&escape_single(&lastresurl());
323: return <<END;
324: // <!-- BEGIN LON-CAPA Internal
325: var editbrowser = null;
326: function openbrowser(formname,elementname,only,omit,titleelement) {
327: var url = '$resurl/?';
328: if (editbrowser == null) {
329: url += 'launch=1&';
330: }
331: url += 'catalogmode=interactive&';
332: url += 'mode=$mode&';
333: url += 'inhibitmenu=yes&';
334: url += 'form=' + formname + '&';
335: if (only != null) {
336: url += 'only=' + only + '&';
337: } else {
338: url += 'only=&';
339: }
340: if (omit != null) {
341: url += 'omit=' + omit + '&';
342: } else {
343: url += 'omit=&';
344: }
345: if (titleelement != null) {
346: url += 'titleelement=' + titleelement + '&';
347: } else {
348: url += 'titleelement=&';
349: }
350: url += 'element=' + elementname + '';
351: var title = 'Browser';
352: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
353: options += ',width=700,height=600';
354: editbrowser = open(url,title,options,'1');
355: editbrowser.focus();
356: }
357: var editsearcher;
358: function opensearcher(formname,elementname,titleelement) {
359: var url = '/adm/searchcat?';
360: if (editsearcher == null) {
361: url += 'launch=1&';
362: }
363: url += 'catalogmode=interactive&';
364: url += 'mode=$mode&';
365: url += 'form=' + formname + '&';
366: if (titleelement != null) {
367: url += 'titleelement=' + titleelement + '&';
368: } else {
369: url += 'titleelement=&';
370: }
371: url += 'element=' + elementname + '';
372: var title = 'Search';
373: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
374: options += ',width=700,height=600';
375: editsearcher = open(url,title,options,'1');
376: editsearcher.focus();
377: }
378: // END LON-CAPA Internal -->
379: END
380: }
381:
382: sub lastresurl {
383: if ($env{'environment.lastresurl'}) {
384: return $env{'environment.lastresurl'}
385: } else {
386: return '/res';
387: }
388: }
389:
390: sub storeresurl {
391: my $resurl=&Apache::lonnet::clutter(shift);
392: unless ($resurl=~/^\/res/) { return 0; }
393: $resurl=~s/\/$//;
394: &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
395: &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
396: return 1;
397: }
398:
399: sub studentbrowser_javascript {
400: unless (
401: (($env{'request.course.id'}) &&
402: (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
403: || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
404: '/'.$env{'request.course.sec'})
405: ))
406: || ($env{'request.role'}=~/^(au|dc|su)/)
407: ) { return ''; }
408: return (<<'ENDSTDBRW');
409: <script type="text/javascript" language="Javascript">
410: // <![CDATA[
411: var stdeditbrowser;
412: function openstdbrowser(formname,uname,udom,roleflag,ignorefilter,courseadvonly) {
413: var url = '/adm/pickstudent?';
414: var filter;
415: if (!ignorefilter) {
416: eval('filter=document.'+formname+'.'+uname+'.value;');
417: }
418: if (filter != null) {
419: if (filter != '') {
420: url += 'filter='+filter+'&';
421: }
422: }
423: url += 'form=' + formname + '&unameelement='+uname+
424: '&udomelement='+udom;
425: if (roleflag) { url+="&roles=1"; }
426: if (courseadvonly) { url+="&courseadvonly=1"; }
427: var title = 'Student_Browser';
428: var options = 'scrollbars=1,resizable=1,menubar=0';
429: options += ',width=700,height=600';
430: stdeditbrowser = open(url,title,options,'1');
431: stdeditbrowser.focus();
432: }
433: // ]]>
434: </script>
435: ENDSTDBRW
436: }
437:
438: sub selectstudent_link {
439: my ($form,$unameele,$udomele,$courseadvonly)=@_;
440: my $callargs = "'".$form."','".$unameele."','".$udomele."'";
441: if ($env{'request.course.id'}) {
442: if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
443: && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
444: '/'.$env{'request.course.sec'})) {
445: return '';
446: }
447: if ($courseadvonly) {
448: $callargs .= ",'',1,1";
449: }
450: return '<span class="LC_nobreak">'.
451: '<a href="javascript:openstdbrowser('.$callargs.');">'.
452: &mt('Select User').'</a></span>';
453: }
454: if ($env{'request.role'}=~/^(au|dc|su)/) {
455: $callargs .= ",1";
456: return '<span class="LC_nobreak">'.
457: '<a href="javascript:openstdbrowser('.$callargs.');">'.
458: &mt('Select User').'</a></span>';
459: }
460: return '';
461: }
462:
463: sub authorbrowser_javascript {
464: return <<"ENDAUTHORBRW";
465: <script type="text/javascript" language="JavaScript">
466: // <![CDATA[
467: var stdeditbrowser;
468:
469: function openauthorbrowser(formname,udom) {
470: var url = '/adm/pickauthor?';
471: url += 'form='+formname+'&roledom='+udom;
472: var title = 'Author_Browser';
473: var options = 'scrollbars=1,resizable=1,menubar=0';
474: options += ',width=700,height=600';
475: stdeditbrowser = open(url,title,options,'1');
476: stdeditbrowser.focus();
477: }
478:
479: // ]]>
480: </script>
481: ENDAUTHORBRW
482: }
483:
484: sub coursebrowser_javascript {
485: my ($domainfilter,$sec_element,$formname)=@_;
486: my $crs_or_grp_alert = &mt('Please select the type of LON-CAPA entity - Course or Community - for which you wish to add/modify a user role');
487: my $output = '
488: <script type="text/javascript" language="JavaScript">
489: // <![CDATA[
490: var stdeditbrowser;'."\n";
491: $output .= <<"ENDSTDBRW";
492: function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,crstype) {
493: var url = '/adm/pickcourse?';
494: var domainfilter = '';
495: var formid = getFormIdByName(formname);
496: if (formid > -1) {
497: var domid = getIndexByName(formid,udom);
498: if (domid > -1) {
499: if (document.forms[formid].elements[domid].type == 'select-one') {
500: domainfilter=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
501: }
502: if (document.forms[formid].elements[domid].type == 'hidden') {
503: domainfilter=document.forms[formid].elements[domid].value;
504: }
505: }
506: }
507: if (domainfilter != null) {
508: if (domainfilter != '') {
509: url += 'domainfilter='+domainfilter+'&';
510: }
511: }
512: url += 'form=' + formname + '&cnumelement='+uname+
513: '&cdomelement='+udom+
514: '&cnameelement='+desc;
515: if (extra_element !=null && extra_element != '') {
516: if (formname == 'rolechoice' || formname == 'studentform') {
517: url += '&roleelement='+extra_element;
518: if (domainfilter == null || domainfilter == '') {
519: url += '&domainfilter='+extra_element;
520: }
521: }
522: else {
523: if (formname == 'portform') {
524: url += '&setroles='+extra_element;
525: } else {
526: if (formname == 'rules') {
527: url += '&fixeddom='+extra_element;
528: }
529: }
530: }
531: }
532: if (formname == 'ccrs') {
533: var ownername = document.forms[formid].ccuname.value;
534: var ownerdom = document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
535: url += '&cloner='+ownername+':'+ownerdom;
536: }
537: if (multflag !=null && multflag != '') {
538: url += '&multiple='+multflag;
539: }
540: if (crstype == 'Course/Community') {
541: if (formname == 'cu') {
542: crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value;
543: if (crstype == "") {
544: alert("$crs_or_grp_alert");
545: return;
546: }
547: }
548: }
549: if (crstype !=null && crstype != '') {
550: url += '&type='+crstype;
551: }
552: var title = 'Course_Browser';
553: var options = 'scrollbars=1,resizable=1,menubar=0';
554: options += ',width=700,height=600';
555: stdeditbrowser = open(url,title,options,'1');
556: stdeditbrowser.focus();
557: }
558:
559: function getFormIdByName(formname) {
560: for (var i=0;i<document.forms.length;i++) {
561: if (document.forms[i].name == formname) {
562: return i;
563: }
564: }
565: return -1;
566: }
567:
568: function getIndexByName(formid,item) {
569: for (var i=0;i<document.forms[formid].elements.length;i++) {
570: if (document.forms[formid].elements[i].name == item) {
571: return i;
572: }
573: }
574: return -1;
575: }
576: ENDSTDBRW
577: if ($sec_element ne '') {
578: $output .= &setsec_javascript($sec_element,$formname);
579: }
580: $output .= '
581: // ]]>
582: </script>';
583: return $output;
584: }
585:
586: sub setsec_javascript {
587: my ($sec_element,$formname) = @_;
588: my $setsections = qq|
589: function setSect(sectionlist) {
590: var sectionsArray = new Array();
591: if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
592: sectionsArray = sectionlist.split(",");
593: }
594: var numSections = sectionsArray.length;
595: document.$formname.$sec_element.length = 0;
596: if (numSections == 0) {
597: document.$formname.$sec_element.multiple=false;
598: document.$formname.$sec_element.size=1;
599: document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
600: } else {
601: if (numSections == 1) {
602: document.$formname.$sec_element.multiple=false;
603: document.$formname.$sec_element.size=1;
604: document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
605: document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
606: document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
607: } else {
608: for (var i=0; i<numSections; i++) {
609: document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
610: }
611: document.$formname.$sec_element.multiple=true
612: if (numSections < 3) {
613: document.$formname.$sec_element.size=numSections;
614: } else {
615: document.$formname.$sec_element.size=3;
616: }
617: document.$formname.$sec_element.options[0].selected = false
618: }
619: }
620: }
621: |;
622: return $setsections;
623: }
624:
625:
626: sub selectcourse_link {
627: my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
628: my $linktext = &mt('Select Course');
629: if ($selecttype eq 'Community') {
630: $linktext = &mt('Select Community');
631: }
632: return '<span class="LC_nobreak">'
633: ."<a href='"
634: .'javascript:opencrsbrowser("'.$form.'","'.$unameele
635: .'","'.$udomele.'","'.$desc.'","'.$extra_element
636: .'","'.$multflag.'","'.$selecttype.'");'
637: ."'>".$linktext.'</a>'
638: .'</span>';
639: }
640:
641: sub selectauthor_link {
642: my ($form,$udom)=@_;
643: return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
644: &mt('Select Author').'</a>';
645: }
646:
647: sub check_uncheck_jscript {
648: my $jscript = <<"ENDSCRT";
649: function checkAll(field) {
650: if (field.length > 0) {
651: for (i = 0; i < field.length; i++) {
652: field[i].checked = true ;
653: }
654: } else {
655: field.checked = true
656: }
657: }
658:
659: function uncheckAll(field) {
660: if (field.length > 0) {
661: for (i = 0; i < field.length; i++) {
662: field[i].checked = false ;
663: }
664: } else {
665: field.checked = false ;
666: }
667: }
668: ENDSCRT
669: return $jscript;
670: }
671:
672: sub select_timezone {
673: my ($name,$selected,$onchange,$includeempty)=@_;
674: my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
675: if ($includeempty) {
676: $output .= '<option value=""';
677: if (($selected eq '') || ($selected eq 'local')) {
678: $output .= ' selected="selected" ';
679: }
680: $output .= '> </option>';
681: }
682: my @timezones = DateTime::TimeZone->all_names;
683: foreach my $tzone (@timezones) {
684: $output.= '<option value="'.$tzone.'"';
685: if ($tzone eq $selected) {
686: $output.=' selected="selected"';
687: }
688: $output.=">$tzone</option>\n";
689: }
690: $output.="</select>";
691: return $output;
692: }
693:
694: sub select_datelocale {
695: my ($name,$selected,$onchange,$includeempty)=@_;
696: my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
697: if ($includeempty) {
698: $output .= '<option value=""';
699: if ($selected eq '') {
700: $output .= ' selected="selected" ';
701: }
702: $output .= '> </option>';
703: }
704: my (@possibles,%locale_names);
705: my @locales = DateTime::Locale::Catalog::Locales;
706: foreach my $locale (@locales) {
707: if (ref($locale) eq 'HASH') {
708: my $id = $locale->{'id'};
709: if ($id ne '') {
710: my $en_terr = $locale->{'en_territory'};
711: my $native_terr = $locale->{'native_territory'};
712: my @languages = &Apache::lonlocal::preferred_languages();
713: if (grep(/^en$/,@languages) || !@languages) {
714: if ($en_terr ne '') {
715: $locale_names{$id} = '('.$en_terr.')';
716: } elsif ($native_terr ne '') {
717: $locale_names{$id} = $native_terr;
718: }
719: } else {
720: if ($native_terr ne '') {
721: $locale_names{$id} = $native_terr.' ';
722: } elsif ($en_terr ne '') {
723: $locale_names{$id} = '('.$en_terr.')';
724: }
725: }
726: push (@possibles,$id);
727: }
728: }
729: }
730: foreach my $item (sort(@possibles)) {
731: $output.= '<option value="'.$item.'"';
732: if ($item eq $selected) {
733: $output.=' selected="selected"';
734: }
735: $output.=">$item";
736: if ($locale_names{$item} ne '') {
737: $output.=" $locale_names{$item}</option>\n";
738: }
739: $output.="</option>\n";
740: }
741: $output.="</select>";
742: return $output;
743: }
744:
745: sub select_language {
746: my ($name,$selected,$includeempty) = @_;
747: my %langchoices;
748: if ($includeempty) {
749: %langchoices = ('' => 'No language preference');
750: }
751: foreach my $id (&languageids()) {
752: my $code = &supportedlanguagecode($id);
753: if ($code) {
754: $langchoices{$code} = &plainlanguagedescription($id);
755: }
756: }
757: return &select_form($selected,$name,%langchoices);
758: }
759:
760: =pod
761:
762: =item * &linked_select_forms(...)
763:
764: linked_select_forms returns a string containing a <script></script> block
765: and html for two <select> menus. The select menus will be linked in that
766: changing the value of the first menu will result in new values being placed
767: in the second menu. The values in the select menu will appear in alphabetical
768: order unless a defined order is provided.
769:
770: linked_select_forms takes the following ordered inputs:
771:
772: =over 4
773:
774: =item * $formname, the name of the <form> tag
775:
776: =item * $middletext, the text which appears between the <select> tags
777:
778: =item * $firstdefault, the default value for the first menu
779:
780: =item * $firstselectname, the name of the first <select> tag
781:
782: =item * $secondselectname, the name of the second <select> tag
783:
784: =item * $hashref, a reference to a hash containing the data for the menus.
785:
786: =item * $menuorder, the order of values in the first menu
787:
788: =back
789:
790: Below is an example of such a hash. Only the 'text', 'default', and
791: 'select2' keys must appear as stated. keys(%menu) are the possible
792: values for the first select menu. The text that coincides with the
793: first menu value is given in $menu{$choice1}->{'text'}. The values
794: and text for the second menu are given in the hash pointed to by
795: $menu{$choice1}->{'select2'}.
796:
797: my %menu = ( A1 => { text =>"Choice A1" ,
798: default => "B3",
799: select2 => {
800: B1 => "Choice B1",
801: B2 => "Choice B2",
802: B3 => "Choice B3",
803: B4 => "Choice B4"
804: },
805: order => ['B4','B3','B1','B2'],
806: },
807: A2 => { text =>"Choice A2" ,
808: default => "C2",
809: select2 => {
810: C1 => "Choice C1",
811: C2 => "Choice C2",
812: C3 => "Choice C3"
813: },
814: order => ['C2','C1','C3'],
815: },
816: A3 => { text =>"Choice A3" ,
817: default => "D6",
818: select2 => {
819: D1 => "Choice D1",
820: D2 => "Choice D2",
821: D3 => "Choice D3",
822: D4 => "Choice D4",
823: D5 => "Choice D5",
824: D6 => "Choice D6",
825: D7 => "Choice D7"
826: },
827: order => ['D4','D3','D2','D1','D7','D6','D5'],
828: }
829: );
830:
831: =cut
832:
833: sub linked_select_forms {
834: my ($formname,
835: $middletext,
836: $firstdefault,
837: $firstselectname,
838: $secondselectname,
839: $hashref,
840: $menuorder,
841: ) = @_;
842: my $second = "document.$formname.$secondselectname";
843: my $first = "document.$formname.$firstselectname";
844: # output the javascript to do the changing
845: my $result = '';
846: $result.='<script type="text/javascript" language="JavaScript">'."\n";
847: $result.="// <![CDATA[\n";
848: $result.="var select2data = new Object();\n";
849: $" = '","';
850: my $debug = '';
851: foreach my $s1 (sort(keys(%$hashref))) {
852: $result.="select2data.d_$s1 = new Object();\n";
853: $result.="select2data.d_$s1.def = new String('".
854: $hashref->{$s1}->{'default'}."');\n";
855: $result.="select2data.d_$s1.values = new Array(";
856: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
857: if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
858: @s2values = @{$hashref->{$s1}->{'order'}};
859: }
860: $result.="\"@s2values\");\n";
861: $result.="select2data.d_$s1.texts = new Array(";
862: my @s2texts;
863: foreach my $value (@s2values) {
864: push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
865: }
866: $result.="\"@s2texts\");\n";
867: }
868: $"=' ';
869: $result.= <<"END";
870:
871: function select1_changed() {
872: // Determine new choice
873: var newvalue = "d_" + $first.value;
874: // update select2
875: var values = select2data[newvalue].values;
876: var texts = select2data[newvalue].texts;
877: var select2def = select2data[newvalue].def;
878: var i;
879: // out with the old
880: for (i = 0; i < $second.options.length; i++) {
881: $second.options[i] = null;
882: }
883: // in with the nuclear
884: for (i=0;i<values.length; i++) {
885: $second.options[i] = new Option(values[i]);
886: $second.options[i].value = values[i];
887: $second.options[i].text = texts[i];
888: if (values[i] == select2def) {
889: $second.options[i].selected = true;
890: }
891: }
892: }
893: // ]]>
894: </script>
895: END
896: # output the initial values for the selection lists
897: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
898: my @order = sort(keys(%{$hashref}));
899: if (ref($menuorder) eq 'ARRAY') {
900: @order = @{$menuorder};
901: }
902: foreach my $value (@order) {
903: $result.=" <option value=\"$value\" ";
904: $result.=" selected=\"selected\" " if ($value eq $firstdefault);
905: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
906: }
907: $result .= "</select>\n";
908: my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
909: $result .= $middletext;
910: $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
911: my $seconddefault = $hashref->{$firstdefault}->{'default'};
912:
913: my @secondorder = sort(keys(%select2));
914: if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
915: @secondorder = @{$hashref->{$firstdefault}->{'order'}};
916: }
917: foreach my $value (@secondorder) {
918: $result.=" <option value=\"$value\" ";
919: $result.=" selected=\"selected\" " if ($value eq $seconddefault);
920: $result.=">".&mt($select2{$value})."</option>\n";
921: }
922: $result .= "</select>\n";
923: # return $debug;
924: return $result;
925: } # end of sub linked_select_forms {
926:
927: =pod
928:
929: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height)
930:
931: Returns a string corresponding to an HTML link to the given help
932: $topic, where $topic corresponds to the name of a .tex file in
933: /home/httpd/html/adm/help/tex, with underscores replaced by
934: spaces.
935:
936: $text will optionally be linked to the same topic, allowing you to
937: link text in addition to the graphic. If you do not want to link
938: text, but wish to specify one of the later parameters, pass an
939: empty string.
940:
941: $stayOnPage is a value that will be interpreted as a boolean. If true,
942: the link will not open a new window. If false, the link will open
943: a new window using Javascript. (Default is false.)
944:
945: $width and $height are optional numerical parameters that will
946: override the width and height of the popped up window, which may
947: be useful for certain help topics with big pictures included.
948:
949: =cut
950:
951: sub help_open_topic {
952: my ($topic, $text, $stayOnPage, $width, $height) = @_;
953: $text = "" if (not defined $text);
954: $stayOnPage = 0 if (not defined $stayOnPage);
955: $width = 350 if (not defined $width);
956: $height = 400 if (not defined $height);
957: my $filename = $topic;
958: $filename =~ s/ /_/g;
959:
960: my $template = "";
961: my $link;
962:
963: $topic=~s/\W/\_/g;
964:
965: if (!$stayOnPage) {
966: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
967: } else {
968: $link = "/adm/help/${filename}.hlp";
969: }
970:
971: # Add the text
972: if ($text ne "") {
973: $template.='<span class="LC_help_open_topic">'
974: .'<a target="_top" href="'.$link.'">'
975: .$text.'</a>';
976: }
977:
978: # (Always) Add the graphic
979: my $title = &mt('Online Help');
980: my $helpicon=&lonhttpdurl("/adm/help/help.png");
981: $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
982: .'<img src="'.$helpicon.'" border="0"'
983: .' alt="'.&mt('Help: [_1]',$topic).'"'
984: .' title="'.$title.'"'
985: .' /></a>';
986: if ($text ne "") {
987: $template.='</span>';
988: }
989: return $template;
990:
991: }
992:
993: # This is a quicky function for Latex cheatsheet editing, since it
994: # appears in at least four places
995: sub helpLatexCheatsheet {
996: my ($topic,$text,$not_author) = @_;
997: my $out;
998: my $addOther = '';
999: if ($topic) {
1000: $addOther = '<span>'.&Apache::loncommon::help_open_topic($topic,&mt($text),
1001: undef, undef, 600).
1002: '</span> ';
1003: }
1004: $out = '<span>' # Start cheatsheet
1005: .$addOther
1006: .'<span>'
1007: .&Apache::loncommon::help_open_topic('Greek_Symbols',&mt('Greek Symbols'),
1008: undef,undef,600)
1009: .'</span> <span>'
1010: .&Apache::loncommon::help_open_topic('Other_Symbols',&mt('Other Symbols'),
1011: undef,undef,600)
1012: .'</span>';
1013: unless ($not_author) {
1014: $out .= ' <span>'
1015: .&Apache::loncommon::help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),
1016: undef,undef,600)
1017: .'</span>';
1018: }
1019: $out .= '</span>'; # End cheatsheet
1020: return $out;
1021: }
1022:
1023: sub general_help {
1024: my $helptopic='Student_Intro';
1025: if ($env{'request.role'}=~/^(ca|au)/) {
1026: $helptopic='Authoring_Intro';
1027: } elsif ($env{'request.role'}=~/^cc/) {
1028: $helptopic='Course_Coordination_Intro';
1029: } elsif ($env{'request.role'}=~/^dc/) {
1030: $helptopic='Domain_Coordination_Intro';
1031: }
1032: return $helptopic;
1033: }
1034:
1035: sub update_help_link {
1036: my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
1037: my $origurl = $ENV{'REQUEST_URI'};
1038: $origurl=~s|^/~|/priv/|;
1039: my $timestamp = time;
1040: foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
1041: $$datum = &escape($$datum);
1042: }
1043:
1044: my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage";
1045: my $output .= <<"ENDOUTPUT";
1046: <script type="text/javascript">
1047: // <![CDATA[
1048: banner_link = '$banner_link';
1049: // ]]>
1050: </script>
1051: ENDOUTPUT
1052: return $output;
1053: }
1054:
1055: # now just updates the help link and generates a blue icon
1056: sub help_open_menu {
1057: my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text)
1058: = @_;
1059: $stayOnPage = 0 if (not defined $stayOnPage);
1060: # only use pop-up help (stayOnPage == 0)
1061: # if environment.remote is on (using remote control UI)
1062: if ($env{'environment.remote'} eq 'off' ) {
1063: $stayOnPage=1;
1064: }
1065: my $output;
1066: if ($component_help) {
1067: if (!$text) {
1068: $output=&help_open_topic($component_help,undef,$stayOnPage,
1069: $width,$height);
1070: } else {
1071: my $help_text;
1072: $help_text=&unescape($topic);
1073: $output='<table><tr><td>'.
1074: &help_open_topic($component_help,$help_text,$stayOnPage,
1075: $width,$height).'</td></tr></table>';
1076: }
1077: }
1078: my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
1079: return $output.$banner_link;
1080: }
1081:
1082: sub top_nav_help {
1083: my ($text) = @_;
1084: $text = &mt($text);
1085: my $stay_on_page =
1086: ($env{'environment.remote'} eq 'off' );
1087: my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1088: : "javascript:helpMenu('open')";
1089: my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1090:
1091: my $title = &mt('Get help');
1092:
1093: return <<"END";
1094: $banner_link
1095: <a href="$link" title="$title">$text</a>
1096: END
1097: }
1098:
1099: sub help_menu_js {
1100: my ($text) = @_;
1101:
1102: my $stayOnPage =
1103: ($env{'environment.remote'} eq 'off' );
1104:
1105: my $width = 620;
1106: my $height = 600;
1107: my $helptopic=&general_help();
1108: my $details_link = '/adm/help/'.$helptopic.'.hlp';
1109: my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1110: my $start_page =
1111: &Apache::loncommon::start_page('Help Menu', undef,
1112: {'frameset' => 1,
1113: 'js_ready' => 1,
1114: 'add_entries' => {
1115: 'border' => '0',
1116: 'rows' => "110,*",},});
1117: my $end_page =
1118: &Apache::loncommon::end_page({'frameset' => 1,
1119: 'js_ready' => 1,});
1120:
1121: my $template .= <<"ENDTEMPLATE";
1122: <script type="text/javascript">
1123: // <!-- BEGIN LON-CAPA Internal
1124: // <![CDATA[
1125: var banner_link = '';
1126: function helpMenu(target) {
1127: var caller = this;
1128: if (target == 'open') {
1129: var newWindow = null;
1130: try {
1131: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1132: }
1133: catch(error) {
1134: writeHelp(caller);
1135: return;
1136: }
1137: if (newWindow) {
1138: caller = newWindow;
1139: }
1140: }
1141: writeHelp(caller);
1142: return;
1143: }
1144: function writeHelp(caller) {
1145: caller.document.writeln('$start_page<frame name="bannerframe" src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
1146: caller.document.close()
1147: caller.focus()
1148: }
1149: // ]]>
1150: // END LON-CAPA Internal -->
1151: </script>
1152: ENDTEMPLATE
1153: return $template;
1154: }
1155:
1156: sub help_open_bug {
1157: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1158: unless ($env{'user.adv'}) { return ''; }
1159: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
1160: $text = "" if (not defined $text);
1161: $stayOnPage = 0 if (not defined $stayOnPage);
1162: if ($env{'environment.remote'} eq 'off' ) {
1163: $stayOnPage=1;
1164: }
1165: $width = 600 if (not defined $width);
1166: $height = 600 if (not defined $height);
1167:
1168: $topic=~s/\W+/\+/g;
1169: my $link='';
1170: my $template='';
1171: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
1172: &escape($ENV{'REQUEST_URI'}).'&component='.$topic;
1173: if (!$stayOnPage)
1174: {
1175: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1176: }
1177: else
1178: {
1179: $link = $url;
1180: }
1181: # Add the text
1182: if ($text ne "")
1183: {
1184: $template .=
1185: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1186: "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1187: }
1188:
1189: # Add the graphic
1190: my $title = &mt('Report a Bug');
1191: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1192: $template .= <<"ENDTEMPLATE";
1193: <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1194: ENDTEMPLATE
1195: if ($text ne '') { $template.='</td></tr></table>' };
1196: return $template;
1197:
1198: }
1199:
1200: sub help_open_faq {
1201: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1202: unless ($env{'user.adv'}) { return ''; }
1203: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
1204: $text = "" if (not defined $text);
1205: $stayOnPage = 0 if (not defined $stayOnPage);
1206: if ($env{'environment.remote'} eq 'off' ) {
1207: $stayOnPage=1;
1208: }
1209: $width = 350 if (not defined $width);
1210: $height = 400 if (not defined $height);
1211:
1212: $topic=~s/\W+/\+/g;
1213: my $link='';
1214: my $template='';
1215: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
1216: if (!$stayOnPage)
1217: {
1218: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1219: }
1220: else
1221: {
1222: $link = $url;
1223: }
1224:
1225: # Add the text
1226: if ($text ne "")
1227: {
1228: $template .=
1229: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1230: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1231: }
1232:
1233: # Add the graphic
1234: my $title = &mt('View the FAQ');
1235: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1236: $template .= <<"ENDTEMPLATE";
1237: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1238: ENDTEMPLATE
1239: if ($text ne '') { $template.='</td></tr></table>' };
1240: return $template;
1241:
1242: }
1243:
1244: ###############################################################
1245: ###############################################################
1246:
1247: =pod
1248:
1249: =item * &change_content_javascript():
1250:
1251: This and the next function allow you to create small sections of an
1252: otherwise static HTML page that you can update on the fly with
1253: Javascript, even in Netscape 4.
1254:
1255: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
1256: must be written to the HTML page once. It will prove the Javascript
1257: function "change(name, content)". Calling the change function with the
1258: name of the section
1259: you want to update, matching the name passed to C<changable_area>, and
1260: the new content you want to put in there, will put the content into
1261: that area.
1262:
1263: B<Note>: Netscape 4 only reserves enough space for the changable area
1264: to contain room for the original contents. You need to "make space"
1265: for whatever changes you wish to make, and be B<sure> to check your
1266: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
1267: it's adequate for updating a one-line status display, but little more.
1268: This script will set the space to 100% width, so you only need to
1269: worry about height in Netscape 4.
1270:
1271: Modern browsers are much less limiting, and if you can commit to the
1272: user not using Netscape 4, this feature may be used freely with
1273: pretty much any HTML.
1274:
1275: =cut
1276:
1277: sub change_content_javascript {
1278: # If we're on Netscape 4, we need to use Layer-based code
1279: if ($env{'browser.type'} eq 'netscape' &&
1280: $env{'browser.version'} =~ /^4\./) {
1281: return (<<NETSCAPE4);
1282: function change(name, content) {
1283: doc = document.layers[name+"___escape"].layers[0].document;
1284: doc.open();
1285: doc.write(content);
1286: doc.close();
1287: }
1288: NETSCAPE4
1289: } else {
1290: # Otherwise, we need to use semi-standards-compliant code
1291: # (technically, "innerHTML" isn't standard but the equivalent
1292: # is really scary, and every useful browser supports it
1293: return (<<DOMBASED);
1294: function change(name, content) {
1295: element = document.getElementById(name);
1296: element.innerHTML = content;
1297: }
1298: DOMBASED
1299: }
1300: }
1301:
1302: =pod
1303:
1304: =item * &changable_area($name,$origContent):
1305:
1306: This provides a "changable area" that can be modified on the fly via
1307: the Javascript code provided in C<change_content_javascript>. $name is
1308: the name you will use to reference the area later; do not repeat the
1309: same name on a given HTML page more then once. $origContent is what
1310: the area will originally contain, which can be left blank.
1311:
1312: =cut
1313:
1314: sub changable_area {
1315: my ($name, $origContent) = @_;
1316:
1317: if ($env{'browser.type'} eq 'netscape' &&
1318: $env{'browser.version'} =~ /^4\./) {
1319: # If this is netscape 4, we need to use the Layer tag
1320: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
1321: } else {
1322: return "<span id='$name'>$origContent</span>";
1323: }
1324: }
1325:
1326: =pod
1327:
1328: =item * &viewport_geometry_js
1329:
1330: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
1331:
1332: =cut
1333:
1334:
1335: sub viewport_geometry_js {
1336: return <<"GEOMETRY";
1337: var Geometry = {};
1338: function init_geometry() {
1339: if (Geometry.init) { return };
1340: Geometry.init=1;
1341: if (window.innerHeight) {
1342: Geometry.getViewportHeight = function() { return window.innerHeight; };
1343: Geometry.getViewportWidth = function() { return window.innerWidth; };
1344: Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
1345: Geometry.getVerticalScroll = function() { return window.pageYOffset; };
1346: }
1347: else if (document.documentElement && document.documentElement.clientHeight) {
1348: Geometry.getViewportHeight =
1349: function() { return document.documentElement.clientHeight; };
1350: Geometry.getViewportWidth =
1351: function() { return document.documentElement.clientWidth; };
1352:
1353: Geometry.getHorizontalScroll =
1354: function() { return document.documentElement.scrollLeft; };
1355: Geometry.getVerticalScroll =
1356: function() { return document.documentElement.scrollTop; };
1357: }
1358: else if (document.body.clientHeight) {
1359: Geometry.getViewportHeight =
1360: function() { return document.body.clientHeight; };
1361: Geometry.getViewportWidth =
1362: function() { return document.body.clientWidth; };
1363: Geometry.getHorizontalScroll =
1364: function() { return document.body.scrollLeft; };
1365: Geometry.getVerticalScroll =
1366: function() { return document.body.scrollTop; };
1367: }
1368: }
1369:
1370: GEOMETRY
1371: }
1372:
1373: =pod
1374:
1375: =item * &viewport_size_js()
1376:
1377: 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.
1378:
1379: =cut
1380:
1381: sub viewport_size_js {
1382: my $geometry = &viewport_geometry_js();
1383: return <<"DIMS";
1384:
1385: $geometry
1386:
1387: function getViewportDims(width,height) {
1388: init_geometry();
1389: width.value = Geometry.getViewportWidth();
1390: height.value = Geometry.getViewportHeight();
1391: return;
1392: }
1393:
1394: DIMS
1395: }
1396:
1397: =pod
1398:
1399: =item * &resize_textarea_js()
1400:
1401: emits the needed javascript to resize a textarea to be as big as possible
1402:
1403: creates a function resize_textrea that takes two IDs first should be
1404: the id of the element to resize, second should be the id of a div that
1405: surrounds everything that comes after the textarea, this routine needs
1406: to be attached to the <body> for the onload and onresize events.
1407:
1408: =back
1409:
1410: =cut
1411:
1412: sub resize_textarea_js {
1413: my $geometry = &viewport_geometry_js();
1414: return <<"RESIZE";
1415: <script type="text/javascript">
1416: // <![CDATA[
1417: $geometry
1418:
1419: function getX(element) {
1420: var x = 0;
1421: while (element) {
1422: x += element.offsetLeft;
1423: element = element.offsetParent;
1424: }
1425: return x;
1426: }
1427: function getY(element) {
1428: var y = 0;
1429: while (element) {
1430: y += element.offsetTop;
1431: element = element.offsetParent;
1432: }
1433: return y;
1434: }
1435:
1436:
1437: function resize_textarea(textarea_id,bottom_id) {
1438: init_geometry();
1439: var textarea = document.getElementById(textarea_id);
1440: //alert(textarea);
1441:
1442: var textarea_top = getY(textarea);
1443: var textarea_height = textarea.offsetHeight;
1444: var bottom = document.getElementById(bottom_id);
1445: var bottom_top = getY(bottom);
1446: var bottom_height = bottom.offsetHeight;
1447: var window_height = Geometry.getViewportHeight();
1448: var fudge = 23;
1449: var new_height = window_height-fudge-textarea_top-bottom_height;
1450: if (new_height < 300) {
1451: new_height = 300;
1452: }
1453: textarea.style.height=new_height+'px';
1454: }
1455: // ]]>
1456: </script>
1457: RESIZE
1458:
1459: }
1460:
1461: =pod
1462:
1463: =head1 Excel and CSV file utility routines
1464:
1465: =over 4
1466:
1467: =cut
1468:
1469: ###############################################################
1470: ###############################################################
1471:
1472: =pod
1473:
1474: =item * &csv_translate($text)
1475:
1476: Translate $text to allow it to be output as a 'comma separated values'
1477: format.
1478:
1479: =cut
1480:
1481: ###############################################################
1482: ###############################################################
1483: sub csv_translate {
1484: my $text = shift;
1485: $text =~ s/\"/\"\"/g;
1486: $text =~ s/\n/ /g;
1487: return $text;
1488: }
1489:
1490: ###############################################################
1491: ###############################################################
1492:
1493: =pod
1494:
1495: =item * &define_excel_formats()
1496:
1497: Define some commonly used Excel cell formats.
1498:
1499: Currently supported formats:
1500:
1501: =over 4
1502:
1503: =item header
1504:
1505: =item bold
1506:
1507: =item h1
1508:
1509: =item h2
1510:
1511: =item h3
1512:
1513: =item h4
1514:
1515: =item i
1516:
1517: =item date
1518:
1519: =back
1520:
1521: Inputs: $workbook
1522:
1523: Returns: $format, a hash reference.
1524:
1525: =cut
1526:
1527: ###############################################################
1528: ###############################################################
1529: sub define_excel_formats {
1530: my ($workbook) = @_;
1531: my $format;
1532: $format->{'header'} = $workbook->add_format(bold => 1,
1533: bottom => 1,
1534: align => 'center');
1535: $format->{'bold'} = $workbook->add_format(bold=>1);
1536: $format->{'h1'} = $workbook->add_format(bold=>1, size=>18);
1537: $format->{'h2'} = $workbook->add_format(bold=>1, size=>16);
1538: $format->{'h3'} = $workbook->add_format(bold=>1, size=>14);
1539: $format->{'h4'} = $workbook->add_format(bold=>1, size=>12);
1540: $format->{'i'} = $workbook->add_format(italic=>1);
1541: $format->{'date'} = $workbook->add_format(num_format=>
1542: 'mm/dd/yyyy hh:mm:ss');
1543: return $format;
1544: }
1545:
1546: ###############################################################
1547: ###############################################################
1548:
1549: =pod
1550:
1551: =item * &create_workbook()
1552:
1553: Create an Excel worksheet. If it fails, output message on the
1554: request object and return undefs.
1555:
1556: Inputs: Apache request object
1557:
1558: Returns (undef) on failure,
1559: Excel worksheet object, scalar with filename, and formats
1560: from &Apache::loncommon::define_excel_formats on success
1561:
1562: =cut
1563:
1564: ###############################################################
1565: ###############################################################
1566: sub create_workbook {
1567: my ($r) = @_;
1568: #
1569: # Create the excel spreadsheet
1570: my $filename = '/prtspool/'.
1571: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1572: time.'_'.rand(1000000000).'.xls';
1573: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
1574: if (! defined($workbook)) {
1575: $r->log_error("Error creating excel spreadsheet $filename: $!");
1576: $r->print('<p>'.&mt("Unable to create new Excel file. ".
1577: "This error has been logged. ".
1578: "Please alert your LON-CAPA administrator").
1579: '</p>');
1580: return (undef);
1581: }
1582: #
1583: $workbook->set_tempdir('/home/httpd/perl/tmp');
1584: #
1585: my $format = &Apache::loncommon::define_excel_formats($workbook);
1586: return ($workbook,$filename,$format);
1587: }
1588:
1589: ###############################################################
1590: ###############################################################
1591:
1592: =pod
1593:
1594: =item * &create_text_file()
1595:
1596: Create a file to write to and eventually make available to the user.
1597: If file creation fails, outputs an error message on the request object and
1598: return undefs.
1599:
1600: Inputs: Apache request object, and file suffix
1601:
1602: Returns (undef) on failure,
1603: Filehandle and filename on success.
1604:
1605: =cut
1606:
1607: ###############################################################
1608: ###############################################################
1609: sub create_text_file {
1610: my ($r,$suffix) = @_;
1611: if (! defined($suffix)) { $suffix = 'txt'; };
1612: my $fh;
1613: my $filename = '/prtspool/'.
1614: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1615: time.'_'.rand(1000000000).'.'.$suffix;
1616: $fh = Apache::File->new('>/home/httpd'.$filename);
1617: if (! defined($fh)) {
1618: $r->log_error("Couldn't open $filename for output $!");
1619: $r->print(&mt('Problems occurred in creating the output file. '
1620: .'This error has been logged. '
1621: .'Please alert your LON-CAPA administrator.'));
1622: }
1623: return ($fh,$filename)
1624: }
1625:
1626:
1627: =pod
1628:
1629: =back
1630:
1631: =cut
1632:
1633: ###############################################################
1634: ## Home server <option> list generating code ##
1635: ###############################################################
1636:
1637: # ------------------------------------------
1638:
1639: sub domain_select {
1640: my ($name,$value,$multiple)=@_;
1641: my %domains=map {
1642: $_ => $_.' '. &Apache::lonnet::domain($_,'description')
1643: } &Apache::lonnet::all_domains();
1644: if ($multiple) {
1645: $domains{''}=&mt('Any domain');
1646: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1647: return &multiple_select_form($name,$value,4,\%domains);
1648: } else {
1649: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1650: return &select_form($name,$value,%domains);
1651: }
1652: }
1653:
1654: #-------------------------------------------
1655:
1656: =pod
1657:
1658: =head1 Routines for form select boxes
1659:
1660: =over 4
1661:
1662: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1663:
1664: Returns a string containing a <select> element int multiple mode
1665:
1666:
1667: Args:
1668: $name - name of the <select> element
1669: $value - scalar or array ref of values that should already be selected
1670: $size - number of rows long the select element is
1671: $hash - the elements should be 'option' => 'shown text'
1672: (shown text should already have been &mt())
1673: $order - (optional) array ref of the order to show the elements in
1674:
1675: =cut
1676:
1677: #-------------------------------------------
1678: sub multiple_select_form {
1679: my ($name,$value,$size,$hash,$order)=@_;
1680: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
1681: my $output='';
1682: if (! defined($size)) {
1683: $size = 4;
1684: if (scalar(keys(%$hash))<4) {
1685: $size = scalar(keys(%$hash));
1686: }
1687: }
1688: $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1689: my @order;
1690: if (ref($order) eq 'ARRAY') {
1691: @order = @{$order};
1692: } else {
1693: @order = sort(keys(%$hash));
1694: }
1695: if (exists($$hash{'select_form_order'})) {
1696: @order = @{$$hash{'select_form_order'}};
1697: }
1698:
1699: foreach my $key (@order) {
1700: $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1701: $output.='selected="selected" ' if ($selected{$key});
1702: $output.='>'.$hash->{$key}."</option>\n";
1703: }
1704: $output.="</select>\n";
1705: return $output;
1706: }
1707:
1708: #-------------------------------------------
1709:
1710: =pod
1711:
1712: =item * &select_form($defdom,$name,%hash)
1713:
1714: Returns a string containing a <select name='$name' size='1'> form to
1715: allow a user to select options from a hash option_name => displayed text.
1716: See lonrights.pm for an example invocation and use.
1717:
1718: =cut
1719:
1720: #-------------------------------------------
1721: sub select_form {
1722: my ($def,$name,%hash) = @_;
1723: my $selectform = "<select name=\"$name\" size=\"1\">\n";
1724: my @keys;
1725: if (exists($hash{'select_form_order'})) {
1726: @keys=@{$hash{'select_form_order'}};
1727: } else {
1728: @keys=sort(keys(%hash));
1729: }
1730: foreach my $key (@keys) {
1731: $selectform.=
1732: '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
1733: ($key eq $def ? 'selected="selected" ' : '').
1734: ">".&mt($hash{$key})."</option>\n";
1735: }
1736: $selectform.="</select>";
1737: return $selectform;
1738: }
1739:
1740: # For display filters
1741:
1742: sub display_filter {
1743: if (!$env{'form.show'}) { $env{'form.show'}=10; }
1744: if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1745: return '<span class="LC_nobreak"><label>'.&mt('Records [_1]',
1746: &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
1747: (&mt('all'),10,20,50,100,1000,10000))).
1748: '</label></span> <span class="LC_nobreak">'.
1749: &mt('Filter [_1]',
1750: &select_form($env{'form.displayfilter'},
1751: 'displayfilter',
1752: ('currentfolder' => 'Current folder/page',
1753: 'containing' => 'Containing phrase',
1754: 'none' => 'None'))).
1755: '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></span>';
1756: }
1757:
1758: sub gradeleveldescription {
1759: my $gradelevel=shift;
1760: my %gradelevels=(0 => 'Not specified',
1761: 1 => 'Grade 1',
1762: 2 => 'Grade 2',
1763: 3 => 'Grade 3',
1764: 4 => 'Grade 4',
1765: 5 => 'Grade 5',
1766: 6 => 'Grade 6',
1767: 7 => 'Grade 7',
1768: 8 => 'Grade 8',
1769: 9 => 'Grade 9',
1770: 10 => 'Grade 10',
1771: 11 => 'Grade 11',
1772: 12 => 'Grade 12',
1773: 13 => 'Grade 13',
1774: 14 => '100 Level',
1775: 15 => '200 Level',
1776: 16 => '300 Level',
1777: 17 => '400 Level',
1778: 18 => 'Graduate Level');
1779: return &mt($gradelevels{$gradelevel});
1780: }
1781:
1782: sub select_level_form {
1783: my ($deflevel,$name)=@_;
1784: unless ($deflevel) { $deflevel=0; }
1785: my $selectform = "<select name=\"$name\" size=\"1\">\n";
1786: for (my $i=0; $i<=18; $i++) {
1787: $selectform.="<option value=\"$i\" ".
1788: ($i==$deflevel ? 'selected="selected" ' : '').
1789: ">".&gradeleveldescription($i)."</option>\n";
1790: }
1791: $selectform.="</select>";
1792: return $selectform;
1793: }
1794:
1795: #-------------------------------------------
1796:
1797: =pod
1798:
1799: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange)
1800:
1801: Returns a string containing a <select name='$name' size='1'> form to
1802: allow a user to select the domain to preform an operation in.
1803: See loncreateuser.pm for an example invocation and use.
1804:
1805: If the $includeempty flag is set, it also includes an empty choice ("no domain
1806: selected");
1807:
1808: If the $showdomdesc flag is set, the domain name is followed by the domain description.
1809:
1810: The optional $onchange argumnet specifies what should occur if the domain selector is changed, e.g., 'this.form.submit()' if the form is to be automatically submitted.
1811:
1812: =cut
1813:
1814: #-------------------------------------------
1815: sub select_dom_form {
1816: my ($defdom,$name,$includeempty,$showdomdesc,$onchange) = @_;
1817: if ($onchange) {
1818: $onchange = ' onchange="'.$onchange.'"';
1819: }
1820: my @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
1821: if ($includeempty) { @domains=('',@domains); }
1822: my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
1823: foreach my $dom (@domains) {
1824: $selectdomain.="<option value=\"$dom\" ".
1825: ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
1826: if ($showdomdesc) {
1827: if ($dom ne '') {
1828: my $domdesc = &Apache::lonnet::domain($dom,'description');
1829: if ($domdesc ne '') {
1830: $selectdomain .= ' ('.$domdesc.')';
1831: }
1832: }
1833: }
1834: $selectdomain .= "</option>\n";
1835: }
1836: $selectdomain.="</select>";
1837: return $selectdomain;
1838: }
1839:
1840: #-------------------------------------------
1841:
1842: =pod
1843:
1844: =item * &home_server_form_item($domain,$name,$defaultflag)
1845:
1846: input: 4 arguments (two required, two optional) -
1847: $domain - domain of new user
1848: $name - name of form element
1849: $default - Value of 'default' causes a default item to be first
1850: option, and selected by default.
1851: $hide - Value of 'hide' causes hiding of the name of the server,
1852: if 1 server found, or default, if 0 found.
1853: output: returns 2 items:
1854: (a) form element which contains either:
1855: (i) <select name="$name">
1856: <option value="$hostid1">$hostid $servers{$hostid}</option>
1857: <option value="$hostid2">$hostid $servers{$hostid}</option>
1858: </select>
1859: form item if there are multiple library servers in $domain, or
1860: (ii) an <input type="hidden" name="$name" value="$hostid" /> form item
1861: if there is only one library server in $domain.
1862:
1863: (b) number of library servers found.
1864:
1865: See loncreateuser.pm for example of use.
1866:
1867: =cut
1868:
1869: #-------------------------------------------
1870: sub home_server_form_item {
1871: my ($domain,$name,$default,$hide) = @_;
1872: my %servers = &Apache::lonnet::get_servers($domain,'library');
1873: my $result;
1874: my $numlib = keys(%servers);
1875: if ($numlib > 1) {
1876: $result .= '<select name="'.$name.'" />'."\n";
1877: if ($default) {
1878: $result .= '<option value="default" selected="selected">'.&mt('default').
1879: '</option>'."\n";
1880: }
1881: foreach my $hostid (sort(keys(%servers))) {
1882: $result.= '<option value="'.$hostid.'">'.
1883: $hostid.' '.$servers{$hostid}."</option>\n";
1884: }
1885: $result .= '</select>'."\n";
1886: } elsif ($numlib == 1) {
1887: my $hostid;
1888: foreach my $item (keys(%servers)) {
1889: $hostid = $item;
1890: }
1891: $result .= '<input type="hidden" name="'.$name.'" value="'.
1892: $hostid.'" />';
1893: if (!$hide) {
1894: $result .= $hostid.' '.$servers{$hostid};
1895: }
1896: $result .= "\n";
1897: } elsif ($default) {
1898: $result .= '<input type="hidden" name="'.$name.
1899: '" value="default" />';
1900: if (!$hide) {
1901: $result .= &mt('default');
1902: }
1903: $result .= "\n";
1904: }
1905: return ($result,$numlib);
1906: }
1907:
1908: =pod
1909:
1910: =back
1911:
1912: =cut
1913:
1914: ###############################################################
1915: ## Decoding User Agent ##
1916: ###############################################################
1917:
1918: =pod
1919:
1920: =head1 Decoding the User Agent
1921:
1922: =over 4
1923:
1924: =item * &decode_user_agent()
1925:
1926: Inputs: $r
1927:
1928: Outputs:
1929:
1930: =over 4
1931:
1932: =item * $httpbrowser
1933:
1934: =item * $clientbrowser
1935:
1936: =item * $clientversion
1937:
1938: =item * $clientmathml
1939:
1940: =item * $clientunicode
1941:
1942: =item * $clientos
1943:
1944: =back
1945:
1946: =back
1947:
1948: =cut
1949:
1950: ###############################################################
1951: ###############################################################
1952: sub decode_user_agent {
1953: my ($r)=@_;
1954: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
1955: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
1956: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1957: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1958: my $clientbrowser='unknown';
1959: my $clientversion='0';
1960: my $clientmathml='';
1961: my $clientunicode='0';
1962: for (my $i=0;$i<=$#browsertype;$i++) {
1963: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
1964: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
1965: $clientbrowser=$bname;
1966: $httpbrowser=~/$vreg/i;
1967: $clientversion=$1;
1968: $clientmathml=($clientversion>=$minv);
1969: $clientunicode=($clientversion>=$univ);
1970: }
1971: }
1972: my $clientos='unknown';
1973: if (($httpbrowser=~/linux/i) ||
1974: ($httpbrowser=~/unix/i) ||
1975: ($httpbrowser=~/ux/i) ||
1976: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
1977: if (($httpbrowser=~/vax/i) ||
1978: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
1979: if ($httpbrowser=~/next/i) { $clientos='next'; }
1980: if (($httpbrowser=~/mac/i) ||
1981: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1982: if ($httpbrowser=~/win/i) { $clientos='win'; }
1983: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1984: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1985: $clientunicode,$clientos,);
1986: }
1987:
1988: ###############################################################
1989: ## Authentication changing form generation subroutines ##
1990: ###############################################################
1991: ##
1992: ## All of the authform_xxxxxxx subroutines take their inputs in a
1993: ## hash, and have reasonable default values.
1994: ##
1995: ## formname = the name given in the <form> tag.
1996: #-------------------------------------------
1997:
1998: =pod
1999:
2000: =head1 Authentication Routines
2001:
2002: =over 4
2003:
2004: =item * &authform_xxxxxx()
2005:
2006: The authform_xxxxxx subroutines provide javascript and html forms which
2007: handle some of the conveniences required for authentication forms.
2008: This is not an optimal method, but it works.
2009:
2010: =over 4
2011:
2012: =item * authform_header
2013:
2014: =item * authform_authorwarning
2015:
2016: =item * authform_nochange
2017:
2018: =item * authform_kerberos
2019:
2020: =item * authform_internal
2021:
2022: =item * authform_filesystem
2023:
2024: =back
2025:
2026: See loncreateuser.pm for invocation and use examples.
2027:
2028: =cut
2029:
2030: #-------------------------------------------
2031: sub authform_header{
2032: my %in = (
2033: formname => 'cu',
2034: kerb_def_dom => '',
2035: @_,
2036: );
2037: $in{'formname'} = 'document.' . $in{'formname'};
2038: my $result='';
2039:
2040: #---------------------------------------------- Code for upper case translation
2041: my $Javascript_toUpperCase;
2042: unless ($in{kerb_def_dom}) {
2043: $Javascript_toUpperCase =<<"END";
2044: switch (choice) {
2045: case 'krb': currentform.elements[choicearg].value =
2046: currentform.elements[choicearg].value.toUpperCase();
2047: break;
2048: default:
2049: }
2050: END
2051: } else {
2052: $Javascript_toUpperCase = "";
2053: }
2054:
2055: my $radioval = "'nochange'";
2056: if (defined($in{'curr_authtype'})) {
2057: if ($in{'curr_authtype'} ne '') {
2058: $radioval = "'".$in{'curr_authtype'}."arg'";
2059: }
2060: }
2061: my $argfield = 'null';
2062: if (defined($in{'mode'})) {
2063: if ($in{'mode'} eq 'modifycourse') {
2064: if (defined($in{'curr_autharg'})) {
2065: if ($in{'curr_autharg'} ne '') {
2066: $argfield = "'$in{'curr_autharg'}'";
2067: }
2068: }
2069: }
2070: }
2071:
2072: $result.=<<"END";
2073: var current = new Object();
2074: current.radiovalue = $radioval;
2075: current.argfield = $argfield;
2076:
2077: function changed_radio(choice,currentform) {
2078: var choicearg = choice + 'arg';
2079: // If a radio button in changed, we need to change the argfield
2080: if (current.radiovalue != choice) {
2081: current.radiovalue = choice;
2082: if (current.argfield != null) {
2083: currentform.elements[current.argfield].value = '';
2084: }
2085: if (choice == 'nochange') {
2086: current.argfield = null;
2087: } else {
2088: current.argfield = choicearg;
2089: switch(choice) {
2090: case 'krb':
2091: currentform.elements[current.argfield].value =
2092: "$in{'kerb_def_dom'}";
2093: break;
2094: default:
2095: break;
2096: }
2097: }
2098: }
2099: return;
2100: }
2101:
2102: function changed_text(choice,currentform) {
2103: var choicearg = choice + 'arg';
2104: if (currentform.elements[choicearg].value !='') {
2105: $Javascript_toUpperCase
2106: // clear old field
2107: if ((current.argfield != choicearg) && (current.argfield != null)) {
2108: currentform.elements[current.argfield].value = '';
2109: }
2110: current.argfield = choicearg;
2111: }
2112: set_auth_radio_buttons(choice,currentform);
2113: return;
2114: }
2115:
2116: function set_auth_radio_buttons(newvalue,currentform) {
2117: var i=0;
2118: while (i < currentform.login.length) {
2119: if (currentform.login[i].value == newvalue) { break; }
2120: i++;
2121: }
2122: if (i == currentform.login.length) {
2123: return;
2124: }
2125: current.radiovalue = newvalue;
2126: currentform.login[i].checked = true;
2127: return;
2128: }
2129: END
2130: return $result;
2131: }
2132:
2133: sub authform_authorwarning{
2134: my $result='';
2135: $result='<i>'.
2136: &mt('As a general rule, only authors or co-authors should be '.
2137: 'filesystem authenticated '.
2138: '(which allows access to the server filesystem).')."</i>\n";
2139: return $result;
2140: }
2141:
2142: sub authform_nochange{
2143: my %in = (
2144: formname => 'document.cu',
2145: kerb_def_dom => 'MSU.EDU',
2146: @_,
2147: );
2148: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2149: my $result;
2150: if (keys(%can_assign) == 0) {
2151: $result = &mt('Under you current role you are not permitted to change login settings for this user');
2152: } else {
2153: $result = '<label>'.&mt('[_1] Do not change login data',
2154: '<input type="radio" name="login" value="nochange" '.
2155: 'checked="checked" onclick="'.
2156: "javascript:changed_radio('nochange',$in{'formname'});".'" />').
2157: '</label>';
2158: }
2159: return $result;
2160: }
2161:
2162: sub authform_kerberos {
2163: my %in = (
2164: formname => 'document.cu',
2165: kerb_def_dom => 'MSU.EDU',
2166: kerb_def_auth => 'krb4',
2167: @_,
2168: );
2169: my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
2170: $autharg,$jscall);
2171: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2172: if ($in{'kerb_def_auth'} eq 'krb5') {
2173: $check5 = ' checked="checked"';
2174: } else {
2175: $check4 = ' checked="checked"';
2176: }
2177: $krbarg = $in{'kerb_def_dom'};
2178: if (defined($in{'curr_authtype'})) {
2179: if ($in{'curr_authtype'} eq 'krb') {
2180: $krbcheck = ' checked="checked"';
2181: if (defined($in{'mode'})) {
2182: if ($in{'mode'} eq 'modifyuser') {
2183: $krbcheck = '';
2184: }
2185: }
2186: if (defined($in{'curr_kerb_ver'})) {
2187: if ($in{'curr_krb_ver'} eq '5') {
2188: $check5 = ' checked="checked"';
2189: $check4 = '';
2190: } else {
2191: $check4 = ' checked="checked"';
2192: $check5 = '';
2193: }
2194: }
2195: if (defined($in{'curr_autharg'})) {
2196: $krbarg = $in{'curr_autharg'};
2197: }
2198: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2199: if (defined($in{'curr_autharg'})) {
2200: $result =
2201: &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
2202: $in{'curr_autharg'},$krbver);
2203: } else {
2204: $result =
2205: &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
2206: }
2207: return $result;
2208: }
2209: }
2210: } else {
2211: if ($authnum == 1) {
2212: $authtype = '<input type="hidden" name="login" value="krb" />';
2213: }
2214: }
2215: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2216: return;
2217: } elsif ($authtype eq '') {
2218: if (defined($in{'mode'})) {
2219: if ($in{'mode'} eq 'modifycourse') {
2220: if ($authnum == 1) {
2221: $authtype = '<input type="hidden" name="login" value="krb" />';
2222: }
2223: }
2224: }
2225: }
2226: $jscall = "javascript:changed_radio('krb',$in{'formname'});";
2227: if ($authtype eq '') {
2228: $authtype = '<input type="radio" name="login" value="krb" '.
2229: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
2230: $krbcheck.' />';
2231: }
2232: if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
2233: ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
2234: $in{'curr_authtype'} eq 'krb5') ||
2235: (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
2236: $in{'curr_authtype'} eq 'krb4')) {
2237: $result .= &mt
2238: ('[_1] Kerberos authenticated with domain [_2] '.
2239: '[_3] Version 4 [_4] Version 5 [_5]',
2240: '<label>'.$authtype,
2241: '</label><input type="text" size="10" name="krbarg" '.
2242: 'value="'.$krbarg.'" '.
2243: 'onchange="'.$jscall.'" />',
2244: '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
2245: '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
2246: '</label>');
2247: } elsif ($can_assign{'krb4'}) {
2248: $result .= &mt
2249: ('[_1] Kerberos authenticated with domain [_2] '.
2250: '[_3] Version 4 [_4]',
2251: '<label>'.$authtype,
2252: '</label><input type="text" size="10" name="krbarg" '.
2253: 'value="'.$krbarg.'" '.
2254: 'onchange="'.$jscall.'" />',
2255: '<label><input type="hidden" name="krbver" value="4" />',
2256: '</label>');
2257: } elsif ($can_assign{'krb5'}) {
2258: $result .= &mt
2259: ('[_1] Kerberos authenticated with domain [_2] '.
2260: '[_3] Version 5 [_4]',
2261: '<label>'.$authtype,
2262: '</label><input type="text" size="10" name="krbarg" '.
2263: 'value="'.$krbarg.'" '.
2264: 'onchange="'.$jscall.'" />',
2265: '<label><input type="hidden" name="krbver" value="5" />',
2266: '</label>');
2267: }
2268: return $result;
2269: }
2270:
2271: sub authform_internal{
2272: my %in = (
2273: formname => 'document.cu',
2274: kerb_def_dom => 'MSU.EDU',
2275: @_,
2276: );
2277: my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
2278: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2279: if (defined($in{'curr_authtype'})) {
2280: if ($in{'curr_authtype'} eq 'int') {
2281: if ($can_assign{'int'}) {
2282: $intcheck = 'checked="checked" ';
2283: if (defined($in{'mode'})) {
2284: if ($in{'mode'} eq 'modifyuser') {
2285: $intcheck = '';
2286: }
2287: }
2288: if (defined($in{'curr_autharg'})) {
2289: $intarg = $in{'curr_autharg'};
2290: }
2291: } else {
2292: $result = &mt('Currently internally authenticated.');
2293: return $result;
2294: }
2295: }
2296: } else {
2297: if ($authnum == 1) {
2298: $authtype = '<input type="hidden" name="login" value="int" />';
2299: }
2300: }
2301: if (!$can_assign{'int'}) {
2302: return;
2303: } elsif ($authtype eq '') {
2304: if (defined($in{'mode'})) {
2305: if ($in{'mode'} eq 'modifycourse') {
2306: if ($authnum == 1) {
2307: $authtype = '<input type="hidden" name="login" value="int" />';
2308: }
2309: }
2310: }
2311: }
2312: $jscall = "javascript:changed_radio('int',$in{'formname'});";
2313: if ($authtype eq '') {
2314: $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
2315: ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
2316: }
2317: $autharg = '<input type="password" size="10" name="intarg" value="'.
2318: $intarg.'" onchange="'.$jscall.'" />';
2319: $result = &mt
2320: ('[_1] Internally authenticated (with initial password [_2])',
2321: '<label>'.$authtype,'</label>'.$autharg);
2322: $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>';
2323: return $result;
2324: }
2325:
2326: sub authform_local{
2327: my %in = (
2328: formname => 'document.cu',
2329: kerb_def_dom => 'MSU.EDU',
2330: @_,
2331: );
2332: my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
2333: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2334: if (defined($in{'curr_authtype'})) {
2335: if ($in{'curr_authtype'} eq 'loc') {
2336: if ($can_assign{'loc'}) {
2337: $loccheck = 'checked="checked" ';
2338: if (defined($in{'mode'})) {
2339: if ($in{'mode'} eq 'modifyuser') {
2340: $loccheck = '';
2341: }
2342: }
2343: if (defined($in{'curr_autharg'})) {
2344: $locarg = $in{'curr_autharg'};
2345: }
2346: } else {
2347: $result = &mt('Currently using local (institutional) authentication.');
2348: return $result;
2349: }
2350: }
2351: } else {
2352: if ($authnum == 1) {
2353: $authtype = '<input type="hidden" name="login" value="loc" />';
2354: }
2355: }
2356: if (!$can_assign{'loc'}) {
2357: return;
2358: } elsif ($authtype eq '') {
2359: if (defined($in{'mode'})) {
2360: if ($in{'mode'} eq 'modifycourse') {
2361: if ($authnum == 1) {
2362: $authtype = '<input type="hidden" name="login" value="loc" />';
2363: }
2364: }
2365: }
2366: }
2367: $jscall = "javascript:changed_radio('loc',$in{'formname'});";
2368: if ($authtype eq '') {
2369: $authtype = '<input type="radio" name="login" value="loc" '.
2370: $loccheck.' onchange="'.$jscall.'" onclick="'.
2371: $jscall.'" />';
2372: }
2373: $autharg = '<input type="text" size="10" name="locarg" value="'.
2374: $locarg.'" onchange="'.$jscall.'" />';
2375: $result = &mt('[_1] Local Authentication with argument [_2]',
2376: '<label>'.$authtype,'</label>'.$autharg);
2377: return $result;
2378: }
2379:
2380: sub authform_filesystem{
2381: my %in = (
2382: formname => 'document.cu',
2383: kerb_def_dom => 'MSU.EDU',
2384: @_,
2385: );
2386: my ($fsyscheck,$result,$authtype,$autharg,$jscall);
2387: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2388: if (defined($in{'curr_authtype'})) {
2389: if ($in{'curr_authtype'} eq 'fsys') {
2390: if ($can_assign{'fsys'}) {
2391: $fsyscheck = 'checked="checked" ';
2392: if (defined($in{'mode'})) {
2393: if ($in{'mode'} eq 'modifyuser') {
2394: $fsyscheck = '';
2395: }
2396: }
2397: } else {
2398: $result = &mt('Currently Filesystem Authenticated.');
2399: return $result;
2400: }
2401: }
2402: } else {
2403: if ($authnum == 1) {
2404: $authtype = '<input type="hidden" name="login" value="fsys" />';
2405: }
2406: }
2407: if (!$can_assign{'fsys'}) {
2408: return;
2409: } elsif ($authtype eq '') {
2410: if (defined($in{'mode'})) {
2411: if ($in{'mode'} eq 'modifycourse') {
2412: if ($authnum == 1) {
2413: $authtype = '<input type="hidden" name="login" value="fsys" />';
2414: }
2415: }
2416: }
2417: }
2418: $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
2419: if ($authtype eq '') {
2420: $authtype = '<input type="radio" name="login" value="fsys" '.
2421: $fsyscheck.' onchange="'.$jscall.'" onclick="'.
2422: $jscall.'" />';
2423: }
2424: $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
2425: ' onchange="'.$jscall.'" />';
2426: $result = &mt
2427: ('[_1] Filesystem Authenticated (with initial password [_2])',
2428: '<label><input type="radio" name="login" value="fsys" '.
2429: $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
2430: '</label><input type="password" size="10" name="fsysarg" value="" '.
2431: 'onchange="'.$jscall.'" />');
2432: return $result;
2433: }
2434:
2435: sub get_assignable_auth {
2436: my ($dom) = @_;
2437: if ($dom eq '') {
2438: $dom = $env{'request.role.domain'};
2439: }
2440: my %can_assign = (
2441: krb4 => 1,
2442: krb5 => 1,
2443: int => 1,
2444: loc => 1,
2445: );
2446: my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
2447: if (ref($domconfig{'usercreation'}) eq 'HASH') {
2448: if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
2449: my $authhash = $domconfig{'usercreation'}{'authtypes'};
2450: my $context;
2451: if ($env{'request.role'} =~ /^au/) {
2452: $context = 'author';
2453: } elsif ($env{'request.role'} =~ /^dc/) {
2454: $context = 'domain';
2455: } elsif ($env{'request.course.id'}) {
2456: $context = 'course';
2457: }
2458: if ($context) {
2459: if (ref($authhash->{$context}) eq 'HASH') {
2460: %can_assign = %{$authhash->{$context}};
2461: }
2462: }
2463: }
2464: }
2465: my $authnum = 0;
2466: foreach my $key (keys(%can_assign)) {
2467: if ($can_assign{$key}) {
2468: $authnum ++;
2469: }
2470: }
2471: if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
2472: $authnum --;
2473: }
2474: return ($authnum,%can_assign);
2475: }
2476:
2477: ###############################################################
2478: ## Get Kerberos Defaults for Domain ##
2479: ###############################################################
2480: ##
2481: ## Returns default kerberos version and an associated argument
2482: ## as listed in file domain.tab. If not listed, provides
2483: ## appropriate default domain and kerberos version.
2484: ##
2485: #-------------------------------------------
2486:
2487: =pod
2488:
2489: =item * &get_kerberos_defaults()
2490:
2491: get_kerberos_defaults($target_domain) returns the default kerberos
2492: version and domain. If not found, it defaults to version 4 and the
2493: domain of the server.
2494:
2495: =over 4
2496:
2497: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
2498:
2499: =back
2500:
2501: =back
2502:
2503: =cut
2504:
2505: #-------------------------------------------
2506: sub get_kerberos_defaults {
2507: my $domain=shift;
2508: my ($krbdef,$krbdefdom);
2509: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
2510: if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
2511: $krbdef = $domdefaults{'auth_def'};
2512: $krbdefdom = $domdefaults{'auth_arg_def'};
2513: } else {
2514: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
2515: my $krbdefdom=$1;
2516: $krbdefdom=~tr/a-z/A-Z/;
2517: $krbdef = "krb4";
2518: }
2519: return ($krbdef,$krbdefdom);
2520: }
2521:
2522:
2523: ###############################################################
2524: ## Thesaurus Functions ##
2525: ###############################################################
2526:
2527: =pod
2528:
2529: =head1 Thesaurus Functions
2530:
2531: =over 4
2532:
2533: =item * &initialize_keywords()
2534:
2535: Initializes the package variable %Keywords if it is empty. Uses the
2536: package variable $thesaurus_db_file.
2537:
2538: =cut
2539:
2540: ###################################################
2541:
2542: sub initialize_keywords {
2543: return 1 if (scalar keys(%Keywords));
2544: # If we are here, %Keywords is empty, so fill it up
2545: # Make sure the file we need exists...
2546: if (! -e $thesaurus_db_file) {
2547: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
2548: " failed because it does not exist");
2549: return 0;
2550: }
2551: # Set up the hash as a database
2552: my %thesaurus_db;
2553: if (! tie(%thesaurus_db,'GDBM_File',
2554: $thesaurus_db_file,&GDBM_READER(),0640)){
2555: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
2556: $thesaurus_db_file);
2557: return 0;
2558: }
2559: # Get the average number of appearances of a word.
2560: my $avecount = $thesaurus_db{'average.count'};
2561: # Put keywords (those that appear > average) into %Keywords
2562: while (my ($word,$data)=each (%thesaurus_db)) {
2563: my ($count,undef) = split /:/,$data;
2564: $Keywords{$word}++ if ($count > $avecount);
2565: }
2566: untie %thesaurus_db;
2567: # Remove special values from %Keywords.
2568: foreach my $value ('total.count','average.count') {
2569: delete($Keywords{$value}) if (exists($Keywords{$value}));
2570: }
2571: return 1;
2572: }
2573:
2574: ###################################################
2575:
2576: =pod
2577:
2578: =item * &keyword($word)
2579:
2580: Returns true if $word is a keyword. A keyword is a word that appears more
2581: than the average number of times in the thesaurus database. Calls
2582: &initialize_keywords
2583:
2584: =cut
2585:
2586: ###################################################
2587:
2588: sub keyword {
2589: return if (!&initialize_keywords());
2590: my $word=lc(shift());
2591: $word=~s/\W//g;
2592: return exists($Keywords{$word});
2593: }
2594:
2595: ###############################################################
2596:
2597: =pod
2598:
2599: =item * &get_related_words()
2600:
2601: Look up a word in the thesaurus. Takes a scalar argument and returns
2602: an array of words. If the keyword is not in the thesaurus, an empty array
2603: will be returned. The order of the words returned is determined by the
2604: database which holds them.
2605:
2606: Uses global $thesaurus_db_file.
2607:
2608: =cut
2609:
2610: ###############################################################
2611: sub get_related_words {
2612: my $keyword = shift;
2613: my %thesaurus_db;
2614: if (! -e $thesaurus_db_file) {
2615: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
2616: "failed because the file does not exist");
2617: return ();
2618: }
2619: if (! tie(%thesaurus_db,'GDBM_File',
2620: $thesaurus_db_file,&GDBM_READER(),0640)){
2621: return ();
2622: }
2623: my @Words=();
2624: my $count=0;
2625: if (exists($thesaurus_db{$keyword})) {
2626: # The first element is the number of times
2627: # the word appears. We do not need it now.
2628: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
2629: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
2630: my $threshold=$mostfrequentcount/10;
2631: foreach my $possibleword (@RelatedWords) {
2632: my ($word,$wordcount)=split(/\,/,$possibleword);
2633: if ($wordcount>$threshold) {
2634: push(@Words,$word);
2635: $count++;
2636: if ($count>10) { last; }
2637: }
2638: }
2639: }
2640: untie %thesaurus_db;
2641: return @Words;
2642: }
2643:
2644: =pod
2645:
2646: =back
2647:
2648: =cut
2649:
2650: # -------------------------------------------------------------- Plaintext name
2651: =pod
2652:
2653: =head1 User Name Functions
2654:
2655: =over 4
2656:
2657: =item * &plainname($uname,$udom,$first)
2658:
2659: Takes a users logon name and returns it as a string in
2660: "first middle last generation" form
2661: if $first is set to 'lastname' then it returns it as
2662: 'lastname generation, firstname middlename' if their is a lastname
2663:
2664: =cut
2665:
2666:
2667: ###############################################################
2668: sub plainname {
2669: my ($uname,$udom,$first)=@_;
2670: return if (!defined($uname) || !defined($udom));
2671: my %names=&getnames($uname,$udom);
2672: my $name=&Apache::lonnet::format_name($names{'firstname'},
2673: $names{'middlename'},
2674: $names{'lastname'},
2675: $names{'generation'},$first);
2676: $name=~s/^\s+//;
2677: $name=~s/\s+$//;
2678: $name=~s/\s+/ /g;
2679: if ($name !~ /\S/) { $name=$uname.':'.$udom; }
2680: return $name;
2681: }
2682:
2683: # -------------------------------------------------------------------- Nickname
2684: =pod
2685:
2686: =item * &nickname($uname,$udom)
2687:
2688: Gets a users name and returns it as a string as
2689:
2690: ""nickname""
2691:
2692: if the user has a nickname or
2693:
2694: "first middle last generation"
2695:
2696: if the user does not
2697:
2698: =cut
2699:
2700: sub nickname {
2701: my ($uname,$udom)=@_;
2702: return if (!defined($uname) || !defined($udom));
2703: my %names=&getnames($uname,$udom);
2704: my $name=$names{'nickname'};
2705: if ($name) {
2706: $name='"'.$name.'"';
2707: } else {
2708: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
2709: $names{'lastname'}.' '.$names{'generation'};
2710: $name=~s/\s+$//;
2711: $name=~s/\s+/ /g;
2712: }
2713: return $name;
2714: }
2715:
2716: sub getnames {
2717: my ($uname,$udom)=@_;
2718: return if (!defined($uname) || !defined($udom));
2719: if ($udom eq 'public' && $uname eq 'public') {
2720: return ('lastname' => &mt('Public'));
2721: }
2722: my $id=$uname.':'.$udom;
2723: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
2724: if ($cached) {
2725: return %{$names};
2726: } else {
2727: my %loadnames=&Apache::lonnet::get('environment',
2728: ['firstname','middlename','lastname','generation','nickname'],
2729: $udom,$uname);
2730: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
2731: return %loadnames;
2732: }
2733: }
2734:
2735: # -------------------------------------------------------------------- getemails
2736:
2737: =pod
2738:
2739: =item * &getemails($uname,$udom)
2740:
2741: Gets a user's email information and returns it as a hash with keys:
2742: notification, critnotification, permanentemail
2743:
2744: For notification and critnotification, values are comma-separated lists
2745: of e-mail addresses; for permanentemail, value is a single e-mail address.
2746:
2747:
2748: =cut
2749:
2750:
2751: sub getemails {
2752: my ($uname,$udom)=@_;
2753: if ($udom eq 'public' && $uname eq 'public') {
2754: return;
2755: }
2756: if (!$udom) { $udom=$env{'user.domain'}; }
2757: if (!$uname) { $uname=$env{'user.name'}; }
2758: my $id=$uname.':'.$udom;
2759: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
2760: if ($cached) {
2761: return %{$names};
2762: } else {
2763: my %loadnames=&Apache::lonnet::get('environment',
2764: ['notification','critnotification',
2765: 'permanentemail'],
2766: $udom,$uname);
2767: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
2768: return %loadnames;
2769: }
2770: }
2771:
2772: sub flush_email_cache {
2773: my ($uname,$udom)=@_;
2774: if (!$udom) { $udom =$env{'user.domain'}; }
2775: if (!$uname) { $uname=$env{'user.name'}; }
2776: return if ($udom eq 'public' && $uname eq 'public');
2777: my $id=$uname.':'.$udom;
2778: &Apache::lonnet::devalidate_cache_new('emailscache',$id);
2779: }
2780:
2781: # -------------------------------------------------------------------- getlangs
2782:
2783: =pod
2784:
2785: =item * &getlangs($uname,$udom)
2786:
2787: Gets a user's language preference and returns it as a hash with key:
2788: language.
2789:
2790: =cut
2791:
2792:
2793: sub getlangs {
2794: my ($uname,$udom) = @_;
2795: if (!$udom) { $udom =$env{'user.domain'}; }
2796: if (!$uname) { $uname=$env{'user.name'}; }
2797: my $id=$uname.':'.$udom;
2798: my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
2799: if ($cached) {
2800: return %{$langs};
2801: } else {
2802: my %loadlangs=&Apache::lonnet::get('environment',['languages'],
2803: $udom,$uname);
2804: &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
2805: return %loadlangs;
2806: }
2807: }
2808:
2809: sub flush_langs_cache {
2810: my ($uname,$udom)=@_;
2811: if (!$udom) { $udom =$env{'user.domain'}; }
2812: if (!$uname) { $uname=$env{'user.name'}; }
2813: return if ($udom eq 'public' && $uname eq 'public');
2814: my $id=$uname.':'.$udom;
2815: &Apache::lonnet::devalidate_cache_new('userlangs',$id);
2816: }
2817:
2818: # ------------------------------------------------------------------ Screenname
2819:
2820: =pod
2821:
2822: =item * &screenname($uname,$udom)
2823:
2824: Gets a users screenname and returns it as a string
2825:
2826: =cut
2827:
2828: sub screenname {
2829: my ($uname,$udom)=@_;
2830: if ($uname eq $env{'user.name'} &&
2831: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
2832: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
2833: return $names{'screenname'};
2834: }
2835:
2836:
2837: # ------------------------------------------------------------- Confirm Wrapper
2838: =pod
2839:
2840: =item confirmwrapper
2841:
2842: Wrap messages about completion of operation in box
2843:
2844: =cut
2845:
2846: sub confirmwrapper {
2847: my ($message)=@_;
2848: if ($message) {
2849: return "\n".'<div class="LC_confirm_box">'."\n"
2850: .$message."\n"
2851: .'</div>'."\n";
2852: } else {
2853: return $message;
2854: }
2855: }
2856:
2857: # ------------------------------------------------------------- Message Wrapper
2858:
2859: sub messagewrapper {
2860: my ($link,$username,$domain,$subject,$text)=@_;
2861: return
2862: '<a href="/adm/email?compose=individual&'.
2863: 'recname='.$username.'&recdom='.$domain.
2864: '&subject='.&escape($subject).'&text='.&escape($text).'" '.
2865: 'title="'.&mt('Send message').'">'.$link.'</a>';
2866: }
2867:
2868: # --------------------------------------------------------------- Notes Wrapper
2869:
2870: sub noteswrapper {
2871: my ($link,$un,$do)=@_;
2872: return
2873: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
2874: }
2875:
2876: # ------------------------------------------------------------- Aboutme Wrapper
2877:
2878: sub aboutmewrapper {
2879: my ($link,$username,$domain,$target)=@_;
2880: if (!defined($username) && !defined($domain)) {
2881: return;
2882: }
2883: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
2884: ($target?' target="$target"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
2885: }
2886:
2887: # ------------------------------------------------------------ Syllabus Wrapper
2888:
2889: sub syllabuswrapper {
2890: my ($linktext,$coursedir,$domain)=@_;
2891: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
2892: }
2893:
2894: # -----------------------------------------------------------------------------
2895:
2896: sub track_student_link {
2897: my ($linktext,$sname,$sdom,$target,$start) = @_;
2898: my $link ="/adm/trackstudent?";
2899: my $title = 'View recent activity';
2900: if (defined($sname) && $sname !~ /^\s*$/ &&
2901: defined($sdom) && $sdom !~ /^\s*$/) {
2902: $link .= "selected_student=$sname:$sdom";
2903: $title .= ' of this student';
2904: }
2905: if (defined($target) && $target !~ /^\s*$/) {
2906: $target = qq{target="$target"};
2907: } else {
2908: $target = '';
2909: }
2910: if ($start) { $link.='&start='.$start; }
2911: $title = &mt($title);
2912: $linktext = &mt($linktext);
2913: return qq{<a href="$link" title="$title" $target>$linktext</a>}.
2914: &help_open_topic('View_recent_activity');
2915: }
2916:
2917: sub slot_reservations_link {
2918: my ($linktext,$sname,$sdom,$target) = @_;
2919: my $link ="/adm/slotrequest?command=showresv&origin=aboutme";
2920: my $title = 'View slot reservation history';
2921: if (defined($sname) && $sname !~ /^\s*$/ &&
2922: defined($sdom) && $sdom !~ /^\s*$/) {
2923: $link .= "&uname=$sname&udom=$sdom";
2924: $title .= ' of this student';
2925: }
2926: if (defined($target) && $target !~ /^\s*$/) {
2927: $target = qq{target="$target"};
2928: } else {
2929: $target = '';
2930: }
2931: $title = &mt($title);
2932: $linktext = &mt($linktext);
2933: return qq{<a href="$link" title="$title" $target>$linktext</a>};
2934: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
2935:
2936: }
2937:
2938: # ===================================================== Display a student photo
2939:
2940:
2941: sub student_image_tag {
2942: my ($domain,$user)=@_;
2943: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
2944: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
2945: return '<img src="'.$imgsrc.'" align="right" />';
2946: } else {
2947: return '';
2948: }
2949: }
2950:
2951: =pod
2952:
2953: =back
2954:
2955: =head1 Access .tab File Data
2956:
2957: =over 4
2958:
2959: =item * &languageids()
2960:
2961: returns list of all language ids
2962:
2963: =cut
2964:
2965: sub languageids {
2966: return sort(keys(%language));
2967: }
2968:
2969: =pod
2970:
2971: =item * &languagedescription()
2972:
2973: returns description of a specified language id
2974:
2975: =cut
2976:
2977: sub languagedescription {
2978: my $code=shift;
2979: return ($supported_language{$code}?'* ':'').
2980: $language{$code}.
2981: ($supported_language{$code}?' ('.&mt('interface available').')':'');
2982: }
2983:
2984: sub plainlanguagedescription {
2985: my $code=shift;
2986: return $language{$code};
2987: }
2988:
2989: sub supportedlanguagecode {
2990: my $code=shift;
2991: return $supported_language{$code};
2992: }
2993:
2994: =pod
2995:
2996: =item * ©rightids()
2997:
2998: returns list of all copyrights
2999:
3000: =cut
3001:
3002: sub copyrightids {
3003: return sort(keys(%cprtag));
3004: }
3005:
3006: =pod
3007:
3008: =item * ©rightdescription()
3009:
3010: returns description of a specified copyright id
3011:
3012: =cut
3013:
3014: sub copyrightdescription {
3015: return &mt($cprtag{shift(@_)});
3016: }
3017:
3018: =pod
3019:
3020: =item * &source_copyrightids()
3021:
3022: returns list of all source copyrights
3023:
3024: =cut
3025:
3026: sub source_copyrightids {
3027: return sort(keys(%scprtag));
3028: }
3029:
3030: =pod
3031:
3032: =item * &source_copyrightdescription()
3033:
3034: returns description of a specified source copyright id
3035:
3036: =cut
3037:
3038: sub source_copyrightdescription {
3039: return &mt($scprtag{shift(@_)});
3040: }
3041:
3042: =pod
3043:
3044: =item * &filecategories()
3045:
3046: returns list of all file categories
3047:
3048: =cut
3049:
3050: sub filecategories {
3051: return sort(keys(%category_extensions));
3052: }
3053:
3054: =pod
3055:
3056: =item * &filecategorytypes()
3057:
3058: returns list of file types belonging to a given file
3059: category
3060:
3061: =cut
3062:
3063: sub filecategorytypes {
3064: my ($cat) = @_;
3065: return @{$category_extensions{lc($cat)}};
3066: }
3067:
3068: =pod
3069:
3070: =item * &fileembstyle()
3071:
3072: returns embedding style for a specified file type
3073:
3074: =cut
3075:
3076: sub fileembstyle {
3077: return $fe{lc(shift(@_))};
3078: }
3079:
3080: sub filemimetype {
3081: return $fm{lc(shift(@_))};
3082: }
3083:
3084:
3085: sub filecategoryselect {
3086: my ($name,$value)=@_;
3087: return &select_form($value,$name,
3088: '' => &mt('Any category'),
3089: map { $_,$_ } sort(keys(%category_extensions)));
3090: }
3091:
3092: =pod
3093:
3094: =item * &filedescription()
3095:
3096: returns description for a specified file type
3097:
3098: =cut
3099:
3100: sub filedescription {
3101: my $file_description = $fd{lc(shift())};
3102: $file_description =~ s:([\[\]]):~$1:g;
3103: return &mt($file_description);
3104: }
3105:
3106: =pod
3107:
3108: =item * &filedescriptionex()
3109:
3110: returns description for a specified file type with
3111: extra formatting
3112:
3113: =cut
3114:
3115: sub filedescriptionex {
3116: my $ex=shift;
3117: my $file_description = $fd{lc($ex)};
3118: $file_description =~ s:([\[\]]):~$1:g;
3119: return '.'.$ex.' '.&mt($file_description);
3120: }
3121:
3122: # End of .tab access
3123: =pod
3124:
3125: =back
3126:
3127: =cut
3128:
3129: # ------------------------------------------------------------------ File Types
3130: sub fileextensions {
3131: return sort(keys(%fe));
3132: }
3133:
3134: # ----------------------------------------------------------- Display Languages
3135: # returns a hash with all desired display languages
3136: #
3137:
3138: sub display_languages {
3139: my %languages=();
3140: foreach my $lang (&Apache::lonlocal::preferred_languages()) {
3141: $languages{$lang}=1;
3142: }
3143: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
3144: if ($env{'form.displaylanguage'}) {
3145: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
3146: $languages{$lang}=1;
3147: }
3148: }
3149: return %languages;
3150: }
3151:
3152: sub languages {
3153: my ($possible_langs) = @_;
3154: my @preferred_langs = &Apache::lonlocal::preferred_languages();
3155: if (!ref($possible_langs)) {
3156: if( wantarray ) {
3157: return @preferred_langs;
3158: } else {
3159: return $preferred_langs[0];
3160: }
3161: }
3162: my %possibilities = map { $_ => 1 } (@$possible_langs);
3163: my @preferred_possibilities;
3164: foreach my $preferred_lang (@preferred_langs) {
3165: if (exists($possibilities{$preferred_lang})) {
3166: push(@preferred_possibilities, $preferred_lang);
3167: }
3168: }
3169: if( wantarray ) {
3170: return @preferred_possibilities;
3171: }
3172: return $preferred_possibilities[0];
3173: }
3174:
3175: sub user_lang {
3176: my ($touname,$toudom,$fromcid) = @_;
3177: my @userlangs;
3178: if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
3179: @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
3180: $env{'course.'.$fromcid.'.languages'}));
3181: } else {
3182: my %langhash = &getlangs($touname,$toudom);
3183: if ($langhash{'languages'} ne '') {
3184: @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
3185: } else {
3186: my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
3187: if ($domdefs{'lang_def'} ne '') {
3188: @userlangs = ($domdefs{'lang_def'});
3189: }
3190: }
3191: }
3192: my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
3193: my $user_lh = Apache::localize->get_handle(@languages);
3194: return $user_lh;
3195: }
3196:
3197:
3198: ###############################################################
3199: ## Student Answer Attempts ##
3200: ###############################################################
3201:
3202: =pod
3203:
3204: =head1 Alternate Problem Views
3205:
3206: =over 4
3207:
3208: =item * &get_previous_attempt($symb, $username, $domain, $course,
3209: $getattempt, $regexp, $gradesub)
3210:
3211: Return string with previous attempt on problem. Arguments:
3212:
3213: =over 4
3214:
3215: =item * $symb: Problem, including path
3216:
3217: =item * $username: username of the desired student
3218:
3219: =item * $domain: domain of the desired student
3220:
3221: =item * $course: Course ID
3222:
3223: =item * $getattempt: Leave blank for all attempts, otherwise put
3224: something
3225:
3226: =item * $regexp: if string matches this regexp, the string will be
3227: sent to $gradesub
3228:
3229: =item * $gradesub: routine that processes the string if it matches $regexp
3230:
3231: =back
3232:
3233: The output string is a table containing all desired attempts, if any.
3234:
3235: =cut
3236:
3237: sub get_previous_attempt {
3238: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
3239: my $prevattempts='';
3240: no strict 'refs';
3241: if ($symb) {
3242: my (%returnhash)=
3243: &Apache::lonnet::restore($symb,$course,$domain,$username);
3244: if ($returnhash{'version'}) {
3245: my %lasthash=();
3246: my $version;
3247: for ($version=1;$version<=$returnhash{'version'};$version++) {
3248: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
3249: $lasthash{$key}=$returnhash{$version.':'.$key};
3250: }
3251: }
3252: $prevattempts=&start_data_table().&start_data_table_header_row();
3253: $prevattempts.='<th>'.&mt('History').'</th>';
3254: foreach my $key (sort(keys(%lasthash))) {
3255: my ($ign,@parts) = split(/\./,$key);
3256: if ($#parts > 0) {
3257: my $data=$parts[-1];
3258: pop(@parts);
3259: $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.' </th>';
3260: } else {
3261: if ($#parts == 0) {
3262: $prevattempts.='<th>'.$parts[0].'</th>';
3263: } else {
3264: $prevattempts.='<th>'.$ign.'</th>';
3265: }
3266: }
3267: }
3268: $prevattempts.=&end_data_table_header_row();
3269: if ($getattempt eq '') {
3270: for ($version=1;$version<=$returnhash{'version'};$version++) {
3271: $prevattempts.=&start_data_table_row().
3272: '<td>'.&mt('Transaction [_1]',$version).'</td>';
3273: foreach my $key (sort(keys(%lasthash))) {
3274: my $value = &format_previous_attempt_value($key,
3275: $returnhash{$version.':'.$key});
3276: $prevattempts.='<td>'.$value.' </td>';
3277: }
3278: $prevattempts.=&end_data_table_row();
3279: }
3280: }
3281: $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
3282: foreach my $key (sort(keys(%lasthash))) {
3283: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3284: if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
3285: $prevattempts.='<td>'.$value.' </td>';
3286: }
3287: $prevattempts.= &end_data_table_row().&end_data_table();
3288: } else {
3289: $prevattempts=
3290: &start_data_table().&start_data_table_row().
3291: '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
3292: &end_data_table_row().&end_data_table();
3293: }
3294: } else {
3295: $prevattempts=
3296: &start_data_table().&start_data_table_row().
3297: '<td>'.&mt('No data.').'</td>'.
3298: &end_data_table_row().&end_data_table();
3299: }
3300: }
3301:
3302: sub format_previous_attempt_value {
3303: my ($key,$value) = @_;
3304: if ($key =~ /timestamp/) {
3305: $value = &Apache::lonlocal::locallocaltime($value);
3306: } elsif (ref($value) eq 'ARRAY') {
3307: $value = '('.join(', ', @{ $value }).')';
3308: } else {
3309: $value = &unescape($value);
3310: }
3311: return $value;
3312: }
3313:
3314:
3315: sub relative_to_absolute {
3316: my ($url,$output)=@_;
3317: my $parser=HTML::TokeParser->new(\$output);
3318: my $token;
3319: my $thisdir=$url;
3320: my @rlinks=();
3321: while ($token=$parser->get_token) {
3322: if ($token->[0] eq 'S') {
3323: if ($token->[1] eq 'a') {
3324: if ($token->[2]->{'href'}) {
3325: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
3326: }
3327: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
3328: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
3329: } elsif ($token->[1] eq 'base') {
3330: $thisdir=$token->[2]->{'href'};
3331: }
3332: }
3333: }
3334: $thisdir=~s-/[^/]*$--;
3335: foreach my $link (@rlinks) {
3336: unless (($link=~/^https?\:\/\//i) ||
3337: ($link=~/^\//) ||
3338: ($link=~/^javascript:/i) ||
3339: ($link=~/^mailto:/i) ||
3340: ($link=~/^\#/)) {
3341: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
3342: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
3343: }
3344: }
3345: # -------------------------------------------------- Deal with Applet codebases
3346: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
3347: return $output;
3348: }
3349:
3350: =pod
3351:
3352: =item * &get_student_view()
3353:
3354: show a snapshot of what student was looking at
3355:
3356: =cut
3357:
3358: sub get_student_view {
3359: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
3360: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
3361: my (%form);
3362: my @elements=('symb','courseid','domain','username');
3363: foreach my $element (@elements) {
3364: $form{'grade_'.$element}=eval '$'.$element #'
3365: }
3366: if (defined($moreenv)) {
3367: %form=(%form,%{$moreenv});
3368: }
3369: if (defined($target)) { $form{'grade_target'} = $target; }
3370: $feedurl=&Apache::lonnet::clutter($feedurl);
3371: my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
3372: $userview=~s/\<body[^\>]*\>//gi;
3373: $userview=~s/\<\/body\>//gi;
3374: $userview=~s/\<html\>//gi;
3375: $userview=~s/\<\/html\>//gi;
3376: $userview=~s/\<head\>//gi;
3377: $userview=~s/\<\/head\>//gi;
3378: $userview=~s/action\s*\=/would_be_action\=/gi;
3379: $userview=&relative_to_absolute($feedurl,$userview);
3380: if (wantarray) {
3381: return ($userview,$response);
3382: } else {
3383: return $userview;
3384: }
3385: }
3386:
3387: sub get_student_view_with_retries {
3388: my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
3389:
3390: my $ok = 0; # True if we got a good response.
3391: my $content;
3392: my $response;
3393:
3394: # Try to get the student_view done. within the retries count:
3395:
3396: do {
3397: ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
3398: $ok = $response->is_success;
3399: if (!$ok) {
3400: &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
3401: }
3402: $retries--;
3403: } while (!$ok && ($retries > 0));
3404:
3405: if (!$ok) {
3406: $content = ''; # On error return an empty content.
3407: }
3408: if (wantarray) {
3409: return ($content, $response);
3410: } else {
3411: return $content;
3412: }
3413: }
3414:
3415: =pod
3416:
3417: =item * &get_student_answers()
3418:
3419: show a snapshot of how student was answering problem
3420:
3421: =cut
3422:
3423: sub get_student_answers {
3424: my ($symb,$username,$domain,$courseid,%form) = @_;
3425: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
3426: my (%moreenv);
3427: my @elements=('symb','courseid','domain','username');
3428: foreach my $element (@elements) {
3429: $moreenv{'grade_'.$element}=eval '$'.$element #'
3430: }
3431: $moreenv{'grade_target'}='answer';
3432: %moreenv=(%form,%moreenv);
3433: $feedurl = &Apache::lonnet::clutter($feedurl);
3434: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
3435: return $userview;
3436: }
3437:
3438: =pod
3439:
3440: =item * &submlink()
3441:
3442: Inputs: $text $uname $udom $symb $target
3443:
3444: Returns: A link to grades.pm such as to see the SUBM view of a student
3445:
3446: =cut
3447:
3448: ###############################################
3449: sub submlink {
3450: my ($text,$uname,$udom,$symb,$target)=@_;
3451: if (!($uname && $udom)) {
3452: (my $cursymb, my $courseid,$udom,$uname)=
3453: &Apache::lonnet::whichuser($symb);
3454: if (!$symb) { $symb=$cursymb; }
3455: }
3456: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
3457: $symb=&escape($symb);
3458: if ($target) { $target="target=\"$target\""; }
3459: return '<a href="/adm/grades?&command=submission&'.
3460: 'symb='.$symb.'&student='.$uname.
3461: '&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
3462: }
3463: ##############################################
3464:
3465: =pod
3466:
3467: =item * &pgrdlink()
3468:
3469: Inputs: $text $uname $udom $symb $target
3470:
3471: Returns: A link to grades.pm such as to see the PGRD view of a student
3472:
3473: =cut
3474:
3475: ###############################################
3476: sub pgrdlink {
3477: my $link=&submlink(@_);
3478: $link=~s/(&command=submission)/$1&showgrading=yes/;
3479: return $link;
3480: }
3481: ##############################################
3482:
3483: =pod
3484:
3485: =item * &pprmlink()
3486:
3487: Inputs: $text $uname $udom $symb $target
3488:
3489: Returns: A link to parmset.pm such as to see the PPRM view of a
3490: student and a specific resource
3491:
3492: =cut
3493:
3494: ###############################################
3495: sub pprmlink {
3496: my ($text,$uname,$udom,$symb,$target)=@_;
3497: if (!($uname && $udom)) {
3498: (my $cursymb, my $courseid,$udom,$uname)=
3499: &Apache::lonnet::whichuser($symb);
3500: if (!$symb) { $symb=$cursymb; }
3501: }
3502: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
3503: $symb=&escape($symb);
3504: if ($target) { $target="target=\"$target\""; }
3505: return '<a href="/adm/parmset?command=set&'.
3506: 'symb='.$symb.'&uname='.$uname.
3507: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
3508: }
3509: ##############################################
3510:
3511: =pod
3512:
3513: =back
3514:
3515: =cut
3516:
3517: ###############################################
3518:
3519:
3520: sub timehash {
3521: my ($thistime) = @_;
3522: my $timezone = &Apache::lonlocal::gettimezone();
3523: my $dt = DateTime->from_epoch(epoch => $thistime)
3524: ->set_time_zone($timezone);
3525: my $wday = $dt->day_of_week();
3526: if ($wday == 7) { $wday = 0; }
3527: return ( 'second' => $dt->second(),
3528: 'minute' => $dt->minute(),
3529: 'hour' => $dt->hour(),
3530: 'day' => $dt->day_of_month(),
3531: 'month' => $dt->month(),
3532: 'year' => $dt->year(),
3533: 'weekday' => $wday,
3534: 'dayyear' => $dt->day_of_year(),
3535: 'dlsav' => $dt->is_dst() );
3536: }
3537:
3538: sub utc_string {
3539: my ($date)=@_;
3540: return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
3541: }
3542:
3543: sub maketime {
3544: my %th=@_;
3545: my ($epoch_time,$timezone,$dt);
3546: $timezone = &Apache::lonlocal::gettimezone();
3547: eval {
3548: $dt = DateTime->new( year => $th{'year'},
3549: month => $th{'month'},
3550: day => $th{'day'},
3551: hour => $th{'hour'},
3552: minute => $th{'minute'},
3553: second => $th{'second'},
3554: time_zone => $timezone,
3555: );
3556: };
3557: if (!$@) {
3558: $epoch_time = $dt->epoch;
3559: if ($epoch_time) {
3560: return $epoch_time;
3561: }
3562: }
3563: return POSIX::mktime(
3564: ($th{'seconds'},$th{'minutes'},$th{'hours'},
3565: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
3566: }
3567:
3568: #########################################
3569:
3570: sub findallcourses {
3571: my ($roles,$uname,$udom) = @_;
3572: my %roles;
3573: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
3574: my %courses;
3575: my $now=time;
3576: if (!defined($uname)) {
3577: $uname = $env{'user.name'};
3578: }
3579: if (!defined($udom)) {
3580: $udom = $env{'user.domain'};
3581: }
3582: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
3583: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
3584: if (!%roles) {
3585: %roles = (
3586: cc => 1,
3587: in => 1,
3588: ep => 1,
3589: ta => 1,
3590: cr => 1,
3591: st => 1,
3592: );
3593: }
3594: foreach my $entry (keys(%roleshash)) {
3595: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
3596: if ($trole =~ /^cr/) {
3597: next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
3598: } else {
3599: next if (!exists($roles{$trole}));
3600: }
3601: if ($tend) {
3602: next if ($tend < $now);
3603: }
3604: if ($tstart) {
3605: next if ($tstart > $now);
3606: }
3607: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
3608: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
3609: if ($secpart eq '') {
3610: ($cnum,$role) = split(/_/,$cnumpart);
3611: $sec = 'none';
3612: $realsec = '';
3613: } else {
3614: $cnum = $cnumpart;
3615: ($sec,$role) = split(/_/,$secpart);
3616: $realsec = $sec;
3617: }
3618: $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
3619: }
3620: } else {
3621: foreach my $key (keys(%env)) {
3622: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
3623: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
3624: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
3625: next if ($role eq 'ca' || $role eq 'aa');
3626: next if (%roles && !exists($roles{$role}));
3627: my ($starttime,$endtime)=split(/\./,$env{$key});
3628: my $active=1;
3629: if ($starttime) {
3630: if ($now<$starttime) { $active=0; }
3631: }
3632: if ($endtime) {
3633: if ($now>$endtime) { $active=0; }
3634: }
3635: if ($active) {
3636: if ($sec eq '') {
3637: $sec = 'none';
3638: }
3639: $courses{$cdom.'_'.$cnum}{$sec} =
3640: $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
3641: }
3642: }
3643: }
3644: }
3645: return %courses;
3646: }
3647:
3648: ###############################################
3649:
3650: sub blockcheck {
3651: my ($setters,$activity,$uname,$udom) = @_;
3652:
3653: if (!defined($udom)) {
3654: $udom = $env{'user.domain'};
3655: }
3656: if (!defined($uname)) {
3657: $uname = $env{'user.name'};
3658: }
3659:
3660: # If uname and udom are for a course, check for blocks in the course.
3661:
3662: if (&Apache::lonnet::is_course($udom,$uname)) {
3663: my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
3664: my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
3665: return ($startblock,$endblock);
3666: }
3667:
3668: my $startblock = 0;
3669: my $endblock = 0;
3670: my %live_courses = &findallcourses(undef,$uname,$udom);
3671:
3672: # If uname is for a user, and activity is course-specific, i.e.,
3673: # boards, chat or groups, check for blocking in current course only.
3674:
3675: if (($activity eq 'boards' || $activity eq 'chat' ||
3676: $activity eq 'groups') && ($env{'request.course.id'})) {
3677: foreach my $key (keys(%live_courses)) {
3678: if ($key ne $env{'request.course.id'}) {
3679: delete($live_courses{$key});
3680: }
3681: }
3682: }
3683:
3684: my $otheruser = 0;
3685: my %own_courses;
3686: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
3687: # Resource belongs to user other than current user.
3688: $otheruser = 1;
3689: # Gather courses for current user
3690: %own_courses =
3691: &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
3692: }
3693:
3694: # Gather active course roles - course coordinator, instructor,
3695: # exam proctor, ta, student, or custom role.
3696:
3697: foreach my $course (keys(%live_courses)) {
3698: my ($cdom,$cnum);
3699: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
3700: $cdom = $env{'course.'.$course.'.domain'};
3701: $cnum = $env{'course.'.$course.'.num'};
3702: } else {
3703: ($cdom,$cnum) = split(/_/,$course);
3704: }
3705: my $no_ownblock = 0;
3706: my $no_userblock = 0;
3707: if ($otheruser && $activity ne 'com') {
3708: # Check if current user has 'evb' priv for this
3709: if (defined($own_courses{$course})) {
3710: foreach my $sec (keys(%{$own_courses{$course}})) {
3711: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
3712: if ($sec ne 'none') {
3713: $checkrole .= '/'.$sec;
3714: }
3715: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
3716: $no_ownblock = 1;
3717: last;
3718: }
3719: }
3720: }
3721: # if they have 'evb' priv and are currently not playing student
3722: next if (($no_ownblock) &&
3723: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
3724: }
3725: foreach my $sec (keys(%{$live_courses{$course}})) {
3726: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
3727: if ($sec ne 'none') {
3728: $checkrole .= '/'.$sec;
3729: }
3730: if ($otheruser) {
3731: # Resource belongs to user other than current user.
3732: # Assemble privs for that user, and check for 'evb' priv.
3733: my ($trole,$tdom,$tnum,$tsec);
3734: my $entry = $live_courses{$course}{$sec};
3735: if ($entry =~ /^cr/) {
3736: ($trole,$tdom,$tnum,$tsec) =
3737: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
3738: } else {
3739: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
3740: }
3741: my ($spec,$area,$trest,%allroles,%userroles);
3742: $area = '/'.$tdom.'/'.$tnum;
3743: $trest = $tnum;
3744: if ($tsec ne '') {
3745: $area .= '/'.$tsec;
3746: $trest .= '/'.$tsec;
3747: }
3748: $spec = $trole.'.'.$area;
3749: if ($trole =~ /^cr/) {
3750: &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
3751: $tdom,$spec,$trest,$area);
3752: } else {
3753: &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
3754: $tdom,$spec,$trest,$area);
3755: }
3756: my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
3757: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
3758: if ($1) {
3759: $no_userblock = 1;
3760: last;
3761: }
3762: }
3763: } else {
3764: # Resource belongs to current user
3765: # Check for 'evb' priv via lonnet::allowed().
3766: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
3767: $no_ownblock = 1;
3768: last;
3769: }
3770: }
3771: }
3772: # if they have the evb priv and are currently not playing student
3773: next if (($no_ownblock) &&
3774: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
3775: next if ($no_userblock);
3776:
3777: # Retrieve blocking times and identity of locker for course
3778: # of specified user, unless user has 'evb' privilege.
3779:
3780: my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
3781: if (($start != 0) &&
3782: (($startblock == 0) || ($startblock > $start))) {
3783: $startblock = $start;
3784: }
3785: if (($end != 0) &&
3786: (($endblock == 0) || ($endblock < $end))) {
3787: $endblock = $end;
3788: }
3789: }
3790: return ($startblock,$endblock);
3791: }
3792:
3793: sub get_blocks {
3794: my ($setters,$activity,$cdom,$cnum) = @_;
3795: my $startblock = 0;
3796: my $endblock = 0;
3797: my $course = $cdom.'_'.$cnum;
3798: $setters->{$course} = {};
3799: $setters->{$course}{'staff'} = [];
3800: $setters->{$course}{'times'} = [];
3801: my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
3802: foreach my $record (keys(%records)) {
3803: my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
3804: if ($start <= time && $end >= time) {
3805: my ($staff_name,$staff_dom,$title,$blocks) =
3806: &parse_block_record($records{$record});
3807: if ($blocks->{$activity} eq 'on') {
3808: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
3809: push(@{$$setters{$course}{'times'}}, [$start,$end]);
3810: if ( ($startblock == 0) || ($startblock > $start) ) {
3811: $startblock = $start;
3812: }
3813: if ( ($endblock == 0) || ($endblock < $end) ) {
3814: $endblock = $end;
3815: }
3816: }
3817: }
3818: }
3819: return ($startblock,$endblock);
3820: }
3821:
3822: sub parse_block_record {
3823: my ($record) = @_;
3824: my ($setuname,$setudom,$title,$blocks);
3825: if (ref($record) eq 'HASH') {
3826: ($setuname,$setudom) = split(/:/,$record->{'setter'});
3827: $title = &unescape($record->{'event'});
3828: $blocks = $record->{'blocks'};
3829: } else {
3830: my @data = split(/:/,$record,3);
3831: if (scalar(@data) eq 2) {
3832: $title = $data[1];
3833: ($setuname,$setudom) = split(/@/,$data[0]);
3834: } else {
3835: ($setuname,$setudom,$title) = @data;
3836: }
3837: $blocks = { 'com' => 'on' };
3838: }
3839: return ($setuname,$setudom,$title,$blocks);
3840: }
3841:
3842: sub blocking_status {
3843: my $blocked;
3844: my ($activity,$uname,$udom) = @_;
3845: my %setters;
3846: my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
3847: if ($startblock && $endblock) {
3848: $blocked = 1;
3849: }
3850: if(!wantarray) {
3851: return $blocked;
3852: }
3853: my $output;
3854: my $querystring;
3855: $querystring = "?activity=$activity";
3856:
3857: $output .= <<"END_MYBLOCK";
3858: <script type="text/javascript">
3859: // <![CDATA[
3860: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
3861: var options = "width=" + w + ",height=" + h + ",";
3862: options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
3863: options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
3864: var newWin = window.open(url, wdwName, options);
3865: newWin.focus();
3866: }
3867:
3868: // ]]>
3869: </script>
3870: END_MYBLOCK
3871: my $popupUrl = "/adm/blockingstatus/$querystring";
3872: $output .= <<"END_BLOCK";
3873: <div class='LC_comblock'>
3874: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
3875: title='Communication Blocked'>
3876: <img class='LC_noBorder LC_middle' title='Communication Blocked' src='/res/adm/pages/comblock.png' alt='Communication Blocked'/></a>
3877: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
3878: title='Communication Blocked'>Communication Blocked</a>
3879: </div>
3880:
3881: END_BLOCK
3882:
3883: return ($blocked, $output);
3884: }
3885:
3886: ###############################################
3887:
3888: sub check_ip_acc {
3889: my ($acc)=@_;
3890: &Apache::lonxml::debug("acc is $acc");
3891: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
3892: return 1;
3893: }
3894: my $allowed=0;
3895: my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
3896:
3897: my $name;
3898: foreach my $pattern (split(',',$acc)) {
3899: $pattern =~ s/^\s*//;
3900: $pattern =~ s/\s*$//;
3901: if ($pattern =~ /\*$/) {
3902: #35.8.*
3903: $pattern=~s/\*//;
3904: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
3905: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
3906: #35.8.3.[34-56]
3907: my $low=$2;
3908: my $high=$3;
3909: $pattern=$1;
3910: if ($ip =~ /^\Q$pattern\E/) {
3911: my $last=(split(/\./,$ip))[3];
3912: if ($last <=$high && $last >=$low) { $allowed=1; }
3913: }
3914: } elsif ($pattern =~ /^\*/) {
3915: #*.msu.edu
3916: $pattern=~s/\*//;
3917: if (!defined($name)) {
3918: use Socket;
3919: my $netaddr=inet_aton($ip);
3920: ($name)=gethostbyaddr($netaddr,AF_INET);
3921: }
3922: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
3923: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
3924: #127.0.0.1
3925: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
3926: } else {
3927: #some.name.com
3928: if (!defined($name)) {
3929: use Socket;
3930: my $netaddr=inet_aton($ip);
3931: ($name)=gethostbyaddr($netaddr,AF_INET);
3932: }
3933: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
3934: }
3935: if ($allowed) { last; }
3936: }
3937: return $allowed;
3938: }
3939:
3940: ###############################################
3941:
3942: =pod
3943:
3944: =head1 Domain Template Functions
3945:
3946: =over 4
3947:
3948: =item * &determinedomain()
3949:
3950: Inputs: $domain (usually will be undef)
3951:
3952: Returns: Determines which domain should be used for designs
3953:
3954: =cut
3955:
3956: ###############################################
3957: sub determinedomain {
3958: my $domain=shift;
3959: if (! $domain) {
3960: # Determine domain if we have not been given one
3961: $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
3962: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
3963: if ($env{'request.role.domain'}) {
3964: $domain=$env{'request.role.domain'};
3965: }
3966: }
3967: return $domain;
3968: }
3969: ###############################################
3970:
3971: sub devalidate_domconfig_cache {
3972: my ($udom)=@_;
3973: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
3974: }
3975:
3976: # ---------------------- Get domain configuration for a domain
3977: sub get_domainconf {
3978: my ($udom) = @_;
3979: my $cachetime=1800;
3980: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
3981: if (defined($cached)) { return %{$result}; }
3982:
3983: my %domconfig = &Apache::lonnet::get_dom('configuration',
3984: ['login','rolecolors'],$udom);
3985: my (%designhash,%legacy);
3986: if (keys(%domconfig) > 0) {
3987: if (ref($domconfig{'login'}) eq 'HASH') {
3988: if (keys(%{$domconfig{'login'}})) {
3989: foreach my $key (keys(%{$domconfig{'login'}})) {
3990: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
3991: foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
3992: $designhash{$udom.'.login.'.$key.'_'.$img} =
3993: $domconfig{'login'}{$key}{$img};
3994: }
3995: } else {
3996: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
3997: }
3998: }
3999: } else {
4000: $legacy{'login'} = 1;
4001: }
4002: } else {
4003: $legacy{'login'} = 1;
4004: }
4005: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
4006: if (keys(%{$domconfig{'rolecolors'}})) {
4007: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
4008: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
4009: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
4010: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
4011: }
4012: }
4013: }
4014: } else {
4015: $legacy{'rolecolors'} = 1;
4016: }
4017: } else {
4018: $legacy{'rolecolors'} = 1;
4019: }
4020: if (keys(%legacy) > 0) {
4021: my %legacyhash = &get_legacy_domconf($udom);
4022: foreach my $item (keys(%legacyhash)) {
4023: if ($item =~ /^\Q$udom\E\.login/) {
4024: if ($legacy{'login'}) {
4025: $designhash{$item} = $legacyhash{$item};
4026: }
4027: } else {
4028: if ($legacy{'rolecolors'}) {
4029: $designhash{$item} = $legacyhash{$item};
4030: }
4031: }
4032: }
4033: }
4034: } else {
4035: %designhash = &get_legacy_domconf($udom);
4036: }
4037: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
4038: $cachetime);
4039: return %designhash;
4040: }
4041:
4042: sub get_legacy_domconf {
4043: my ($udom) = @_;
4044: my %legacyhash;
4045: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
4046: my $designfile = $designdir.'/'.$udom.'.tab';
4047: if (-e $designfile) {
4048: if ( open (my $fh,"<$designfile") ) {
4049: while (my $line = <$fh>) {
4050: next if ($line =~ /^\#/);
4051: chomp($line);
4052: my ($key,$val)=(split(/\=/,$line));
4053: if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
4054: }
4055: close($fh);
4056: }
4057: }
4058: if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
4059: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
4060: }
4061: return %legacyhash;
4062: }
4063:
4064: =pod
4065:
4066: =item * &domainlogo()
4067:
4068: Inputs: $domain (usually will be undef)
4069:
4070: Returns: A link to a domain logo, if the domain logo exists.
4071: If the domain logo does not exist, a description of the domain.
4072:
4073: =cut
4074:
4075: ###############################################
4076: sub domainlogo {
4077: my $domain = &determinedomain(shift);
4078: my %designhash = &get_domainconf($domain);
4079: # See if there is a logo
4080: if ($designhash{$domain.'.login.domlogo'} ne '') {
4081: my $imgsrc = $designhash{$domain.'.login.domlogo'};
4082: if ($imgsrc =~ m{^/(adm|res)/}) {
4083: if ($imgsrc =~ m{^/res/}) {
4084: my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
4085: &Apache::lonnet::repcopy($local_name);
4086: }
4087: $imgsrc = &lonhttpdurl($imgsrc);
4088: }
4089: return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
4090: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
4091: return &Apache::lonnet::domain($domain,'description');
4092: } else {
4093: return '';
4094: }
4095: }
4096: ##############################################
4097:
4098: =pod
4099:
4100: =item * &designparm()
4101:
4102: Inputs: $which parameter; $domain (usually will be undef)
4103:
4104: Returns: value of designparamter $which
4105:
4106: =cut
4107:
4108:
4109: ##############################################
4110: sub designparm {
4111: my ($which,$domain)=@_;
4112: if (exists($env{'environment.color.'.$which})) {
4113: return $env{'environment.color.'.$which};
4114: }
4115: $domain=&determinedomain($domain);
4116: my %domdesign = &get_domainconf($domain);
4117: my $output;
4118: if ($domdesign{$domain.'.'.$which} ne '') {
4119: $output = $domdesign{$domain.'.'.$which};
4120: } else {
4121: $output = $defaultdesign{$which};
4122: }
4123: if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
4124: ($which =~ /login\.(img|logo|domlogo|login)/)) {
4125: if ($output =~ m{^/(adm|res)/}) {
4126: if ($output =~ m{^/res/}) {
4127: my $local_name = &Apache::lonnet::filelocation('',$output);
4128: &Apache::lonnet::repcopy($local_name);
4129: }
4130: $output = &lonhttpdurl($output);
4131: }
4132: }
4133: return $output;
4134: }
4135:
4136: ##############################################
4137: =pod
4138:
4139: =item * &authorspace()
4140:
4141: Inputs: ./.
4142:
4143: Returns: Path to the Construction Space of the current user's
4144: accessed author space
4145: The author space will be that of the current user
4146: when accessing the own author space
4147: and that of the co-author/assistent co-author
4148: when accessing the co-author's/assistent co-author's
4149: space
4150:
4151: =cut
4152:
4153: sub authorspace {
4154: my $caname = '';
4155: if ($env{'request.role'} =~ /^ca|^aa/) {
4156: (undef,$caname) =
4157: ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
4158: } else {
4159: $caname = $env{'user.name'};
4160: }
4161: return '/priv/'.$caname.'/';
4162: }
4163:
4164: ##############################################
4165: =pod
4166:
4167: =item * &head_subbox()
4168:
4169: Inputs: $content (contains HTML code with page functions, etc.)
4170:
4171: Returns: HTML div with $content
4172: To be included in page header
4173:
4174: =cut
4175:
4176: sub head_subbox {
4177: my ($content)=@_;
4178: my $output =
4179: '<div id="LC_head_subbox">'
4180: .$content
4181: .'</div>'
4182: }
4183:
4184: ##############################################
4185: =pod
4186:
4187: =item * &CSTR_pageheader()
4188:
4189: Inputs: ./.
4190:
4191: Returns: HTML div with CSTR path and recent box
4192: To be included on Construction Space pages
4193:
4194: =cut
4195:
4196: sub CSTR_pageheader {
4197: # this is for resources; directories have customtitle, and crumbs
4198: # and select recent are created in lonpubdir.pm
4199: my ($uname,$thisdisfn)=
4200: ($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
4201: my $formaction='/priv/'.$uname.'/'.$thisdisfn;
4202: $formaction=~s/\/+/\//g;
4203:
4204: my $parentpath = '';
4205: my $lastitem = '';
4206: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
4207: $parentpath = $1;
4208: $lastitem = $2;
4209: } else {
4210: $lastitem = $thisdisfn;
4211: }
4212: return
4213: '<div>'
4214: .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
4215: .'<b>'.&mt('Construction Space:').'</b> '
4216: .'<form name="dirs" method="post" action="'.$formaction
4217: .'" target="_top"><tt><b>' #FIXME lonpubdir: target="_parent"
4218: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."$lastitem</b></tt><br />"
4219: #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
4220: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
4221: .'</form>'
4222: .&Apache::lonmenu::constspaceform()
4223: .'</div>';
4224: }
4225:
4226: ###############################################
4227: ###############################################
4228:
4229: =pod
4230:
4231: =back
4232:
4233: =head1 HTML Helpers
4234:
4235: =over 4
4236:
4237: =item * &bodytag()
4238:
4239: Returns a uniform header for LON-CAPA web pages.
4240:
4241: Inputs:
4242:
4243: =over 4
4244:
4245: =item * $title, A title to be displayed on the page.
4246:
4247: =item * $function, the current role (can be undef).
4248:
4249: =item * $addentries, extra parameters for the <body> tag.
4250:
4251: =item * $bodyonly, if defined, only return the <body> tag.
4252:
4253: =item * $domain, if defined, force a given domain.
4254:
4255: =item * $forcereg, if page should register as content page (relevant for
4256: text interface only)
4257:
4258: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
4259: navigational links
4260:
4261: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
4262:
4263: =item * $no_inline_link, if true and in remote mode, don't show the
4264: 'Switch To Inline Menu' link
4265:
4266: =item * $args, optional argument valid values are
4267: no_auto_mt_title -> prevents &mt()ing the title arg
4268: inherit_jsmath -> when creating popup window in a page,
4269: should it have jsmath forced on by the
4270: current page
4271:
4272: =back
4273:
4274: Returns: A uniform header for LON-CAPA web pages.
4275: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
4276: If $bodyonly is undef or zero, an html string containing a <body> tag and
4277: other decorations will be returned.
4278:
4279: =cut
4280:
4281: sub bodytag {
4282: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
4283: $no_nav_bar,$bgcolor,$no_inline_link,$args)=@_;
4284:
4285: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
4286:
4287: $function = &get_users_function() if (!$function);
4288: my $img = &designparm($function.'.img',$domain);
4289: my $font = &designparm($function.'.font',$domain);
4290: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
4291:
4292: my %design = ( 'style' => 'margin-top: 0',
4293: 'bgcolor' => $pgbg,
4294: 'text' => $font,
4295: 'alink' => &designparm($function.'.alink',$domain),
4296: 'vlink' => &designparm($function.'.vlink',$domain),
4297: 'link' => &designparm($function.'.link',$domain),);
4298: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
4299:
4300: # role and realm
4301: my ($role,$realm) = split(/\./,$env{'request.role'},2);
4302: if ($role eq 'ca') {
4303: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
4304: $realm = &plainname($rname,$rdom);
4305: }
4306: # realm
4307: if ($env{'request.course.id'}) {
4308: if ($env{'request.role'} !~ /^cr/) {
4309: $role = &Apache::lonnet::plaintext($role,&course_type());
4310: }
4311: $realm = $env{'course.'.$env{'request.course.id'}.'.description'};
4312: } else {
4313: $role = &Apache::lonnet::plaintext($role);
4314: }
4315:
4316: if (!$realm) { $realm=' '; }
4317: # Set messages
4318: my $messages=&domainlogo($domain);
4319:
4320: my $extra_body_attr = &make_attr_string($forcereg,\%design);
4321:
4322: # construct main body tag
4323: my $bodytag = "<body $extra_body_attr>".
4324: &Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
4325:
4326: if ($bodyonly) {
4327: return $bodytag;
4328: }
4329:
4330: my $name = &plainname($env{'user.name'},$env{'user.domain'});
4331: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4332: undef($role);
4333: } else {
4334: $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
4335: }
4336:
4337: my $titleinfo = '<h1>'.$title.'</h1>';
4338: #
4339: # Extra info if you are the DC
4340: my $dc_info = '';
4341: if ($env{'user.adv'} && exists($env{'user.role.dc./'.
4342: $env{'course.'.$env{'request.course.id'}.
4343: '.domain'}.'/'})) {
4344: my $cid = $env{'request.course.id'};
4345: $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
4346: $dc_info =~ s/\s+$//;
4347: $dc_info = '('.$dc_info.')';
4348: }
4349:
4350: $role = "($role)" if $role;
4351: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
4352:
4353: if ($env{'environment.remote'} eq 'off') {
4354: # No Remote
4355: if ($env{'request.state'} eq 'construct') {
4356: $forcereg=1;
4357: }
4358:
4359: # if ($env{'request.state'} eq 'construct') {
4360: # $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
4361: # }
4362:
4363: my $titletable = '<table id="LC_title_bar">'
4364: ."<tr><td> $titleinfo $dc_info</td>"
4365: .'</tr></table>';
4366:
4367: if ($no_nav_bar) {
4368: $bodytag .= $titletable;
4369: } else {
4370: $bodytag .= qq|<div id="LC_nav_bar">$name $role<br />
4371: <em>$realm</em> $dc_info</div>| unless $env{'form.inhibitmenu'};
4372:
4373: if ($env{'request.state'} eq 'construct') {
4374: $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$titletable);
4375: } else {
4376: $bodytag .= &Apache::lonmenu::menubuttons($forcereg).$titletable;
4377: }
4378: }
4379: return $bodytag;
4380: }
4381:
4382: #
4383: # Top frame rendering, Remote is up
4384: #
4385:
4386: my $imgsrc = $img;
4387: if ($img =~ /^\/adm/) {
4388: $imgsrc = &lonhttpdurl($img);
4389: }
4390: my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
4391:
4392: # Explicit link to get inline menu
4393: my $menu= ($no_inline_link?''
4394: :'<a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
4395: $bodytag .= qq|<div id="LC_nav_bar">$name $role
4396: <em>$realm</em> $dc_info </div>
4397: <ol class="LC_smallMenu LC_right">
4398: <li>$menu</li>
4399: </ol>| unless $env{'form.inhibitmenu'};
4400: #
4401: return(<<ENDBODY);
4402: $bodytag
4403: <table id="LC_title_bar" class="LC_with_remote">
4404: <tr><td>$upperleft</td>
4405: <td>$messages </td>
4406: </tr>
4407: <tr><td>$titleinfo $dc_info $menu</td>
4408: </tr>
4409: </table>
4410: ENDBODY
4411: }
4412:
4413: sub make_attr_string {
4414: my ($register,$attr_ref) = @_;
4415:
4416: if ($attr_ref && !ref($attr_ref)) {
4417: die("addentries Must be a hash ref ".
4418: join(':',caller(1))." ".
4419: join(':',caller(0))." ");
4420: }
4421:
4422: if ($register) {
4423: my ($on_load,$on_unload);
4424: foreach my $key (keys(%{$attr_ref})) {
4425: if (lc($key) eq 'onload') {
4426: $on_load.=$attr_ref->{$key}.';';
4427: delete($attr_ref->{$key});
4428:
4429: } elsif (lc($key) eq 'onunload') {
4430: $on_unload.=$attr_ref->{$key}.';';
4431: delete($attr_ref->{$key});
4432: }
4433: }
4434: $attr_ref->{'onload'} =
4435: &Apache::lonmenu::loadevents(). $on_load;
4436: $attr_ref->{'onunload'}=
4437: &Apache::lonmenu::unloadevents().$on_unload;
4438: }
4439:
4440: # Accessibility font enhance
4441: if ($env{'browser.fontenhance'} eq 'on') {
4442: my $style;
4443: foreach my $key (keys(%{$attr_ref})) {
4444: if (lc($key) eq 'style') {
4445: $style.=$attr_ref->{$key}.';';
4446: delete($attr_ref->{$key});
4447: }
4448: }
4449: $attr_ref->{'style'}=$style.'; font-size: x-large;';
4450: }
4451:
4452: my $attr_string;
4453: foreach my $attr (keys(%$attr_ref)) {
4454: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
4455: }
4456: return $attr_string;
4457: }
4458:
4459:
4460: ###############################################
4461: ###############################################
4462:
4463: =pod
4464:
4465: =item * &endbodytag()
4466:
4467: Returns a uniform footer for LON-CAPA web pages.
4468:
4469: Inputs: 1 - optional reference to an args hash
4470: If in the hash, key for noredirectlink has a value which evaluates to true,
4471: a 'Continue' link is not displayed if the page contains an
4472: internal redirect in the <head></head> section,
4473: i.e., $env{'internal.head.redirect'} exists
4474:
4475: =cut
4476:
4477: sub endbodytag {
4478: my ($args) = @_;
4479: my $endbodytag='</body>';
4480: $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
4481: if ( exists( $env{'internal.head.redirect'} ) ) {
4482: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
4483: $endbodytag=
4484: "<br /><a href=\"$env{'internal.head.redirect'}\">".
4485: &mt('Continue').'</a>'.
4486: $endbodytag;
4487: }
4488: }
4489: return $endbodytag;
4490: }
4491:
4492: =pod
4493:
4494: =item * &standard_css()
4495:
4496: Returns a style sheet
4497:
4498: Inputs: (all optional)
4499: domain -> force to color decorate a page for a specific
4500: domain
4501: function -> force usage of a specific rolish color scheme
4502: bgcolor -> override the default page bgcolor
4503:
4504: =cut
4505:
4506: sub standard_css {
4507: my ($function,$domain,$bgcolor) = @_;
4508: $function = &get_users_function() if (!$function);
4509: my $img = &designparm($function.'.img', $domain);
4510: my $tabbg = &designparm($function.'.tabbg', $domain);
4511: my $font = &designparm($function.'.font', $domain);
4512: my $fontmenu = &designparm($function.'.fontmenu', $domain);
4513: #second colour for later usage
4514: my $sidebg = &designparm($function.'.sidebg',$domain);
4515: my $pgbg_or_bgcolor =
4516: $bgcolor ||
4517: &designparm($function.'.pgbg', $domain);
4518: my $pgbg = &designparm($function.'.pgbg', $domain);
4519: my $alink = &designparm($function.'.alink', $domain);
4520: my $vlink = &designparm($function.'.vlink', $domain);
4521: my $link = &designparm($function.'.link', $domain);
4522:
4523: my $loginbg = &designparm('login.sidebg',$domain);
4524: my $bgcol = &designparm('login.bgcol',$domain);
4525: my $textcol = &designparm('login.textcol',$domain);
4526:
4527: my $sans = 'Verdana,Arial,Helvetica,sans-serif';
4528: my $mono = 'monospace';
4529: my $data_table_head = $sidebg;
4530: my $data_table_light = '#FAFAFA';
4531: my $data_table_dark = '#F0F0F0';
4532: my $data_table_darker = '#CCCCCC';
4533: my $data_table_highlight = '#FFFF00';
4534: my $mail_new = '#FFBB77';
4535: my $mail_new_hover = '#DD9955';
4536: my $mail_read = '#BBBB77';
4537: my $mail_read_hover = '#999944';
4538: my $mail_replied = '#AAAA88';
4539: my $mail_replied_hover = '#888855';
4540: my $mail_other = '#99BBBB';
4541: my $mail_other_hover = '#669999';
4542: my $table_header = '#DDDDDD';
4543: my $feedback_link_bg = '#BBBBBB';
4544: my $lg_border_color = '#C8C8C8';
4545:
4546: my $border = ($env{'browser.type'} eq 'explorer' ||
4547: $env{'browser.type'} eq 'safari' ) ? '0 2px 0 2px'
4548: : '0 3px 0 4px';
4549:
4550:
4551: return <<END;
4552: body {
4553: font-family: $sans;
4554: line-height:130%;
4555: font-size:0.83em;
4556: color:$font;
4557: }
4558:
4559: a:link, a:visited {
4560: font-size:100%;
4561: }
4562:
4563: a:focus {
4564: color: red;
4565: background: yellow
4566: }
4567:
4568: hr {
4569: clear: both;
4570: color: $tabbg;
4571: background-color: $tabbg;
4572: height: 3px;
4573: border: none;
4574: }
4575:
4576: form, .inline {
4577: display: inline;
4578: }
4579:
4580: .LC_right {
4581: text-align:right;
4582: }
4583:
4584: .LC_middle {
4585: vertical-align:middle;
4586: }
4587:
4588: /* just for tests */
4589: .LC_400Box {width:400px; }
4590: /* end */
4591:
4592: .LC_filename {
4593: font-family: $mono;
4594: white-space:pre;
4595: }
4596:
4597: .LC_fileicon {
4598: border: none;
4599: height: 1.3em;
4600: vertical-align: text-bottom;
4601: margin-right: 0.3em;
4602: text-decoration:none;
4603: }
4604:
4605: .LC_error {
4606: color: red;
4607: font-size: larger;
4608: }
4609:
4610: .LC_warning,
4611: .LC_diff_removed {
4612: color: red;
4613: }
4614:
4615: .LC_info,
4616: .LC_success,
4617: .LC_diff_added {
4618: color: green;
4619: }
4620:
4621: div.LC_confirm_box {
4622: background-color: #FAFAFA;
4623: border: 1px solid $lg_border_color;
4624: margin-right: 0;
4625: padding: 5px;
4626: }
4627:
4628: div.LC_confirm_box .LC_error img,
4629: div.LC_confirm_box .LC_success img {
4630: vertical-align: middle;
4631: }
4632:
4633: .LC_icon {
4634: border: none;
4635: vertical-align: middle;
4636: }
4637:
4638: .LC_docs_spacer {
4639: width: 25px;
4640: height: 1px;
4641: border: none;
4642: }
4643:
4644: .LC_internal_info {
4645: color: #999999;
4646: }
4647:
4648: .LC_discussion {
4649: background: $tabbg;
4650: border: 1px solid black;
4651: margin: 2px;
4652: }
4653:
4654: .LC_disc_action_links_bar {
4655: background: $tabbg;
4656: border: none;
4657: margin: 4px;
4658: }
4659:
4660: .LC_disc_action_left {
4661: text-align: left;
4662: }
4663:
4664: .LC_disc_action_right {
4665: text-align: right;
4666: }
4667:
4668: .LC_disc_new_item {
4669: background: white;
4670: border: 2px solid red;
4671: margin: 2px;
4672: }
4673:
4674: .LC_disc_old_item {
4675: background: white;
4676: border: 1px solid black;
4677: margin: 2px;
4678: }
4679:
4680: table.LC_pastsubmission {
4681: border: 1px solid black;
4682: margin: 2px;
4683: }
4684:
4685: table#LC_top_nav,
4686: table#LC_menubuttons,
4687: table#LC_nav_location {
4688: width: 100%;
4689: background: $pgbg;
4690: border: 2px;
4691: border-collapse: separate;
4692: padding: 0;
4693: }
4694:
4695: table#LC_title_bar a {
4696: color: $fontmenu;
4697: }
4698:
4699: table#LC_title_bar {
4700: clear: both;
4701: display: none;
4702: }
4703:
4704: table#LC_title_bar,
4705: table.LC_breadcrumbs,
4706: table#LC_title_bar.LC_with_remote {
4707: width: 100%;
4708: border-color: $pgbg;
4709: border-style: solid;
4710: border-width: $border;
4711: background: $pgbg;
4712: color: $fontmenu;
4713: border-collapse: collapse;
4714: padding: 0;
4715: margin: 0;
4716: }
4717:
4718: table#LC_title_bar td {
4719: background: $tabbg;
4720: }
4721:
4722: table#LC_menubuttons img{
4723: border: none;
4724: }
4725:
4726: table#LC_top_nav td {
4727: background: $tabbg;
4728: border: none;
4729: font-size: small;
4730: vertical-align:top;
4731: padding:2px 5px 2px 5px;
4732: }
4733:
4734: table#LC_top_nav td a,
4735: div#LC_top_nav a {
4736: color: $font;
4737: }
4738:
4739: table#LC_top_nav td.LC_top_nav_logo {
4740: background: $tabbg;
4741: text-align: left;
4742: white-space: nowrap;
4743: width: 31px;
4744: }
4745:
4746: table#LC_top_nav td.LC_top_nav_logo img {
4747: border: none;
4748: vertical-align: bottom;
4749: }
4750:
4751: table#LC_top_nav td.LC_top_nav_exit,
4752: table#LC_top_nav td.LC_top_nav_help {
4753: width: 2.0em;
4754: }
4755:
4756: table#LC_top_nav td.LC_top_nav_login {
4757: width: 4.0em;
4758: text-align: center;
4759: }
4760:
4761: .LC_breadcrumbs_component {
4762: float: right;
4763: margin: 0 1em;
4764: }
4765: .LC_breadcrumbs_component img {
4766: vertical-align: middle;
4767: }
4768:
4769: td.LC_table_cell_checkbox {
4770: text-align: center;
4771: }
4772:
4773: table#LC_mainmenu td.LC_mainmenu_column {
4774: vertical-align: top;
4775: }
4776:
4777: .LC_fontsize_small {
4778: font-size: 70%;
4779: }
4780:
4781: #LC_breadcrumbs {
4782: clear:both;
4783: background: $sidebg;
4784: border-bottom: 1px solid $lg_border_color;
4785: line-height: 32px;
4786: margin: 0;
4787: padding: 0;
4788: }
4789:
4790: /* Preliminary fix to hide breadcrumbs inside remote control window */
4791: #LC_remote #LC_breadcrumbs {
4792: display:none;
4793: }
4794:
4795: #LC_head_subbox {
4796: clear:both;
4797: background: #F8F8F8; /* $sidebg; */
4798: border-bottom: 1px solid $lg_border_color;
4799: margin: 0 0 10px 0;
4800: padding: 5px;
4801: }
4802:
4803: .LC_fontsize_medium {
4804: font-size: 85%;
4805: }
4806:
4807: .LC_fontsize_large {
4808: font-size: 120%;
4809: }
4810:
4811: .LC_menubuttons_inline_text {
4812: color: $font;
4813: font-size: 90%;
4814: padding-left:3px;
4815: }
4816:
4817: .LC_menubuttons_link {
4818: text-decoration: none;
4819: }
4820:
4821: .LC_menubuttons_category {
4822: color: $font;
4823: background: $pgbg;
4824: font-size: larger;
4825: font-weight: bold;
4826: }
4827:
4828: td.LC_menubuttons_text {
4829: color: $font;
4830: }
4831:
4832: .LC_current_location {
4833: background: $tabbg;
4834: }
4835:
4836: .LC_new_mail {
4837: background: $tabbg;
4838: font-weight: bold;
4839: }
4840:
4841: .LC_roleslog_note {
4842: font-size: small;
4843: }
4844:
4845: table.LC_data_table,
4846: table.LC_mail_list {
4847: border: 1px solid #000000;
4848: border-collapse: separate;
4849: border-spacing: 1px;
4850: background: $pgbg;
4851: }
4852:
4853: .LC_data_table_dense {
4854: font-size: small;
4855: }
4856:
4857: table.LC_nested_outer {
4858: border: 1px solid #000000;
4859: border-collapse: collapse;
4860: border-spacing: 0;
4861: width: 100%;
4862: }
4863:
4864: table.LC_nested {
4865: border: none;
4866: border-collapse: collapse;
4867: border-spacing: 0;
4868: width: 100%;
4869: }
4870:
4871: table.LC_data_table tr th,
4872: table.LC_calendar tr th,
4873: table.LC_mail_list tr th,
4874: table.LC_prior_tries tr th {
4875: font-weight: bold;
4876: background-color: $data_table_head;
4877: color:$fontmenu;
4878: font-size:90%;
4879: }
4880:
4881: table.LC_data_table tr.LC_info_row > td {
4882: background-color: #CCCCCC;
4883: font-weight: bold;
4884: text-align: left;
4885: }
4886:
4887: table.LC_data_table tr.LC_odd_row > td,
4888: table.LC_pick_box tr > td.LC_odd_row {
4889: background-color: $data_table_light;
4890: padding: 2px;
4891: }
4892:
4893: table.LC_data_table tr.LC_even_row > td,
4894: table.LC_pick_box tr > td.LC_even_row {
4895: background-color: $data_table_dark;
4896: padding: 2px;
4897: }
4898:
4899: table.LC_data_table tr.LC_data_table_highlight td {
4900: background-color: $data_table_darker;
4901: }
4902:
4903: table.LC_data_table tr td.LC_leftcol_header {
4904: background-color: $data_table_head;
4905: font-weight: bold;
4906: }
4907:
4908: table.LC_data_table tr.LC_empty_row td,
4909: table.LC_nested tr.LC_empty_row td {
4910: background-color: #FFFFFF;
4911: font-weight: bold;
4912: font-style: italic;
4913: text-align: center;
4914: padding: 8px;
4915: }
4916:
4917: table.LC_nested tr.LC_empty_row td {
4918: padding: 4ex
4919: }
4920:
4921: table.LC_nested_outer tr th {
4922: font-weight: bold;
4923: color:$fontmenu;
4924: background-color: $data_table_head;
4925: font-size: small;
4926: border-bottom: 1px solid #000000;
4927: }
4928:
4929: table.LC_nested_outer tr td.LC_subheader {
4930: background-color: $data_table_head;
4931: font-weight: bold;
4932: font-size: small;
4933: border-bottom: 1px solid #000000;
4934: text-align: right;
4935: }
4936:
4937: table.LC_nested tr.LC_info_row td {
4938: background-color: #CCCCCC;
4939: font-weight: bold;
4940: font-size: small;
4941: text-align: center;
4942: }
4943:
4944: table.LC_nested tr.LC_info_row td.LC_left_item,
4945: table.LC_nested_outer tr th.LC_left_item {
4946: text-align: left;
4947: }
4948:
4949: table.LC_nested td {
4950: background-color: #FFFFFF;
4951: font-size: small;
4952: }
4953:
4954: table.LC_nested_outer tr th.LC_right_item,
4955: table.LC_nested tr.LC_info_row td.LC_right_item,
4956: table.LC_nested tr.LC_odd_row td.LC_right_item,
4957: table.LC_nested tr td.LC_right_item {
4958: text-align: right;
4959: }
4960:
4961: table.LC_nested tr.LC_odd_row td {
4962: background-color: #EEEEEE;
4963: }
4964:
4965: table.LC_createuser {
4966: }
4967:
4968: table.LC_createuser tr.LC_section_row td {
4969: font-size: small;
4970: }
4971:
4972: table.LC_createuser tr.LC_info_row td {
4973: background-color: #CCCCCC;
4974: font-weight: bold;
4975: text-align: center;
4976: }
4977:
4978: table.LC_calendar {
4979: border: 1px solid #000000;
4980: border-collapse: collapse;
4981: }
4982:
4983: table.LC_calendar_pickdate {
4984: font-size: xx-small;
4985: }
4986:
4987: table.LC_calendar tr td {
4988: border: 1px solid #000000;
4989: vertical-align: top;
4990: }
4991:
4992: table.LC_calendar tr td.LC_calendar_day_empty {
4993: background-color: $data_table_dark;
4994: }
4995:
4996: table.LC_calendar tr td.LC_calendar_day_current {
4997: background-color: $data_table_highlight;
4998: }
4999:
5000: table.LC_mail_list tr.LC_mail_new {
5001: background-color: $mail_new;
5002: }
5003:
5004: table.LC_mail_list tr.LC_mail_new:hover {
5005: background-color: $mail_new_hover;
5006: }
5007:
5008: table.LC_mail_list tr.LC_mail_even {
5009: }
5010:
5011: table.LC_mail_list tr.LC_mail_odd {
5012: }
5013:
5014: table.LC_mail_list tr.LC_mail_read {
5015: background-color: $mail_read;
5016: }
5017:
5018: table.LC_mail_list tr.LC_mail_read:hover {
5019: background-color: $mail_read_hover;
5020: }
5021:
5022: table.LC_mail_list tr.LC_mail_replied {
5023: background-color: $mail_replied;
5024: }
5025:
5026: table.LC_mail_list tr.LC_mail_replied:hover {
5027: background-color: $mail_replied_hover;
5028: }
5029:
5030: table.LC_mail_list tr.LC_mail_other {
5031: background-color: $mail_other;
5032: }
5033:
5034: table.LC_mail_list tr.LC_mail_other:hover {
5035: background-color: $mail_other_hover;
5036: }
5037:
5038: table.LC_data_table tr > td.LC_browser_file,
5039: table.LC_data_table tr > td.LC_browser_file_published {
5040: background: #CCFF88;
5041: }
5042:
5043: table.LC_data_table tr > td.LC_browser_file_locked,
5044: table.LC_data_table tr > td.LC_browser_file_unpublished {
5045: background: #FFAA99;
5046: }
5047:
5048: table.LC_data_table tr > td.LC_browser_file_obsolete {
5049: background: #AAAAAA;
5050: }
5051:
5052: table.LC_data_table tr > td.LC_browser_file_modified,
5053: table.LC_data_table tr > td.LC_browser_file_metamodified {
5054: background: #FFFF77;
5055: }
5056:
5057: table.LC_data_table tr.LC_browser_folder > td {
5058: background: #CCCCFF;
5059: }
5060:
5061: table.LC_data_table tr > td.LC_roles_is {
5062: /* background: #77FF77; */
5063: }
5064:
5065: table.LC_data_table tr > td.LC_roles_future {
5066: background: #FFFF77;
5067: }
5068:
5069: table.LC_data_table tr > td.LC_roles_will {
5070: background: #FFAA77;
5071: }
5072:
5073: table.LC_data_table tr > td.LC_roles_expired {
5074: background: #FF7777;
5075: }
5076:
5077: table.LC_data_table tr > td.LC_roles_will_not {
5078: background: #AAFF77;
5079: }
5080:
5081: table.LC_data_table tr > td.LC_roles_selected {
5082: background: #11CC55;
5083: }
5084:
5085: span.LC_current_location {
5086: font-size:larger;
5087: background: $pgbg;
5088: }
5089:
5090: span.LC_parm_menu_item {
5091: font-size: larger;
5092: }
5093:
5094: span.LC_parm_scope_all {
5095: color: red;
5096: }
5097:
5098: span.LC_parm_scope_folder {
5099: color: green;
5100: }
5101:
5102: span.LC_parm_scope_resource {
5103: color: orange;
5104: }
5105:
5106: span.LC_parm_part {
5107: color: blue;
5108: }
5109:
5110: span.LC_parm_folder, span.LC_parm_symb {
5111: font-size: x-small;
5112: font-family: $mono;
5113: color: #AAAAAA;
5114: }
5115:
5116: td.LC_parm_overview_level_menu,
5117: td.LC_parm_overview_map_menu,
5118: td.LC_parm_overview_parm_selectors,
5119: td.LC_parm_overview_restrictions {
5120: border: 1px solid black;
5121: border-collapse: collapse;
5122: }
5123:
5124: table.LC_parm_overview_restrictions td {
5125: border-width: 1px 4px 1px 4px;
5126: border-style: solid;
5127: border-color: $pgbg;
5128: text-align: center;
5129: }
5130:
5131: table.LC_parm_overview_restrictions th {
5132: background: $tabbg;
5133: border-width: 1px 4px 1px 4px;
5134: border-style: solid;
5135: border-color: $pgbg;
5136: }
5137:
5138: table#LC_helpmenu {
5139: border: none;
5140: height: 55px;
5141: border-spacing: 0;
5142: }
5143:
5144: table#LC_helpmenu fieldset legend {
5145: font-size: larger;
5146: }
5147:
5148: table#LC_helpmenu_links {
5149: width: 100%;
5150: border: 1px solid black;
5151: background: $pgbg;
5152: padding: 0;
5153: border-spacing: 1px;
5154: }
5155:
5156: table#LC_helpmenu_links tr td {
5157: padding: 1px;
5158: background: $tabbg;
5159: text-align: center;
5160: font-weight: bold;
5161: }
5162:
5163: table#LC_helpmenu_links a:link,
5164: table#LC_helpmenu_links a:visited,
5165: table#LC_helpmenu_links a:active {
5166: text-decoration: none;
5167: color: $font;
5168: }
5169:
5170: table#LC_helpmenu_links a:hover {
5171: text-decoration: underline;
5172: color: $vlink;
5173: }
5174:
5175: .LC_chrt_popup_exists {
5176: border: 1px solid #339933;
5177: margin: -1px;
5178: }
5179:
5180: .LC_chrt_popup_up {
5181: border: 1px solid yellow;
5182: margin: -1px;
5183: }
5184:
5185: .LC_chrt_popup {
5186: border: 1px solid #8888FF;
5187: background: #CCCCFF;
5188: }
5189:
5190: table.LC_pick_box {
5191: border-collapse: separate;
5192: background: white;
5193: border: 1px solid black;
5194: border-spacing: 1px;
5195: }
5196:
5197: table.LC_pick_box td.LC_pick_box_title {
5198: background: $sidebg;
5199: font-weight: bold;
5200: text-align: right;
5201: vertical-align: top;
5202: width: 184px;
5203: padding: 8px;
5204: }
5205:
5206: table.LC_pick_box td.LC_pick_box_value {
5207: text-align: left;
5208: padding: 8px;
5209: }
5210:
5211: table.LC_pick_box td.LC_pick_box_select {
5212: text-align: left;
5213: padding: 8px;
5214: }
5215:
5216: table.LC_pick_box td.LC_pick_box_separator {
5217: padding: 0;
5218: height: 1px;
5219: background: black;
5220: }
5221:
5222: table.LC_pick_box td.LC_pick_box_submit {
5223: text-align: right;
5224: }
5225:
5226: table.LC_pick_box td.LC_evenrow_value {
5227: text-align: left;
5228: padding: 8px;
5229: background-color: $data_table_light;
5230: }
5231:
5232: table.LC_pick_box td.LC_oddrow_value {
5233: text-align: left;
5234: padding: 8px;
5235: background-color: $data_table_light;
5236: }
5237:
5238: table.LC_helpform_receipt {
5239: width: 620px;
5240: border-collapse: separate;
5241: background: white;
5242: border: 1px solid black;
5243: border-spacing: 1px;
5244: }
5245:
5246: table.LC_helpform_receipt td.LC_pick_box_title {
5247: background: $tabbg;
5248: font-weight: bold;
5249: text-align: right;
5250: width: 184px;
5251: padding: 8px;
5252: }
5253:
5254: table.LC_helpform_receipt td.LC_evenrow_value {
5255: text-align: left;
5256: padding: 8px;
5257: background-color: $data_table_light;
5258: }
5259:
5260: table.LC_helpform_receipt td.LC_oddrow_value {
5261: text-align: left;
5262: padding: 8px;
5263: background-color: $data_table_light;
5264: }
5265:
5266: table.LC_helpform_receipt td.LC_pick_box_separator {
5267: padding: 0;
5268: height: 1px;
5269: background: black;
5270: }
5271:
5272: span.LC_helpform_receipt_cat {
5273: font-weight: bold;
5274: }
5275:
5276: table.LC_group_priv_box {
5277: background: white;
5278: border: 1px solid black;
5279: border-spacing: 1px;
5280: }
5281:
5282: table.LC_group_priv_box td.LC_pick_box_title {
5283: background: $tabbg;
5284: font-weight: bold;
5285: text-align: right;
5286: width: 184px;
5287: }
5288:
5289: table.LC_group_priv_box td.LC_groups_fixed {
5290: background: $data_table_light;
5291: text-align: center;
5292: }
5293:
5294: table.LC_group_priv_box td.LC_groups_optional {
5295: background: $data_table_dark;
5296: text-align: center;
5297: }
5298:
5299: table.LC_group_priv_box td.LC_groups_functionality {
5300: background: $data_table_darker;
5301: text-align: center;
5302: font-weight: bold;
5303: }
5304:
5305: table.LC_group_priv td {
5306: text-align: left;
5307: padding: 0;
5308: }
5309:
5310: table.LC_notify_front_page {
5311: background: white;
5312: border: 1px solid black;
5313: padding: 8px;
5314: }
5315:
5316: table.LC_notify_front_page td {
5317: padding: 8px;
5318: }
5319:
5320: .LC_navbuttons {
5321: margin: 2ex 0ex 2ex 0ex;
5322: }
5323:
5324: .LC_topic_bar {
5325: font-weight: bold;
5326: width: 100%;
5327: background: $tabbg;
5328: vertical-align: middle;
5329: margin: 2ex 0ex 2ex 0ex;
5330: padding: 3px;
5331: }
5332:
5333: .LC_topic_bar span {
5334: vertical-align: middle;
5335: }
5336:
5337: .LC_topic_bar img {
5338: vertical-align: bottom;
5339: }
5340:
5341: table.LC_course_group_status {
5342: margin: 20px;
5343: }
5344:
5345: table.LC_status_selector td {
5346: vertical-align: top;
5347: text-align: center;
5348: padding: 4px;
5349: }
5350:
5351: div.LC_feedback_link {
5352: clear: both;
5353: background: $sidebg;
5354: width: 100%;
5355: padding-bottom: 10px;
5356: border: 1px $tabbg solid;
5357: height: 22px;
5358: line-height: 22px;
5359: padding-top: 5px;
5360: }
5361:
5362: div.LC_feedback_link img {
5363: height: 22px;
5364: vertical-align:middle;
5365: }
5366:
5367: div.LC_feedback_link a{
5368: text-decoration: none;
5369: }
5370:
5371: div.LC_comblock {
5372: display:inline;
5373: color:$font;
5374: font-size:90%;
5375: }
5376:
5377: div.LC_feedback_link div.LC_comblock {
5378: padding-left:5px;
5379: }
5380:
5381: div.LC_feedback_link div.LC_comblock a {
5382: color:$font;
5383: }
5384:
5385: span.LC_feedback_link {
5386: /* background: $feedback_link_bg; */
5387: font-size: larger;
5388: }
5389:
5390: span.LC_message_link {
5391: /* background: $feedback_link_bg; */
5392: font-size: larger;
5393: position: absolute;
5394: right: 1em;
5395: }
5396:
5397: table.LC_prior_tries {
5398: border: 1px solid #000000;
5399: border-collapse: separate;
5400: border-spacing: 1px;
5401: }
5402:
5403: table.LC_prior_tries td {
5404: padding: 2px;
5405: }
5406:
5407: .LC_answer_correct {
5408: background: lightgreen;
5409: color: darkgreen;
5410: padding: 6px;
5411: }
5412:
5413: .LC_answer_charged_try {
5414: background: #FFAAAA;
5415: color: darkred;
5416: padding: 6px;
5417: }
5418:
5419: .LC_answer_not_charged_try,
5420: .LC_answer_no_grade,
5421: .LC_answer_late {
5422: background: lightyellow;
5423: color: black;
5424: padding: 6px;
5425: }
5426:
5427: .LC_answer_previous {
5428: background: lightblue;
5429: color: darkblue;
5430: padding: 6px;
5431: }
5432:
5433: .LC_answer_no_message {
5434: background: #FFFFFF;
5435: color: black;
5436: padding: 6px;
5437: }
5438:
5439: .LC_answer_unknown {
5440: background: orange;
5441: color: black;
5442: padding: 6px;
5443: }
5444:
5445: span.LC_prior_numerical,
5446: span.LC_prior_string,
5447: span.LC_prior_custom,
5448: span.LC_prior_reaction,
5449: span.LC_prior_math {
5450: font-family: monospace;
5451: white-space: pre;
5452: }
5453:
5454: span.LC_prior_string {
5455: font-family: monospace;
5456: white-space: pre;
5457: }
5458:
5459: table.LC_prior_option {
5460: width: 100%;
5461: border-collapse: collapse;
5462: }
5463:
5464: table.LC_prior_rank,
5465: table.LC_prior_match {
5466: border-collapse: collapse;
5467: }
5468:
5469: table.LC_prior_option tr td,
5470: table.LC_prior_rank tr td,
5471: table.LC_prior_match tr td {
5472: border: 1px solid #000000;
5473: }
5474:
5475: .LC_nobreak {
5476: white-space: nowrap;
5477: }
5478:
5479: span.LC_cusr_emph {
5480: font-style: italic;
5481: }
5482:
5483: span.LC_cusr_subheading {
5484: font-weight: normal;
5485: font-size: 85%;
5486: }
5487:
5488: table.LC_docs_documents {
5489: background: #BBBBBB;
5490: border-width: 0;
5491: border-collapse: collapse;
5492: }
5493:
5494: table.LC_docs_documents td.LC_docs_document {
5495: border: 2px solid black;
5496: padding: 4px;
5497: }
5498:
5499: div.LC_docs_entry_move {
5500: border: 1px solid #BBBBBB;
5501: background: #DDDDDD;
5502: width: 22px;
5503: padding: 1px;
5504: margin: 0;
5505: }
5506:
5507: table.LC_data_table tr > td.LC_docs_entry_commands,
5508: table.LC_data_table tr > td.LC_docs_entry_parameter {
5509: background: #DDDDDD;
5510: font-size: x-small;
5511: }
5512:
5513: .LC_docs_entry_parameter {
5514: white-space: nowrap;
5515: }
5516:
5517: .LC_docs_copy {
5518: color: #000099;
5519: }
5520:
5521: .LC_docs_cut {
5522: color: #550044;
5523: }
5524:
5525: .LC_docs_rename {
5526: color: #009900;
5527: }
5528:
5529: .LC_docs_remove {
5530: color: #990000;
5531: }
5532:
5533: .LC_docs_reinit_warn,
5534: .LC_docs_ext_edit {
5535: font-size: x-small;
5536: }
5537:
5538: table.LC_docs_adddocs td,
5539: table.LC_docs_adddocs th {
5540: border: 1px solid #BBBBBB;
5541: padding: 4px;
5542: background: #DDDDDD;
5543: }
5544:
5545: table.LC_sty_begin {
5546: background: #BBFFBB;
5547: }
5548:
5549: table.LC_sty_end {
5550: background: #FFBBBB;
5551: }
5552:
5553: table.LC_double_column {
5554: border-width: 0;
5555: border-collapse: collapse;
5556: width: 100%;
5557: padding: 2px;
5558: }
5559:
5560: table.LC_double_column tr td.LC_left_col {
5561: top: 2px;
5562: left: 2px;
5563: width: 47%;
5564: vertical-align: top;
5565: }
5566:
5567: table.LC_double_column tr td.LC_right_col {
5568: top: 2px;
5569: right: 2px;
5570: width: 47%;
5571: vertical-align: top;
5572: }
5573:
5574: div.LC_left_float {
5575: float: left;
5576: padding-right: 5%;
5577: padding-bottom: 4px;
5578: }
5579:
5580: div.LC_clear_float_header {
5581: padding-bottom: 2px;
5582: }
5583:
5584: div.LC_clear_float_footer {
5585: padding-top: 10px;
5586: clear: both;
5587: }
5588:
5589: div.LC_grade_show_user {
5590: margin-top: 20px;
5591: border: 1px solid black;
5592: }
5593:
5594: div.LC_grade_user_name {
5595: background: #DDDDEE;
5596: border-bottom: 1px solid black;
5597: font-weight: bold;
5598: font-size: large;
5599: }
5600:
5601: div.LC_grade_show_user_odd_row div.LC_grade_user_name {
5602: background: #DDEEDD;
5603: }
5604:
5605: div.LC_grade_show_problem,
5606: div.LC_grade_submissions,
5607: div.LC_grade_message_center,
5608: div.LC_grade_info_links,
5609: div.LC_grade_assign {
5610: margin: 5px;
5611: width: 99%;
5612: background: #FFFFFF;
5613: }
5614:
5615: div.LC_grade_show_problem_header,
5616: div.LC_grade_submissions_header,
5617: div.LC_grade_message_center_header,
5618: div.LC_grade_assign_header {
5619: font-weight: bold;
5620: font-size: large;
5621: }
5622:
5623: div.LC_grade_show_problem_problem,
5624: div.LC_grade_submissions_body,
5625: div.LC_grade_message_center_body,
5626: div.LC_grade_assign_body {
5627: border: 1px solid black;
5628: width: 99%;
5629: background: #FFFFFF;
5630: }
5631:
5632: span.LC_grade_check_note {
5633: font-weight: normal;
5634: font-size: medium;
5635: display: inline;
5636: position: absolute;
5637: right: 1em;
5638: }
5639:
5640: table.LC_scantron_action {
5641: width: 100%;
5642: }
5643:
5644: table.LC_scantron_action tr th {
5645: font-weight:bold;
5646: font-style:normal;
5647: }
5648:
5649: .LC_edit_problem_header,
5650: div.LC_edit_problem_footer {
5651: font-weight: normal;
5652: font-size: medium;
5653: margin: 2px;
5654: }
5655:
5656: div.LC_edit_problem_header,
5657: div.LC_edit_problem_header div,
5658: div.LC_edit_problem_footer,
5659: div.LC_edit_problem_footer div,
5660: div.LC_edit_problem_editxml_header,
5661: div.LC_edit_problem_editxml_header div {
5662: margin-top: 5px;
5663: }
5664:
5665: div.LC_edit_problem_header_title {
5666: font-weight: bold;
5667: font-size: larger;
5668: background: $tabbg;
5669: padding: 3px;
5670: }
5671:
5672: table.LC_edit_problem_header_title {
5673: font-size: larger;
5674: font-weight: bold;
5675: width: 100%;
5676: border-color: $pgbg;
5677: border-style: solid;
5678: border-width: $border;
5679: background: $tabbg;
5680: border-collapse: collapse;
5681: padding: 0;
5682: }
5683:
5684: div.LC_edit_problem_discards {
5685: float: left;
5686: padding-bottom: 5px;
5687: }
5688:
5689: div.LC_edit_problem_saves {
5690: float: right;
5691: padding-bottom: 5px;
5692: }
5693:
5694: img.stift{
5695: border-width: 0;
5696: vertical-align: middle;
5697: }
5698:
5699: table#LC_mainmenu{
5700: margin-top:10px;
5701: width:80%;
5702: }
5703:
5704: table#LC_mainmenu td.LC_mainmenu_col_fieldset{
5705: vertical-align: top;
5706: width: 45%;
5707: }
5708:
5709: .LC_mainmenu_fieldset_category {
5710: color: $font;
5711: background: $pgbg;
5712: font-size: small;
5713: font-weight: bold;
5714: }
5715:
5716: div.LC_createcourse {
5717: margin: 10px 10px 10px 10px;
5718: }
5719:
5720: /* ---- Remove when done ----
5721: # The following styles is part of the redesign of LON-CAPA and are
5722: # subject to change during this project.
5723: # Don't rely on their current functionality as they might be
5724: # changed or removed.
5725: # --------------------------*/
5726:
5727: a:hover,
5728: ol.LC_smallMenu a:hover,
5729: ol#LC_MenuBreadcrumbs a:hover,
5730: ol#LC_PathBreadcrumbs a:hover,
5731: ul#LC_TabMainMenuContent a:hover,
5732: .LC_FormSectionClearButton input:hover
5733: ul.LC_TabContent li:hover a {
5734: color:#BF2317;
5735: text-decoration:none;
5736: }
5737:
5738: h1 {
5739: padding: 0;
5740: line-height:130%;
5741: }
5742:
5743: h2,h3,h4,h5,h6 {
5744: margin: 5px 0 5px 0;
5745: padding: 0;
5746: line-height:130%;
5747: }
5748:
5749: .LC_hcell {
5750: padding:3px 15px 3px 15px;
5751: margin: 0;
5752: background-color:$tabbg;
5753: color:$fontmenu;
5754: border-bottom:solid 1px $lg_border_color;
5755: }
5756:
5757: .LC_Box > .LC_hcell {
5758: margin: 0 -10px 10px -10px;
5759: }
5760:
5761: .LC_noBorder {
5762: border: 0;
5763: }
5764:
5765: .LC_Right {
5766: float: right;
5767: margin: 0;
5768: padding: 0;
5769: }
5770:
5771: .LC_FormSectionClearButton input {
5772: background-color:transparent;
5773: border: none;
5774: cursor:pointer;
5775: text-decoration:underline;
5776: }
5777:
5778: .LC_help_open_topic {
5779: color: #FFFFFF;
5780: background-color: #EEEEFF;
5781: margin: 1px;
5782: padding: 4px;
5783: border: 1px solid #000033;
5784: white-space: nowrap;
5785: /* vertical-align: middle; */
5786: }
5787:
5788: dl,ul,div,fieldset {
5789: margin: 10px 10px 10px 0;
5790: /* overflow: hidden; */
5791: }
5792:
5793: fieldset > legend {
5794: font-weight: bold;
5795: padding: 0 5px 0 5px;
5796: }
5797:
5798: #LC_nav_bar {
5799: float: left;
5800: margin: 0.2em 0 0 0;
5801: }
5802:
5803: #LC_nav_bar em{
5804: font-weight: bold;
5805: font-style: normal;
5806: }
5807:
5808: ol.LC_smallMenu {
5809: float: right;
5810: margin: 0.2em 0 0 0;
5811: }
5812:
5813: ol#LC_PathBreadcrumbs {
5814: margin: 0;
5815: }
5816:
5817: ol.LC_smallMenu li {
5818: display: inline;
5819: padding: 5px 5px 0 10px;
5820: vertical-align: top;
5821: }
5822:
5823: ol.LC_smallMenu li img {
5824: vertical-align: bottom;
5825: }
5826:
5827: ol.LC_smallMenu a {
5828: font-size: 90%;
5829: color: RGB(80, 80, 80);
5830: text-decoration: none;
5831: }
5832:
5833: ul#LC_TabMainMenuContent {
5834: clear: both;
5835: color: $fontmenu;
5836: background: $tabbg;
5837: list-style: none;
5838: padding: 0;
5839: margin: 0;
5840: width: 100%;
5841: }
5842:
5843: ul#LC_TabMainMenuContent li {
5844: font-weight: bold;
5845: line-height: 1.8em;
5846: padding: 0 0.8em;
5847: border-right: 1px solid black;
5848: display: inline;
5849: vertical-align: middle;
5850: }
5851:
5852: ul.LC_TabContent {
5853: display:block;
5854: background: $sidebg;
5855: border-bottom: solid 1px $lg_border_color;
5856: list-style:none;
5857: margin: 0 -10px;
5858: padding: 0;
5859: }
5860:
5861: ul.LC_TabContent li,
5862: ul.LC_TabContentBigger li {
5863: float:left;
5864: }
5865:
5866: ul#LC_TabMainMenuContent li a {
5867: color: $fontmenu;
5868: text-decoration: none;
5869: }
5870:
5871: ul.LC_TabContent {
5872: min-height:1.5em;
5873: }
5874:
5875: ul.LC_TabContent li {
5876: vertical-align:middle;
5877: padding: 0 10px 0 10px;
5878: background-color:$tabbg;
5879: border-bottom:solid 1px $lg_border_color;
5880: }
5881:
5882: ul.LC_TabContent .right {
5883: float:right;
5884: }
5885:
5886: ul.LC_TabContent li a, ul.LC_TabContent li {
5887: color:rgb(47,47,47);
5888: text-decoration:none;
5889: font-size:95%;
5890: font-weight:bold;
5891: padding-right: 16px;
5892: }
5893:
5894: ul.LC_TabContent li:hover, ul.LC_TabContent li.active {
5895: background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
5896: border-bottom:solid 2px #FFFFFF;
5897: padding-right: 16px;
5898: }
5899:
5900: #maincoursedoc {
5901: clear:both;
5902: }
5903:
5904: ul.LC_TabContentBigger {
5905: display:block;
5906: list-style:none;
5907: padding: 0;
5908: }
5909:
5910: ul.LC_TabContentBigger li {
5911: vertical-align:bottom;
5912: height: 30px;
5913: font-size:110%;
5914: font-weight:bold;
5915: color: #737373;
5916: }
5917:
5918:
5919: ul.LC_TabContentBigger li a {
5920: background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
5921: height: 30px;
5922: line-height: 30px;
5923: text-align: center;
5924: display: block;
5925: text-decoration: none;
5926: }
5927:
5928: ul.LC_TabContentBigger li:hover a,
5929: ul.LC_TabContentBigger li.active a {
5930: background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
5931: color:$font;
5932: text-decoration: underline;
5933: }
5934:
5935:
5936: ul.LC_TabContentBigger li b {
5937: background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
5938: display: block;
5939: float: left;
5940: padding: 0 30px;
5941: }
5942:
5943: ul.LC_TabContentBigger li:hover b,
5944: ul.LC_TabContentBigger li.active b {
5945: background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
5946: color:$font;
5947: border-bottom: 1px solid #FFFFFF;
5948: }
5949:
5950:
5951: ul.LC_CourseBreadcrumbs {
5952: background: $sidebg;
5953: line-height: 32px;
5954: padding-left: 10px;
5955: margin: 0 0 10px 0;
5956: list-style-position: inside;
5957:
5958: }
5959:
5960: ol#LC_MenuBreadcrumbs,
5961: ol#LC_PathBreadcrumbs {
5962: padding-left: 10px;
5963: margin: 0;
5964: list-style-position: inside;
5965: }
5966:
5967: ol#LC_MenuBreadcrumbs li,
5968: ol#LC_PathBreadcrumbs li,
5969: ul.LC_CourseBreadcrumbs li {
5970: display: inline;
5971: white-space: nowrap;
5972: }
5973:
5974: ol#LC_MenuBreadcrumbs li a,
5975: ul.LC_CourseBreadcrumbs li a {
5976: text-decoration: none;
5977: font-size:90%;
5978: }
5979:
5980: ol#LC_PathBreadcrumbs li a {
5981: text-decoration:none;
5982: font-size:100%;
5983: font-weight:bold;
5984: }
5985:
5986: .LC_Box {
5987: border: solid 1px $lg_border_color;
5988: padding: 0 10px 10px 10px;
5989: }
5990:
5991: .LC_AboutMe_Image {
5992: float:left;
5993: margin-right:10px;
5994: }
5995:
5996: .LC_Clear_AboutMe_Image {
5997: clear:left;
5998: }
5999:
6000: dl.LC_ListStyleClean dt {
6001: padding-right: 5px;
6002: display: table-header-group;
6003: }
6004:
6005: dl.LC_ListStyleClean dd {
6006: display: table-row;
6007: }
6008:
6009: .LC_ListStyleClean,
6010: .LC_ListStyleSimple,
6011: .LC_ListStyleNormal,
6012: .LC_ListStyle_Border,
6013: .LC_ListStyleSpecial {
6014: /*display:block; */
6015: list-style-position: inside;
6016: list-style-type: none;
6017: overflow: hidden;
6018: padding: 0;
6019: }
6020:
6021: .LC_ListStyleSimple li,
6022: .LC_ListStyleSimple dd,
6023: .LC_ListStyleNormal li,
6024: .LC_ListStyleNormal dd,
6025: .LC_ListStyleSpecial li,
6026: .LC_ListStyleSpecial dd {
6027: margin: 0;
6028: padding: 5px 5px 5px 10px;
6029: clear: both;
6030: }
6031:
6032: .LC_ListStyleClean li,
6033: .LC_ListStyleClean dd {
6034: padding-top: 0;
6035: padding-bottom: 0;
6036: }
6037:
6038: .LC_ListStyleSimple dd,
6039: .LC_ListStyleSimple li {
6040: border-bottom: solid 1px $lg_border_color;
6041: }
6042:
6043: .LC_ListStyleSpecial li,
6044: .LC_ListStyleSpecial dd {
6045: list-style-type: none;
6046: background-color: RGB(220, 220, 220);
6047: margin-bottom: 4px;
6048: }
6049:
6050: table.LC_SimpleTable {
6051: margin:5px;
6052: border:solid 1px $lg_border_color;
6053: }
6054:
6055: table.LC_SimpleTable tr {
6056: padding: 0;
6057: border:solid 1px $lg_border_color;
6058: }
6059:
6060: table.LC_SimpleTable thead {
6061: background:rgb(220,220,220);
6062: }
6063:
6064: div.LC_columnSection {
6065: display: block;
6066: clear: both;
6067: overflow: hidden;
6068: margin: 0;
6069: }
6070:
6071: div.LC_columnSection>* {
6072: float: left;
6073: margin: 10px 20px 10px 0;
6074: overflow:hidden;
6075: }
6076:
6077: .LC_loginpage_container {
6078: text-align:left;
6079: margin : 0 auto;
6080: width:90%;
6081: padding: 10px;
6082: height: auto;
6083: background-color:#FFFFFF;
6084: border:1px solid #CCCCCC;
6085: }
6086:
6087:
6088: .LC_loginpage_loginContainer {
6089: float:left;
6090: width: 182px;
6091: padding: 2px;
6092: border:1px solid #CCCCCC;
6093: background-color:$loginbg;
6094: }
6095:
6096: .LC_loginpage_loginContainer h2 {
6097: margin-top: 0;
6098: display:block;
6099: background:$bgcol;
6100: color:$textcol;
6101: padding-left:5px;
6102: }
6103:
6104: .LC_loginpage_loginInfo {
6105: float:left;
6106: width:182px;
6107: border:1px solid #CCCCCC;
6108: padding:2px;
6109: }
6110:
6111: .LC_loginpage_space {
6112: clear: both;
6113: margin-bottom: 20px;
6114: border-bottom: 1px solid #CCCCCC;
6115: }
6116:
6117: .LC_loginpage_floatLeft {
6118: float: left;
6119: width: 200px;
6120: margin: 0;
6121: }
6122:
6123: table em {
6124: font-weight: bold;
6125: font-style: normal;
6126: }
6127:
6128: table.LC_tableBrowseRes,
6129: table.LC_tableOfContent {
6130: border:none;
6131: border-spacing: 1px;
6132: padding: 3px;
6133: background-color: #FFFFFF;
6134: font-size: 90%;
6135: }
6136:
6137: table.LC_tableOfContent{
6138: border-collapse: collapse;
6139: }
6140:
6141: table.LC_tableBrowseRes a,
6142: table.LC_tableOfContent a {
6143: background-color: transparent;
6144: text-decoration: none;
6145: }
6146:
6147: table.LC_tableBrowseRes tr.LC_trOdd,
6148: table.LC_tableOfContent tr.LC_trOdd{
6149: background-color: #EEEEEE;
6150: }
6151:
6152: table.LC_tableOfContent img {
6153: border: none;
6154: height: 1.3em;
6155: vertical-align: text-bottom;
6156: margin-right: 0.3em;
6157: }
6158:
6159: a#LC_content_toolbar_firsthomework {
6160: background-image:url(/res/adm/pages/open-first-problem.gif);
6161: }
6162:
6163: a#LC_content_toolbar_launchnav {
6164: background-image:url(/res/adm/pages/start-navigation.gif);
6165: }
6166:
6167: a#LC_content_toolbar_closenav {
6168: background-image:url(/res/adm/pages/close-navigation.gif);
6169: }
6170:
6171: a#LC_content_toolbar_everything {
6172: background-image:url(/res/adm/pages/show-all.gif);
6173: }
6174:
6175: a#LC_content_toolbar_uncompleted {
6176: background-image:url(/res/adm/pages/show-incomplete-problems.gif);
6177: }
6178:
6179: #LC_content_toolbar_clearbubbles {
6180: background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
6181: }
6182:
6183: a#LC_content_toolbar_changefolder {
6184: background : url(/res/adm/pages/close-all-folders.gif) top center ;
6185: }
6186:
6187: a#LC_content_toolbar_changefolder_toggled {
6188: background-image:url(/res/adm/pages/open-all-folders.gif);
6189: }
6190:
6191: ul#LC_toolbar li a:hover {
6192: background-position: bottom center;
6193: }
6194:
6195: ul#LC_toolbar {
6196: padding: 0;
6197: margin: 2px;
6198: list-style:none;
6199: position:relative;
6200: background-color:white;
6201: }
6202:
6203: ul#LC_toolbar li {
6204: border:1px solid white;
6205: padding: 0;
6206: margin: 0;
6207: float: left;
6208: display:inline;
6209: vertical-align:middle;
6210: }
6211:
6212:
6213: a.LC_toolbarItem {
6214: display:block;
6215: padding: 0;
6216: margin: 0;
6217: height: 32px;
6218: width: 32px;
6219: color:white;
6220: border: none;
6221: background-repeat:no-repeat;
6222: background-color:transparent;
6223: }
6224:
6225: ul.LC_funclist li {
6226: float: left;
6227: white-space: nowrap;
6228: height: 35px; /* at least as high as heighest list item */
6229: margin: 0 15px 15px 10px;
6230: }
6231:
6232:
6233: END
6234: }
6235:
6236: =pod
6237:
6238: =item * &headtag()
6239:
6240: Returns a uniform footer for LON-CAPA web pages.
6241:
6242: Inputs: $title - optional title for the head
6243: $head_extra - optional extra HTML to put inside the <head>
6244: $args - optional arguments
6245: force_register - if is true call registerurl so the remote is
6246: informed
6247: redirect -> array ref of
6248: 1- seconds before redirect occurs
6249: 2- url to redirect to
6250: 3- whether the side effect should occur
6251: (side effect of setting
6252: $env{'internal.head.redirect'} to the url
6253: redirected too)
6254: domain -> force to color decorate a page for a specific
6255: domain
6256: function -> force usage of a specific rolish color scheme
6257: bgcolor -> override the default page bgcolor
6258: no_auto_mt_title
6259: -> prevent &mt()ing the title arg
6260:
6261: =cut
6262:
6263: sub headtag {
6264: my ($title,$head_extra,$args) = @_;
6265:
6266: my $function = $args->{'function'} || &get_users_function();
6267: my $domain = $args->{'domain'} || &determinedomain();
6268: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
6269: my $url = join(':',$env{'user.name'},$env{'user.domain'},
6270: $Apache::lonnet::perlvar{'lonVersion'},
6271: #time(),
6272: $env{'environment.color.timestamp'},
6273: $function,$domain,$bgcolor);
6274:
6275: $url = '/adm/css/'.&escape($url).'.css';
6276:
6277: my $result =
6278: '<head>'.
6279: &font_settings();
6280:
6281: if (!$args->{'frameset'}) {
6282: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
6283: }
6284: if ($args->{'force_register'}) {
6285: $result .= &Apache::lonmenu::registerurl(1);
6286: }
6287: if (!$args->{'no_nav_bar'}
6288: && !$args->{'only_body'}
6289: && !$args->{'frameset'}) {
6290: $result .= &help_menu_js();
6291: }
6292:
6293: if (ref($args->{'redirect'})) {
6294: my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
6295: $url = &Apache::lonenc::check_encrypt($url);
6296: if (!$inhibit_continue) {
6297: $env{'internal.head.redirect'} = $url;
6298: }
6299: $result.=<<ADDMETA
6300: <meta http-equiv="pragma" content="no-cache" />
6301: <meta http-equiv="Refresh" content="$time; url=$url" />
6302: ADDMETA
6303: }
6304: if (!defined($title)) {
6305: $title = 'The LearningOnline Network with CAPA';
6306: }
6307: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
6308: $result .= '<title> LON-CAPA '.$title.'</title>'
6309: .'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
6310: .$head_extra;
6311: return $result;
6312: }
6313:
6314: =pod
6315:
6316: =item * &font_settings()
6317:
6318: Returns neccessary <meta> to set the proper encoding
6319:
6320: Inputs: none
6321:
6322: =cut
6323:
6324: sub font_settings {
6325: my $headerstring='';
6326: if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
6327: $headerstring.=
6328: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
6329: }
6330: return $headerstring;
6331: }
6332:
6333: =pod
6334:
6335: =item * &xml_begin()
6336:
6337: Returns the needed doctype and <html>
6338:
6339: Inputs: none
6340:
6341: =cut
6342:
6343: sub xml_begin {
6344: my $output='';
6345:
6346: if ($env{'internal.start_page'}==1) {
6347: &Apache::lonhtmlcommon::init_htmlareafields();
6348: }
6349:
6350: if ($env{'browser.mathml'}) {
6351: $output='<?xml version="1.0"?>'
6352: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
6353: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
6354:
6355: # .'<!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">] >'
6356: .'<!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">'
6357: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
6358: .'xmlns="http://www.w3.org/1999/xhtml">';
6359: } else {
6360: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
6361: .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
6362: }
6363: return $output;
6364: }
6365:
6366: =pod
6367:
6368: =item * &endheadtag()
6369:
6370: Returns a uniform </head> for LON-CAPA web pages.
6371:
6372: Inputs: none
6373:
6374: =cut
6375:
6376: sub endheadtag {
6377: return '</head>';
6378: }
6379:
6380: =pod
6381:
6382: =item * &head()
6383:
6384: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
6385:
6386: Inputs:
6387:
6388: =over 4
6389:
6390: $title - optional title for the page
6391:
6392: $head_extra - optional extra HTML to put inside the <head>
6393:
6394: =back
6395:
6396: =cut
6397:
6398: sub head {
6399: my ($title,$head_extra,$args) = @_;
6400: return &headtag($title,$head_extra,$args).&endheadtag();
6401: }
6402:
6403: =pod
6404:
6405: =item * &start_page()
6406:
6407: Returns a complete <html> .. <body> section for LON-CAPA web pages.
6408:
6409: Inputs:
6410:
6411: =over 4
6412:
6413: $title - optional title for the page
6414:
6415: $head_extra - optional extra HTML to incude inside the <head>
6416:
6417: $args - additional optional args supported are:
6418:
6419: =over 8
6420:
6421: only_body -> is true will set &bodytag() onlybodytag
6422: arg on
6423: no_nav_bar -> is true will set &bodytag() no_nav_bar arg on
6424: add_entries -> additional attributes to add to the <body>
6425: domain -> force to color decorate a page for a
6426: specific domain
6427: function -> force usage of a specific rolish color
6428: scheme
6429: redirect -> see &headtag()
6430: bgcolor -> override the default page bg color
6431: js_ready -> return a string ready for being used in
6432: a javascript writeln
6433: html_encode -> return a string ready for being used in
6434: a html attribute
6435: force_register -> if is true will turn on the &bodytag()
6436: $forcereg arg
6437: frameset -> if true will start with a <frameset>
6438: rather than <body>
6439: skip_phases -> hash ref of
6440: head -> skip the <html><head> generation
6441: body -> skip all <body> generation
6442: no_inline_link -> if true and in remote mode, don't show the
6443: 'Switch To Inline Menu' link
6444: no_auto_mt_title -> prevent &mt()ing the title arg
6445: inherit_jsmath -> when creating popup window in a page,
6446: should it have jsmath forced on by the
6447: current page
6448: bread_crumbs -> Array containing breadcrumbs
6449: bread_crumbs_components -> if exists show it as headline else show only the breadcrumbs
6450:
6451: =back
6452:
6453: =back
6454:
6455: =cut
6456:
6457: sub start_page {
6458: my ($title,$head_extra,$args) = @_;
6459: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
6460: my %head_args;
6461: foreach my $arg ('redirect','force_register','domain','function',
6462: 'bgcolor','frameset','no_nav_bar','only_body',
6463: 'no_auto_mt_title') {
6464: if (defined($args->{$arg})) {
6465: $head_args{$arg} = $args->{$arg};
6466: }
6467: }
6468:
6469: $env{'internal.start_page'}++;
6470: my $result;
6471: if (! exists($args->{'skip_phases'}{'head'}) ) {
6472: $result.=
6473: &xml_begin().
6474: &headtag($title,$head_extra,\%head_args).&endheadtag();
6475: }
6476:
6477: if (! exists($args->{'skip_phases'}{'body'}) ) {
6478: if ($args->{'frameset'}) {
6479: my $attr_string = &make_attr_string($args->{'force_register'},
6480: $args->{'add_entries'});
6481: $result .= "\n<frameset $attr_string>\n";
6482: } else {
6483: $result .=
6484: &bodytag($title,
6485: $args->{'function'}, $args->{'add_entries'},
6486: $args->{'only_body'}, $args->{'domain'},
6487: $args->{'force_register'}, $args->{'no_nav_bar'},
6488: $args->{'bgcolor'}, $args->{'no_inline_link'},
6489: $args);
6490: }
6491: }
6492:
6493: if ($args->{'js_ready'}) {
6494: $result = &js_ready($result);
6495: }
6496: if ($args->{'html_encode'}) {
6497: $result = &html_encode($result);
6498: }
6499:
6500: # Preparation for new and consistent functionlist at top of screen
6501: # if ($args->{'functionlist'}) {
6502: # $result .= &build_functionlist();
6503: #}
6504:
6505: # Don't add anything more if only_body wanted
6506: return $result if $args->{'only_body'};
6507:
6508: #Breadcrumbs
6509: if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
6510: &Apache::lonhtmlcommon::clear_breadcrumbs();
6511: #if any br links exists, add them to the breadcrumbs
6512: if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {
6513: foreach my $crumb (@{$args->{'bread_crumbs'}}){
6514: &Apache::lonhtmlcommon::add_breadcrumb($crumb);
6515: }
6516: }
6517:
6518: #if bread_crumbs_component exists show it as headline else show only the breadcrumbs
6519: if(exists($args->{'bread_crumbs_component'})){
6520: $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
6521: }else{
6522: $result .= &Apache::lonhtmlcommon::breadcrumbs();
6523: }
6524: }
6525: return $result;
6526: }
6527:
6528:
6529: =pod
6530:
6531: =item * &head()
6532:
6533: Returns a complete </body></html> section for LON-CAPA web pages.
6534:
6535: Inputs: $args - additional optional args supported are:
6536: js_ready -> return a string ready for being used in
6537: a javascript writeln
6538: html_encode -> return a string ready for being used in
6539: a html attribute
6540: frameset -> if true will start with a <frameset>
6541: rather than <body>
6542: dicsussion -> if true will get discussion from
6543: lonxml::xmlend
6544: (you can pass the target and parser arguments
6545: through optional 'target' and 'parser' args
6546: to this routine)
6547:
6548: =cut
6549:
6550: sub end_page {
6551: my ($args) = @_;
6552: $env{'internal.end_page'}++;
6553: my $result;
6554: if ($args->{'discussion'}) {
6555: my ($target,$parser);
6556: if (ref($args->{'discussion'})) {
6557: ($target,$parser) =($args->{'discussion'}{'target'},
6558: $args->{'discussion'}{'parser'});
6559: }
6560: $result .= &Apache::lonxml::xmlend($target,$parser);
6561: }
6562:
6563: if ($args->{'frameset'}) {
6564: $result .= '</frameset>';
6565: } else {
6566: $result .= &endbodytag($args);
6567: }
6568: $result .= "\n</html>";
6569:
6570: if ($args->{'js_ready'}) {
6571: $result = &js_ready($result);
6572: }
6573:
6574: if ($args->{'html_encode'}) {
6575: $result = &html_encode($result);
6576: }
6577:
6578: return $result;
6579: }
6580:
6581: sub html_encode {
6582: my ($result) = @_;
6583:
6584: $result = &HTML::Entities::encode($result,'<>&"');
6585:
6586: return $result;
6587: }
6588: sub js_ready {
6589: my ($result) = @_;
6590:
6591: $result =~ s/[\n\r]/ /xmsg;
6592: $result =~ s/\\/\\\\/xmsg;
6593: $result =~ s/'/\\'/xmsg;
6594: $result =~ s{</}{<\\/}xmsg;
6595:
6596: return $result;
6597: }
6598:
6599: sub validate_page {
6600: if ( exists($env{'internal.start_page'})
6601: && $env{'internal.start_page'} > 1) {
6602: &Apache::lonnet::logthis('start_page called multiple times '.
6603: $env{'internal.start_page'}.' '.
6604: $ENV{'request.filename'});
6605: }
6606: if ( exists($env{'internal.end_page'})
6607: && $env{'internal.end_page'} > 1) {
6608: &Apache::lonnet::logthis('end_page called multiple times '.
6609: $env{'internal.end_page'}.' '.
6610: $env{'request.filename'});
6611: }
6612: if ( exists($env{'internal.start_page'})
6613: && ! exists($env{'internal.end_page'})) {
6614: &Apache::lonnet::logthis('start_page called without end_page '.
6615: $env{'request.filename'});
6616: }
6617: if ( ! exists($env{'internal.start_page'})
6618: && exists($env{'internal.end_page'})) {
6619: &Apache::lonnet::logthis('end_page called without start_page'.
6620: $env{'request.filename'});
6621: }
6622: }
6623:
6624: sub simple_error_page {
6625: my ($r,$title,$msg) = @_;
6626: my $page =
6627: &Apache::loncommon::start_page($title).
6628: &mt($msg).
6629: &Apache::loncommon::end_page();
6630: if (ref($r)) {
6631: $r->print($page);
6632: return;
6633: }
6634: return $page;
6635: }
6636:
6637: {
6638: my @row_count;
6639: sub start_data_table {
6640: my ($add_class) = @_;
6641: my $css_class = (join(' ','LC_data_table',$add_class));
6642: unshift(@row_count,0);
6643: return '<table class="'.$css_class.'">'."\n";
6644: }
6645:
6646: sub end_data_table {
6647: shift(@row_count);
6648: return '</table>'."\n";;
6649: }
6650:
6651: sub start_data_table_row {
6652: my ($add_class) = @_;
6653: $row_count[0]++;
6654: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
6655: $css_class = (join(' ',$css_class,$add_class));
6656: return '<tr class="'.$css_class.'">'."\n";;
6657: }
6658:
6659: sub continue_data_table_row {
6660: my ($add_class) = @_;
6661: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
6662: $css_class = (join(' ',$css_class,$add_class));
6663: return '<tr class="'.$css_class.'">'."\n";;
6664: }
6665:
6666: sub end_data_table_row {
6667: return '</tr>'."\n";;
6668: }
6669:
6670: sub start_data_table_empty_row {
6671: # $row_count[0]++;
6672: return '<tr class="LC_empty_row" >'."\n";;
6673: }
6674:
6675: sub end_data_table_empty_row {
6676: return '</tr>'."\n";;
6677: }
6678:
6679: sub start_data_table_header_row {
6680: return '<tr class="LC_header_row">'."\n";;
6681: }
6682:
6683: sub end_data_table_header_row {
6684: return '</tr>'."\n";;
6685: }
6686: }
6687:
6688: =pod
6689:
6690: =item * &inhibit_menu_check($arg)
6691:
6692: Checks for a inhibitmenu state and generates output to preserve it
6693:
6694: Inputs: $arg - can be any of
6695: - undef - in which case the return value is a string
6696: to add into arguments list of a uri
6697: - 'input' - in which case the return value is a HTML
6698: <form> <input> field of type hidden to
6699: preserve the value
6700: - a url - in which case the return value is the url with
6701: the neccesary cgi args added to preserve the
6702: inhibitmenu state
6703: - a ref to a url - no return value, but the string is
6704: updated to include the neccessary cgi
6705: args to preserve the inhibitmenu state
6706:
6707: =cut
6708:
6709: sub inhibit_menu_check {
6710: my ($arg) = @_;
6711: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
6712: if ($arg eq 'input') {
6713: if ($env{'form.inhibitmenu'}) {
6714: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
6715: } else {
6716: return
6717: }
6718: }
6719: if ($env{'form.inhibitmenu'}) {
6720: if (ref($arg)) {
6721: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
6722: } elsif ($arg eq '') {
6723: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
6724: } else {
6725: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
6726: }
6727: }
6728: if (!ref($arg)) {
6729: return $arg;
6730: }
6731: }
6732:
6733: ###############################################
6734:
6735: =pod
6736:
6737: =back
6738:
6739: =head1 User Information Routines
6740:
6741: =over 4
6742:
6743: =item * &get_users_function()
6744:
6745: Used by &bodytag to determine the current users primary role.
6746: Returns either 'student','coordinator','admin', or 'author'.
6747:
6748: =cut
6749:
6750: ###############################################
6751: sub get_users_function {
6752: my $function = 'norole';
6753: if ($env{'request.role'}=~/^(st)/) {
6754: $function='student';
6755: }
6756: if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
6757: $function='coordinator';
6758: }
6759: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
6760: $function='admin';
6761: }
6762: if (($env{'request.role'}=~/^(au|ca|aa)/) ||
6763: ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
6764: $function='author';
6765: }
6766: return $function;
6767: }
6768:
6769: ###############################################
6770:
6771: =pod
6772:
6773: =item * &show_course()
6774:
6775: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
6776: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
6777:
6778: Inputs:
6779: None
6780:
6781: Outputs:
6782: Scalar: 1 if 'Course' to be used, 0 otherwise.
6783:
6784: =cut
6785:
6786: ###############################################
6787: sub show_course {
6788: my $course = !$env{'user.adv'};
6789: if (!$env{'user.adv'}) {
6790: foreach my $env (keys(%env)) {
6791: next if ($env !~ m/^user\.priv\./);
6792: if ($env !~ m/^user\.priv\.(?:st|cm)/) {
6793: $course = 0;
6794: last;
6795: }
6796: }
6797: }
6798: return $course;
6799: }
6800:
6801: ###############################################
6802:
6803: =pod
6804:
6805: =item * &check_user_status()
6806:
6807: Determines current status of supplied role for a
6808: specific user. Roles can be active, previous or future.
6809:
6810: Inputs:
6811: user's domain, user's username, course's domain,
6812: course's number, optional section ID.
6813:
6814: Outputs:
6815: role status: active, previous or future.
6816:
6817: =cut
6818:
6819: sub check_user_status {
6820: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
6821: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
6822: my @uroles = keys %userinfo;
6823: my $srchstr;
6824: my $active_chk = 'none';
6825: my $now = time;
6826: if (@uroles > 0) {
6827: if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
6828: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
6829: } else {
6830: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
6831: }
6832: if (grep/^\Q$srchstr\E$/,@uroles) {
6833: my $role_end = 0;
6834: my $role_start = 0;
6835: $active_chk = 'active';
6836: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
6837: $role_end = $1;
6838: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
6839: $role_start = $1;
6840: }
6841: }
6842: if ($role_start > 0) {
6843: if ($now < $role_start) {
6844: $active_chk = 'future';
6845: }
6846: }
6847: if ($role_end > 0) {
6848: if ($now > $role_end) {
6849: $active_chk = 'previous';
6850: }
6851: }
6852: }
6853: }
6854: return $active_chk;
6855: }
6856:
6857: ###############################################
6858:
6859: =pod
6860:
6861: =item * &get_sections()
6862:
6863: Determines all the sections for a course including
6864: sections with students and sections containing other roles.
6865: Incoming parameters:
6866:
6867: 1. domain
6868: 2. course number
6869: 3. reference to array containing roles for which sections should
6870: be gathered (optional).
6871: 4. reference to array containing status types for which sections
6872: should be gathered (optional).
6873:
6874: If the third argument is undefined, sections are gathered for any role.
6875: If the fourth argument is undefined, sections are gathered for any status.
6876: Permissible values are 'active' or 'future' or 'previous'.
6877:
6878: Returns section hash (keys are section IDs, values are
6879: number of users in each section), subject to the
6880: optional roles filter, optional status filter
6881:
6882: =cut
6883:
6884: ###############################################
6885: sub get_sections {
6886: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
6887: if (!defined($cdom) || !defined($cnum)) {
6888: my $cid = $env{'request.course.id'};
6889:
6890: return if (!defined($cid));
6891:
6892: $cdom = $env{'course.'.$cid.'.domain'};
6893: $cnum = $env{'course.'.$cid.'.num'};
6894: }
6895:
6896: my %sectioncount;
6897: my $now = time;
6898:
6899: if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
6900: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
6901: my $sec_index = &Apache::loncoursedata::CL_SECTION();
6902: my $status_index = &Apache::loncoursedata::CL_STATUS();
6903: my $start_index = &Apache::loncoursedata::CL_START();
6904: my $end_index = &Apache::loncoursedata::CL_END();
6905: my $status;
6906: while (my ($student,$data) = each(%$classlist)) {
6907: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
6908: $data->[$status_index],
6909: $data->[$start_index],
6910: $data->[$end_index]);
6911: if ($stu_status eq 'Active') {
6912: $status = 'active';
6913: } elsif ($end < $now) {
6914: $status = 'previous';
6915: } elsif ($start > $now) {
6916: $status = 'future';
6917: }
6918: if ($section ne '-1' && $section !~ /^\s*$/) {
6919: if ((!defined($possible_status)) || (($status ne '') &&
6920: (grep/^\Q$status\E$/,@{$possible_status}))) {
6921: $sectioncount{$section}++;
6922: }
6923: }
6924: }
6925: }
6926: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
6927: foreach my $user (sort(keys(%courseroles))) {
6928: if ($user !~ /^(\w{2})/) { next; }
6929: my ($role) = ($user =~ /^(\w{2})/);
6930: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
6931: my ($section,$status);
6932: if ($role eq 'cr' &&
6933: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
6934: $section=$1;
6935: }
6936: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
6937: if (!defined($section) || $section eq '-1') { next; }
6938: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
6939: if ($end == -1 && $start == -1) {
6940: next; #deleted role
6941: }
6942: if (!defined($possible_status)) {
6943: $sectioncount{$section}++;
6944: } else {
6945: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
6946: $status = 'active';
6947: } elsif ($end < $now) {
6948: $status = 'future';
6949: } elsif ($start > $now) {
6950: $status = 'previous';
6951: }
6952: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
6953: $sectioncount{$section}++;
6954: }
6955: }
6956: }
6957: return %sectioncount;
6958: }
6959:
6960: ###############################################
6961:
6962: =pod
6963:
6964: =item * &get_course_users()
6965:
6966: Retrieves usernames:domains for users in the specified course
6967: with specific role(s), and access status.
6968:
6969: Incoming parameters:
6970: 1. course domain
6971: 2. course number
6972: 3. access status: users must have - either active,
6973: previous, future, or all.
6974: 4. reference to array of permissible roles
6975: 5. reference to array of section restrictions (optional)
6976: 6. reference to results object (hash of hashes).
6977: 7. reference to optional userdata hash
6978: 8. reference to optional statushash
6979: 9. flag if privileged users (except those set to unhide in
6980: course settings) should be excluded
6981: Keys of top level results hash are roles.
6982: Keys of inner hashes are username:domain, with
6983: values set to access type.
6984: Optional userdata hash returns an array with arguments in the
6985: same order as loncoursedata::get_classlist() for student data.
6986:
6987: Optional statushash returns
6988:
6989: Entries for end, start, section and status are blank because
6990: of the possibility of multiple values for non-student roles.
6991:
6992: =cut
6993:
6994: ###############################################
6995:
6996: sub get_course_users {
6997: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
6998: my %idx = ();
6999: my %seclists;
7000:
7001: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
7002: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
7003: $idx{end} = &Apache::loncoursedata::CL_END();
7004: $idx{start} = &Apache::loncoursedata::CL_START();
7005: $idx{id} = &Apache::loncoursedata::CL_ID();
7006: $idx{section} = &Apache::loncoursedata::CL_SECTION();
7007: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
7008: $idx{status} = &Apache::loncoursedata::CL_STATUS();
7009:
7010: if (grep(/^st$/,@{$roles})) {
7011: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
7012: my $now = time;
7013: foreach my $student (keys(%{$classlist})) {
7014: my $match = 0;
7015: my $secmatch = 0;
7016: my $section = $$classlist{$student}[$idx{section}];
7017: my $status = $$classlist{$student}[$idx{status}];
7018: if ($section eq '') {
7019: $section = 'none';
7020: }
7021: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
7022: if (grep(/^all$/,@{$sections})) {
7023: $secmatch = 1;
7024: } elsif ($$classlist{$student}[$idx{section}] eq '') {
7025: if (grep(/^none$/,@{$sections})) {
7026: $secmatch = 1;
7027: }
7028: } else {
7029: if (grep(/^\Q$section\E$/,@{$sections})) {
7030: $secmatch = 1;
7031: }
7032: }
7033: if (!$secmatch) {
7034: next;
7035: }
7036: }
7037: if (defined($$types{'active'})) {
7038: if ($$classlist{$student}[$idx{status}] eq 'Active') {
7039: push(@{$$users{st}{$student}},'active');
7040: $match = 1;
7041: }
7042: }
7043: if (defined($$types{'previous'})) {
7044: if ($$classlist{$student}[$idx{status}] eq 'Expired') {
7045: push(@{$$users{st}{$student}},'previous');
7046: $match = 1;
7047: }
7048: }
7049: if (defined($$types{'future'})) {
7050: if ($$classlist{$student}[$idx{status}] eq 'Future') {
7051: push(@{$$users{st}{$student}},'future');
7052: $match = 1;
7053: }
7054: }
7055: if ($match) {
7056: push(@{$seclists{$student}},$section);
7057: if (ref($userdata) eq 'HASH') {
7058: $$userdata{$student} = $$classlist{$student};
7059: }
7060: if (ref($statushash) eq 'HASH') {
7061: $statushash->{$student}{'st'}{$section} = $status;
7062: }
7063: }
7064: }
7065: }
7066: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
7067: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
7068: my $now = time;
7069: my %displaystatus = ( previous => 'Expired',
7070: active => 'Active',
7071: future => 'Future',
7072: );
7073: my %nothide;
7074: if ($hidepriv) {
7075: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
7076: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
7077: if ($user !~ /:/) {
7078: $nothide{join(':',split(/[\@]/,$user))}=1;
7079: } else {
7080: $nothide{$user} = 1;
7081: }
7082: }
7083: }
7084: foreach my $person (sort(keys(%coursepersonnel))) {
7085: my $match = 0;
7086: my $secmatch = 0;
7087: my $status;
7088: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
7089: $user =~ s/:$//;
7090: my ($end,$start) = split(/:/,$coursepersonnel{$person});
7091: if ($end == -1 || $start == -1) {
7092: next;
7093: }
7094: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
7095: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
7096: my ($uname,$udom) = split(/:/,$user);
7097: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
7098: if (grep(/^all$/,@{$sections})) {
7099: $secmatch = 1;
7100: } elsif ($usec eq '') {
7101: if (grep(/^none$/,@{$sections})) {
7102: $secmatch = 1;
7103: }
7104: } else {
7105: if (grep(/^\Q$usec\E$/,@{$sections})) {
7106: $secmatch = 1;
7107: }
7108: }
7109: if (!$secmatch) {
7110: next;
7111: }
7112: }
7113: if ($usec eq '') {
7114: $usec = 'none';
7115: }
7116: if ($uname ne '' && $udom ne '') {
7117: if ($hidepriv) {
7118: if ((&Apache::lonnet::privileged($uname,$udom)) &&
7119: (!$nothide{$uname.':'.$udom})) {
7120: next;
7121: }
7122: }
7123: if ($end > 0 && $end < $now) {
7124: $status = 'previous';
7125: } elsif ($start > $now) {
7126: $status = 'future';
7127: } else {
7128: $status = 'active';
7129: }
7130: foreach my $type (keys(%{$types})) {
7131: if ($status eq $type) {
7132: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
7133: push(@{$$users{$role}{$user}},$type);
7134: }
7135: $match = 1;
7136: }
7137: }
7138: if (($match) && (ref($userdata) eq 'HASH')) {
7139: if (!exists($$userdata{$uname.':'.$udom})) {
7140: &get_user_info($udom,$uname,\%idx,$userdata);
7141: }
7142: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
7143: push(@{$seclists{$uname.':'.$udom}},$usec);
7144: }
7145: if (ref($statushash) eq 'HASH') {
7146: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
7147: }
7148: }
7149: }
7150: }
7151: }
7152: if (grep(/^ow$/,@{$roles})) {
7153: if ((defined($cdom)) && (defined($cnum))) {
7154: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
7155: if ( defined($csettings{'internal.courseowner'}) ) {
7156: my $owner = $csettings{'internal.courseowner'};
7157: next if ($owner eq '');
7158: my ($ownername,$ownerdom);
7159: if ($owner =~ /^([^:]+):([^:]+)$/) {
7160: $ownername = $1;
7161: $ownerdom = $2;
7162: } else {
7163: $ownername = $owner;
7164: $ownerdom = $cdom;
7165: $owner = $ownername.':'.$ownerdom;
7166: }
7167: @{$$users{'ow'}{$owner}} = 'any';
7168: if (defined($userdata) &&
7169: !exists($$userdata{$owner})) {
7170: &get_user_info($ownerdom,$ownername,\%idx,$userdata);
7171: if (!grep(/^none$/,@{$seclists{$owner}})) {
7172: push(@{$seclists{$owner}},'none');
7173: }
7174: if (ref($statushash) eq 'HASH') {
7175: $statushash->{$owner}{'ow'}{'none'} = 'Any';
7176: }
7177: }
7178: }
7179: }
7180: }
7181: foreach my $user (keys(%seclists)) {
7182: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
7183: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
7184: }
7185: }
7186: return;
7187: }
7188:
7189: sub get_user_info {
7190: my ($udom,$uname,$idx,$userdata) = @_;
7191: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
7192: &plainname($uname,$udom,'lastname');
7193: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
7194: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
7195: my %idhash = &Apache::lonnet::idrget($udom,($uname));
7196: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname};
7197: return;
7198: }
7199:
7200: ###############################################
7201:
7202: =pod
7203:
7204: =item * &get_user_quota()
7205:
7206: Retrieves quota assigned for storage of portfolio files for a user
7207:
7208: Incoming parameters:
7209: 1. user's username
7210: 2. user's domain
7211:
7212: Returns:
7213: 1. Disk quota (in Mb) assigned to student.
7214: 2. (Optional) Type of setting: custom or default
7215: (individually assigned or default for user's
7216: institutional status).
7217: 3. (Optional) - User's institutional status (e.g., faculty, staff
7218: or student - types as defined in localenroll::inst_usertypes
7219: for user's domain, which determines default quota for user.
7220: 4. (Optional) - Default quota which would apply to the user.
7221:
7222: If a value has been stored in the user's environment,
7223: it will return that, otherwise it returns the maximal default
7224: defined for the user's instituional status(es) in the domain.
7225:
7226: =cut
7227:
7228: ###############################################
7229:
7230:
7231: sub get_user_quota {
7232: my ($uname,$udom) = @_;
7233: my ($quota,$quotatype,$settingstatus,$defquota);
7234: if (!defined($udom)) {
7235: $udom = $env{'user.domain'};
7236: }
7237: if (!defined($uname)) {
7238: $uname = $env{'user.name'};
7239: }
7240: if (($udom eq '' || $uname eq '') ||
7241: ($udom eq 'public') && ($uname eq 'public')) {
7242: $quota = 0;
7243: $quotatype = 'default';
7244: $defquota = 0;
7245: } else {
7246: my $inststatus;
7247: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
7248: $quota = $env{'environment.portfolioquota'};
7249: $inststatus = $env{'environment.inststatus'};
7250: } else {
7251: my %userenv =
7252: &Apache::lonnet::get('environment',['portfolioquota',
7253: 'inststatus'],$udom,$uname);
7254: my ($tmp) = keys(%userenv);
7255: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
7256: $quota = $userenv{'portfolioquota'};
7257: $inststatus = $userenv{'inststatus'};
7258: } else {
7259: undef(%userenv);
7260: }
7261: }
7262: ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
7263: if ($quota eq '') {
7264: $quota = $defquota;
7265: $quotatype = 'default';
7266: } else {
7267: $quotatype = 'custom';
7268: }
7269: }
7270: if (wantarray) {
7271: return ($quota,$quotatype,$settingstatus,$defquota);
7272: } else {
7273: return $quota;
7274: }
7275: }
7276:
7277: ###############################################
7278:
7279: =pod
7280:
7281: =item * &default_quota()
7282:
7283: Retrieves default quota assigned for storage of user portfolio files,
7284: given an (optional) user's institutional status.
7285:
7286: Incoming parameters:
7287: 1. domain
7288: 2. (Optional) institutional status(es). This is a : separated list of
7289: status types (e.g., faculty, staff, student etc.)
7290: which apply to the user for whom the default is being retrieved.
7291: If the institutional status string in undefined, the domain
7292: default quota will be returned.
7293:
7294: Returns:
7295: 1. Default disk quota (in Mb) for user portfolios in the domain.
7296: 2. (Optional) institutional type which determined the value of the
7297: default quota.
7298:
7299: If a value has been stored in the domain's configuration db,
7300: it will return that, otherwise it returns 20 (for backwards
7301: compatibility with domains which have not set up a configuration
7302: db file; the original statically defined portfolio quota was 20 Mb).
7303:
7304: If the user's status includes multiple types (e.g., staff and student),
7305: the largest default quota which applies to the user determines the
7306: default quota returned.
7307:
7308: =back
7309:
7310: =cut
7311:
7312: ###############################################
7313:
7314:
7315: sub default_quota {
7316: my ($udom,$inststatus) = @_;
7317: my ($defquota,$settingstatus);
7318: my %quotahash = &Apache::lonnet::get_dom('configuration',
7319: ['quotas'],$udom);
7320: if (ref($quotahash{'quotas'}) eq 'HASH') {
7321: if ($inststatus ne '') {
7322: my @statuses = map { &unescape($_); } split(/:/,$inststatus);
7323: foreach my $item (@statuses) {
7324: if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
7325: if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
7326: if ($defquota eq '') {
7327: $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
7328: $settingstatus = $item;
7329: } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
7330: $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
7331: $settingstatus = $item;
7332: }
7333: }
7334: } else {
7335: if ($quotahash{'quotas'}{$item} ne '') {
7336: if ($defquota eq '') {
7337: $defquota = $quotahash{'quotas'}{$item};
7338: $settingstatus = $item;
7339: } elsif ($quotahash{'quotas'}{$item} > $defquota) {
7340: $defquota = $quotahash{'quotas'}{$item};
7341: $settingstatus = $item;
7342: }
7343: }
7344: }
7345: }
7346: }
7347: if ($defquota eq '') {
7348: if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
7349: $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
7350: } else {
7351: $defquota = $quotahash{'quotas'}{'default'};
7352: }
7353: $settingstatus = 'default';
7354: }
7355: } else {
7356: $settingstatus = 'default';
7357: $defquota = 20;
7358: }
7359: if (wantarray) {
7360: return ($defquota,$settingstatus);
7361: } else {
7362: return $defquota;
7363: }
7364: }
7365:
7366: sub get_secgrprole_info {
7367: my ($cdom,$cnum,$needroles,$type) = @_;
7368: my %sections_count = &get_sections($cdom,$cnum);
7369: my @sections = (sort {$a <=> $b} keys(%sections_count));
7370: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
7371: my @groups = sort(keys(%curr_groups));
7372: my $allroles = [];
7373: my $rolehash;
7374: my $accesshash = {
7375: active => 'Currently has access',
7376: future => 'Will have future access',
7377: previous => 'Previously had access',
7378: };
7379: if ($needroles) {
7380: $rolehash = {'all' => 'all'};
7381: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
7382: if (&Apache::lonnet::error(%user_roles)) {
7383: undef(%user_roles);
7384: }
7385: foreach my $item (keys(%user_roles)) {
7386: my ($role)=split(/\:/,$item,2);
7387: if ($role eq 'cr') { next; }
7388: if ($role =~ /^cr/) {
7389: $$rolehash{$role} = (split('/',$role))[3];
7390: } else {
7391: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
7392: }
7393: }
7394: foreach my $key (sort(keys(%{$rolehash}))) {
7395: push(@{$allroles},$key);
7396: }
7397: push (@{$allroles},'st');
7398: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
7399: }
7400: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
7401: }
7402:
7403: sub user_picker {
7404: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
7405: my $currdom = $dom;
7406: my %curr_selected = (
7407: srchin => 'dom',
7408: srchby => 'lastname',
7409: );
7410: my $srchterm;
7411: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
7412: if ($srch->{'srchby'} ne '') {
7413: $curr_selected{'srchby'} = $srch->{'srchby'};
7414: }
7415: if ($srch->{'srchin'} ne '') {
7416: $curr_selected{'srchin'} = $srch->{'srchin'};
7417: }
7418: if ($srch->{'srchtype'} ne '') {
7419: $curr_selected{'srchtype'} = $srch->{'srchtype'};
7420: }
7421: if ($srch->{'srchdomain'} ne '') {
7422: $currdom = $srch->{'srchdomain'};
7423: }
7424: $srchterm = $srch->{'srchterm'};
7425: }
7426: my %lt=&Apache::lonlocal::texthash(
7427: 'usr' => 'Search criteria',
7428: 'doma' => 'Domain/institution to search',
7429: 'uname' => 'username',
7430: 'lastname' => 'last name',
7431: 'lastfirst' => 'last name, first name',
7432: 'crs' => 'in this course',
7433: 'dom' => 'in selected LON-CAPA domain',
7434: 'alc' => 'all LON-CAPA',
7435: 'instd' => 'in institutional directory for selected domain',
7436: 'exact' => 'is',
7437: 'contains' => 'contains',
7438: 'begins' => 'begins with',
7439: 'youm' => "You must include some text to search for.",
7440: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
7441: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
7442: 'yomc' => "You must choose a domain when using an institutional directory search.",
7443: 'ymcd' => "You must choose a domain when using a domain search.",
7444: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.",
7445: 'whse' => "When searching by last,first you must include at least one character in the first name.",
7446: 'thfo' => "The following need to be corrected before the search can be run:",
7447: );
7448: my $domform = &select_dom_form($currdom,'srchdomain',1,1);
7449: my $srchinsel = ' <select name="srchin">';
7450:
7451: my @srchins = ('crs','dom','alc','instd');
7452:
7453: foreach my $option (@srchins) {
7454: # FIXME 'alc' option unavailable until
7455: # loncreateuser::print_user_query_page()
7456: # has been completed.
7457: next if ($option eq 'alc');
7458: next if ($option eq 'crs' && !$env{'request.course.id'});
7459: if ($curr_selected{'srchin'} eq $option) {
7460: $srchinsel .= '
7461: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
7462: } else {
7463: $srchinsel .= '
7464: <option value="'.$option.'">'.$lt{$option}.'</option>';
7465: }
7466: }
7467: $srchinsel .= "\n </select>\n";
7468:
7469: my $srchbysel = ' <select name="srchby">';
7470: foreach my $option ('lastname','lastfirst','uname') {
7471: if ($curr_selected{'srchby'} eq $option) {
7472: $srchbysel .= '
7473: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
7474: } else {
7475: $srchbysel .= '
7476: <option value="'.$option.'">'.$lt{$option}.'</option>';
7477: }
7478: }
7479: $srchbysel .= "\n </select>\n";
7480:
7481: my $srchtypesel = ' <select name="srchtype">';
7482: foreach my $option ('begins','contains','exact') {
7483: if ($curr_selected{'srchtype'} eq $option) {
7484: $srchtypesel .= '
7485: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
7486: } else {
7487: $srchtypesel .= '
7488: <option value="'.$option.'">'.$lt{$option}.'</option>';
7489: }
7490: }
7491: $srchtypesel .= "\n </select>\n";
7492:
7493: my ($newuserscript,$new_user_create);
7494:
7495: if ($forcenewuser) {
7496: if (ref($srch) eq 'HASH') {
7497: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
7498: if ($cancreate) {
7499: $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>';
7500: } else {
7501: my $helplink = 'javascript:helpMenu('."'display'".')';
7502: my %usertypetext = (
7503: official => 'institutional',
7504: unofficial => 'non-institutional',
7505: );
7506: $new_user_create = '<p class="LC_warning">'
7507: .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
7508: .' '
7509: .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
7510: ,'<a href="'.$helplink.'">','</a>')
7511: .'</p><br />';
7512: }
7513: }
7514: }
7515:
7516: $newuserscript = <<"ENDSCRIPT";
7517:
7518: function setSearch(createnew,callingForm) {
7519: if (createnew == 1) {
7520: for (var i=0; i<callingForm.srchby.length; i++) {
7521: if (callingForm.srchby.options[i].value == 'uname') {
7522: callingForm.srchby.selectedIndex = i;
7523: }
7524: }
7525: for (var i=0; i<callingForm.srchin.length; i++) {
7526: if ( callingForm.srchin.options[i].value == 'dom') {
7527: callingForm.srchin.selectedIndex = i;
7528: }
7529: }
7530: for (var i=0; i<callingForm.srchtype.length; i++) {
7531: if (callingForm.srchtype.options[i].value == 'exact') {
7532: callingForm.srchtype.selectedIndex = i;
7533: }
7534: }
7535: for (var i=0; i<callingForm.srchdomain.length; i++) {
7536: if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
7537: callingForm.srchdomain.selectedIndex = i;
7538: }
7539: }
7540: }
7541: }
7542: ENDSCRIPT
7543:
7544: }
7545:
7546: my $output = <<"END_BLOCK";
7547: <script type="text/javascript">
7548: // <![CDATA[
7549: function validateEntry(callingForm) {
7550:
7551: var checkok = 1;
7552: var srchin;
7553: for (var i=0; i<callingForm.srchin.length; i++) {
7554: if ( callingForm.srchin[i].checked ) {
7555: srchin = callingForm.srchin[i].value;
7556: }
7557: }
7558:
7559: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
7560: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
7561: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
7562: var srchterm = callingForm.srchterm.value;
7563: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
7564: var msg = "";
7565:
7566: if (srchterm == "") {
7567: checkok = 0;
7568: msg += "$lt{'youm'}\\n";
7569: }
7570:
7571: if (srchtype== 'begins') {
7572: if (srchterm.length < 2) {
7573: checkok = 0;
7574: msg += "$lt{'thte'}\\n";
7575: }
7576: }
7577:
7578: if (srchtype== 'contains') {
7579: if (srchterm.length < 3) {
7580: checkok = 0;
7581: msg += "$lt{'thet'}\\n";
7582: }
7583: }
7584: if (srchin == 'instd') {
7585: if (srchdomain == '') {
7586: checkok = 0;
7587: msg += "$lt{'yomc'}\\n";
7588: }
7589: }
7590: if (srchin == 'dom') {
7591: if (srchdomain == '') {
7592: checkok = 0;
7593: msg += "$lt{'ymcd'}\\n";
7594: }
7595: }
7596: if (srchby == 'lastfirst') {
7597: if (srchterm.indexOf(",") == -1) {
7598: checkok = 0;
7599: msg += "$lt{'whus'}\\n";
7600: }
7601: if (srchterm.indexOf(",") == srchterm.length -1) {
7602: checkok = 0;
7603: msg += "$lt{'whse'}\\n";
7604: }
7605: }
7606: if (checkok == 0) {
7607: alert("$lt{'thfo'}\\n"+msg);
7608: return;
7609: }
7610: if (checkok == 1) {
7611: callingForm.submit();
7612: }
7613: }
7614:
7615: $newuserscript
7616:
7617: // ]]>
7618: </script>
7619:
7620: $new_user_create
7621:
7622: <table>
7623: <tr>
7624: <td>$lt{'doma'}:</td>
7625: <td>$domform</td>
7626: </td>
7627: </tr>
7628: <tr>
7629: <td>$lt{'usr'}:</td>
7630: <td>$srchbysel
7631: $srchtypesel
7632: <input type="text" size="15" name="srchterm" value="$srchterm" />
7633: $srchinsel
7634: </td>
7635: </tr>
7636: </table>
7637: <br />
7638: END_BLOCK
7639:
7640: return $output;
7641: }
7642:
7643: sub user_rule_check {
7644: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
7645: my $response;
7646: if (ref($usershash) eq 'HASH') {
7647: foreach my $user (keys(%{$usershash})) {
7648: my ($uname,$udom) = split(/:/,$user);
7649: next if ($udom eq '' || $uname eq '');
7650: my ($id,$newuser);
7651: if (ref($usershash->{$user}) eq 'HASH') {
7652: $newuser = $usershash->{$user}->{'newuser'};
7653: $id = $usershash->{$user}->{'id'};
7654: }
7655: my $inst_response;
7656: if (ref($checks) eq 'HASH') {
7657: if (defined($checks->{'username'})) {
7658: ($inst_response,%{$inst_results->{$user}}) =
7659: &Apache::lonnet::get_instuser($udom,$uname);
7660: } elsif (defined($checks->{'id'})) {
7661: ($inst_response,%{$inst_results->{$user}}) =
7662: &Apache::lonnet::get_instuser($udom,undef,$id);
7663: }
7664: } else {
7665: ($inst_response,%{$inst_results->{$user}}) =
7666: &Apache::lonnet::get_instuser($udom,$uname);
7667: return;
7668: }
7669: if (!$got_rules->{$udom}) {
7670: my %domconfig = &Apache::lonnet::get_dom('configuration',
7671: ['usercreation'],$udom);
7672: if (ref($domconfig{'usercreation'}) eq 'HASH') {
7673: foreach my $item ('username','id') {
7674: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
7675: $$curr_rules{$udom}{$item} =
7676: $domconfig{'usercreation'}{$item.'_rule'};
7677: }
7678: }
7679: }
7680: $got_rules->{$udom} = 1;
7681: }
7682: foreach my $item (keys(%{$checks})) {
7683: if (ref($$curr_rules{$udom}) eq 'HASH') {
7684: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
7685: if (@{$$curr_rules{$udom}{$item}} > 0) {
7686: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
7687: foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
7688: if ($rule_check{$rule}) {
7689: $$rulematch{$user}{$item} = $rule;
7690: if ($inst_response eq 'ok') {
7691: if (ref($inst_results) eq 'HASH') {
7692: if (ref($inst_results->{$user}) eq 'HASH') {
7693: if (keys(%{$inst_results->{$user}}) == 0) {
7694: $$alerts{$item}{$udom}{$uname} = 1;
7695: }
7696: }
7697: }
7698: }
7699: last;
7700: }
7701: }
7702: }
7703: }
7704: }
7705: }
7706: }
7707: }
7708: return;
7709: }
7710:
7711: sub user_rule_formats {
7712: my ($domain,$domdesc,$curr_rules,$check) = @_;
7713: my %text = (
7714: 'username' => 'Usernames',
7715: 'id' => 'IDs',
7716: );
7717: my $output;
7718: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
7719: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
7720: if (@{$ruleorder} > 0) {
7721: $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>';
7722: foreach my $rule (@{$ruleorder}) {
7723: if (ref($curr_rules) eq 'ARRAY') {
7724: if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
7725: if (ref($rules->{$rule}) eq 'HASH') {
7726: $output .= '<li>'.$rules->{$rule}{'name'}.': '.
7727: $rules->{$rule}{'desc'}.'</li>';
7728: }
7729: }
7730: }
7731: }
7732: $output .= '</ul>';
7733: }
7734: }
7735: return $output;
7736: }
7737:
7738: sub instrule_disallow_msg {
7739: my ($checkitem,$domdesc,$count,$mode) = @_;
7740: my $response;
7741: my %text = (
7742: item => 'username',
7743: items => 'usernames',
7744: match => 'matches',
7745: do => 'does',
7746: action => 'a username',
7747: one => 'one',
7748: );
7749: if ($count > 1) {
7750: $text{'item'} = 'usernames';
7751: $text{'match'} ='match';
7752: $text{'do'} = 'do';
7753: $text{'action'} = 'usernames',
7754: $text{'one'} = 'ones';
7755: }
7756: if ($checkitem eq 'id') {
7757: $text{'items'} = 'IDs';
7758: $text{'item'} = 'ID';
7759: $text{'action'} = 'an ID';
7760: if ($count > 1) {
7761: $text{'item'} = 'IDs';
7762: $text{'action'} = 'IDs';
7763: }
7764: }
7765: $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 />';
7766: if ($mode eq 'upload') {
7767: if ($checkitem eq 'username') {
7768: $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'}.");
7769: } elsif ($checkitem eq 'id') {
7770: $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.");
7771: }
7772: } elsif ($mode eq 'selfcreate') {
7773: if ($checkitem eq 'id') {
7774: $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.");
7775: }
7776: } else {
7777: if ($checkitem eq 'username') {
7778: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
7779: } elsif ($checkitem eq 'id') {
7780: $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.");
7781: }
7782: }
7783: return $response;
7784: }
7785:
7786: sub personal_data_fieldtitles {
7787: my %fieldtitles = &Apache::lonlocal::texthash (
7788: id => 'Student/Employee ID',
7789: permanentemail => 'E-mail address',
7790: lastname => 'Last Name',
7791: firstname => 'First Name',
7792: middlename => 'Middle Name',
7793: generation => 'Generation',
7794: gen => 'Generation',
7795: inststatus => 'Affiliation',
7796: );
7797: return %fieldtitles;
7798: }
7799:
7800: sub sorted_inst_types {
7801: my ($dom) = @_;
7802: my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
7803: my $othertitle = &mt('All users');
7804: if ($env{'request.course.id'}) {
7805: $othertitle = &mt('Any users');
7806: }
7807: my @types;
7808: if (ref($order) eq 'ARRAY') {
7809: @types = @{$order};
7810: }
7811: if (@types == 0) {
7812: if (ref($usertypes) eq 'HASH') {
7813: @types = sort(keys(%{$usertypes}));
7814: }
7815: }
7816: if (keys(%{$usertypes}) > 0) {
7817: $othertitle = &mt('Other users');
7818: }
7819: return ($othertitle,$usertypes,\@types);
7820: }
7821:
7822: sub get_institutional_codes {
7823: my ($settings,$allcourses,$LC_code) = @_;
7824: # Get complete list of course sections to update
7825: my @currsections = ();
7826: my @currxlists = ();
7827: my $coursecode = $$settings{'internal.coursecode'};
7828:
7829: if ($$settings{'internal.sectionnums'} ne '') {
7830: @currsections = split(/,/,$$settings{'internal.sectionnums'});
7831: }
7832:
7833: if ($$settings{'internal.crosslistings'} ne '') {
7834: @currxlists = split(/,/,$$settings{'internal.crosslistings'});
7835: }
7836:
7837: if (@currxlists > 0) {
7838: foreach (@currxlists) {
7839: if (m/^([^:]+):(\w*)$/) {
7840: unless (grep/^$1$/,@{$allcourses}) {
7841: push @{$allcourses},$1;
7842: $$LC_code{$1} = $2;
7843: }
7844: }
7845: }
7846: }
7847:
7848: if (@currsections > 0) {
7849: foreach (@currsections) {
7850: if (m/^(\w+):(\w*)$/) {
7851: my $sec = $coursecode.$1;
7852: my $lc_sec = $2;
7853: unless (grep/^$sec$/,@{$allcourses}) {
7854: push @{$allcourses},$sec;
7855: $$LC_code{$sec} = $lc_sec;
7856: }
7857: }
7858: }
7859: }
7860: return;
7861: }
7862:
7863: =pod
7864:
7865: =head1 Slot Helpers
7866:
7867: =over 4
7868:
7869: =item * sorted_slots()
7870:
7871: Sorts an array of slot names in order of slot start time (earliest first).
7872:
7873: Inputs:
7874:
7875: =over 4
7876:
7877: slotsarr - Reference to array of unsorted slot names.
7878:
7879: slots - Reference to hash of hash, where outer hash keys are slot names.
7880:
7881: =back
7882:
7883: Returns:
7884:
7885: =over 4
7886:
7887: sorted - An array of slot names sorted by the start time of the slot.
7888:
7889: =back
7890:
7891: =back
7892:
7893: =cut
7894:
7895:
7896: sub sorted_slots {
7897: my ($slotsarr,$slots) = @_;
7898: my @sorted;
7899: if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
7900: @sorted =
7901: sort {
7902: if (ref($slots->{$a}) && ref($slots->{$b})) {
7903: return $slots->{$a}{'starttime'} <=> $slots->{$b}{'starttime'}
7904: }
7905: if (ref($slots->{$a})) { return -1;}
7906: if (ref($slots->{$b})) { return 1;}
7907: return 0;
7908: } @{$slotsarr};
7909: }
7910: return @sorted;
7911: }
7912:
7913:
7914: =pod
7915:
7916: =head1 HTTP Helpers
7917:
7918: =over 4
7919:
7920: =item * &get_unprocessed_cgi($query,$possible_names)
7921:
7922: Modify the %env hash to contain unprocessed CGI form parameters held in
7923: $query. The parameters listed in $possible_names (an array reference),
7924: will be set in $env{'form.name'} if they do not already exist.
7925:
7926: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
7927: $possible_names is an ref to an array of form element names. As an example:
7928: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
7929: will result in $env{'form.uname'} and $env{'form.udom'} being set.
7930:
7931: =cut
7932:
7933: sub get_unprocessed_cgi {
7934: my ($query,$possible_names)= @_;
7935: # $Apache::lonxml::debug=1;
7936: foreach my $pair (split(/&/,$query)) {
7937: my ($name, $value) = split(/=/,$pair);
7938: $name = &unescape($name);
7939: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
7940: $value =~ tr/+/ /;
7941: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
7942: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
7943: }
7944: }
7945: }
7946:
7947: =pod
7948:
7949: =item * &cacheheader()
7950:
7951: returns cache-controlling header code
7952:
7953: =cut
7954:
7955: sub cacheheader {
7956: unless ($env{'request.method'} eq 'GET') { return ''; }
7957: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
7958: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
7959: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
7960: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
7961: return $output;
7962: }
7963:
7964: =pod
7965:
7966: =item * &no_cache($r)
7967:
7968: specifies header code to not have cache
7969:
7970: =cut
7971:
7972: sub no_cache {
7973: my ($r) = @_;
7974: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
7975: $env{'request.method'} ne 'GET') { return ''; }
7976: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
7977: $r->no_cache(1);
7978: $r->header_out("Expires" => $date);
7979: $r->header_out("Pragma" => "no-cache");
7980: }
7981:
7982: sub content_type {
7983: my ($r,$type,$charset) = @_;
7984: if ($r) {
7985: # Note that printout.pl calls this with undef for $r.
7986: &no_cache($r);
7987: }
7988: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
7989: unless ($charset) {
7990: $charset=&Apache::lonlocal::current_encoding;
7991: }
7992: if ($charset) { $type.='; charset='.$charset; }
7993: if ($r) {
7994: $r->content_type($type);
7995: } else {
7996: print("Content-type: $type\n\n");
7997: }
7998: }
7999:
8000: =pod
8001:
8002: =item * &add_to_env($name,$value)
8003:
8004: adds $name to the %env hash with value
8005: $value, if $name already exists, the entry is converted to an array
8006: reference and $value is added to the array.
8007:
8008: =cut
8009:
8010: sub add_to_env {
8011: my ($name,$value)=@_;
8012: if (defined($env{$name})) {
8013: if (ref($env{$name})) {
8014: #already have multiple values
8015: push(@{ $env{$name} },$value);
8016: } else {
8017: #first time seeing multiple values, convert hash entry to an arrayref
8018: my $first=$env{$name};
8019: undef($env{$name});
8020: push(@{ $env{$name} },$first,$value);
8021: }
8022: } else {
8023: $env{$name}=$value;
8024: }
8025: }
8026:
8027: =pod
8028:
8029: =item * &get_env_multiple($name)
8030:
8031: gets $name from the %env hash, it seemlessly handles the cases where multiple
8032: values may be defined and end up as an array ref.
8033:
8034: returns an array of values
8035:
8036: =cut
8037:
8038: sub get_env_multiple {
8039: my ($name) = @_;
8040: my @values;
8041: if (defined($env{$name})) {
8042: # exists is it an array
8043: if (ref($env{$name})) {
8044: @values=@{ $env{$name} };
8045: } else {
8046: $values[0]=$env{$name};
8047: }
8048: }
8049: return(@values);
8050: }
8051:
8052: sub ask_for_embedded_content {
8053: my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
8054: my $upload_output = '
8055: <form name="upload_embedded" action="'.$actionurl.'"
8056: method="post" enctype="multipart/form-data">';
8057: $upload_output .= $state;
8058: $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
8059:
8060: my $num = 0;
8061: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
8062: $upload_output .= &start_data_table_row().
8063: '<td>'.$embed_file.'</td><td>';
8064: if ($args->{'ignore_remote_references'}
8065: && $embed_file =~ m{^\w+://}) {
8066: $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
8067: } elsif ($args->{'error_on_invalid_names'}
8068: && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
8069:
8070: $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
8071:
8072: } else {
8073: $upload_output .='
8074: <input name="embedded_item_'.$num.'" type="file" value="" />
8075: <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
8076: my $attrib = join(':',@{$$allfiles{$embed_file}});
8077: $upload_output .=
8078: "\n\t\t".
8079: '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
8080: $attrib.'" />';
8081: if (exists($$codebase{$embed_file})) {
8082: $upload_output .=
8083: "\n\t\t".
8084: '<input name="codebase_'.$num.'" type="hidden" value="'.
8085: &escape($$codebase{$embed_file}).'" />';
8086: }
8087: }
8088: $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
8089: $num++;
8090: }
8091: $upload_output .= &Apache::loncommon::end_data_table().'<br />
8092: <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
8093: <input type ="submit" value="'.&mt('Upload Listed Files').'" />
8094: '.&mt('(only files for which a location has been provided will be uploaded)').'
8095: </form>';
8096: return $upload_output;
8097: }
8098:
8099: sub upload_embedded {
8100: my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
8101: $current_disk_usage) = @_;
8102: my $output;
8103: for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
8104: next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
8105: my $orig_uploaded_filename =
8106: $env{'form.embedded_item_'.$i.'.filename'};
8107:
8108: $env{'form.embedded_orig_'.$i} =
8109: &unescape($env{'form.embedded_orig_'.$i});
8110: my ($path,$fname) =
8111: ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
8112: # no path, whole string is fname
8113: if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
8114:
8115: $path = $env{'form.currentpath'}.$path;
8116: $fname = &Apache::lonnet::clean_filename($fname);
8117: # See if there is anything left
8118: next if ($fname eq '');
8119:
8120: # Check if file already exists as a file or directory.
8121: my ($state,$msg);
8122: if ($context eq 'portfolio') {
8123: my $port_path = $dirpath;
8124: if ($group ne '') {
8125: $port_path = "groups/$group/$port_path";
8126: }
8127: ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
8128: $dir_root,$port_path,$disk_quota,
8129: $current_disk_usage,$uname,$udom);
8130: if ($state eq 'will_exceed_quota'
8131: || $state eq 'file_locked'
8132: || $state eq 'file_exists' ) {
8133: $output .= $msg;
8134: next;
8135: }
8136: } elsif (($context eq 'author') || ($context eq 'testbank')) {
8137: ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
8138: if ($state eq 'exists') {
8139: $output .= $msg;
8140: next;
8141: }
8142: }
8143: # Check if extension is valid
8144: if (($fname =~ /\.(\w+)$/) &&
8145: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
8146: $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
8147: next;
8148: } elsif (($fname =~ /\.(\w+)$/) &&
8149: (!defined(&Apache::loncommon::fileembstyle($1)))) {
8150: $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
8151: next;
8152: } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
8153: $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
8154: next;
8155: }
8156:
8157: $env{'form.embedded_item_'.$i.'.filename'}=$fname;
8158: if ($context eq 'portfolio') {
8159: my $result=
8160: &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
8161: $dirpath.$path);
8162: if ($result !~ m|^/uploaded/|) {
8163: $output .= '<span class="LC_error">'
8164: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
8165: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
8166: .'</span><br />';
8167: next;
8168: } else {
8169: $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
8170: $path.$fname.'</span>').'</p>';
8171: }
8172: } else {
8173: # Save the file
8174: my $target = $env{'form.embedded_item_'.$i};
8175: my $fullpath = $dir_root.$dirpath.'/'.$path;
8176: my $dest = $fullpath.$fname;
8177: my $url = $url_root.$dirpath.'/'.$path.$fname;
8178: my @parts=split(/\//,$fullpath);
8179: my $count;
8180: my $filepath = $dir_root;
8181: for ($count=4;$count<=$#parts;$count++) {
8182: $filepath .= "/$parts[$count]";
8183: if ((-e $filepath)!=1) {
8184: mkdir($filepath,0770);
8185: }
8186: }
8187: my $fh;
8188: if (!open($fh,'>'.$dest)) {
8189: &Apache::lonnet::logthis('Failed to create '.$dest);
8190: $output .= '<span class="LC_error">'.
8191: &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
8192: '</span><br />';
8193: } else {
8194: if (!print $fh $env{'form.embedded_item_'.$i}) {
8195: &Apache::lonnet::logthis('Failed to write to '.$dest);
8196: $output .= '<span class="LC_error">'.
8197: &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
8198: '</span><br />';
8199: } else {
8200: if ($context eq 'testbank') {
8201: $output .= &mt('Embedded file uploaded successfully:').
8202: ' <a href="'.$url.'">'.
8203: $orig_uploaded_filename.'</a><br />';
8204: } else {
8205: $output .= '<span class=\"LC_fontsize_large\">'.
8206: &mt('View embedded file: [_1]','<a href="'.$url.'">'.
8207: $orig_uploaded_filename.'</a>').'</span><br />';
8208: }
8209: }
8210: close($fh);
8211: }
8212: }
8213: }
8214: return $output;
8215: }
8216:
8217: sub check_for_existing {
8218: my ($path,$fname,$element) = @_;
8219: my ($state,$msg);
8220: if (-d $path.'/'.$fname) {
8221: $state = 'exists';
8222: $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
8223: } elsif (-e $path.'/'.$fname) {
8224: $state = 'exists';
8225: $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
8226: }
8227: if ($state eq 'exists') {
8228: $msg = '<span class="LC_error">'.$msg.'</span><br />';
8229: }
8230: return ($state,$msg);
8231: }
8232:
8233: sub check_for_upload {
8234: my ($path,$fname,$group,$element,$portfolio_root,$port_path,
8235: $disk_quota,$current_disk_usage,$uname,$udom) = @_;
8236: my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
8237: my $getpropath = 1;
8238: my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
8239: $getpropath);
8240: my $found_file = 0;
8241: my $locked_file = 0;
8242: foreach my $line (@dir_list) {
8243: my ($file_name)=split(/\&/,$line,2);
8244: if ($file_name eq $fname){
8245: $file_name = $path.$file_name;
8246: if ($group ne '') {
8247: $file_name = $group.$file_name;
8248: }
8249: $found_file = 1;
8250: if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
8251: $locked_file = 1;
8252: }
8253: }
8254: }
8255: if (($current_disk_usage + $filesize) > $disk_quota){
8256: my $msg = '<span class="LC_error">'.
8257: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
8258: '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
8259: return ('will_exceed_quota',$msg);
8260: } elsif ($found_file) {
8261: if ($locked_file) {
8262: my $msg = '<span class="LC_error">';
8263: $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>');
8264: $msg .= '</span><br />';
8265: $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
8266: return ('file_locked',$msg);
8267: } else {
8268: my $msg = '<span class="LC_error">';
8269: $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'});
8270: $msg .= '</span>';
8271: $msg .= '<br />';
8272: $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
8273: return ('file_exists',$msg);
8274: }
8275: }
8276: }
8277:
8278:
8279: =pod
8280:
8281: =back
8282:
8283: =head1 CSV Upload/Handling functions
8284:
8285: =over 4
8286:
8287: =item * &upfile_store($r)
8288:
8289: Store uploaded file, $r should be the HTTP Request object,
8290: needs $env{'form.upfile'}
8291: returns $datatoken to be put into hidden field
8292:
8293: =cut
8294:
8295: sub upfile_store {
8296: my $r=shift;
8297: $env{'form.upfile'}=~s/\r/\n/gs;
8298: $env{'form.upfile'}=~s/\f/\n/gs;
8299: $env{'form.upfile'}=~s/\n+/\n/gs;
8300: $env{'form.upfile'}=~s/\n+$//gs;
8301:
8302: my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
8303: '_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
8304: {
8305: my $datafile = $r->dir_config('lonDaemons').
8306: '/tmp/'.$datatoken.'.tmp';
8307: if ( open(my $fh,">$datafile") ) {
8308: print $fh $env{'form.upfile'};
8309: close($fh);
8310: }
8311: }
8312: return $datatoken;
8313: }
8314:
8315: =pod
8316:
8317: =item * &load_tmp_file($r)
8318:
8319: Load uploaded file from tmp, $r should be the HTTP Request object,
8320: needs $env{'form.datatoken'},
8321: sets $env{'form.upfile'} to the contents of the file
8322:
8323: =cut
8324:
8325: sub load_tmp_file {
8326: my $r=shift;
8327: my @studentdata=();
8328: {
8329: my $studentfile = $r->dir_config('lonDaemons').
8330: '/tmp/'.$env{'form.datatoken'}.'.tmp';
8331: if ( open(my $fh,"<$studentfile") ) {
8332: @studentdata=<$fh>;
8333: close($fh);
8334: }
8335: }
8336: $env{'form.upfile'}=join('',@studentdata);
8337: }
8338:
8339: =pod
8340:
8341: =item * &upfile_record_sep()
8342:
8343: Separate uploaded file into records
8344: returns array of records,
8345: needs $env{'form.upfile'} and $env{'form.upfiletype'}
8346:
8347: =cut
8348:
8349: sub upfile_record_sep {
8350: if ($env{'form.upfiletype'} eq 'xml') {
8351: } else {
8352: my @records;
8353: foreach my $line (split(/\n/,$env{'form.upfile'})) {
8354: if ($line=~/^\s*$/) { next; }
8355: push(@records,$line);
8356: }
8357: return @records;
8358: }
8359: }
8360:
8361: =pod
8362:
8363: =item * &record_sep($record)
8364:
8365: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
8366:
8367: =cut
8368:
8369: sub takeleft {
8370: my $index=shift;
8371: return substr('0000'.$index,-4,4);
8372: }
8373:
8374: sub record_sep {
8375: my $record=shift;
8376: my %components=();
8377: if ($env{'form.upfiletype'} eq 'xml') {
8378: } elsif ($env{'form.upfiletype'} eq 'space') {
8379: my $i=0;
8380: foreach my $field (split(/\s+/,$record)) {
8381: $field=~s/^(\"|\')//;
8382: $field=~s/(\"|\')$//;
8383: $components{&takeleft($i)}=$field;
8384: $i++;
8385: }
8386: } elsif ($env{'form.upfiletype'} eq 'tab') {
8387: my $i=0;
8388: foreach my $field (split(/\t/,$record)) {
8389: $field=~s/^(\"|\')//;
8390: $field=~s/(\"|\')$//;
8391: $components{&takeleft($i)}=$field;
8392: $i++;
8393: }
8394: } else {
8395: my $separator=',';
8396: if ($env{'form.upfiletype'} eq 'semisv') {
8397: $separator=';';
8398: }
8399: my $i=0;
8400: # the character we are looking for to indicate the end of a quote or a record
8401: my $looking_for=$separator;
8402: # do not add the characters to the fields
8403: my $ignore=0;
8404: # we just encountered a separator (or the beginning of the record)
8405: my $just_found_separator=1;
8406: # store the field we are working on here
8407: my $field='';
8408: # work our way through all characters in record
8409: foreach my $character ($record=~/(.)/g) {
8410: if ($character eq $looking_for) {
8411: if ($character ne $separator) {
8412: # Found the end of a quote, again looking for separator
8413: $looking_for=$separator;
8414: $ignore=1;
8415: } else {
8416: # Found a separator, store away what we got
8417: $components{&takeleft($i)}=$field;
8418: $i++;
8419: $just_found_separator=1;
8420: $ignore=0;
8421: $field='';
8422: }
8423: next;
8424: }
8425: # single or double quotation marks after a separator indicate beginning of a quote
8426: # we are now looking for the end of the quote and need to ignore separators
8427: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) {
8428: $looking_for=$character;
8429: next;
8430: }
8431: # ignore would be true after we reached the end of a quote
8432: if ($ignore) { next; }
8433: if (($just_found_separator) && ($character=~/\s/)) { next; }
8434: $field.=$character;
8435: $just_found_separator=0;
8436: }
8437: # catch the very last entry, since we never encountered the separator
8438: $components{&takeleft($i)}=$field;
8439: }
8440: return %components;
8441: }
8442:
8443: ######################################################
8444: ######################################################
8445:
8446: =pod
8447:
8448: =item * &upfile_select_html()
8449:
8450: Return HTML code to select a file from the users machine and specify
8451: the file type.
8452:
8453: =cut
8454:
8455: ######################################################
8456: ######################################################
8457: sub upfile_select_html {
8458: my %Types = (
8459: csv => &mt('CSV (comma separated values, spreadsheet)'),
8460: semisv => &mt('Semicolon separated values'),
8461: space => &mt('Space separated'),
8462: tab => &mt('Tabulator separated'),
8463: # xml => &mt('HTML/XML'),
8464: );
8465: my $Str = '<input type="file" name="upfile" size="50" />'.
8466: '<br />'.&mt('Type').': <select name="upfiletype">';
8467: foreach my $type (sort(keys(%Types))) {
8468: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
8469: }
8470: $Str .= "</select>\n";
8471: return $Str;
8472: }
8473:
8474: sub get_samples {
8475: my ($records,$toget) = @_;
8476: my @samples=({});
8477: my $got=0;
8478: foreach my $rec (@$records) {
8479: my %temp = &record_sep($rec);
8480: if (! grep(/\S/, values(%temp))) { next; }
8481: if (%temp) {
8482: $samples[$got]=\%temp;
8483: $got++;
8484: if ($got == $toget) { last; }
8485: }
8486: }
8487: return \@samples;
8488: }
8489:
8490: ######################################################
8491: ######################################################
8492:
8493: =pod
8494:
8495: =item * &csv_print_samples($r,$records)
8496:
8497: Prints a table of sample values from each column uploaded $r is an
8498: Apache Request ref, $records is an arrayref from
8499: &Apache::loncommon::upfile_record_sep
8500:
8501: =cut
8502:
8503: ######################################################
8504: ######################################################
8505: sub csv_print_samples {
8506: my ($r,$records) = @_;
8507: my $samples = &get_samples($records,5);
8508:
8509: $r->print(&mt('Samples').'<br />'.&start_data_table().
8510: &start_data_table_header_row());
8511: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
8512: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
8513: $r->print(&end_data_table_header_row());
8514: foreach my $hash (@$samples) {
8515: $r->print(&start_data_table_row());
8516: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
8517: $r->print('<td>');
8518: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
8519: $r->print('</td>');
8520: }
8521: $r->print(&end_data_table_row());
8522: }
8523: $r->print(&end_data_table().'<br />'."\n");
8524: }
8525:
8526: ######################################################
8527: ######################################################
8528:
8529: =pod
8530:
8531: =item * &csv_print_select_table($r,$records,$d)
8532:
8533: Prints a table to create associations between values and table columns.
8534:
8535: $r is an Apache Request ref,
8536: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
8537: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
8538:
8539: =cut
8540:
8541: ######################################################
8542: ######################################################
8543: sub csv_print_select_table {
8544: my ($r,$records,$d) = @_;
8545: my $i=0;
8546: my $samples = &get_samples($records,1);
8547: $r->print(&mt('Associate columns with student attributes.')."\n".
8548: &start_data_table().&start_data_table_header_row().
8549: '<th>'.&mt('Attribute').'</th>'.
8550: '<th>'.&mt('Column').'</th>'.
8551: &end_data_table_header_row()."\n");
8552: foreach my $array_ref (@$d) {
8553: my ($value,$display,$defaultcol)=@{ $array_ref };
8554: $r->print(&start_data_table_row().'<td>'.$display.'</td>');
8555:
8556: $r->print('<td><select name="f'.$i.'"'.
8557: ' onchange="javascript:flip(this.form,'.$i.');">');
8558: $r->print('<option value="none"></option>');
8559: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
8560: $r->print('<option value="'.$sample.'"'.
8561: ($sample eq $defaultcol ? ' selected="selected" ' : '').
8562: '>'.&mt('Column [_1]',($sample+1)).'</option>');
8563: }
8564: $r->print('</select></td>'.&end_data_table_row()."\n");
8565: $i++;
8566: }
8567: $r->print(&end_data_table());
8568: $i--;
8569: return $i;
8570: }
8571:
8572: ######################################################
8573: ######################################################
8574:
8575: =pod
8576:
8577: =item * &csv_samples_select_table($r,$records,$d)
8578:
8579: Prints a table of sample values from the upload and can make associate samples to internal names.
8580:
8581: $r is an Apache Request ref,
8582: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
8583: $d is an array of 2 element arrays (internal name, displayed name)
8584:
8585: =cut
8586:
8587: ######################################################
8588: ######################################################
8589: sub csv_samples_select_table {
8590: my ($r,$records,$d) = @_;
8591: my $i=0;
8592: #
8593: my $max_samples = 5;
8594: my $samples = &get_samples($records,$max_samples);
8595: $r->print(&start_data_table().
8596: &start_data_table_header_row().'<th>'.
8597: &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
8598: &end_data_table_header_row());
8599:
8600: foreach my $key (sort(keys(%{ $samples->[0] }))) {
8601: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
8602: ' onchange="javascript:flip(this.form,'.$i.');">');
8603: foreach my $option (@$d) {
8604: my ($value,$display,$defaultcol)=@{ $option };
8605: $r->print('<option value="'.$value.'"'.
8606: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
8607: $display.'</option>');
8608: }
8609: $r->print('</select></td><td>');
8610: foreach my $line (0..($max_samples-1)) {
8611: if (defined($samples->[$line]{$key})) {
8612: $r->print($samples->[$line]{$key}."<br />\n");
8613: }
8614: }
8615: $r->print('</td>'.&end_data_table_row());
8616: $i++;
8617: }
8618: $r->print(&end_data_table());
8619: $i--;
8620: return($i);
8621: }
8622:
8623: ######################################################
8624: ######################################################
8625:
8626: =pod
8627:
8628: =item * &clean_excel_name($name)
8629:
8630: Returns a replacement for $name which does not contain any illegal characters.
8631:
8632: =cut
8633:
8634: ######################################################
8635: ######################################################
8636: sub clean_excel_name {
8637: my ($name) = @_;
8638: $name =~ s/[:\*\?\/\\]//g;
8639: if (length($name) > 31) {
8640: $name = substr($name,0,31);
8641: }
8642: return $name;
8643: }
8644:
8645: =pod
8646:
8647: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
8648:
8649: Returns either 1 or undef
8650:
8651: 1 if the part is to be hidden, undef if it is to be shown
8652:
8653: Arguments are:
8654:
8655: $id the id of the part to be checked
8656: $symb, optional the symb of the resource to check
8657: $udom, optional the domain of the user to check for
8658: $uname, optional the username of the user to check for
8659:
8660: =cut
8661:
8662: sub check_if_partid_hidden {
8663: my ($id,$symb,$udom,$uname) = @_;
8664: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
8665: $symb,$udom,$uname);
8666: my $truth=1;
8667: #if the string starts with !, then the list is the list to show not hide
8668: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
8669: my @hiddenlist=split(/,/,$hiddenparts);
8670: foreach my $checkid (@hiddenlist) {
8671: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
8672: }
8673: return !$truth;
8674: }
8675:
8676:
8677: ############################################################
8678: ############################################################
8679:
8680: =pod
8681:
8682: =back
8683:
8684: =head1 cgi-bin script and graphing routines
8685:
8686: =over 4
8687:
8688: =item * &get_cgi_id()
8689:
8690: Inputs: none
8691:
8692: Returns an id which can be used to pass environment variables
8693: to various cgi-bin scripts. These environment variables will
8694: be removed from the users environment after a given time by
8695: the routine &Apache::lonnet::transfer_profile_to_env.
8696:
8697: =cut
8698:
8699: ############################################################
8700: ############################################################
8701: my $uniq=0;
8702: sub get_cgi_id {
8703: $uniq=($uniq+1)%100000;
8704: return (time.'_'.$$.'_'.$uniq);
8705: }
8706:
8707: ############################################################
8708: ############################################################
8709:
8710: =pod
8711:
8712: =item * &DrawBarGraph()
8713:
8714: Facilitates the plotting of data in a (stacked) bar graph.
8715: Puts plot definition data into the users environment in order for
8716: graph.png to plot it. Returns an <img> tag for the plot.
8717: The bars on the plot are labeled '1','2',...,'n'.
8718:
8719: Inputs:
8720:
8721: =over 4
8722:
8723: =item $Title: string, the title of the plot
8724:
8725: =item $xlabel: string, text describing the X-axis of the plot
8726:
8727: =item $ylabel: string, text describing the Y-axis of the plot
8728:
8729: =item $Max: scalar, the maximum Y value to use in the plot
8730: If $Max is < any data point, the graph will not be rendered.
8731:
8732: =item $colors: array ref holding the colors to be used for the data sets when
8733: they are plotted. If undefined, default values will be used.
8734:
8735: =item $labels: array ref holding the labels to use on the x-axis for the bars.
8736:
8737: =item @Values: An array of array references. Each array reference holds data
8738: to be plotted in a stacked bar chart.
8739:
8740: =item If the final element of @Values is a hash reference the key/value
8741: pairs will be added to the graph definition.
8742:
8743: =back
8744:
8745: Returns:
8746:
8747: An <img> tag which references graph.png and the appropriate identifying
8748: information for the plot.
8749:
8750: =cut
8751:
8752: ############################################################
8753: ############################################################
8754: sub DrawBarGraph {
8755: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
8756: #
8757: if (! defined($colors)) {
8758: $colors = ['#33ff00',
8759: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
8760: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
8761: ];
8762: }
8763: my $extra_settings = {};
8764: if (ref($Values[-1]) eq 'HASH') {
8765: $extra_settings = pop(@Values);
8766: }
8767: #
8768: my $identifier = &get_cgi_id();
8769: my $id = 'cgi.'.$identifier;
8770: if (! @Values || ref($Values[0]) ne 'ARRAY') {
8771: return '';
8772: }
8773: #
8774: my @Labels;
8775: if (defined($labels)) {
8776: @Labels = @$labels;
8777: } else {
8778: for (my $i=0;$i<@{$Values[0]};$i++) {
8779: push (@Labels,$i+1);
8780: }
8781: }
8782: #
8783: my $NumBars = scalar(@{$Values[0]});
8784: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
8785: my %ValuesHash;
8786: my $NumSets=1;
8787: foreach my $array (@Values) {
8788: next if (! ref($array));
8789: $ValuesHash{$id.'.data.'.$NumSets++} =
8790: join(',',@$array);
8791: }
8792: #
8793: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
8794: if ($NumBars < 3) {
8795: $width = 120+$NumBars*32;
8796: $xskip = 1;
8797: $bar_width = 30;
8798: } elsif ($NumBars < 5) {
8799: $width = 120+$NumBars*20;
8800: $xskip = 1;
8801: $bar_width = 20;
8802: } elsif ($NumBars < 10) {
8803: $width = 120+$NumBars*15;
8804: $xskip = 1;
8805: $bar_width = 15;
8806: } elsif ($NumBars <= 25) {
8807: $width = 120+$NumBars*11;
8808: $xskip = 5;
8809: $bar_width = 8;
8810: } elsif ($NumBars <= 50) {
8811: $width = 120+$NumBars*8;
8812: $xskip = 5;
8813: $bar_width = 4;
8814: } else {
8815: $width = 120+$NumBars*8;
8816: $xskip = 5;
8817: $bar_width = 4;
8818: }
8819: #
8820: $Max = 1 if ($Max < 1);
8821: if ( int($Max) < $Max ) {
8822: $Max++;
8823: $Max = int($Max);
8824: }
8825: $Title = '' if (! defined($Title));
8826: $xlabel = '' if (! defined($xlabel));
8827: $ylabel = '' if (! defined($ylabel));
8828: $ValuesHash{$id.'.title'} = &escape($Title);
8829: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
8830: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
8831: $ValuesHash{$id.'.y_max_value'} = $Max;
8832: $ValuesHash{$id.'.NumBars'} = $NumBars;
8833: $ValuesHash{$id.'.NumSets'} = $NumSets;
8834: $ValuesHash{$id.'.PlotType'} = 'bar';
8835: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
8836: $ValuesHash{$id.'.height'} = $height;
8837: $ValuesHash{$id.'.width'} = $width;
8838: $ValuesHash{$id.'.xskip'} = $xskip;
8839: $ValuesHash{$id.'.bar_width'} = $bar_width;
8840: $ValuesHash{$id.'.labels'} = join(',',@Labels);
8841: #
8842: # Deal with other parameters
8843: while (my ($key,$value) = each(%$extra_settings)) {
8844: $ValuesHash{$id.'.'.$key} = $value;
8845: }
8846: #
8847: &Apache::lonnet::appenv(\%ValuesHash);
8848: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
8849: }
8850:
8851: ############################################################
8852: ############################################################
8853:
8854: =pod
8855:
8856: =item * &DrawXYGraph()
8857:
8858: Facilitates the plotting of data in an XY graph.
8859: Puts plot definition data into the users environment in order for
8860: graph.png to plot it. Returns an <img> tag for the plot.
8861:
8862: Inputs:
8863:
8864: =over 4
8865:
8866: =item $Title: string, the title of the plot
8867:
8868: =item $xlabel: string, text describing the X-axis of the plot
8869:
8870: =item $ylabel: string, text describing the Y-axis of the plot
8871:
8872: =item $Max: scalar, the maximum Y value to use in the plot
8873: If $Max is < any data point, the graph will not be rendered.
8874:
8875: =item $colors: Array ref containing the hex color codes for the data to be
8876: plotted in. If undefined, default values will be used.
8877:
8878: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
8879:
8880: =item $Ydata: Array ref containing Array refs.
8881: Each of the contained arrays will be plotted as a separate curve.
8882:
8883: =item %Values: hash indicating or overriding any default values which are
8884: passed to graph.png.
8885: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
8886:
8887: =back
8888:
8889: Returns:
8890:
8891: An <img> tag which references graph.png and the appropriate identifying
8892: information for the plot.
8893:
8894: =cut
8895:
8896: ############################################################
8897: ############################################################
8898: sub DrawXYGraph {
8899: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
8900: #
8901: # Create the identifier for the graph
8902: my $identifier = &get_cgi_id();
8903: my $id = 'cgi.'.$identifier;
8904: #
8905: $Title = '' if (! defined($Title));
8906: $xlabel = '' if (! defined($xlabel));
8907: $ylabel = '' if (! defined($ylabel));
8908: my %ValuesHash =
8909: (
8910: $id.'.title' => &escape($Title),
8911: $id.'.xlabel' => &escape($xlabel),
8912: $id.'.ylabel' => &escape($ylabel),
8913: $id.'.y_max_value'=> $Max,
8914: $id.'.labels' => join(',',@$Xlabels),
8915: $id.'.PlotType' => 'XY',
8916: );
8917: #
8918: if (defined($colors) && ref($colors) eq 'ARRAY') {
8919: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
8920: }
8921: #
8922: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
8923: return '';
8924: }
8925: my $NumSets=1;
8926: foreach my $array (@{$Ydata}){
8927: next if (! ref($array));
8928: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
8929: }
8930: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
8931: #
8932: # Deal with other parameters
8933: while (my ($key,$value) = each(%Values)) {
8934: $ValuesHash{$id.'.'.$key} = $value;
8935: }
8936: #
8937: &Apache::lonnet::appenv(\%ValuesHash);
8938: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
8939: }
8940:
8941: ############################################################
8942: ############################################################
8943:
8944: =pod
8945:
8946: =item * &DrawXYYGraph()
8947:
8948: Facilitates the plotting of data in an XY graph with two Y axes.
8949: Puts plot definition data into the users environment in order for
8950: graph.png to plot it. Returns an <img> tag for the plot.
8951:
8952: Inputs:
8953:
8954: =over 4
8955:
8956: =item $Title: string, the title of the plot
8957:
8958: =item $xlabel: string, text describing the X-axis of the plot
8959:
8960: =item $ylabel: string, text describing the Y-axis of the plot
8961:
8962: =item $colors: Array ref containing the hex color codes for the data to be
8963: plotted in. If undefined, default values will be used.
8964:
8965: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
8966:
8967: =item $Ydata1: The first data set
8968:
8969: =item $Min1: The minimum value of the left Y-axis
8970:
8971: =item $Max1: The maximum value of the left Y-axis
8972:
8973: =item $Ydata2: The second data set
8974:
8975: =item $Min2: The minimum value of the right Y-axis
8976:
8977: =item $Max2: The maximum value of the left Y-axis
8978:
8979: =item %Values: hash indicating or overriding any default values which are
8980: passed to graph.png.
8981: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
8982:
8983: =back
8984:
8985: Returns:
8986:
8987: An <img> tag which references graph.png and the appropriate identifying
8988: information for the plot.
8989:
8990: =cut
8991:
8992: ############################################################
8993: ############################################################
8994: sub DrawXYYGraph {
8995: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
8996: $Ydata2,$Min2,$Max2,%Values)=@_;
8997: #
8998: # Create the identifier for the graph
8999: my $identifier = &get_cgi_id();
9000: my $id = 'cgi.'.$identifier;
9001: #
9002: $Title = '' if (! defined($Title));
9003: $xlabel = '' if (! defined($xlabel));
9004: $ylabel = '' if (! defined($ylabel));
9005: my %ValuesHash =
9006: (
9007: $id.'.title' => &escape($Title),
9008: $id.'.xlabel' => &escape($xlabel),
9009: $id.'.ylabel' => &escape($ylabel),
9010: $id.'.labels' => join(',',@$Xlabels),
9011: $id.'.PlotType' => 'XY',
9012: $id.'.NumSets' => 2,
9013: $id.'.two_axes' => 1,
9014: $id.'.y1_max_value' => $Max1,
9015: $id.'.y1_min_value' => $Min1,
9016: $id.'.y2_max_value' => $Max2,
9017: $id.'.y2_min_value' => $Min2,
9018: );
9019: #
9020: if (defined($colors) && ref($colors) eq 'ARRAY') {
9021: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
9022: }
9023: #
9024: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
9025: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
9026: return '';
9027: }
9028: my $NumSets=1;
9029: foreach my $array ($Ydata1,$Ydata2){
9030: next if (! ref($array));
9031: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
9032: }
9033: #
9034: # Deal with other parameters
9035: while (my ($key,$value) = each(%Values)) {
9036: $ValuesHash{$id.'.'.$key} = $value;
9037: }
9038: #
9039: &Apache::lonnet::appenv(\%ValuesHash);
9040: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
9041: }
9042:
9043: ############################################################
9044: ############################################################
9045:
9046: =pod
9047:
9048: =back
9049:
9050: =head1 Statistics helper routines?
9051:
9052: Bad place for them but what the hell.
9053:
9054: =over 4
9055:
9056: =item * &chartlink()
9057:
9058: Returns a link to the chart for a specific student.
9059:
9060: Inputs:
9061:
9062: =over 4
9063:
9064: =item $linktext: The text of the link
9065:
9066: =item $sname: The students username
9067:
9068: =item $sdomain: The students domain
9069:
9070: =back
9071:
9072: =back
9073:
9074: =cut
9075:
9076: ############################################################
9077: ############################################################
9078: sub chartlink {
9079: my ($linktext, $sname, $sdomain) = @_;
9080: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
9081: '&SelectedStudent='.&escape($sname.':'.$sdomain).
9082: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
9083: '">'.$linktext.'</a>';
9084: }
9085:
9086: #######################################################
9087: #######################################################
9088:
9089: =pod
9090:
9091: =head1 Course Environment Routines
9092:
9093: =over 4
9094:
9095: =item * &restore_course_settings()
9096:
9097: =item * &store_course_settings()
9098:
9099: Restores/Store indicated form parameters from the course environment.
9100: Will not overwrite existing values of the form parameters.
9101:
9102: Inputs:
9103: a scalar describing the data (e.g. 'chart', 'problem_analysis')
9104:
9105: a hash ref describing the data to be stored. For example:
9106:
9107: %Save_Parameters = ('Status' => 'scalar',
9108: 'chartoutputmode' => 'scalar',
9109: 'chartoutputdata' => 'scalar',
9110: 'Section' => 'array',
9111: 'Group' => 'array',
9112: 'StudentData' => 'array',
9113: 'Maps' => 'array');
9114:
9115: Returns: both routines return nothing
9116:
9117: =back
9118:
9119: =cut
9120:
9121: #######################################################
9122: #######################################################
9123: sub store_course_settings {
9124: return &store_settings($env{'request.course.id'},@_);
9125: }
9126:
9127: sub store_settings {
9128: # save to the environment
9129: # appenv the same items, just to be safe
9130: my $udom = $env{'user.domain'};
9131: my $uname = $env{'user.name'};
9132: my ($context,$prefix,$Settings) = @_;
9133: my %SaveHash;
9134: my %AppHash;
9135: while (my ($setting,$type) = each(%$Settings)) {
9136: my $basename = join('.','internal',$context,$prefix,$setting);
9137: my $envname = 'environment.'.$basename;
9138: if (exists($env{'form.'.$setting})) {
9139: # Save this value away
9140: if ($type eq 'scalar' &&
9141: (! exists($env{$envname}) ||
9142: $env{$envname} ne $env{'form.'.$setting})) {
9143: $SaveHash{$basename} = $env{'form.'.$setting};
9144: $AppHash{$envname} = $env{'form.'.$setting};
9145: } elsif ($type eq 'array') {
9146: my $stored_form;
9147: if (ref($env{'form.'.$setting})) {
9148: $stored_form = join(',',
9149: map {
9150: &escape($_);
9151: } sort(@{$env{'form.'.$setting}}));
9152: } else {
9153: $stored_form =
9154: &escape($env{'form.'.$setting});
9155: }
9156: # Determine if the array contents are the same.
9157: if ($stored_form ne $env{$envname}) {
9158: $SaveHash{$basename} = $stored_form;
9159: $AppHash{$envname} = $stored_form;
9160: }
9161: }
9162: }
9163: }
9164: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
9165: $udom,$uname);
9166: if ($put_result !~ /^(ok|delayed)/) {
9167: &Apache::lonnet::logthis('unable to save form parameters, '.
9168: 'got error:'.$put_result);
9169: }
9170: # Make sure these settings stick around in this session, too
9171: &Apache::lonnet::appenv(\%AppHash);
9172: return;
9173: }
9174:
9175: sub restore_course_settings {
9176: return &restore_settings($env{'request.course.id'},@_);
9177: }
9178:
9179: sub restore_settings {
9180: my ($context,$prefix,$Settings) = @_;
9181: while (my ($setting,$type) = each(%$Settings)) {
9182: next if (exists($env{'form.'.$setting}));
9183: my $envname = 'environment.internal.'.$context.'.'.$prefix.
9184: '.'.$setting;
9185: if (exists($env{$envname})) {
9186: if ($type eq 'scalar') {
9187: $env{'form.'.$setting} = $env{$envname};
9188: } elsif ($type eq 'array') {
9189: $env{'form.'.$setting} = [
9190: map {
9191: &unescape($_);
9192: } split(',',$env{$envname})
9193: ];
9194: }
9195: }
9196: }
9197: }
9198:
9199: #######################################################
9200: #######################################################
9201:
9202: =pod
9203:
9204: =head1 Domain E-mail Routines
9205:
9206: =over 4
9207:
9208: =item * &build_recipient_list()
9209:
9210: Build recipient lists for four types of e-mail:
9211: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
9212: (d) Help requests, generated by
9213: lonerrorhandler.pm, CHECKRPMS, loncron, and lonsupportreq.pm respectively.
9214:
9215: Inputs:
9216: defmail (scalar - email address of default recipient),
9217: mailing type (scalar - errormail, packagesmail, or helpdeskmail),
9218: defdom (domain for which to retrieve configuration settings),
9219: origmail (scalar - email address of recipient from loncapa.conf,
9220: i.e., predates configuration by DC via domainprefs.pm
9221:
9222: Returns: comma separated list of addresses to which to send e-mail.
9223:
9224: =back
9225:
9226: =cut
9227:
9228: ############################################################
9229: ############################################################
9230: sub build_recipient_list {
9231: my ($defmail,$mailing,$defdom,$origmail) = @_;
9232: my @recipients;
9233: my $otheremails;
9234: my %domconfig =
9235: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
9236: if (ref($domconfig{'contacts'}) eq 'HASH') {
9237: if (exists($domconfig{'contacts'}{$mailing})) {
9238: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
9239: my @contacts = ('adminemail','supportemail');
9240: foreach my $item (@contacts) {
9241: if ($domconfig{'contacts'}{$mailing}{$item}) {
9242: my $addr = $domconfig{'contacts'}{$item};
9243: if (!grep(/^\Q$addr\E$/,@recipients)) {
9244: push(@recipients,$addr);
9245: }
9246: }
9247: $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
9248: }
9249: }
9250: } elsif ($origmail ne '') {
9251: push(@recipients,$origmail);
9252: }
9253: } elsif ($origmail ne '') {
9254: push(@recipients,$origmail);
9255: }
9256: if (defined($defmail)) {
9257: if ($defmail ne '') {
9258: push(@recipients,$defmail);
9259: }
9260: }
9261: if ($otheremails) {
9262: my @others;
9263: if ($otheremails =~ /,/) {
9264: @others = split(/,/,$otheremails);
9265: } else {
9266: push(@others,$otheremails);
9267: }
9268: foreach my $addr (@others) {
9269: if (!grep(/^\Q$addr\E$/,@recipients)) {
9270: push(@recipients,$addr);
9271: }
9272: }
9273: }
9274: my $recipientlist = join(',',@recipients);
9275: return $recipientlist;
9276: }
9277:
9278: ############################################################
9279: ############################################################
9280:
9281: =pod
9282:
9283: =head1 Course Catalog Routines
9284:
9285: =over 4
9286:
9287: =item * &gather_categories()
9288:
9289: Converts category definitions - keys of categories hash stored in
9290: coursecategories in configuration.db on the primary library server in a
9291: domain - to an array. Also generates javascript and idx hash used to
9292: generate Domain Coordinator interface for editing Course Categories.
9293:
9294: Inputs:
9295:
9296: categories (reference to hash of category definitions).
9297:
9298: cats (reference to array of arrays/hashes which encapsulates hierarchy of
9299: categories and subcategories).
9300:
9301: idx (reference to hash of counters used in Domain Coordinator interface for
9302: editing Course Categories).
9303:
9304: jsarray (reference to array of categories used to create Javascript arrays for
9305: Domain Coordinator interface for editing Course Categories).
9306:
9307: Returns: nothing
9308:
9309: Side effects: populates cats, idx and jsarray.
9310:
9311: =cut
9312:
9313: sub gather_categories {
9314: my ($categories,$cats,$idx,$jsarray) = @_;
9315: my %counters;
9316: my $num = 0;
9317: foreach my $item (keys(%{$categories})) {
9318: my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
9319: if ($container eq '' && $depth == 0) {
9320: $cats->[$depth][$categories->{$item}] = $cat;
9321: } else {
9322: $cats->[$depth]{$container}[$categories->{$item}] = $cat;
9323: }
9324: my ($escitem,$tail) = split(/:/,$item,2);
9325: if ($counters{$tail} eq '') {
9326: $counters{$tail} = $num;
9327: $num ++;
9328: }
9329: if (ref($idx) eq 'HASH') {
9330: $idx->{$item} = $counters{$tail};
9331: }
9332: if (ref($jsarray) eq 'ARRAY') {
9333: push(@{$jsarray->[$counters{$tail}]},$item);
9334: }
9335: }
9336: return;
9337: }
9338:
9339: =pod
9340:
9341: =item * &extract_categories()
9342:
9343: Used to generate breadcrumb trails for course categories.
9344:
9345: Inputs:
9346:
9347: categories (reference to hash of category definitions).
9348:
9349: cats (reference to array of arrays/hashes which encapsulates hierarchy of
9350: categories and subcategories).
9351:
9352: trails (reference to array of breacrumb trails for each category).
9353:
9354: allitems (reference to hash - key is category key
9355: (format: escaped(name):escaped(parent category):depth in hierarchy).
9356:
9357: idx (reference to hash of counters used in Domain Coordinator interface for
9358: editing Course Categories).
9359:
9360: jsarray (reference to array of categories used to create Javascript arrays for
9361: Domain Coordinator interface for editing Course Categories).
9362:
9363: subcats (reference to hash of arrays containing all subcategories within each
9364: category, -recursive)
9365:
9366: Returns: nothing
9367:
9368: Side effects: populates trails and allitems hash references.
9369:
9370: =cut
9371:
9372: sub extract_categories {
9373: my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
9374: if (ref($categories) eq 'HASH') {
9375: &gather_categories($categories,$cats,$idx,$jsarray);
9376: if (ref($cats->[0]) eq 'ARRAY') {
9377: for (my $i=0; $i<@{$cats->[0]}; $i++) {
9378: my $name = $cats->[0][$i];
9379: my $item = &escape($name).'::0';
9380: my $trailstr;
9381: if ($name eq 'instcode') {
9382: $trailstr = &mt('Official courses (with institutional codes)');
9383: } else {
9384: $trailstr = $name;
9385: }
9386: if ($allitems->{$item} eq '') {
9387: push(@{$trails},$trailstr);
9388: $allitems->{$item} = scalar(@{$trails})-1;
9389: }
9390: my @parents = ($name);
9391: if (ref($cats->[1]{$name}) eq 'ARRAY') {
9392: for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
9393: my $category = $cats->[1]{$name}[$j];
9394: if (ref($subcats) eq 'HASH') {
9395: push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
9396: }
9397: &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
9398: }
9399: } else {
9400: if (ref($subcats) eq 'HASH') {
9401: $subcats->{$item} = [];
9402: }
9403: }
9404: }
9405: }
9406: }
9407: return;
9408: }
9409:
9410: =pod
9411:
9412: =item *&recurse_categories()
9413:
9414: Recursively used to generate breadcrumb trails for course categories.
9415:
9416: Inputs:
9417:
9418: cats (reference to array of arrays/hashes which encapsulates hierarchy of
9419: categories and subcategories).
9420:
9421: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
9422:
9423: category (current course category, for which breadcrumb trail is being generated).
9424:
9425: trails (reference to array of breadcrumb trails for each category).
9426:
9427: allitems (reference to hash - key is category key
9428: (format: escaped(name):escaped(parent category):depth in hierarchy).
9429:
9430: parents (array containing containers directories for current category,
9431: back to top level).
9432:
9433: Returns: nothing
9434:
9435: Side effects: populates trails and allitems hash references
9436:
9437: =cut
9438:
9439: sub recurse_categories {
9440: my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
9441: my $shallower = $depth - 1;
9442: if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
9443: for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
9444: my $name = $cats->[$depth]{$category}[$k];
9445: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
9446: my $trailstr = join(' -> ',(@{$parents},$category));
9447: if ($allitems->{$item} eq '') {
9448: push(@{$trails},$trailstr);
9449: $allitems->{$item} = scalar(@{$trails})-1;
9450: }
9451: my $deeper = $depth+1;
9452: push(@{$parents},$category);
9453: if (ref($subcats) eq 'HASH') {
9454: my $subcat = &escape($name).':'.$category.':'.$depth;
9455: for (my $j=@{$parents}; $j>=0; $j--) {
9456: my $higher;
9457: if ($j > 0) {
9458: $higher = &escape($parents->[$j]).':'.
9459: &escape($parents->[$j-1]).':'.$j;
9460: } else {
9461: $higher = &escape($parents->[$j]).'::'.$j;
9462: }
9463: push(@{$subcats->{$higher}},$subcat);
9464: }
9465: }
9466: &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
9467: $subcats);
9468: pop(@{$parents});
9469: }
9470: } else {
9471: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
9472: my $trailstr = join(' -> ',(@{$parents},$category));
9473: if ($allitems->{$item} eq '') {
9474: push(@{$trails},$trailstr);
9475: $allitems->{$item} = scalar(@{$trails})-1;
9476: }
9477: }
9478: return;
9479: }
9480:
9481: =pod
9482:
9483: =item *&assign_categories_table()
9484:
9485: Create a datatable for display of hierarchical categories in a domain,
9486: with checkboxes to allow a course to be categorized.
9487:
9488: Inputs:
9489:
9490: cathash - reference to hash of categories defined for the domain (from
9491: configuration.db)
9492:
9493: currcat - scalar with an & separated list of categories assigned to a course.
9494:
9495: Returns: $output (markup to be displayed)
9496:
9497: =cut
9498:
9499: sub assign_categories_table {
9500: my ($cathash,$currcat) = @_;
9501: my $output;
9502: if (ref($cathash) eq 'HASH') {
9503: my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
9504: &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
9505: $maxdepth = scalar(@cats);
9506: if (@cats > 0) {
9507: my $itemcount = 0;
9508: if (ref($cats[0]) eq 'ARRAY') {
9509: $output = &Apache::loncommon::start_data_table();
9510: my @currcategories;
9511: if ($currcat ne '') {
9512: @currcategories = split('&',$currcat);
9513: }
9514: for (my $i=0; $i<@{$cats[0]}; $i++) {
9515: my $parent = $cats[0][$i];
9516: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
9517: next if ($parent eq 'instcode');
9518: my $item = &escape($parent).'::0';
9519: my $checked = '';
9520: if (@currcategories > 0) {
9521: if (grep(/^\Q$item\E$/,@currcategories)) {
9522: $checked = ' checked="checked"';
9523: }
9524: }
9525: $output .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
9526: '<input type="checkbox" name="usecategory" value="'.
9527: $item.'"'.$checked.' />'.$parent.'</span>'.
9528: '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
9529: my $depth = 1;
9530: push(@path,$parent);
9531: $output .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
9532: pop(@path);
9533: $output .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
9534: $itemcount ++;
9535: }
9536: $output .= &Apache::loncommon::end_data_table();
9537: }
9538: }
9539: }
9540: return $output;
9541: }
9542:
9543: =pod
9544:
9545: =item *&assign_category_rows()
9546:
9547: Create a datatable row for display of nested categories in a domain,
9548: with checkboxes to allow a course to be categorized,called recursively.
9549:
9550: Inputs:
9551:
9552: itemcount - track row number for alternating colors
9553:
9554: cats - reference to array of arrays/hashes which encapsulates hierarchy of
9555: categories and subcategories.
9556:
9557: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
9558:
9559: parent - parent of current category item
9560:
9561: path - Array containing all categories back up through the hierarchy from the
9562: current category to the top level.
9563:
9564: currcategories - reference to array of current categories assigned to the course
9565:
9566: Returns: $output (markup to be displayed).
9567:
9568: =cut
9569:
9570: sub assign_category_rows {
9571: my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
9572: my ($text,$name,$item,$chgstr);
9573: if (ref($cats) eq 'ARRAY') {
9574: my $maxdepth = scalar(@{$cats});
9575: if (ref($cats->[$depth]) eq 'HASH') {
9576: if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
9577: my $numchildren = @{$cats->[$depth]{$parent}};
9578: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
9579: $text .= '<td><table class="LC_datatable">';
9580: for (my $j=0; $j<$numchildren; $j++) {
9581: $name = $cats->[$depth]{$parent}[$j];
9582: $item = &escape($name).':'.&escape($parent).':'.$depth;
9583: my $deeper = $depth+1;
9584: my $checked = '';
9585: if (ref($currcategories) eq 'ARRAY') {
9586: if (@{$currcategories} > 0) {
9587: if (grep(/^\Q$item\E$/,@{$currcategories})) {
9588: $checked = ' checked="checked"';
9589: }
9590: }
9591: }
9592: $text .= '<tr><td><span class="LC_nobreak"><label>'.
9593: '<input type="checkbox" name="usecategory" value="'.
9594: $item.'"'.$checked.' />'.$name.'</label></span>'.
9595: '<input type="hidden" name="catname" value="'.$name.'" />'.
9596: '</td><td>';
9597: if (ref($path) eq 'ARRAY') {
9598: push(@{$path},$name);
9599: $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
9600: pop(@{$path});
9601: }
9602: $text .= '</td></tr>';
9603: }
9604: $text .= '</table></td>';
9605: }
9606: }
9607: }
9608: return $text;
9609: }
9610:
9611: ############################################################
9612: ############################################################
9613:
9614:
9615: sub commit_customrole {
9616: my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
9617: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
9618: ($start?', '.&mt('starting').' '.localtime($start):'').
9619: ($end?', ending '.localtime($end):'').': <b>'.
9620: &Apache::lonnet::assigncustomrole(
9621: $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
9622: '</b><br />';
9623: return $output;
9624: }
9625:
9626: sub commit_standardrole {
9627: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
9628: my ($output,$logmsg,$linefeed);
9629: if ($context eq 'auto') {
9630: $linefeed = "\n";
9631: } else {
9632: $linefeed = "<br />\n";
9633: }
9634: if ($three eq 'st') {
9635: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
9636: $one,$two,$sec,$context);
9637: if (($result =~ /^error/) || ($result eq 'not_in_class') ||
9638: ($result eq 'unknown_course') || ($result eq 'refused')) {
9639: $output = $logmsg.' '.&mt('Error: ').$result."\n";
9640: } else {
9641: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
9642: ($start?', '.&mt('starting').' '.localtime($start):'').
9643: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
9644: if ($context eq 'auto') {
9645: $output .= $result.$linefeed.&mt('Add to classlist').': ok';
9646: } else {
9647: $output .= '<b>'.$result.'</b>'.$linefeed.
9648: &mt('Add to classlist').': <b>ok</b>';
9649: }
9650: $output .= $linefeed;
9651: }
9652: } else {
9653: $output = &mt('Assigning').' '.$three.' in '.$url.
9654: ($start?', '.&mt('starting').' '.localtime($start):'').
9655: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
9656: my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
9657: if ($context eq 'auto') {
9658: $output .= $result.$linefeed;
9659: } else {
9660: $output .= '<b>'.$result.'</b>'.$linefeed;
9661: }
9662: }
9663: return $output;
9664: }
9665:
9666: sub commit_studentrole {
9667: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
9668: my ($result,$linefeed,$oldsecurl,$newsecurl);
9669: if ($context eq 'auto') {
9670: $linefeed = "\n";
9671: } else {
9672: $linefeed = '<br />'."\n";
9673: }
9674: if (defined($one) && defined($two)) {
9675: my $cid=$one.'_'.$two;
9676: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
9677: my $secchange = 0;
9678: my $expire_role_result;
9679: my $modify_section_result;
9680: if ($oldsec ne '-1') {
9681: if ($oldsec ne $sec) {
9682: $secchange = 1;
9683: my $now = time;
9684: my $uurl='/'.$cid;
9685: $uurl=~s/\_/\//g;
9686: if ($oldsec) {
9687: $uurl.='/'.$oldsec;
9688: }
9689: $oldsecurl = $uurl;
9690: $expire_role_result =
9691: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
9692: if ($env{'request.course.sec'} ne '') {
9693: if ($expire_role_result eq 'refused') {
9694: my @roles = ('st');
9695: my @statuses = ('previous');
9696: my @roledoms = ($one);
9697: my $withsec = 1;
9698: my %roleshash =
9699: &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
9700: \@statuses,\@roles,\@roledoms,$withsec);
9701: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
9702: my ($oldstart,$oldend) =
9703: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
9704: if ($oldend > 0 && $oldend <= $now) {
9705: $expire_role_result = 'ok';
9706: }
9707: }
9708: }
9709: }
9710: $result = $expire_role_result;
9711: }
9712: }
9713: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
9714: $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
9715: if ($modify_section_result =~ /^ok/) {
9716: if ($secchange == 1) {
9717: if ($sec eq '') {
9718: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
9719: } else {
9720: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
9721: }
9722: } elsif ($oldsec eq '-1') {
9723: if ($sec eq '') {
9724: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
9725: } else {
9726: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
9727: }
9728: } else {
9729: if ($sec eq '') {
9730: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
9731: } else {
9732: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
9733: }
9734: }
9735: } else {
9736: if ($secchange) {
9737: $$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;
9738: } else {
9739: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
9740: }
9741: }
9742: $result = $modify_section_result;
9743: } elsif ($secchange == 1) {
9744: if ($oldsec eq '') {
9745: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
9746: } else {
9747: $$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;
9748: }
9749: if ($expire_role_result eq 'refused') {
9750: my $newsecurl = '/'.$cid;
9751: $newsecurl =~ s/\_/\//g;
9752: if ($sec ne '') {
9753: $newsecurl.='/'.$sec;
9754: }
9755: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
9756: if ($sec eq '') {
9757: $$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;
9758: } else {
9759: $$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;
9760: }
9761: }
9762: }
9763: }
9764: } else {
9765: $$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;
9766: $result = "error: incomplete course id\n";
9767: }
9768: return $result;
9769: }
9770:
9771: ############################################################
9772: ############################################################
9773:
9774: sub check_clone {
9775: my ($args,$linefeed) = @_;
9776: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
9777: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
9778: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
9779: my $clonemsg;
9780: my $can_clone = 0;
9781:
9782: if ($clonehome eq 'no_host') {
9783: $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'});
9784: } else {
9785: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
9786: if ($env{'request.role.domain'} eq $args->{'clonedomain'}) {
9787: $can_clone = 1;
9788: } else {
9789: my %clonehash = &Apache::lonnet::get('environment',['cloners'],
9790: $args->{'clonedomain'},$args->{'clonecourse'});
9791: my @cloners = split(/,/,$clonehash{'cloners'});
9792: if (grep(/^\*$/,@cloners)) {
9793: $can_clone = 1;
9794: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
9795: $can_clone = 1;
9796: } else {
9797: my %roleshash =
9798: &Apache::lonnet::get_my_roles($args->{'ccuname'},
9799: $args->{'ccdomain'},
9800: 'userroles',['active'],['cc'],
9801: [$args->{'clonedomain'}]);
9802: if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
9803: $can_clone = 1;
9804: } else {
9805: $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'});
9806: }
9807: }
9808: }
9809: }
9810: return ($can_clone, $clonemsg, $cloneid, $clonehome);
9811: }
9812:
9813: sub construct_course {
9814: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context) = @_;
9815: my $outcome;
9816: my $linefeed = '<br />'."\n";
9817: if ($context eq 'auto') {
9818: $linefeed = "\n";
9819: }
9820:
9821: #
9822: # Are we cloning?
9823: #
9824: my ($can_clone, $clonemsg, $cloneid, $clonehome);
9825: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
9826: ($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
9827: if ($context ne 'auto') {
9828: if ($clonemsg ne '') {
9829: $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
9830: }
9831: }
9832: $outcome .= $clonemsg.$linefeed;
9833:
9834: if (!$can_clone) {
9835: return (0,$outcome);
9836: }
9837: }
9838:
9839: #
9840: # Open course
9841: #
9842: my $crstype = lc($args->{'crstype'});
9843: my %cenv=();
9844: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
9845: $args->{'cdescr'},
9846: $args->{'curl'},
9847: $args->{'course_home'},
9848: $args->{'nonstandard'},
9849: $args->{'crscode'},
9850: $args->{'ccuname'}.':'.
9851: $args->{'ccdomain'},
9852: $args->{'crstype'});
9853:
9854: # Note: The testing routines depend on this being output; see
9855: # Utils::Course. This needs to at least be output as a comment
9856: # if anyone ever decides to not show this, and Utils::Course::new
9857: # will need to be suitably modified.
9858: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
9859: #
9860: # Check if created correctly
9861: #
9862: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
9863: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
9864: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
9865:
9866: #
9867: # Do the cloning
9868: #
9869: if ($can_clone && $cloneid) {
9870: $clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
9871: if ($context ne 'auto') {
9872: $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
9873: }
9874: $outcome .= $clonemsg.$linefeed;
9875: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
9876: # Copy all files
9877: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
9878: # Restore URL
9879: $cenv{'url'}=$oldcenv{'url'};
9880: # Restore title
9881: $cenv{'description'}=$oldcenv{'description'};
9882: # Mark as cloned
9883: $cenv{'clonedfrom'}=$cloneid;
9884: # Need to clone grading mode
9885: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
9886: $cenv{'grading'}=$newenv{'grading'};
9887: # Do not clone these environment entries
9888: &Apache::lonnet::del('environment',
9889: ['default_enrollment_start_date',
9890: 'default_enrollment_end_date',
9891: 'question.email',
9892: 'policy.email',
9893: 'comment.email',
9894: 'pch.users.denied',
9895: 'plc.users.denied',
9896: 'hidefromcat',
9897: 'categories'],
9898: $$crsudom,$$crsunum);
9899: }
9900:
9901: #
9902: # Set environment (will override cloned, if existing)
9903: #
9904: my @sections = ();
9905: my @xlists = ();
9906: if ($args->{'crstype'}) {
9907: $cenv{'type'}=$args->{'crstype'};
9908: }
9909: if ($args->{'crsid'}) {
9910: $cenv{'courseid'}=$args->{'crsid'};
9911: }
9912: if ($args->{'crscode'}) {
9913: $cenv{'internal.coursecode'}=$args->{'crscode'};
9914: }
9915: if ($args->{'crsquota'} ne '') {
9916: $cenv{'internal.coursequota'}=$args->{'crsquota'};
9917: } else {
9918: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
9919: }
9920: if ($args->{'ccuname'}) {
9921: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
9922: ':'.$args->{'ccdomain'};
9923: } else {
9924: $cenv{'internal.courseowner'} = $args->{'curruser'};
9925: }
9926: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
9927: if ($args->{'crssections'}) {
9928: $cenv{'internal.sectionnums'} = '';
9929: if ($args->{'crssections'} =~ m/,/) {
9930: @sections = split/,/,$args->{'crssections'};
9931: } else {
9932: $sections[0] = $args->{'crssections'};
9933: }
9934: if (@sections > 0) {
9935: foreach my $item (@sections) {
9936: my ($sec,$gp) = split/:/,$item;
9937: my $class = $args->{'crscode'}.$sec;
9938: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
9939: $cenv{'internal.sectionnums'} .= $item.',';
9940: unless ($addcheck eq 'ok') {
9941: push @badclasses, $class;
9942: }
9943: }
9944: $cenv{'internal.sectionnums'} =~ s/,$//;
9945: }
9946: }
9947: # do not hide course coordinator from staff listing,
9948: # even if privileged
9949: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
9950: # add crosslistings
9951: if ($args->{'crsxlist'}) {
9952: $cenv{'internal.crosslistings'}='';
9953: if ($args->{'crsxlist'} =~ m/,/) {
9954: @xlists = split/,/,$args->{'crsxlist'};
9955: } else {
9956: $xlists[0] = $args->{'crsxlist'};
9957: }
9958: if (@xlists > 0) {
9959: foreach my $item (@xlists) {
9960: my ($xl,$gp) = split/:/,$item;
9961: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
9962: $cenv{'internal.crosslistings'} .= $item.',';
9963: unless ($addcheck eq 'ok') {
9964: push @badclasses, $xl;
9965: }
9966: }
9967: $cenv{'internal.crosslistings'} =~ s/,$//;
9968: }
9969: }
9970: if ($args->{'autoadds'}) {
9971: $cenv{'internal.autoadds'}=$args->{'autoadds'};
9972: }
9973: if ($args->{'autodrops'}) {
9974: $cenv{'internal.autodrops'}=$args->{'autodrops'};
9975: }
9976: # check for notification of enrollment changes
9977: my @notified = ();
9978: if ($args->{'notify_owner'}) {
9979: if ($args->{'ccuname'} ne '') {
9980: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
9981: }
9982: }
9983: if ($args->{'notify_dc'}) {
9984: if ($uname ne '') {
9985: push(@notified,$uname.':'.$udom);
9986: }
9987: }
9988: if (@notified > 0) {
9989: my $notifylist;
9990: if (@notified > 1) {
9991: $notifylist = join(',',@notified);
9992: } else {
9993: $notifylist = $notified[0];
9994: }
9995: $cenv{'internal.notifylist'} = $notifylist;
9996: }
9997: if (@badclasses > 0) {
9998: my %lt=&Apache::lonlocal::texthash(
9999: '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',
10000: 'dnhr' => 'does not have rights to access enrollment in these classes',
10001: 'adby' => 'as determined by the policies of your institution on access to official classlists'
10002: );
10003: my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
10004: ' ('.$lt{'adby'}.')';
10005: if ($context eq 'auto') {
10006: $outcome .= $badclass_msg.$linefeed;
10007: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
10008: foreach my $item (@badclasses) {
10009: if ($context eq 'auto') {
10010: $outcome .= " - $item\n";
10011: } else {
10012: $outcome .= "<li>$item</li>\n";
10013: }
10014: }
10015: if ($context eq 'auto') {
10016: $outcome .= $linefeed;
10017: } else {
10018: $outcome .= "</ul><br /><br /></div>\n";
10019: }
10020: }
10021: }
10022: if ($args->{'no_end_date'}) {
10023: $args->{'endaccess'} = 0;
10024: }
10025: $cenv{'internal.autostart'}=$args->{'enrollstart'};
10026: $cenv{'internal.autoend'}=$args->{'enrollend'};
10027: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
10028: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
10029: if ($args->{'showphotos'}) {
10030: $cenv{'internal.showphotos'}=$args->{'showphotos'};
10031: }
10032: $cenv{'internal.authtype'} = $args->{'authtype'};
10033: $cenv{'internal.autharg'} = $args->{'autharg'};
10034: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
10035: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
10036: 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');
10037: if ($context eq 'auto') {
10038: $outcome .= $krb_msg;
10039: } else {
10040: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
10041: }
10042: $outcome .= $linefeed;
10043: }
10044: }
10045: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
10046: if ($args->{'setpolicy'}) {
10047: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10048: }
10049: if ($args->{'setcontent'}) {
10050: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10051: }
10052: }
10053: if ($args->{'reshome'}) {
10054: $cenv{'reshome'}=$args->{'reshome'}.'/';
10055: $cenv{'reshome'}=~s/\/+$/\//;
10056: }
10057: #
10058: # course has keyed access
10059: #
10060: if ($args->{'setkeys'}) {
10061: $cenv{'keyaccess'}='yes';
10062: }
10063: # if specified, key authority is not course, but user
10064: # only active if keyaccess is yes
10065: if ($args->{'keyauth'}) {
10066: my ($user,$domain) = split(':',$args->{'keyauth'});
10067: $user = &LONCAPA::clean_username($user);
10068: $domain = &LONCAPA::clean_username($domain);
10069: if ($user ne '' && $domain ne '') {
10070: $cenv{'keyauth'}=$user.':'.$domain;
10071: }
10072: }
10073:
10074: if ($args->{'disresdis'}) {
10075: $cenv{'pch.roles.denied'}='st';
10076: }
10077: if ($args->{'disablechat'}) {
10078: $cenv{'plc.roles.denied'}='st';
10079: }
10080:
10081: # Record we've not yet viewed the Course Initialization Helper for this
10082: # course
10083: $cenv{'course.helper.not.run'} = 1;
10084: #
10085: # Use new Randomseed
10086: #
10087: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
10088: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
10089: #
10090: # The encryption code and receipt prefix for this course
10091: #
10092: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
10093: $cenv{'internal.encpref'}=100+int(9*rand(99));
10094: #
10095: # By default, use standard grading
10096: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
10097:
10098: $outcome .= $linefeed.&mt('Setting environment').': '.
10099: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
10100: #
10101: # Open all assignments
10102: #
10103: if ($args->{'openall'}) {
10104: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
10105: my %storecontent = ($storeunder => time,
10106: $storeunder.'.type' => 'date_start');
10107:
10108: $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
10109: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
10110: }
10111: #
10112: # Set first page
10113: #
10114: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
10115: || ($cloneid)) {
10116: use LONCAPA::map;
10117: $outcome .= &mt('Setting first resource').': ';
10118:
10119: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
10120: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
10121:
10122: $outcome .= ($fatal?$errtext:'read ok').' - ';
10123: my $title; my $url;
10124: if ($args->{'firstres'} eq 'syl') {
10125: $title=&mt('Syllabus');
10126: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
10127: } else {
10128: $title=&mt('Navigate Contents');
10129: $url='/adm/navmaps';
10130: }
10131:
10132: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
10133: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
10134:
10135: if ($errtext) { $fatal=2; }
10136: $outcome .= ($fatal?$errtext:'write ok').$linefeed;
10137: }
10138:
10139: return (1,$outcome);
10140: }
10141:
10142: ############################################################
10143: ############################################################
10144:
10145: sub course_type {
10146: my ($cid) = @_;
10147: if (!defined($cid)) {
10148: $cid = $env{'request.course.id'};
10149: }
10150: if (defined($env{'course.'.$cid.'.type'})) {
10151: return $env{'course.'.$cid.'.type'};
10152: } else {
10153: return 'Course';
10154: }
10155: }
10156:
10157: sub group_term {
10158: my $crstype = &course_type();
10159: my %names = (
10160: 'Course' => 'group',
10161: 'Community' => 'group',
10162: );
10163: return $names{$crstype};
10164: }
10165:
10166: sub icon {
10167: my ($file)=@_;
10168: my $curfext = lc((split(/\./,$file))[-1]);
10169: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
10170: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
10171: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
10172: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
10173: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
10174: $curfext.".gif") {
10175: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
10176: $curfext.".gif";
10177: }
10178: }
10179: return &lonhttpdurl($iconname);
10180: }
10181:
10182: sub lonhttpdurl {
10183: #
10184: # Had been used for "small fry" static images on separate port 8080.
10185: # Modify here if lightweight http functionality desired again.
10186: # Currently eliminated due to increasing firewall issues.
10187: #
10188: my ($url)=@_;
10189: return $url;
10190: }
10191:
10192: sub connection_aborted {
10193: my ($r)=@_;
10194: $r->print(" ");$r->rflush();
10195: my $c = $r->connection;
10196: return $c->aborted();
10197: }
10198:
10199: # Escapes strings that may have embedded 's that will be put into
10200: # strings as 'strings'.
10201: sub escape_single {
10202: my ($input) = @_;
10203: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
10204: $input =~ s/\'/\\\'/g; # Esacpe the 's....
10205: return $input;
10206: }
10207:
10208: # Same as escape_single, but escape's "'s This
10209: # can be used for "strings"
10210: sub escape_double {
10211: my ($input) = @_;
10212: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
10213: $input =~ s/\"/\\\"/g; # Esacpe the "s....
10214: return $input;
10215: }
10216:
10217: # Escapes the last element of a full URL.
10218: sub escape_url {
10219: my ($url) = @_;
10220: my @urlslices = split(/\//, $url,-1);
10221: my $lastitem = &escape(pop(@urlslices));
10222: return join('/',@urlslices).'/'.$lastitem;
10223: }
10224:
10225: sub compare_arrays {
10226: my ($arrayref1,$arrayref2) = @_;
10227: my (@difference,%count);
10228: @difference = ();
10229: %count = ();
10230: if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
10231: foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
10232: foreach my $element (keys(%count)) {
10233: if ($count{$element} == 1) {
10234: push(@difference,$element);
10235: }
10236: }
10237: }
10238: return @difference;
10239: }
10240:
10241: # -------------------------------------------------------- Initialize user login
10242: sub init_user_environment {
10243: my ($r, $username, $domain, $authhost, $form, $args) = @_;
10244: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
10245:
10246: my $public=($username eq 'public' && $domain eq 'public');
10247:
10248: # See if old ID present, if so, remove
10249:
10250: my ($filename,$cookie,$userroles);
10251: my $now=time;
10252:
10253: if ($public) {
10254: my $max_public=100;
10255: my $oldest;
10256: my $oldest_time=0;
10257: for(my $next=1;$next<=$max_public;$next++) {
10258: if (-e $lonids."/publicuser_$next.id") {
10259: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
10260: if ($mtime<$oldest_time || !$oldest_time) {
10261: $oldest_time=$mtime;
10262: $oldest=$next;
10263: }
10264: } else {
10265: $cookie="publicuser_$next";
10266: last;
10267: }
10268: }
10269: if (!$cookie) { $cookie="publicuser_$oldest"; }
10270: } else {
10271: # if this isn't a robot, kill any existing non-robot sessions
10272: if (!$args->{'robot'}) {
10273: opendir(DIR,$lonids);
10274: while ($filename=readdir(DIR)) {
10275: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
10276: unlink($lonids.'/'.$filename);
10277: }
10278: }
10279: closedir(DIR);
10280: }
10281: # Give them a new cookie
10282: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
10283: : $now.$$.int(rand(10000)));
10284: $cookie="$username\_$id\_$domain\_$authhost";
10285:
10286: # Initialize roles
10287:
10288: $userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
10289: }
10290: # ------------------------------------ Check browser type and MathML capability
10291:
10292: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
10293: $clientunicode,$clientos) = &decode_user_agent($r);
10294:
10295: # ------------------------------------------------------------- Get environment
10296:
10297: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
10298: my ($tmp) = keys(%userenv);
10299: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10300: # default remote control to off
10301: if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
10302: } else {
10303: undef(%userenv);
10304: }
10305: if (($userenv{'interface'}) && (!$form->{'interface'})) {
10306: $form->{'interface'}=$userenv{'interface'};
10307: }
10308: $env{'environment.remote'}=$userenv{'remote'};
10309: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
10310:
10311: # --------------- Do not trust query string to be put directly into environment
10312: foreach my $option ('interface','localpath','localres') {
10313: $form->{$option}=~s/[\n\r\=]//gs;
10314: }
10315: # --------------------------------------------------------- Write first profile
10316:
10317: {
10318: my %initial_env =
10319: ("user.name" => $username,
10320: "user.domain" => $domain,
10321: "user.home" => $authhost,
10322: "browser.type" => $clientbrowser,
10323: "browser.version" => $clientversion,
10324: "browser.mathml" => $clientmathml,
10325: "browser.unicode" => $clientunicode,
10326: "browser.os" => $clientos,
10327: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
10328: "request.course.fn" => '',
10329: "request.course.uri" => '',
10330: "request.course.sec" => '',
10331: "request.role" => 'cm',
10332: "request.role.adv" => $env{'user.adv'},
10333: "request.host" => $ENV{'REMOTE_ADDR'},);
10334:
10335: if ($form->{'localpath'}) {
10336: $initial_env{"browser.localpath"} = $form->{'localpath'};
10337: $initial_env{"browser.localres"} = $form->{'localres'};
10338: }
10339:
10340: if ($public) {
10341: $initial_env{"environment.remote"} = "off";
10342: }
10343: if ($form->{'interface'}) {
10344: $form->{'interface'}=~s/\W//gs;
10345: $initial_env{"browser.interface"} = $form->{'interface'};
10346: $env{'browser.interface'}=$form->{'interface'};
10347: }
10348:
10349: foreach my $tool ('aboutme','blog','portfolio') {
10350: $userenv{'availabletools.'.$tool} =
10351: &Apache::lonnet::usertools_access($username,$domain,$tool,'reload');
10352: }
10353:
10354: foreach my $crstype ('official','unofficial','community') {
10355: $userenv{'canrequest.'.$crstype} =
10356: &Apache::lonnet::usertools_access($username,$domain,$crstype,
10357: 'reload','requestcourses');
10358: }
10359:
10360: $env{'user.environment'} = "$lonids/$cookie.id";
10361:
10362: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
10363: &GDBM_WRCREAT(),0640)) {
10364: &_add_to_env(\%disk_env,\%initial_env);
10365: &_add_to_env(\%disk_env,\%userenv,'environment.');
10366: &_add_to_env(\%disk_env,$userroles);
10367: if (ref($args->{'extra_env'})) {
10368: &_add_to_env(\%disk_env,$args->{'extra_env'});
10369: }
10370: untie(%disk_env);
10371: } else {
10372: &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
10373: 'Could not create environment storage in lonauth: '.$!.'</span>');
10374: return 'error: '.$!;
10375: }
10376: }
10377: $env{'request.role'}='cm';
10378: $env{'request.role.adv'}=$env{'user.adv'};
10379: $env{'browser.type'}=$clientbrowser;
10380:
10381: return $cookie;
10382:
10383: }
10384:
10385: sub _add_to_env {
10386: my ($idf,$env_data,$prefix) = @_;
10387: if (ref($env_data) eq 'HASH') {
10388: while (my ($key,$value) = each(%$env_data)) {
10389: $idf->{$prefix.$key} = $value;
10390: $env{$prefix.$key} = $value;
10391: }
10392: }
10393: }
10394:
10395: # --- Get the symbolic name of a problem and the url
10396: sub get_symb {
10397: my ($request,$silent) = @_;
10398: (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10399: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
10400: if ($symb eq '') {
10401: if (!$silent) {
10402: $request->print("Unable to handle ambiguous references:$url:.");
10403: return ();
10404: }
10405: }
10406: &Apache::lonenc::check_decrypt(\$symb);
10407: return ($symb);
10408: }
10409:
10410: # --------------------------------------------------------------Get annotation
10411:
10412: sub get_annotation {
10413: my ($symb,$enc) = @_;
10414:
10415: my $key = $symb;
10416: if (!$enc) {
10417: $key =
10418: &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
10419: }
10420: my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
10421: return $annotation{$key};
10422: }
10423:
10424: sub clean_symb {
10425: my ($symb,$delete_enc) = @_;
10426:
10427: &Apache::lonenc::check_decrypt(\$symb);
10428: my $enc = $env{'request.enc'};
10429: if ($delete_enc) {
10430: delete($env{'request.enc'});
10431: }
10432:
10433: return ($symb,$enc);
10434: }
10435:
10436: =pod
10437:
10438: =back
10439:
10440: =cut
10441:
10442: 1;
10443: __END__;
10444:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>