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