Annotation of loncom/interface/loncommon.pm, revision 1.161
1.10 albertel 1: # The LearningOnline Network with CAPA
1.1 albertel 2: # a pile of common routines
1.10 albertel 3: #
1.161 ! www 4: # $Id: loncommon.pm,v 1.160 2003/12/17 19:20:23 matthew Exp $
1.10 albertel 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: #
1.1 albertel 28:
29: # Makes a table out of the previous attempts
1.2 albertel 30: # Inputs result_from_symbread, user, domain, course_id
1.16 harris41 31: # Reads in non-network-related .tab files
1.1 albertel 32:
1.35 matthew 33: # POD header:
34:
1.45 matthew 35: =pod
36:
1.35 matthew 37: =head1 NAME
38:
39: Apache::loncommon - pile of common routines
40:
41: =head1 SYNOPSIS
42:
1.112 bowersj2 43: Common routines for manipulating connections, student answers,
44: domains, common Javascript fragments, etc.
1.35 matthew 45:
1.112 bowersj2 46: =head1 OVERVIEW
1.35 matthew 47:
1.112 bowersj2 48: A collection of commonly used subroutines that don't have a natural
49: home anywhere else. This collection helps remove
1.35 matthew 50: redundancy from other modules and increase efficiency of memory usage.
51:
52: =cut
53:
54: # End of POD header
1.1 albertel 55: package Apache::loncommon;
56:
57: use strict;
1.22 www 58: use Apache::lonnet();
1.46 matthew 59: use GDBM_File;
1.51 www 60: use POSIX qw(strftime mktime);
1.99 www 61: use Apache::Constants qw(:common :http :methods);
1.1 albertel 62: use Apache::lonmsg();
1.82 www 63: use Apache::lonmenu();
1.117 www 64: use Apache::lonlocal;
1.139 matthew 65: use HTML::Entities;
1.117 www 66:
1.22 www 67: my $readit;
68:
1.157 matthew 69: ##
70: ## Global Variables
71: ##
1.46 matthew 72:
1.20 www 73: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12 harris41 74: my %language;
1.124 www 75: my %supported_language;
1.12 harris41 76: my %cprtag;
77: my %fe; my %fd;
1.41 ng 78: my %category_extensions;
1.12 harris41 79:
1.63 www 80: # ---------------------------------------------- Designs
81:
82: my %designhash;
83:
1.46 matthew 84: # ---------------------------------------------- Thesaurus variables
1.144 matthew 85: #
86: # %Keywords:
87: # A hash used by &keyword to determine if a word is considered a keyword.
88: # $thesaurus_db_file
89: # Scalar containing the full path to the thesaurus database.
1.46 matthew 90:
91: my %Keywords;
92: my $thesaurus_db_file;
93:
1.144 matthew 94: #
95: # Initialize values from language.tab, copyright.tab, filetypes.tab,
96: # thesaurus.tab, and filecategories.tab.
97: #
1.18 www 98: BEGIN {
1.46 matthew 99: # Variable initialization
100: $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
101: #
1.22 www 102: unless ($readit) {
1.12 harris41 103: # ------------------------------------------------------------------- languages
104: {
1.158 raeburn 105: my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
106: '/language.tab';
107: if ( open(my $fh,"<$langtabfile") ) {
108: while (<$fh>) {
109: next if /^\#/;
110: chomp;
111: my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$_));
112: $language{$key}=$val.' - '.$enc;
113: if ($sup) {
114: $supported_language{$key}=$sup;
115: }
116: }
117: close($fh);
118: }
1.12 harris41 119: }
120: # ------------------------------------------------------------------ copyrights
121: {
1.158 raeburn 122: my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
123: '/copyright.tab';
124: if ( open (my $fh,"<$copyrightfile") ) {
125: while (<$fh>) {
126: next if /^\#/;
127: chomp;
128: my ($key,$val)=(split(/\s+/,$_,2));
129: $cprtag{$key}=$val;
130: }
131: close($fh);
132: }
1.12 harris41 133: }
1.63 www 134:
135: # -------------------------------------------------------------- domain designs
136:
137: my $filename;
138: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
139: opendir(DIR,$designdir);
140: while ($filename=readdir(DIR)) {
141: my ($domain)=($filename=~/^(\w+)\./);
142: {
1.158 raeburn 143: my $designfile = $designdir.'/'.$filename;
144: if ( open (my $fh,"<$designfile") ) {
145: while (<$fh>) {
146: next if /^\#/;
147: chomp;
148: my ($key,$val)=(split(/\=/,$_));
149: if ($val) { $designhash{$domain.'.'.$key}=$val; }
150: }
151: close($fh);
152: }
1.63 www 153: }
154:
155: }
156: closedir(DIR);
157:
158:
1.15 harris41 159: # ------------------------------------------------------------- file categories
160: {
1.158 raeburn 161: my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
162: '/filecategories.tab';
163: if ( open (my $fh,"<$categoryfile") ) {
164: while (<$fh>) {
165: next if /^\#/;
166: chomp;
167: my ($extension,$category)=(split(/\s+/,$_,2));
168: push @{$category_extensions{lc($category)}},$extension;
169: }
170: close($fh);
171: }
172:
1.15 harris41 173: }
1.12 harris41 174: # ------------------------------------------------------------------ file types
175: {
1.158 raeburn 176: my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
177: '/filetypes.tab';
178: if ( open (my $fh,"<$typesfile") ) {
1.16 harris41 179: while (<$fh>) {
1.158 raeburn 180: next if (/^\#/);
181: chomp;
182: my ($ending,$emb,$descr)=split(/\s+/,$_,3);
183: if ($descr ne '') {
184: $fe{$ending}=lc($emb);
185: $fd{$ending}=$descr;
186: }
187: }
188: close($fh);
189: }
1.12 harris41 190: }
1.22 www 191: &Apache::lonnet::logthis(
1.46 matthew 192: "<font color=yellow>INFO: Read file types</font>");
1.22 www 193: $readit=1;
1.46 matthew 194: } # end of unless($readit)
1.32 matthew 195:
196: }
1.112 bowersj2 197:
1.42 matthew 198: ###############################################################
199: ## HTML and Javascript Helper Functions ##
200: ###############################################################
201:
202: =pod
203:
1.112 bowersj2 204: =head1 HTML and Javascript Functions
1.42 matthew 205:
1.112 bowersj2 206: =over 4
207:
208: =item * browser_and_searcher_javascript ()
209:
210: X<browsing, javascript>X<searching, javascript>Returns a string
211: containing javascript with two functions, C<openbrowser> and
212: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
213: tags.
1.42 matthew 214:
1.112 bowersj2 215: =item * openbrowser(formname,elementname,only,omit) [javascript]
1.42 matthew 216:
217: inputs: formname, elementname, only, omit
218:
219: formname and elementname indicate the name of the html form and name of
220: the element that the results of the browsing selection are to be placed in.
221:
222: Specifying 'only' will restrict the browser to displaying only files
223: with the given extension. Can be a comma seperated list.
224:
225: Specifying 'omit' will restrict the browser to NOT displaying files
226: with the given extension. Can be a comma seperated list.
227:
1.112 bowersj2 228: =item * opensearcher(formname, elementname) [javascript]
1.42 matthew 229:
230: Inputs: formname, elementname
231:
232: formname and elementname specify the name of the html form and the name
233: of the element the selection from the search results will be placed in.
234:
235: =cut
236:
237: sub browser_and_searcher_javascript {
238: return <<END;
1.50 matthew 239: var editbrowser = null;
1.135 albertel 240: function openbrowser(formname,elementname,only,omit,titleelement) {
1.42 matthew 241: var url = '/res/?';
242: if (editbrowser == null) {
243: url += 'launch=1&';
244: }
245: url += 'catalogmode=interactive&';
246: url += 'mode=edit&';
247: url += 'form=' + formname + '&';
248: if (only != null) {
249: url += 'only=' + only + '&';
250: }
251: if (omit != null) {
252: url += 'omit=' + omit + '&';
253: }
1.135 albertel 254: if (titleelement != null) {
255: url += 'titleelement=' + titleelement + '&';
256: }
1.42 matthew 257: url += 'element=' + elementname + '';
258: var title = 'Browser';
259: var options = 'scrollbars=1,resizable=1,menubar=0';
260: options += ',width=700,height=600';
261: editbrowser = open(url,title,options,'1');
262: editbrowser.focus();
263: }
264: var editsearcher;
1.135 albertel 265: function opensearcher(formname,elementname,titleelement) {
1.42 matthew 266: var url = '/adm/searchcat?';
267: if (editsearcher == null) {
268: url += 'launch=1&';
269: }
270: url += 'catalogmode=interactive&';
271: url += 'mode=edit&';
272: url += 'form=' + formname + '&';
1.135 albertel 273: if (titleelement != null) {
274: url += 'titleelement=' + titleelement + '&';
275: }
1.42 matthew 276: url += 'element=' + elementname + '';
277: var title = 'Search';
278: var options = 'scrollbars=1,resizable=1,menubar=0';
279: options += ',width=700,height=600';
280: editsearcher = open(url,title,options,'1');
281: editsearcher.focus();
282: }
283: END
284: }
285:
1.74 www 286: sub studentbrowser_javascript {
1.111 www 287: unless (
288: (($ENV{'request.course.id'}) &&
289: (&Apache::lonnet::allowed('srm',$ENV{'request.course.id'})))
290: || ($ENV{'request.role'}=~/^(au|dc|su)/)
291: ) { return ''; }
1.74 www 292: return (<<'ENDSTDBRW');
293: <script type="text/javascript" language="Javascript" >
294: var stdeditbrowser;
1.111 www 295: function openstdbrowser(formname,uname,udom,roleflag) {
1.74 www 296: var url = '/adm/pickstudent?';
297: var filter;
298: eval('filter=document.'+formname+'.'+uname+'.value;');
299: if (filter != null) {
300: if (filter != '') {
301: url += 'filter='+filter+'&';
302: }
303: }
304: url += 'form=' + formname + '&unameelement='+uname+
305: '&udomelement='+udom;
1.111 www 306: if (roleflag) { url+="&roles=1"; }
1.102 www 307: var title = 'Student_Browser';
1.74 www 308: var options = 'scrollbars=1,resizable=1,menubar=0';
309: options += ',width=700,height=600';
310: stdeditbrowser = open(url,title,options,'1');
311: stdeditbrowser.focus();
312: }
313: </script>
314: ENDSTDBRW
315: }
1.42 matthew 316:
1.74 www 317: sub selectstudent_link {
1.111 www 318: my ($form,$unameele,$udomele)=@_;
319: if ($ENV{'request.course.id'}) {
320: unless (&Apache::lonnet::allowed('srm',$ENV{'request.course.id'})) {
321: return '';
322: }
323: return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
1.119 www 324: '","'.$udomele.'");'."'>".&mt('Select User')."</a>";
1.74 www 325: }
1.111 www 326: if ($ENV{'request.role'}=~/^(au|dc|su)/) {
327: return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
1.119 www 328: '","'.$udomele.'",1);'."'>".&mt('Select User')."</a>";
1.111 www 329: }
330: return '';
1.91 www 331: }
332:
333: sub coursebrowser_javascript {
1.128 albertel 334: my ($domainfilter)=@_;
335: return (<<ENDSTDBRW);
1.91 www 336: <script type="text/javascript" language="Javascript" >
337: var stdeditbrowser;
338: function opencrsbrowser(formname,uname,udom) {
339: var url = '/adm/pickcourse?';
340: var filter;
341: if (filter != null) {
342: if (filter != '') {
343: url += 'filter='+filter+'&';
344: }
345: }
1.128 albertel 346: var domainfilter='$domainfilter';
347: if (domainfilter != null) {
348: if (domainfilter != '') {
349: url += 'domainfilter='+domainfilter+'&';
350: }
351: }
1.91 www 352: url += 'form=' + formname + '&cnumelement='+uname+
353: '&cdomelement='+udom;
1.102 www 354: var title = 'Course_Browser';
1.91 www 355: var options = 'scrollbars=1,resizable=1,menubar=0';
356: options += ',width=700,height=600';
357: stdeditbrowser = open(url,title,options,'1');
358: stdeditbrowser.focus();
359: }
360: </script>
361: ENDSTDBRW
362: }
363:
364: sub selectcourse_link {
365: my ($form,$unameele,$udomele)=@_;
366: return "<a href='".'javascript:opencrsbrowser("'.$form.'","'.$unameele.
1.119 www 367: '","'.$udomele.'");'."'>".&mt('Select Course')."</a>";
1.74 www 368: }
1.42 matthew 369:
370: =pod
1.36 matthew 371:
1.112 bowersj2 372: =item * linked_select_forms(...)
1.36 matthew 373:
374: linked_select_forms returns a string containing a <script></script> block
375: and html for two <select> menus. The select menus will be linked in that
376: changing the value of the first menu will result in new values being placed
377: in the second menu. The values in the select menu will appear in alphabetical
378: order.
379:
380: linked_select_forms takes the following ordered inputs:
381:
382: =over 4
383:
1.112 bowersj2 384: =item * $formname, the name of the <form> tag
1.36 matthew 385:
1.112 bowersj2 386: =item * $middletext, the text which appears between the <select> tags
1.36 matthew 387:
1.112 bowersj2 388: =item * $firstdefault, the default value for the first menu
1.36 matthew 389:
1.112 bowersj2 390: =item * $firstselectname, the name of the first <select> tag
1.36 matthew 391:
1.112 bowersj2 392: =item * $secondselectname, the name of the second <select> tag
1.36 matthew 393:
1.112 bowersj2 394: =item * $hashref, a reference to a hash containing the data for the menus.
1.36 matthew 395:
1.41 ng 396: =back
397:
1.36 matthew 398: Below is an example of such a hash. Only the 'text', 'default', and
399: 'select2' keys must appear as stated. keys(%menu) are the possible
400: values for the first select menu. The text that coincides with the
1.41 ng 401: first menu value is given in $menu{$choice1}->{'text'}. The values
1.36 matthew 402: and text for the second menu are given in the hash pointed to by
403: $menu{$choice1}->{'select2'}.
404:
1.112 bowersj2 405: my %menu = ( A1 => { text =>"Choice A1" ,
406: default => "B3",
407: select2 => {
408: B1 => "Choice B1",
409: B2 => "Choice B2",
410: B3 => "Choice B3",
411: B4 => "Choice B4"
412: }
413: },
414: A2 => { text =>"Choice A2" ,
415: default => "C2",
416: select2 => {
417: C1 => "Choice C1",
418: C2 => "Choice C2",
419: C3 => "Choice C3"
420: }
421: },
422: A3 => { text =>"Choice A3" ,
423: default => "D6",
424: select2 => {
425: D1 => "Choice D1",
426: D2 => "Choice D2",
427: D3 => "Choice D3",
428: D4 => "Choice D4",
429: D5 => "Choice D5",
430: D6 => "Choice D6",
431: D7 => "Choice D7"
432: }
433: }
434: );
1.36 matthew 435:
436: =cut
437:
438: sub linked_select_forms {
439: my ($formname,
440: $middletext,
441: $firstdefault,
442: $firstselectname,
443: $secondselectname,
444: $hashref
445: ) = @_;
446: my $second = "document.$formname.$secondselectname";
447: my $first = "document.$formname.$firstselectname";
448: # output the javascript to do the changing
449: my $result = '';
450: $result.="<script>\n";
451: $result.="var select2data = new Object();\n";
452: $" = '","';
453: my $debug = '';
454: foreach my $s1 (sort(keys(%$hashref))) {
455: $result.="select2data.d_$s1 = new Object();\n";
456: $result.="select2data.d_$s1.def = new String('".
457: $hashref->{$s1}->{'default'}."');\n";
458: $result.="select2data.d_$s1.values = new Array(";
459: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
460: $result.="\"@s2values\");\n";
461: $result.="select2data.d_$s1.texts = new Array(";
462: my @s2texts;
463: foreach my $value (@s2values) {
464: push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
465: }
466: $result.="\"@s2texts\");\n";
467: }
468: $"=' ';
469: $result.= <<"END";
470:
471: function select1_changed() {
472: // Determine new choice
473: var newvalue = "d_" + $first.value;
474: // update select2
475: var values = select2data[newvalue].values;
476: var texts = select2data[newvalue].texts;
477: var select2def = select2data[newvalue].def;
478: var i;
479: // out with the old
480: for (i = 0; i < $second.options.length; i++) {
481: $second.options[i] = null;
482: }
483: // in with the nuclear
484: for (i=0;i<values.length; i++) {
485: $second.options[i] = new Option(values[i]);
1.143 matthew 486: $second.options[i].value = values[i];
1.36 matthew 487: $second.options[i].text = texts[i];
488: if (values[i] == select2def) {
489: $second.options[i].selected = true;
490: }
491: }
492: }
493: </script>
494: END
495: # output the initial values for the selection lists
496: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
497: foreach my $value (sort(keys(%$hashref))) {
498: $result.=" <option value=\"$value\" ";
499: $result.=" selected=\"true\" " if ($value eq $firstdefault);
1.119 www 500: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36 matthew 501: }
502: $result .= "</select>\n";
503: my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
504: $result .= $middletext;
505: $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
506: my $seconddefault = $hashref->{$firstdefault}->{'default'};
507: foreach my $value (sort(keys(%select2))) {
508: $result.=" <option value=\"$value\" ";
509: $result.=" selected=\"true\" " if ($value eq $seconddefault);
1.119 www 510: $result.=">".&mt($select2{$value})."</option>\n";
1.36 matthew 511: }
512: $result .= "</select>\n";
513: # return $debug;
514: return $result;
515: } # end of sub linked_select_forms {
516:
1.45 matthew 517: =pod
1.44 bowersj2 518:
1.112 bowersj2 519: =item * help_open_topic($topic, $text, $stayOnPage, $width, $height)
1.44 bowersj2 520:
1.112 bowersj2 521: Returns a string corresponding to an HTML link to the given help
522: $topic, where $topic corresponds to the name of a .tex file in
523: /home/httpd/html/adm/help/tex, with underscores replaced by
524: spaces.
525:
526: $text will optionally be linked to the same topic, allowing you to
527: link text in addition to the graphic. If you do not want to link
528: text, but wish to specify one of the later parameters, pass an
529: empty string.
530:
531: $stayOnPage is a value that will be interpreted as a boolean. If true,
532: the link will not open a new window. If false, the link will open
533: a new window using Javascript. (Default is false.)
534:
535: $width and $height are optional numerical parameters that will
536: override the width and height of the popped up window, which may
537: be useful for certain help topics with big pictures included.
1.44 bowersj2 538:
539: =cut
540:
541: sub help_open_topic {
1.48 bowersj2 542: my ($topic, $text, $stayOnPage, $width, $height) = @_;
543: $text = "" if (not defined $text);
1.44 bowersj2 544: $stayOnPage = 0 if (not defined $stayOnPage);
1.108 bowersj2 545: if ($ENV{'browser.interface'} eq 'textual' ||
546: $ENV{'environment.remote'} eq 'off' ) {
1.79 www 547: $stayOnPage=1;
548: }
1.44 bowersj2 549: $width = 350 if (not defined $width);
550: $height = 400 if (not defined $height);
551: my $filename = $topic;
552: $filename =~ s/ /_/g;
553:
1.48 bowersj2 554: my $template = "";
555: my $link;
1.159 www 556:
557: $topic=~s/\W/\_/g;
1.44 bowersj2 558:
559: if (!$stayOnPage)
560: {
1.72 bowersj2 561: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1.44 bowersj2 562: }
563: else
564: {
1.48 bowersj2 565: $link = "/adm/help/${filename}.hlp";
566: }
567:
568: # Add the text
569: if ($text ne "")
570: {
1.77 www 571: $template .=
572: "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
1.78 www 573: "<td bgcolor='#5555FF'><a href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
1.48 bowersj2 574: }
575:
576: # Add the graphic
577: $template .= <<"ENDTEMPLATE";
1.77 www 578: <a href="$link"><image src="/adm/help/gif/smallHelp.gif" border="0" alt="(Help: $topic)" /></a>
1.44 bowersj2 579: ENDTEMPLATE
1.78 www 580: if ($text ne '') { $template.='</td></tr></table>' };
1.44 bowersj2 581: return $template;
582:
1.106 bowersj2 583: }
584:
585: # This is a quicky function for Latex cheatsheet editing, since it
586: # appears in at least four places
587: sub helpLatexCheatsheet {
588: my $other = shift;
589: my $addOther = '';
590: if ($other) {
591: $addOther = Apache::loncommon::help_open_topic($other, shift,
592: undef, undef, 600) .
593: '</td><td>';
594: }
595: return '<table><tr><td>'.
596: $addOther .
597: &Apache::loncommon::help_open_topic("Greek_Symbols",'Greek Symbols',
598: undef,undef,600)
599: .'</td><td>'.
600: &Apache::loncommon::help_open_topic("Other_Symbols",'Other Symbols',
601: undef,undef,600)
602: .'</td></tr></table>';
1.44 bowersj2 603: }
1.37 matthew 604:
1.45 matthew 605: =pod
606:
1.112 bowersj2 607: =item * csv_translate($text)
1.37 matthew 608:
609: Translate $text to allow it to be output as a 'comma seperated values'
610: format.
611:
612: =cut
613:
614: sub csv_translate {
615: my $text = shift;
616: $text =~ s/\"/\"\"/g;
617: $text =~ s/\n//g;
618: return $text;
619: }
1.113 bowersj2 620:
621: =pod
622:
623: =item * change_content_javascript():
624:
625: This and the next function allow you to create small sections of an
626: otherwise static HTML page that you can update on the fly with
627: Javascript, even in Netscape 4.
628:
629: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
630: must be written to the HTML page once. It will prove the Javascript
631: function "change(name, content)". Calling the change function with the
632: name of the section
633: you want to update, matching the name passed to C<changable_area>, and
634: the new content you want to put in there, will put the content into
635: that area.
636:
637: B<Note>: Netscape 4 only reserves enough space for the changable area
638: to contain room for the original contents. You need to "make space"
639: for whatever changes you wish to make, and be B<sure> to check your
640: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
641: it's adequate for updating a one-line status display, but little more.
642: This script will set the space to 100% width, so you only need to
643: worry about height in Netscape 4.
644:
645: Modern browsers are much less limiting, and if you can commit to the
646: user not using Netscape 4, this feature may be used freely with
647: pretty much any HTML.
648:
649: =cut
650:
651: sub change_content_javascript {
652: # If we're on Netscape 4, we need to use Layer-based code
653: if ($ENV{'browser.type'} eq 'netscape' &&
654: $ENV{'browser.version'} =~ /^4\./) {
655: return (<<NETSCAPE4);
656: function change(name, content) {
657: doc = document.layers[name+"___escape"].layers[0].document;
658: doc.open();
659: doc.write(content);
660: doc.close();
661: }
662: NETSCAPE4
663: } else {
664: # Otherwise, we need to use semi-standards-compliant code
665: # (technically, "innerHTML" isn't standard but the equivalent
666: # is really scary, and every useful browser supports it
667: return (<<DOMBASED);
668: function change(name, content) {
669: element = document.getElementById(name);
670: element.innerHTML = content;
671: }
672: DOMBASED
673: }
674: }
675:
676: =pod
677:
678: =item * changable_area($name, $origContent):
679:
680: This provides a "changable area" that can be modified on the fly via
681: the Javascript code provided in C<change_content_javascript>. $name is
682: the name you will use to reference the area later; do not repeat the
683: same name on a given HTML page more then once. $origContent is what
684: the area will originally contain, which can be left blank.
685:
686: =cut
687:
688: sub changable_area {
689: my ($name, $origContent) = @_;
690:
691: if ($ENV{'browser.type'} eq 'netscape' &&
692: $ENV{'browser.version'} =~ /^4\./) {
693: # If this is netscape 4, we need to use the Layer tag
694: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
695: } else {
696: return "<span id='$name'>$origContent</span>";
697: }
698: }
699:
700: =pod
701:
702: =back
703:
704: =cut
1.37 matthew 705:
706: ###############################################################
1.33 matthew 707: ## Home server <option> list generating code ##
708: ###############################################################
1.35 matthew 709:
1.45 matthew 710: =pod
711:
1.112 bowersj2 712: =head1 Home Server option list generating code
713:
714: =over 4
715:
716: =item * get_domains()
1.35 matthew 717:
718: Returns an array containing each of the domains listed in the hosts.tab
719: file.
720:
721: =cut
722:
723: #-------------------------------------------
1.34 matthew 724: sub get_domains {
725: # The code below was stolen from "The Perl Cookbook", p 102, 1st ed.
726: my @domains;
727: my %seen;
728: foreach (sort values(%Apache::lonnet::hostdom)) {
729: push (@domains,$_) unless $seen{$_}++;
730: }
731: return @domains;
732: }
1.88 www 733:
734: #-------------------------------------------
735:
736: =pod
737:
1.112 bowersj2 738: =item * select_form($defdom,$name,%hash)
1.88 www 739:
740: Returns a string containing a <select name='$name' size='1'> form to
741: allow a user to select options from a hash option_name => displayed text.
742: See lonrights.pm for an example invocation and use.
743:
744: =cut
745:
746: #-------------------------------------------
747: sub select_form {
748: my ($def,$name,%hash) = @_;
749: my $selectform = "<select name=\"$name\" size=\"1\">\n";
1.128 albertel 750: my @keys;
751: if (exists($hash{'select_form_order'})) {
752: @keys=@{$hash{'select_form_order'}};
753: } else {
754: @keys=sort(keys(%hash));
755: }
756: foreach (@keys) {
1.88 www 757: $selectform.="<option value=\"$_\" ".
758: ($_ eq $def ? 'selected' : '').
1.119 www 759: ">".&mt($hash{$_})."</option>\n";
1.88 www 760: }
761: $selectform.="</select>";
762: return $selectform;
763: }
764:
1.34 matthew 765:
1.35 matthew 766: #-------------------------------------------
767:
1.45 matthew 768: =pod
769:
1.112 bowersj2 770: =item * select_dom_form($defdom,$name,$includeempty)
1.35 matthew 771:
772: Returns a string containing a <select name='$name' size='1'> form to
773: allow a user to select the domain to preform an operation in.
774: See loncreateuser.pm for an example invocation and use.
775:
1.90 www 776: If the $includeempty flag is set, it also includes an empty choice ("no domain
777: selected");
778:
1.35 matthew 779: =cut
780:
781: #-------------------------------------------
1.34 matthew 782: sub select_dom_form {
1.90 www 783: my ($defdom,$name,$includeempty) = @_;
1.34 matthew 784: my @domains = get_domains();
1.90 www 785: if ($includeempty) { @domains=('',@domains); }
1.34 matthew 786: my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
787: foreach (@domains) {
788: $selectdomain.="<option value=\"$_\" ".
789: ($_ eq $defdom ? 'selected' : '').
790: ">$_</option>\n";
791: }
792: $selectdomain.="</select>";
793: return $selectdomain;
794: }
795:
1.35 matthew 796: #-------------------------------------------
797:
1.45 matthew 798: =pod
799:
1.112 bowersj2 800: =item * get_library_servers($domain)
1.35 matthew 801:
802: Returns a hash which contains keys like '103l3' and values like
803: 'kirk.lite.msu.edu'. All of the keys will be for machines in the
804: given $domain.
805:
806: =cut
807:
808: #-------------------------------------------
1.52 matthew 809: sub get_library_servers {
1.33 matthew 810: my $domain = shift;
1.52 matthew 811: my %library_servers;
1.33 matthew 812: foreach (keys(%Apache::lonnet::libserv)) {
813: if ($Apache::lonnet::hostdom{$_} eq $domain) {
1.52 matthew 814: $library_servers{$_} = $Apache::lonnet::hostname{$_};
1.33 matthew 815: }
816: }
1.52 matthew 817: return %library_servers;
1.33 matthew 818: }
819:
1.35 matthew 820: #-------------------------------------------
821:
1.45 matthew 822: =pod
823:
1.112 bowersj2 824: =item * home_server_option_list($domain)
1.35 matthew 825:
826: returns a string which contains an <option> list to be used in a
827: <select> form input. See loncreateuser.pm for an example.
828:
829: =cut
830:
831: #-------------------------------------------
1.33 matthew 832: sub home_server_option_list {
833: my $domain = shift;
1.52 matthew 834: my %servers = &get_library_servers($domain);
1.33 matthew 835: my $result = '';
836: foreach (sort keys(%servers)) {
837: $result.=
838: '<option value="'.$_.'">'.$_.' '.$servers{$_}."</option>\n";
839: }
840: return $result;
841: }
1.112 bowersj2 842:
843: =pod
844:
845: =back
846:
847: =cut
1.87 matthew 848:
849: ###############################################################
1.112 bowersj2 850: ## Decoding User Agent ##
1.87 matthew 851: ###############################################################
852:
853: =pod
854:
1.112 bowersj2 855: =head1 Decoding the User Agent
856:
857: =over 4
858:
859: =item * &decode_user_agent()
1.87 matthew 860:
861: Inputs: $r
862:
863: Outputs:
864:
865: =over 4
866:
1.112 bowersj2 867: =item * $httpbrowser
1.87 matthew 868:
1.112 bowersj2 869: =item * $clientbrowser
1.87 matthew 870:
1.112 bowersj2 871: =item * $clientversion
1.87 matthew 872:
1.112 bowersj2 873: =item * $clientmathml
1.87 matthew 874:
1.112 bowersj2 875: =item * $clientunicode
1.87 matthew 876:
1.112 bowersj2 877: =item * $clientos
1.87 matthew 878:
879: =back
880:
1.157 matthew 881: =back
882:
1.87 matthew 883: =cut
884:
885: ###############################################################
886: ###############################################################
887: sub decode_user_agent {
888: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
889: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
890: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
891: my $clientbrowser='unknown';
892: my $clientversion='0';
893: my $clientmathml='';
894: my $clientunicode='0';
895: for (my $i=0;$i<=$#browsertype;$i++) {
896: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
897: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
898: $clientbrowser=$bname;
899: $httpbrowser=~/$vreg/i;
900: $clientversion=$1;
901: $clientmathml=($clientversion>=$minv);
902: $clientunicode=($clientversion>=$univ);
903: }
904: }
905: my $clientos='unknown';
906: if (($httpbrowser=~/linux/i) ||
907: ($httpbrowser=~/unix/i) ||
908: ($httpbrowser=~/ux/i) ||
909: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
910: if (($httpbrowser=~/vax/i) ||
911: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
912: if ($httpbrowser=~/next/i) { $clientos='next'; }
913: if (($httpbrowser=~/mac/i) ||
914: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
915: if ($httpbrowser=~/win/i) { $clientos='win'; }
916: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
917: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
918: $clientunicode,$clientos,);
919: }
920:
1.32 matthew 921: ###############################################################
922: ## Authentication changing form generation subroutines ##
923: ###############################################################
924: ##
925: ## All of the authform_xxxxxxx subroutines take their inputs in a
926: ## hash, and have reasonable default values.
927: ##
928: ## formname = the name given in the <form> tag.
1.35 matthew 929: #-------------------------------------------
930:
1.45 matthew 931: =pod
932:
1.112 bowersj2 933: =head1 Authentication Routines
934:
935: =over 4
936:
937: =item * authform_xxxxxx
1.35 matthew 938:
939: The authform_xxxxxx subroutines provide javascript and html forms which
940: handle some of the conveniences required for authentication forms.
941: This is not an optimal method, but it works.
942:
943: See loncreateuser.pm for invocation and use examples.
944:
945: =over 4
946:
1.112 bowersj2 947: =item * authform_header
1.35 matthew 948:
1.112 bowersj2 949: =item * authform_authorwarning
1.35 matthew 950:
1.112 bowersj2 951: =item * authform_nochange
1.35 matthew 952:
1.112 bowersj2 953: =item * authform_kerberos
1.35 matthew 954:
1.112 bowersj2 955: =item * authform_internal
1.35 matthew 956:
1.112 bowersj2 957: =item * authform_filesystem
1.35 matthew 958:
959: =back
960:
1.157 matthew 961: =back
962:
1.35 matthew 963: =cut
964:
965: #-------------------------------------------
1.32 matthew 966: sub authform_header{
967: my %in = (
968: formname => 'cu',
1.80 albertel 969: kerb_def_dom => '',
1.32 matthew 970: @_,
971: );
972: $in{'formname'} = 'document.' . $in{'formname'};
973: my $result='';
1.80 albertel 974:
975: #---------------------------------------------- Code for upper case translation
976: my $Javascript_toUpperCase;
977: unless ($in{kerb_def_dom}) {
978: $Javascript_toUpperCase =<<"END";
979: switch (choice) {
980: case 'krb': currentform.elements[choicearg].value =
981: currentform.elements[choicearg].value.toUpperCase();
982: break;
983: default:
984: }
985: END
986: } else {
987: $Javascript_toUpperCase = "";
988: }
989:
1.32 matthew 990: $result.=<<"END";
991: var current = new Object();
992: current.radiovalue = 'nochange';
993: current.argfield = null;
994:
995: function changed_radio(choice,currentform) {
996: var choicearg = choice + 'arg';
997: // If a radio button in changed, we need to change the argfield
998: if (current.radiovalue != choice) {
999: current.radiovalue = choice;
1000: if (current.argfield != null) {
1001: currentform.elements[current.argfield].value = '';
1002: }
1003: if (choice == 'nochange') {
1004: current.argfield = null;
1005: } else {
1006: current.argfield = choicearg;
1007: switch(choice) {
1008: case 'krb':
1009: currentform.elements[current.argfield].value =
1010: "$in{'kerb_def_dom'}";
1011: break;
1012: default:
1013: break;
1014: }
1015: }
1016: }
1017: return;
1018: }
1.22 www 1019:
1.32 matthew 1020: function changed_text(choice,currentform) {
1021: var choicearg = choice + 'arg';
1022: if (currentform.elements[choicearg].value !='') {
1.80 albertel 1023: $Javascript_toUpperCase
1.32 matthew 1024: // clear old field
1025: if ((current.argfield != choicearg) && (current.argfield != null)) {
1026: currentform.elements[current.argfield].value = '';
1027: }
1028: current.argfield = choicearg;
1029: }
1030: set_auth_radio_buttons(choice,currentform);
1031: return;
1.20 www 1032: }
1.32 matthew 1033:
1034: function set_auth_radio_buttons(newvalue,currentform) {
1035: var i=0;
1036: while (i < currentform.login.length) {
1037: if (currentform.login[i].value == newvalue) { break; }
1038: i++;
1039: }
1040: if (i == currentform.login.length) {
1041: return;
1042: }
1043: current.radiovalue = newvalue;
1044: currentform.login[i].checked = true;
1045: return;
1046: }
1047: END
1048: return $result;
1049: }
1050:
1051: sub authform_authorwarning{
1052: my $result='';
1.144 matthew 1053: $result='<i>'.
1054: &mt('As a general rule, only authors or co-authors should be '.
1055: 'filesystem authenticated '.
1056: '(which allows access to the server filesystem).')."</i>\n";
1.32 matthew 1057: return $result;
1058: }
1059:
1060: sub authform_nochange{
1061: my %in = (
1062: formname => 'document.cu',
1063: kerb_def_dom => 'MSU.EDU',
1064: @_,
1065: );
1.144 matthew 1066: my $result = &mt('[_1] Do not change login data',
1067: '<input type="radio" name="login" value="nochange" '.
1068: 'checked="checked" onclick="'.
1069: "javascript:changed_radio('nochange',$in{'formname'});".'" />');
1.32 matthew 1070: return $result;
1071: }
1072:
1073: sub authform_kerberos{
1074: my %in = (
1075: formname => 'document.cu',
1076: kerb_def_dom => 'MSU.EDU',
1.80 albertel 1077: kerb_def_auth => 'krb4',
1.32 matthew 1078: @_,
1079: );
1.144 matthew 1080: my ($check4,$check5);
1.80 albertel 1081: if ($in{'kerb_def_auth'} eq 'krb5') {
1082: $check5 = " checked=\"on\"";
1083: } else {
1084: $check4 = " checked=\"on\"";
1085: }
1.144 matthew 1086: my $jscall = "javascript:changed_radio('krb',$in{'formname'});";
1087: my $result .= &mt
1088: ('[_1] Kerberos authenticated with domain [_2] '.
1089: '[_3] Version 4 [_4] Version 5',
1090: '<input type="radio" name="login" value="krb" '.
1091: 'onclick="'.$jscall.'" onchange="'.$jscall.'" />',
1092: '<input type="text" size="10" name="krbarg" '.
1093: 'value="'.$in{'kerb_def_dom'}.'" '.
1094: 'onchange="'.$jscall.'" />',
1095: '<input type="radio" name="krbver" value="4" '.$check4.' />',
1096: '<input type="radio" name="krbver" value="5" '.$check5.' />');
1.32 matthew 1097: return $result;
1098: }
1099:
1100: sub authform_internal{
1101: my %args = (
1102: formname => 'document.cu',
1103: kerb_def_dom => 'MSU.EDU',
1104: @_,
1105: );
1.144 matthew 1106: my $jscall = "javascript:changed_radio('int',$args{'formname'});";
1107: my $result.=&mt
1108: ('[_1] Internally authenticated (with initial password [_2])',
1109: '<input type="radio" name="login" value="int" '.
1110: 'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1111: '<input type="text" size="10" name="intarg" value="" '.
1112: 'onchange="'.$jscall.'" />');
1.32 matthew 1113: return $result;
1114: }
1115:
1116: sub authform_local{
1117: my %in = (
1118: formname => 'document.cu',
1119: kerb_def_dom => 'MSU.EDU',
1120: @_,
1121: );
1.144 matthew 1122: my $jscall = "javascript:changed_radio('loc',$in{'formname'});";
1.160 matthew 1123: my $result.=&mt('[_1] Local Authentication with argument [_2]',
1.144 matthew 1124: '<input type="radio" name="login" value="loc" '.
1125: 'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1126: '<input type="text" size="10" name="locarg" value="" '.
1127: 'onchange="'.$jscall.'" />');
1.32 matthew 1128: return $result;
1129: }
1130:
1131: sub authform_filesystem{
1132: my %in = (
1133: formname => 'document.cu',
1134: kerb_def_dom => 'MSU.EDU',
1135: @_,
1136: );
1.144 matthew 1137: my $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
1138: my $result.= &mt
1139: ('[_1] Filesystem Authenticated (with initial password [_2])',
1140: '<input type="radio" name="login" value="fsys" '.
1141: 'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1142: '<input type="text" size="10" name="fsysarg" value="" '.
1143: 'onchange="'.$jscall.'" />');
1.32 matthew 1144: return $result;
1145: }
1146:
1.80 albertel 1147: ###############################################################
1148: ## Get Authentication Defaults for Domain ##
1149: ###############################################################
1150:
1151: =pod
1152:
1.112 bowersj2 1153: =head1 Domains and Authentication
1154:
1155: Returns default authentication type and an associated argument as
1156: listed in file 'domain.tab'.
1157:
1158: =over 4
1159:
1160: =item * get_auth_defaults
1.80 albertel 1161:
1162: get_auth_defaults($target_domain) returns the default authentication
1163: type and an associated argument (initial password or a kerberos domain).
1164: These values are stored in lonTabs/domain.tab
1165:
1166: ($def_auth, $def_arg) = &get_auth_defaults($target_domain);
1167:
1168: If target_domain is not found in domain.tab, returns nothing ('').
1169:
1170: =cut
1171:
1172: #-------------------------------------------
1173: sub get_auth_defaults {
1174: my $domain=shift;
1175: return ($Apache::lonnet::domain_auth_def{$domain},$Apache::lonnet::domain_auth_arg_def{$domain});
1176: }
1177: ###############################################################
1178: ## End Get Authentication Defaults for Domain ##
1179: ###############################################################
1180:
1181: ###############################################################
1182: ## Get Kerberos Defaults for Domain ##
1183: ###############################################################
1184: ##
1185: ## Returns default kerberos version and an associated argument
1186: ## as listed in file domain.tab. If not listed, provides
1187: ## appropriate default domain and kerberos version.
1188: ##
1189: #-------------------------------------------
1190:
1191: =pod
1192:
1.112 bowersj2 1193: =item * get_kerberos_defaults
1.80 albertel 1194:
1195: get_kerberos_defaults($target_domain) returns the default kerberos
1196: version and domain. If not found in domain.tabs, it defaults to
1197: version 4 and the domain of the server.
1198:
1199: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
1200:
1201: =cut
1202:
1203: #-------------------------------------------
1204: sub get_kerberos_defaults {
1205: my $domain=shift;
1206: my ($krbdef,$krbdefdom) =
1207: &Apache::loncommon::get_auth_defaults($domain);
1208: unless ($krbdef =~/^krb/ && $krbdefdom) {
1209: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
1210: my $krbdefdom=$1;
1211: $krbdefdom=~tr/a-z/A-Z/;
1212: $krbdef = "krb4";
1213: }
1214: return ($krbdef,$krbdefdom);
1215: }
1.112 bowersj2 1216:
1217: =pod
1218:
1219: =back
1220:
1221: =cut
1.32 matthew 1222:
1.46 matthew 1223: ###############################################################
1224: ## Thesaurus Functions ##
1225: ###############################################################
1.20 www 1226:
1.46 matthew 1227: =pod
1.20 www 1228:
1.112 bowersj2 1229: =head1 Thesaurus Functions
1230:
1231: =over 4
1232:
1233: =item * initialize_keywords
1.46 matthew 1234:
1235: Initializes the package variable %Keywords if it is empty. Uses the
1236: package variable $thesaurus_db_file.
1237:
1238: =cut
1239:
1240: ###################################################
1241:
1242: sub initialize_keywords {
1243: return 1 if (scalar keys(%Keywords));
1244: # If we are here, %Keywords is empty, so fill it up
1245: # Make sure the file we need exists...
1246: if (! -e $thesaurus_db_file) {
1247: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
1248: " failed because it does not exist");
1249: return 0;
1250: }
1251: # Set up the hash as a database
1252: my %thesaurus_db;
1253: if (! tie(%thesaurus_db,'GDBM_File',
1.53 albertel 1254: $thesaurus_db_file,&GDBM_READER(),0640)){
1.46 matthew 1255: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
1256: $thesaurus_db_file);
1257: return 0;
1258: }
1259: # Get the average number of appearances of a word.
1260: my $avecount = $thesaurus_db{'average.count'};
1261: # Put keywords (those that appear > average) into %Keywords
1262: while (my ($word,$data)=each (%thesaurus_db)) {
1263: my ($count,undef) = split /:/,$data;
1264: $Keywords{$word}++ if ($count > $avecount);
1265: }
1266: untie %thesaurus_db;
1267: # Remove special values from %Keywords.
1268: foreach ('total.count','average.count') {
1269: delete($Keywords{$_}) if (exists($Keywords{$_}));
1270: }
1271: return 1;
1272: }
1273:
1274: ###################################################
1275:
1276: =pod
1277:
1.112 bowersj2 1278: =item * keyword($word)
1.46 matthew 1279:
1280: Returns true if $word is a keyword. A keyword is a word that appears more
1281: than the average number of times in the thesaurus database. Calls
1282: &initialize_keywords
1283:
1284: =cut
1285:
1286: ###################################################
1.20 www 1287:
1288: sub keyword {
1.46 matthew 1289: return if (!&initialize_keywords());
1290: my $word=lc(shift());
1291: $word=~s/\W//g;
1292: return exists($Keywords{$word});
1.20 www 1293: }
1.46 matthew 1294:
1295: ###############################################################
1296:
1297: =pod
1.20 www 1298:
1.112 bowersj2 1299: =item * get_related_words
1.46 matthew 1300:
1.160 matthew 1301: Look up a word in the thesaurus. Takes a scalar argument and returns
1.46 matthew 1302: an array of words. If the keyword is not in the thesaurus, an empty array
1303: will be returned. The order of the words returned is determined by the
1304: database which holds them.
1305:
1306: Uses global $thesaurus_db_file.
1307:
1308: =cut
1309:
1310: ###############################################################
1311: sub get_related_words {
1312: my $keyword = shift;
1313: my %thesaurus_db;
1314: if (! -e $thesaurus_db_file) {
1315: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
1316: "failed because the file does not exist");
1317: return ();
1318: }
1319: if (! tie(%thesaurus_db,'GDBM_File',
1.53 albertel 1320: $thesaurus_db_file,&GDBM_READER(),0640)){
1.46 matthew 1321: return ();
1322: }
1323: my @Words=();
1324: if (exists($thesaurus_db{$keyword})) {
1325: $_ = $thesaurus_db{$keyword};
1326: (undef,@Words) = split/:/; # The first element is the number of times
1327: # the word appears. We do not need it now.
1328: for (my $i=0;$i<=$#Words;$i++) {
1329: ($Words[$i],undef)= split/\,/,$Words[$i];
1.20 www 1330: }
1331: }
1.46 matthew 1332: untie %thesaurus_db;
1333: return @Words;
1.14 harris41 1334: }
1.46 matthew 1335:
1.112 bowersj2 1336: =pod
1337:
1338: =back
1339:
1340: =cut
1.61 www 1341:
1342: # -------------------------------------------------------------- Plaintext name
1.81 albertel 1343: =pod
1344:
1.112 bowersj2 1345: =head1 User Name Functions
1346:
1347: =over 4
1348:
1349: =item * plainname($uname,$udom)
1.81 albertel 1350:
1.112 bowersj2 1351: Takes a users logon name and returns it as a string in
1352: "first middle last generation" form
1.81 albertel 1353:
1354: =cut
1.61 www 1355:
1.81 albertel 1356: ###############################################################
1.61 www 1357: sub plainname {
1358: my ($uname,$udom)=@_;
1359: my %names=&Apache::lonnet::get('environment',
1360: ['firstname','middlename','lastname','generation'],
1361: $udom,$uname);
1.62 www 1362: my $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
1.61 www 1363: $names{'lastname'}.' '.$names{'generation'};
1.62 www 1364: $name=~s/\s+$//;
1365: $name=~s/\s+/ /g;
1366: return $name;
1.61 www 1367: }
1.66 www 1368:
1369: # -------------------------------------------------------------------- Nickname
1.81 albertel 1370: =pod
1371:
1.112 bowersj2 1372: =item * nickname($uname,$udom)
1.81 albertel 1373:
1374: Gets a users name and returns it as a string as
1375:
1376: ""nickname""
1.66 www 1377:
1.81 albertel 1378: if the user has a nickname or
1379:
1380: "first middle last generation"
1381:
1382: if the user does not
1383:
1384: =cut
1.66 www 1385:
1386: sub nickname {
1387: my ($uname,$udom)=@_;
1388: my %names=&Apache::lonnet::get('environment',
1389: ['nickname','firstname','middlename','lastname','generation'],$udom,$uname);
1.68 albertel 1390: my $name=$names{'nickname'};
1.66 www 1391: if ($name) {
1392: $name='"'.$name.'"';
1393: } else {
1394: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
1395: $names{'lastname'}.' '.$names{'generation'};
1396: $name=~s/\s+$//;
1397: $name=~s/\s+/ /g;
1398: }
1399: return $name;
1400: }
1401:
1.61 www 1402:
1403: # ------------------------------------------------------------------ Screenname
1.81 albertel 1404:
1405: =pod
1406:
1.112 bowersj2 1407: =item * screenname($uname,$udom)
1.81 albertel 1408:
1409: Gets a users screenname and returns it as a string
1410:
1411: =cut
1.61 www 1412:
1413: sub screenname {
1414: my ($uname,$udom)=@_;
1415: my %names=
1416: &Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68 albertel 1417: return $names{'screenname'};
1.62 www 1418: }
1419:
1420: # ------------------------------------------------------------- Message Wrapper
1421:
1422: sub messagewrapper {
1423: my ($link,$un,$do)=@_;
1424: return
1425: "<a href='/adm/email?compose=individual&recname=$un&recdom=$do'>$link</a>";
1.74 www 1426: }
1427: # --------------------------------------------------------------- Notes Wrapper
1428:
1429: sub noteswrapper {
1430: my ($link,$un,$do)=@_;
1431: return
1432: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
1.62 www 1433: }
1434: # ------------------------------------------------------------- Aboutme Wrapper
1435:
1436: sub aboutmewrapper {
1.69 matthew 1437: my ($link,$username,$domain)=@_;
1438: return "<a href='/adm/$domain/$username/aboutme'>$link</a>";
1.62 www 1439: }
1440:
1441: # ------------------------------------------------------------ Syllabus Wrapper
1442:
1443:
1444: sub syllabuswrapper {
1.109 matthew 1445: my ($linktext,$coursedir,$domain,$fontcolor)=@_;
1446: if ($fontcolor) {
1447: $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>';
1448: }
1449: return "<a href='/public/$domain/$coursedir/syllabus'>$linktext</a>";
1.61 www 1450: }
1.14 harris41 1451:
1.112 bowersj2 1452: =pod
1453:
1454: =back
1455:
1456: =head1 Access .tab File Data
1457:
1458: =over 4
1459:
1460: =item * languageids()
1461:
1462: returns list of all language ids
1463:
1464: =cut
1465:
1.14 harris41 1466: sub languageids {
1.16 harris41 1467: return sort(keys(%language));
1.14 harris41 1468: }
1469:
1.112 bowersj2 1470: =pod
1471:
1472: =item * languagedescription()
1473:
1474: returns description of a specified language id
1475:
1476: =cut
1477:
1.14 harris41 1478: sub languagedescription {
1.125 www 1479: my $code=shift;
1480: return ($supported_language{$code}?'* ':'').
1481: $language{$code}.
1.126 www 1482: ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145 www 1483: }
1484:
1485: sub plainlanguagedescription {
1486: my $code=shift;
1487: return $language{$code};
1488: }
1489:
1490: sub supportedlanguagecode {
1491: my $code=shift;
1492: return $supported_language{$code};
1.97 www 1493: }
1494:
1.112 bowersj2 1495: =pod
1496:
1497: =item * copyrightids()
1498:
1499: returns list of all copyrights
1500:
1501: =cut
1502:
1503: sub copyrightids {
1504: return sort(keys(%cprtag));
1505: }
1506:
1507: =pod
1508:
1509: =item * copyrightdescription()
1510:
1511: returns description of a specified copyright id
1512:
1513: =cut
1514:
1515: sub copyrightdescription {
1516: return $cprtag{shift(@_)};
1517: }
1518:
1519: =pod
1520:
1521: =item * filecategories()
1522:
1523: returns list of all file categories
1524:
1525: =cut
1526:
1527: sub filecategories {
1528: return sort(keys(%category_extensions));
1529: }
1530:
1531: =pod
1532:
1533: =item * filecategorytypes()
1534:
1535: returns list of file types belonging to a given file
1536: category
1537:
1538: =cut
1539:
1540: sub filecategorytypes {
1541: return @{$category_extensions{lc($_[0])}};
1542: }
1543:
1544: =pod
1545:
1546: =item * fileembstyle()
1547:
1548: returns embedding style for a specified file type
1549:
1550: =cut
1551:
1552: sub fileembstyle {
1553: return $fe{lc(shift(@_))};
1554: }
1555:
1556: =pod
1557:
1558: =item * filedescription()
1559:
1560: returns description for a specified file type
1561:
1562: =cut
1563:
1564: sub filedescription {
1565: return $fd{lc(shift(@_))};
1566: }
1567:
1568: =pod
1569:
1570: =item * filedescriptionex()
1571:
1572: returns description for a specified file type with
1573: extra formatting
1574:
1575: =cut
1576:
1577: sub filedescriptionex {
1578: my $ex=shift;
1579: return '.'.$ex.' '.$fd{lc($ex)};
1580: }
1581:
1582: # End of .tab access
1583: =pod
1584:
1585: =back
1586:
1587: =cut
1588:
1589: # ------------------------------------------------------------------ File Types
1590: sub fileextensions {
1591: return sort(keys(%fe));
1592: }
1593:
1.97 www 1594: # ----------------------------------------------------------- Display Languages
1595: # returns a hash with all desired display languages
1596: #
1597:
1598: sub display_languages {
1599: my %languages=();
1.118 www 1600: foreach (&preferred_languages()) {
1601: $languages{$_}=1;
1.97 www 1602: }
1603: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1604: if ($ENV{'form.displaylanguage'}) {
1605: foreach (split(/\s*(\,|\;|\:)\s*/,$ENV{'form.displaylanguage'})) {
1606: $languages{$_}=1;
1607: }
1608: }
1609: return %languages;
1.14 harris41 1610: }
1611:
1.117 www 1612: sub preferred_languages {
1613: my @languages=();
1614: if ($ENV{'environment.languages'}) {
1615: @languages=split(/\s*(\,|\;|\:)\s*/,$ENV{'environment.languages'});
1616: }
1617: if ($ENV{'course.'.$ENV{'request.course.id'}.'.languages'}) {
1618: @languages=(@languages,split(/\s*(\,|\;|\:)\s*/,
1619: $ENV{'course.'.$ENV{'request.course.id'}.'.languages'}));
1.118 www 1620: }
1621: if ($Apache::lonnet::domain_lang_def{$ENV{'user.domain'}}) {
1622: @languages=(@languages,
1623: $Apache::lonnet::domain_lang_def{$ENV{'user.domain'}});
1624: }
1625: if ($Apache::lonnet::domain_lang_def{$ENV{'request.role.domain'}}) {
1626: @languages=(@languages,
1627: $Apache::lonnet::domain_lang_def{$ENV{'request.role.domain'}});
1628: }
1629: if ($Apache::lonnet::domain_lang_def{
1630: $Apache::lonnet::perlvar{'lonDefDomain'}}) {
1631: @languages=(@languages,
1632: $Apache::lonnet::domain_lang_def{
1633: $Apache::lonnet::perlvar{'lonDefDomain'}});
1634: }
1635: # turn "en-ca" into "en-ca,en"
1636: my @genlanguages;
1637: foreach (@languages) {
1638: unless ($_=~/\w/) { next; }
1639: push (@genlanguages,$_);
1640: if ($_=~/(\-|\_)/) {
1641: push (@genlanguages,(split(/(\-|\_)/,$_))[0]);
1642: }
1643: }
1644: return @genlanguages;
1.117 www 1645: }
1646:
1.112 bowersj2 1647: ###############################################################
1648: ## Student Answer Attempts ##
1649: ###############################################################
1650:
1651: =pod
1652:
1653: =head1 Alternate Problem Views
1654:
1655: =over 4
1656:
1657: =item * get_previous_attempt($symb, $username, $domain, $course,
1658: $getattempt, $regexp, $gradesub)
1659:
1660: Return string with previous attempt on problem. Arguments:
1661:
1662: =over 4
1663:
1664: =item * $symb: Problem, including path
1665:
1666: =item * $username: username of the desired student
1667:
1668: =item * $domain: domain of the desired student
1.14 harris41 1669:
1.112 bowersj2 1670: =item * $course: Course ID
1.14 harris41 1671:
1.112 bowersj2 1672: =item * $getattempt: Leave blank for all attempts, otherwise put
1673: something
1.14 harris41 1674:
1.112 bowersj2 1675: =item * $regexp: if string matches this regexp, the string will be
1676: sent to $gradesub
1.14 harris41 1677:
1.112 bowersj2 1678: =item * $gradesub: routine that processes the string if it matches $regexp
1.14 harris41 1679:
1.112 bowersj2 1680: =back
1.14 harris41 1681:
1.112 bowersj2 1682: The output string is a table containing all desired attempts, if any.
1.16 harris41 1683:
1.112 bowersj2 1684: =cut
1.1 albertel 1685:
1686: sub get_previous_attempt {
1.43 ng 1687: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
1.1 albertel 1688: my $prevattempts='';
1.43 ng 1689: no strict 'refs';
1.1 albertel 1690: if ($symb) {
1.3 albertel 1691: my (%returnhash)=
1692: &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1 albertel 1693: if ($returnhash{'version'}) {
1694: my %lasthash=();
1695: my $version;
1696: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.19 harris41 1697: foreach (sort(split(/\:/,$returnhash{$version.':keys'}))) {
1.1 albertel 1698: $lasthash{$_}=$returnhash{$version.':'.$_};
1.19 harris41 1699: }
1.1 albertel 1700: }
1.43 ng 1701: $prevattempts='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1.40 ng 1702: $prevattempts.='<table border="0" width="100%"><tr bgcolor="#e6ffff"><td>History</td>';
1.16 harris41 1703: foreach (sort(keys %lasthash)) {
1.31 albertel 1704: my ($ign,@parts) = split(/\./,$_);
1.41 ng 1705: if ($#parts > 0) {
1.31 albertel 1706: my $data=$parts[-1];
1707: pop(@parts);
1.40 ng 1708: $prevattempts.='<td>Part '.join('.',@parts).'<br />'.$data.' </td>';
1.31 albertel 1709: } else {
1.41 ng 1710: if ($#parts == 0) {
1711: $prevattempts.='<th>'.$parts[0].'</th>';
1712: } else {
1713: $prevattempts.='<th>'.$ign.'</th>';
1714: }
1.31 albertel 1715: }
1.16 harris41 1716: }
1.40 ng 1717: if ($getattempt eq '') {
1718: for ($version=1;$version<=$returnhash{'version'};$version++) {
1719: $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Transaction '.$version.'</td>';
1720: foreach (sort(keys %lasthash)) {
1721: my $value;
1722: if ($_ =~ /timestamp/) {
1723: $value=scalar(localtime($returnhash{$version.':'.$_}));
1724: } else {
1725: $value=$returnhash{$version.':'.$_};
1726: }
1.142 albertel 1727: $prevattempts.='<td>'.&Apache::lonnet::unescape($value).' </td>';
1.40 ng 1728: }
1729: }
1.1 albertel 1730: }
1.40 ng 1731: $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Current</td>';
1.16 harris41 1732: foreach (sort(keys %lasthash)) {
1.5 albertel 1733: my $value;
1734: if ($_ =~ /timestamp/) {
1735: $value=scalar(localtime($lasthash{$_}));
1736: } else {
1737: $value=$lasthash{$_};
1738: }
1.142 albertel 1739: $value=&Apache::lonnet::unescape($value);
1.49 ng 1740: if ($_ =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
1.40 ng 1741: $prevattempts.='<td>'.$value.' </td>';
1.16 harris41 1742: }
1.40 ng 1743: $prevattempts.='</tr></table></td></tr></table>';
1.1 albertel 1744: } else {
1745: $prevattempts='Nothing submitted - no attempts.';
1746: }
1747: } else {
1748: $prevattempts='No data.';
1749: }
1.10 albertel 1750: }
1751:
1.107 albertel 1752: sub relative_to_absolute {
1753: my ($url,$output)=@_;
1754: my $parser=HTML::TokeParser->new(\$output);
1755: my $token;
1756: my $thisdir=$url;
1757: my @rlinks=();
1758: while ($token=$parser->get_token) {
1759: if ($token->[0] eq 'S') {
1760: if ($token->[1] eq 'a') {
1761: if ($token->[2]->{'href'}) {
1762: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
1763: }
1764: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
1765: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
1766: } elsif ($token->[1] eq 'base') {
1767: $thisdir=$token->[2]->{'href'};
1768: }
1769: }
1770: }
1771: $thisdir=~s-/[^/]*$--;
1772: foreach (@rlinks) {
1773: unless (($_=~/^http:\/\//i) ||
1774: ($_=~/^\//) ||
1775: ($_=~/^javascript:/i) ||
1776: ($_=~/^mailto:/i) ||
1777: ($_=~/^\#/)) {
1778: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$_);
1779: $output=~s/(\"|\'|\=\s*)$_(\"|\'|\s|\>)/$1$newlocation$2/;
1780: }
1781: }
1782: # -------------------------------------------------- Deal with Applet codebases
1783: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
1784: return $output;
1785: }
1786:
1.112 bowersj2 1787: =pod
1788:
1789: =item * get_student_view
1790:
1791: show a snapshot of what student was looking at
1792:
1793: =cut
1794:
1.10 albertel 1795: sub get_student_view {
1.64 sakharuk 1796: my ($symb,$username,$domain,$courseid,$target) = @_;
1.114 www 1797: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.10 albertel 1798: my (%old,%moreenv);
1799: my @elements=('symb','courseid','domain','username');
1800: foreach my $element (@elements) {
1801: $old{$element}=$ENV{'form.grade_'.$element};
1802: $moreenv{'form.grade_'.$element}=eval '$'.$element #'
1803: }
1.64 sakharuk 1804: if ($target eq 'tex') {$moreenv{'form.grade_target'} = 'tex';}
1.11 albertel 1805: &Apache::lonnet::appenv(%moreenv);
1.107 albertel 1806: $feedurl=&Apache::lonnet::clutter($feedurl);
1807: my $userview=&Apache::lonnet::ssi_body($feedurl);
1.11 albertel 1808: &Apache::lonnet::delenv('form.grade_');
1809: foreach my $element (@elements) {
1810: $ENV{'form.grade_'.$element}=$old{$element};
1811: }
1812: $userview=~s/\<body[^\>]*\>//gi;
1813: $userview=~s/\<\/body\>//gi;
1814: $userview=~s/\<html\>//gi;
1815: $userview=~s/\<\/html\>//gi;
1816: $userview=~s/\<head\>//gi;
1817: $userview=~s/\<\/head\>//gi;
1818: $userview=~s/action\s*\=/would_be_action\=/gi;
1.107 albertel 1819: $userview=&relative_to_absolute($feedurl,$userview);
1.11 albertel 1820: return $userview;
1821: }
1822:
1.112 bowersj2 1823: =pod
1824:
1825: =item * get_student_answers()
1826:
1827: show a snapshot of how student was answering problem
1828:
1829: =cut
1830:
1.11 albertel 1831: sub get_student_answers {
1.100 sakharuk 1832: my ($symb,$username,$domain,$courseid,%form) = @_;
1.114 www 1833: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.11 albertel 1834: my (%old,%moreenv);
1835: my @elements=('symb','courseid','domain','username');
1836: foreach my $element (@elements) {
1837: $old{$element}=$ENV{'form.grade_'.$element};
1838: $moreenv{'form.grade_'.$element}=eval '$'.$element #'
1839: }
1840: $moreenv{'form.grade_target'}='answer';
1.10 albertel 1841: &Apache::lonnet::appenv(%moreenv);
1.100 sakharuk 1842: my $userview=&Apache::lonnet::ssi('/res/'.$feedurl,%form);
1.10 albertel 1843: &Apache::lonnet::delenv('form.grade_');
1844: foreach my $element (@elements) {
1845: $ENV{'form.grade_'.$element}=$old{$element};
1846: }
1847: return $userview;
1.1 albertel 1848: }
1.116 albertel 1849:
1850: =pod
1851:
1852: =item * &submlink()
1853:
1854: Inputs: $text $uname $udom $symb
1855:
1856: Returns: A link to grades.pm such as to see the SUBM view of a student
1857:
1858: =cut
1859:
1860: ###############################################
1861: sub submlink {
1862: my ($text,$uname,$udom,$symb)=@_;
1863: if (!($uname && $udom)) {
1864: (my $cursymb, my $courseid,$udom,$uname)=
1865: &Apache::lonxml::whichuser($symb);
1866: if (!$symb) { $symb=$cursymb; }
1867: }
1868: if (!$symb) { $symb=&symbread(); }
1869: return '<a href="/adm/grades?symb='.$symb.'&student='.$uname.
1870: '&userdom='.$udom.'&command=submission">'.$text.'</a>';
1871: }
1872: ##############################################
1.37 matthew 1873:
1.112 bowersj2 1874: =pod
1875:
1876: =back
1877:
1878: =cut
1879:
1.37 matthew 1880: ###############################################
1.51 www 1881:
1882:
1883: sub timehash {
1884: my @ltime=localtime(shift);
1885: return ( 'seconds' => $ltime[0],
1886: 'minutes' => $ltime[1],
1887: 'hours' => $ltime[2],
1888: 'day' => $ltime[3],
1889: 'month' => $ltime[4]+1,
1890: 'year' => $ltime[5]+1900,
1891: 'weekday' => $ltime[6],
1892: 'dayyear' => $ltime[7]+1,
1893: 'dlsav' => $ltime[8] );
1894: }
1895:
1896: sub maketime {
1897: my %th=@_;
1898: return POSIX::mktime(
1899: ($th{'seconds'},$th{'minutes'},$th{'hours'},
1900: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,$th{'dlsav'}));
1901: }
1902:
1.70 www 1903:
1904: #########################################
1905: #
1906: # Retro-fixing of un-backward-compatible time format
1907:
1908: sub unsqltime {
1909: my $timestamp=shift;
1910: if ($timestamp=~/^(\d+)\-(\d+)\-(\d+)\s+(\d+)\:(\d+)\:(\d+)$/) {
1911: $timestamp=&maketime(
1912: 'year'=>$1,'month'=>$2,'day'=>$3,
1913: 'hours'=>$4,'minutes'=>$5,'seconds'=>$6);
1914: }
1915: return $timestamp;
1916: }
1917:
1918: #########################################
1.51 www 1919:
1920: sub findallcourses {
1921: my %courses=();
1922: my $now=time;
1923: foreach (keys %ENV) {
1924: if ($_=~/^user\.role\.\w+\.\/(\w+)\/(\w+)/) {
1925: my ($starttime,$endtime)=$ENV{$_};
1926: my $active=1;
1927: if ($starttime) {
1928: if ($now<$starttime) { $active=0; }
1929: }
1930: if ($endtime) {
1931: if ($now>$endtime) { $active=0; }
1932: }
1933: if ($active) { $courses{$1.'_'.$2}=1; }
1934: }
1935: }
1936: return keys %courses;
1937: }
1.37 matthew 1938:
1.54 www 1939: ###############################################
1.60 matthew 1940: ###############################################
1941:
1942: =pod
1943:
1.112 bowersj2 1944: =head1 Domain Template Functions
1945:
1946: =over 4
1947:
1948: =item * &determinedomain()
1.60 matthew 1949:
1950: Inputs: $domain (usually will be undef)
1951:
1.63 www 1952: Returns: Determines which domain should be used for designs
1.60 matthew 1953:
1954: =cut
1.54 www 1955:
1.60 matthew 1956: ###############################################
1.63 www 1957: sub determinedomain {
1958: my $domain=shift;
1959: if (! $domain) {
1.60 matthew 1960: # Determine domain if we have not been given one
1961: $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
1962: if ($ENV{'user.domain'}) { $domain=$ENV{'user.domain'}; }
1963: if ($ENV{'request.role.domain'}) {
1964: $domain=$ENV{'request.role.domain'};
1965: }
1966: }
1.63 www 1967: return $domain;
1968: }
1969: ###############################################
1970: =pod
1971:
1.112 bowersj2 1972: =item * &domainlogo()
1.63 www 1973:
1974: Inputs: $domain (usually will be undef)
1975:
1976: Returns: A link to a domain logo, if the domain logo exists.
1977: If the domain logo does not exist, a description of the domain.
1978:
1979: =cut
1.112 bowersj2 1980:
1.63 www 1981: ###############################################
1982: sub domainlogo {
1983: my $domain = &determinedomain(shift);
1984: # See if there is a logo
1.59 www 1985: if (-e '/home/httpd/html/adm/lonDomLogos/'.$domain.'.gif') {
1.83 albertel 1986: my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
1987: if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
1988: return '<img src="http://'.$ENV{'HTTP_HOST'}.':'.$lonhttpdPort.
1.150 matthew 1989: '/adm/lonDomLogos/'.$domain.'.gif" alt="'.$domain.'" />';
1.60 matthew 1990: } elsif(exists($Apache::lonnet::domaindescription{$domain})) {
1991: return $Apache::lonnet::domaindescription{$domain};
1.59 www 1992: } else {
1.60 matthew 1993: return '';
1.59 www 1994: }
1995: }
1.63 www 1996: ##############################################
1997:
1998: =pod
1999:
1.112 bowersj2 2000: =item * &designparm()
1.63 www 2001:
2002: Inputs: $which parameter; $domain (usually will be undef)
2003:
2004: Returns: value of designparamter $which
2005:
2006: =cut
1.112 bowersj2 2007:
1.63 www 2008: ##############################################
2009: sub designparm {
2010: my ($which,$domain)=@_;
1.110 www 2011: if ($ENV{'browser.blackwhite'} eq 'on') {
2012: if ($which=~/\.(font|alink|vlink|link)$/) {
2013: return '#000000';
2014: }
2015: if ($which=~/\.(pgbg|sidebg)$/) {
2016: return '#FFFFFF';
2017: }
2018: if ($which=~/\.tabbg$/) {
2019: return '#CCCCCC';
2020: }
2021: }
1.96 www 2022: if ($ENV{'environment.color.'.$which}) {
2023: return $ENV{'environment.color.'.$which};
2024: }
1.63 www 2025: $domain=&determinedomain($domain);
2026: if ($designhash{$domain.'.'.$which}) {
2027: return $designhash{$domain.'.'.$which};
2028: } else {
2029: return $designhash{'default.'.$which};
2030: }
2031: }
1.59 www 2032:
1.60 matthew 2033: ###############################################
2034: ###############################################
2035:
2036: =pod
2037:
1.112 bowersj2 2038: =back
2039:
2040: =head1 HTTP Helpers
2041:
2042: =over 4
2043:
2044: =item * &bodytag()
1.60 matthew 2045:
2046: Returns a uniform header for LON-CAPA web pages.
2047:
2048: Inputs:
2049:
1.112 bowersj2 2050: =over 4
2051:
2052: =item * $title, A title to be displayed on the page.
2053:
2054: =item * $function, the current role (can be undef).
2055:
2056: =item * $addentries, extra parameters for the <body> tag.
2057:
2058: =item * $bodyonly, if defined, only return the <body> tag.
2059:
2060: =item * $domain, if defined, force a given domain.
2061:
2062: =item * $forcereg, if page should register as content page (relevant for
1.86 www 2063: text interface only)
1.60 matthew 2064:
1.112 bowersj2 2065: =back
2066:
1.60 matthew 2067: Returns: A uniform header for LON-CAPA web pages.
2068: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
2069: If $bodyonly is undef or zero, an html string containing a <body> tag and
2070: other decorations will be returned.
2071:
2072: =cut
2073:
1.54 www 2074: sub bodytag {
1.86 www 2075: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg)=@_;
1.117 www 2076: $title=&mt($title);
1.55 www 2077: unless ($function) {
2078: $function='student';
2079: if ($ENV{'request.role'}=~/^(cc|in|ta|ep)/) {
2080: $function='coordinator';
2081: }
2082: if ($ENV{'request.role'}=~/^(su|dc|ad|li)/) {
2083: $function='admin';
2084: }
2085: if (($ENV{'request.role'}=~/^(au|ca)/) ||
2086: ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
2087: $function='author';
2088: }
2089: }
1.63 www 2090: my $img=&designparm($function.'.img',$domain);
2091: my $pgbg=&designparm($function.'.pgbg',$domain);
2092: my $tabbg=&designparm($function.'.tabbg',$domain);
2093: my $font=&designparm($function.'.font',$domain);
2094: my $link=&designparm($function.'.link',$domain);
2095: my $alink=&designparm($function.'.alink',$domain);
2096: my $vlink=&designparm($function.'.vlink',$domain);
2097: my $sidebg=&designparm($function.'.sidebg',$domain);
1.110 www 2098: # Accessibility font enhance
2099: unless ($addentries) { $addentries=''; }
1.146 www 2100: my $addstyle='';
1.110 www 2101: if ($ENV{'browser.fontenhance'} eq 'on') {
1.146 www 2102: $addstyle=' font-size: x-large;';
1.110 www 2103: }
1.63 www 2104: # role and realm
1.55 www 2105: my ($role,$realm)
2106: =&Apache::lonnet::plaintext((split(/\./,$ENV{'request.role'}))[0]);
2107: # realm
1.54 www 2108: if ($ENV{'request.course.id'}) {
1.55 www 2109: $realm=
2110: $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
1.54 www 2111: }
1.55 www 2112: unless ($realm) { $realm=' '; }
2113: # Set messages
1.60 matthew 2114: my $messages=&domainlogo($domain);
1.101 www 2115: # Port for miniserver
1.83 albertel 2116: my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
2117: if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
1.101 www 2118: # construct main body tag
1.60 matthew 2119: my $bodytag = <<END;
1.146 www 2120: <style>
1.147 www 2121: h1, h2, h3, th { font-family: Arial, Helvetica, sans-serif }
1.146 www 2122: a:focus { color: red; background: yellow }
2123: </style>
1.54 www 2124: <body bgcolor="$pgbg" text="$font" alink="$alink" vlink="$vlink" link="$link"
1.151 www 2125: style="margin-top: 0px;$addstyle" $addentries>
1.60 matthew 2126: END
1.94 www 2127: my $upperleft='<img src="http://'.$ENV{'HTTP_HOST'}.':'.
1.150 matthew 2128: $lonhttpdPort.$img.'" alt="'.$function.'" />';
1.60 matthew 2129: if ($bodyonly) {
2130: return $bodytag;
1.79 www 2131: } elsif ($ENV{'browser.interface'} eq 'textual') {
1.95 www 2132: # Accessibility
1.93 www 2133: return $bodytag.&Apache::lonmenu::menubuttons($forcereg,'web',
2134: $forcereg).
2135: '<h1>LON-CAPA: '.$title.'</h1>';
2136: } elsif ($ENV{'environment.remote'} eq 'off') {
1.95 www 2137: # No Remote
2138: return $bodytag.&Apache::lonmenu::menubuttons($forcereg,'web',
2139: $forcereg).
1.151 www 2140: '<table bgcolor="'.$pgbg.'" width="100%" border="0" cellspacing="3" cellpadding="3"><tr><td bgcolor="'.$tabbg.'"><font face="Arial, Helvetica, sans-serif" size="+3" color="'.$font.'"><b>'.$title.
1.95 www 2141: '</b></font></td></tr></table>';
1.94 www 2142: }
1.95 www 2143:
1.93 www 2144: #
1.95 www 2145: # Top frame rendering, Remote is up
1.93 www 2146: #
1.94 www 2147: return(<<ENDBODY);
1.60 matthew 2148: $bodytag
1.55 www 2149: <table width="100%" cellspacing="0" border="0" cellpadding="0">
1.95 www 2150: <tr><td bgcolor="$sidebg">
1.94 www 2151: $upperleft</td>
1.95 www 2152: <td bgcolor="$sidebg" align="right">$messages </td>
1.55 www 2153: </tr>
1.54 www 2154: <tr>
1.55 www 2155: <td rowspan="3" bgcolor="$tabbg">
1.146 www 2156: <font size="5" face="Arial, Helvetica, sans-serif"><b>$title</b></font>
2157: <td bgcolor="$tabbg" align="right">
2158: <font size="2" face="Arial, Helvetica, sans-serif">
1.54 www 2159: $ENV{'environment.firstname'}
2160: $ENV{'environment.middlename'}
2161: $ENV{'environment.lastname'}
2162: $ENV{'environment.generation'}
1.55 www 2163: </font>
1.54 www 2164: </td>
2165: </tr>
2166: <tr><td bgcolor="$tabbg" align="right">
1.146 www 2167: <font size="2" face="Arial, Helvetica, sans-serif">$role</font>
1.54 www 2168: </td></tr>
1.55 www 2169: <tr>
1.148 www 2170: <td bgcolor="$tabbg" align="right"><font size="2" face="Arial, Helvetica, sans-serif">$realm</font> </td></tr>
1.54 www 2171: </table><br>
2172: ENDBODY
2173: }
1.99 www 2174:
2175: ###############################################
2176:
2177: sub get_posted_cgi {
2178: my $r=shift;
2179:
2180: my $buffer;
2181:
2182: $r->read($buffer,$r->header_in('Content-length'),0);
2183: unless ($buffer=~/^(\-+\w+)\s+Content\-Disposition\:\s*form\-data/si) {
2184: my @pairs=split(/&/,$buffer);
2185: my $pair;
2186: foreach $pair (@pairs) {
2187: my ($name,$value) = split(/=/,$pair);
2188: $value =~ tr/+/ /;
2189: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
2190: $name =~ tr/+/ /;
2191: $name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
2192: &add_to_env("form.$name",$value);
2193: }
2194: } else {
2195: my $contentsep=$1;
2196: my @lines = split (/\n/,$buffer);
2197: my $name='';
2198: my $value='';
2199: my $fname='';
2200: my $fmime='';
2201: my $i;
2202: for ($i=0;$i<=$#lines;$i++) {
2203: if ($lines[$i]=~/^$contentsep/) {
2204: if ($name) {
2205: chomp($value);
2206: if ($fname) {
2207: $ENV{"form.$name.filename"}=$fname;
2208: $ENV{"form.$name.mimetype"}=$fmime;
2209: } else {
2210: $value=~s/\s+$//s;
2211: }
2212: &add_to_env("form.$name",$value);
2213: }
2214: if ($i<$#lines) {
2215: $i++;
2216: $lines[$i]=~
2217: /Content\-Disposition\:\s*form\-data\;\s*name\=\"([^\"]+)\"/i;
2218: $name=$1;
2219: $value='';
2220: if ($lines[$i]=~/filename\=\"([^\"]+)\"/i) {
2221: $fname=$1;
2222: if
2223: ($lines[$i+1]=~/Content\-Type\:\s*([\w\-\/]+)/i) {
2224: $fmime=$1;
2225: $i++;
2226: } else {
2227: $fmime='';
2228: }
2229: } else {
2230: $fname='';
2231: $fmime='';
2232: }
2233: $i++;
2234: }
2235: } else {
2236: $value.=$lines[$i]."\n";
2237: }
2238: }
2239: }
2240: $ENV{'request.method'}=$ENV{'REQUEST_METHOD'};
2241: $r->method_number(M_GET);
2242: $r->method('GET');
2243: $r->headers_in->unset('Content-length');
2244: }
2245:
1.112 bowersj2 2246: =pod
2247:
2248: =item * get_unprocessed_cgi($query,$possible_names)
2249:
2250: Modify the %ENV hash to contain unprocessed CGI form parameters held in
2251: $query. The parameters listed in $possible_names (an array reference),
2252: will be set in $ENV{'form.name'} if they do not already exist.
2253:
2254: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
2255: $possible_names is an ref to an array of form element names. As an example:
2256: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
2257: will result in $ENV{'form.uname'} and $ENV{'form.udom'} being set.
2258:
2259: =cut
1.1 albertel 2260:
1.6 albertel 2261: sub get_unprocessed_cgi {
1.25 albertel 2262: my ($query,$possible_names)= @_;
1.26 matthew 2263: # $Apache::lonxml::debug=1;
1.16 harris41 2264: foreach (split(/&/,$query)) {
1.6 albertel 2265: my ($name, $value) = split(/=/,$_);
1.25 albertel 2266: $name = &Apache::lonnet::unescape($name);
2267: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
2268: $value =~ tr/+/ /;
2269: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
2270: &Apache::lonxml::debug("Seting :$name: to :$value:");
1.30 albertel 2271: unless (defined($ENV{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25 albertel 2272: }
1.16 harris41 2273: }
1.6 albertel 2274: }
2275:
1.112 bowersj2 2276: =pod
2277:
2278: =item * cacheheader()
2279:
2280: returns cache-controlling header code
2281:
2282: =cut
2283:
1.7 albertel 2284: sub cacheheader {
1.23 www 2285: unless ($ENV{'request.method'} eq 'GET') { return ''; }
1.8 albertel 2286: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
1.7 albertel 2287: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
2288: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
2289: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
2290: return $output;
2291: }
2292:
1.112 bowersj2 2293: =pod
2294:
2295: =item * no_cache($r)
2296:
2297: specifies header code to not have cache
2298:
2299: =cut
2300:
1.9 albertel 2301: sub no_cache {
2302: my ($r) = @_;
1.23 www 2303: unless ($ENV{'request.method'} eq 'GET') { return ''; }
1.24 albertel 2304: #my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
1.9 albertel 2305: $r->no_cache(1);
2306: $r->header_out("Pragma" => "no-cache");
1.24 albertel 2307: #$r->header_out("Expires" => $date);
1.123 www 2308: }
2309:
2310: sub content_type {
2311: my ($r,$type,$charset) = @_;
2312: unless ($charset) {
2313: $charset=&Apache::lonlocal::current_encoding;
2314: }
2315: $r->content_type($type.($charset?'; charset='.$charset:''));
1.9 albertel 2316: }
1.25 albertel 2317:
1.112 bowersj2 2318: =pod
2319:
2320: =item * add_to_env($name,$value)
2321:
2322: adds $name to the %ENV hash with value
2323: $value, if $name already exists, the entry is converted to an array
2324: reference and $value is added to the array.
2325:
2326: =cut
2327:
1.25 albertel 2328: sub add_to_env {
2329: my ($name,$value)=@_;
1.28 albertel 2330: if (defined($ENV{$name})) {
1.27 albertel 2331: if (ref($ENV{$name})) {
1.25 albertel 2332: #already have multiple values
2333: push(@{ $ENV{$name} },$value);
2334: } else {
2335: #first time seeing multiple values, convert hash entry to an arrayref
2336: my $first=$ENV{$name};
2337: undef($ENV{$name});
2338: push(@{ $ENV{$name} },$first,$value);
2339: }
2340: } else {
2341: $ENV{$name}=$value;
2342: }
1.31 albertel 2343: }
1.149 albertel 2344:
2345: =pod
2346:
2347: =item * get_env_multiple($name)
2348:
2349: gets $name from the %ENV hash, it seemlessly handles the cases where multiple
2350: values may be defined and end up as an array ref.
2351:
2352: returns an array of values
2353:
2354: =cut
2355:
2356: sub get_env_multiple {
2357: my ($name) = @_;
2358: my @values;
2359: if (defined($ENV{$name})) {
2360: # exists is it an array
2361: if (ref($ENV{$name})) {
2362: @values=@{ $ENV{$name} };
2363: } else {
2364: $values[0]=$ENV{$name};
2365: }
2366: }
2367: return(@values);
2368: }
2369:
1.31 albertel 2370:
1.41 ng 2371: =pod
1.45 matthew 2372:
2373: =back
1.41 ng 2374:
1.112 bowersj2 2375: =head1 CSV Upload/Handling functions
1.38 albertel 2376:
1.41 ng 2377: =over 4
2378:
1.112 bowersj2 2379: =item * upfile_store($r)
1.41 ng 2380:
2381: Store uploaded file, $r should be the HTTP Request object,
2382: needs $ENV{'form.upfile'}
2383: returns $datatoken to be put into hidden field
2384:
2385: =cut
1.31 albertel 2386:
2387: sub upfile_store {
2388: my $r=shift;
2389: $ENV{'form.upfile'}=~s/\r/\n/gs;
2390: $ENV{'form.upfile'}=~s/\f/\n/gs;
2391: $ENV{'form.upfile'}=~s/\n+/\n/gs;
2392: $ENV{'form.upfile'}=~s/\n+$//gs;
2393:
2394: my $datatoken=$ENV{'user.name'}.'_'.$ENV{'user.domain'}.
2395: '_enroll_'.$ENV{'request.course.id'}.'_'.time.'_'.$$;
2396: {
1.158 raeburn 2397: my $datafile = $r->dir_config('lonDaemons').
2398: '/tmp/'.$datatoken.'.tmp';
2399: if ( open(my $fh,">$datafile") ) {
2400: print $fh $ENV{'form.upfile'};
2401: close($fh);
2402: }
1.31 albertel 2403: }
2404: return $datatoken;
2405: }
2406:
1.56 matthew 2407: =pod
2408:
1.112 bowersj2 2409: =item * load_tmp_file($r)
1.41 ng 2410:
2411: Load uploaded file from tmp, $r should be the HTTP Request object,
2412: needs $ENV{'form.datatoken'},
2413: sets $ENV{'form.upfile'} to the contents of the file
2414:
2415: =cut
1.31 albertel 2416:
2417: sub load_tmp_file {
2418: my $r=shift;
2419: my @studentdata=();
2420: {
1.158 raeburn 2421: my $studentfile = $r->dir_config('lonDaemons').
2422: '/tmp/'.$ENV{'form.datatoken'}.'.tmp';
2423: if ( open(my $fh,"<$studentfile") ) {
2424: @studentdata=<$fh>;
2425: close($fh);
2426: }
1.31 albertel 2427: }
2428: $ENV{'form.upfile'}=join('',@studentdata);
2429: }
2430:
1.56 matthew 2431: =pod
2432:
1.112 bowersj2 2433: =item * upfile_record_sep()
1.41 ng 2434:
2435: Separate uploaded file into records
2436: returns array of records,
2437: needs $ENV{'form.upfile'} and $ENV{'form.upfiletype'}
2438:
2439: =cut
1.31 albertel 2440:
2441: sub upfile_record_sep {
2442: if ($ENV{'form.upfiletype'} eq 'xml') {
2443: } else {
2444: return split(/\n/,$ENV{'form.upfile'});
2445: }
2446: }
2447:
1.56 matthew 2448: =pod
2449:
1.112 bowersj2 2450: =item * record_sep($record)
1.41 ng 2451:
2452: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $ENV{'form.upfiletype'}
2453:
2454: =cut
2455:
1.31 albertel 2456: sub record_sep {
2457: my $record=shift;
2458: my %components=();
2459: if ($ENV{'form.upfiletype'} eq 'xml') {
2460: } elsif ($ENV{'form.upfiletype'} eq 'space') {
2461: my $i=0;
2462: foreach (split(/\s+/,$record)) {
2463: my $field=$_;
2464: $field=~s/^(\"|\')//;
2465: $field=~s/(\"|\')$//;
2466: $components{$i}=$field;
2467: $i++;
2468: }
2469: } elsif ($ENV{'form.upfiletype'} eq 'tab') {
2470: my $i=0;
2471: foreach (split(/\t+/,$record)) {
2472: my $field=$_;
2473: $field=~s/^(\"|\')//;
2474: $field=~s/(\"|\')$//;
2475: $components{$i}=$field;
2476: $i++;
2477: }
2478: } else {
2479: my @allfields=split(/\,/,$record);
2480: my $i=0;
2481: my $j;
2482: for ($j=0;$j<=$#allfields;$j++) {
2483: my $field=$allfields[$j];
2484: if ($field=~/^\s*(\"|\')/) {
2485: my $delimiter=$1;
2486: while (($field!~/$delimiter$/) && ($j<$#allfields)) {
2487: $j++;
2488: $field.=','.$allfields[$j];
2489: }
2490: $field=~s/^\s*$delimiter//;
2491: $field=~s/$delimiter\s*$//;
2492: }
2493: $components{$i}=$field;
2494: $i++;
2495: }
2496: }
2497: return %components;
2498: }
2499:
1.144 matthew 2500: ######################################################
2501: ######################################################
2502:
1.56 matthew 2503: =pod
2504:
1.112 bowersj2 2505: =item * upfile_select_html()
1.41 ng 2506:
1.144 matthew 2507: Return HTML code to select a file from the users machine and specify
2508: the file type.
1.41 ng 2509:
2510: =cut
2511:
1.144 matthew 2512: ######################################################
2513: ######################################################
1.31 albertel 2514: sub upfile_select_html {
1.144 matthew 2515: my %Types = (
2516: csv => &mt('CSV (comma separated values, spreadsheet)'),
2517: space => &mt('Space separated'),
2518: tab => &mt('Tabulator separated'),
2519: # xml => &mt('HTML/XML'),
2520: );
2521: my $Str = '<input type="file" name="upfile" size="50" />'.
2522: '<br />Type: <select name="upfiletype">';
2523: foreach my $type (sort(keys(%Types))) {
2524: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
2525: }
2526: $Str .= "</select>\n";
2527: return $Str;
1.31 albertel 2528: }
2529:
1.144 matthew 2530: ######################################################
2531: ######################################################
2532:
1.56 matthew 2533: =pod
2534:
1.112 bowersj2 2535: =item * csv_print_samples($r,$records)
1.41 ng 2536:
2537: Prints a table of sample values from each column uploaded $r is an
2538: Apache Request ref, $records is an arrayref from
2539: &Apache::loncommon::upfile_record_sep
2540:
2541: =cut
2542:
1.144 matthew 2543: ######################################################
2544: ######################################################
1.31 albertel 2545: sub csv_print_samples {
2546: my ($r,$records) = @_;
2547: my (%sone,%stwo,%sthree);
2548: %sone=&record_sep($$records[0]);
2549: if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
2550: if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
1.144 matthew 2551: #
2552: $r->print(&mt('Samples').'<br /><table border="2"><tr>');
2553: foreach (sort({$a <=> $b} keys(%sone))) {
2554: $r->print('<th>'.&mt('Column [_1]',($_+1)).'</th>'); }
1.31 albertel 2555: $r->print('</tr>');
2556: foreach my $hash (\%sone,\%stwo,\%sthree) {
2557: $r->print('<tr>');
2558: foreach (sort({$a <=> $b} keys(%sone))) {
2559: $r->print('<td>');
2560: if (defined($$hash{$_})) { $r->print($$hash{$_}); }
2561: $r->print('</td>');
2562: }
2563: $r->print('</tr>');
2564: }
2565: $r->print('</tr></table><br />'."\n");
2566: }
2567:
1.144 matthew 2568: ######################################################
2569: ######################################################
2570:
1.56 matthew 2571: =pod
2572:
1.112 bowersj2 2573: =item * csv_print_select_table($r,$records,$d)
1.41 ng 2574:
2575: Prints a table to create associations between values and table columns.
1.144 matthew 2576:
1.41 ng 2577: $r is an Apache Request ref,
2578: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
2579: $d is an array of 2 element arrays (internal name, displayed name)
2580:
2581: =cut
2582:
1.144 matthew 2583: ######################################################
2584: ######################################################
1.31 albertel 2585: sub csv_print_select_table {
2586: my ($r,$records,$d) = @_;
2587: my $i=0;my %sone;
2588: %sone=&record_sep($$records[0]);
1.144 matthew 2589: $r->print(&mt('Associate columns with student attributes.')."\n".
2590: '<table border="2"><tr>'.
2591: '<th>'.&mt('Attribute').'</th>'.
2592: '<th>'.&mt('Column').'</th></tr>'."\n");
1.31 albertel 2593: foreach (@$d) {
2594: my ($value,$display)=@{ $_ };
2595: $r->print('<tr><td>'.$display.'</td>');
2596:
2597: $r->print('<td><select name=f'.$i.
1.32 matthew 2598: ' onchange="javascript:flip(this.form,'.$i.');">');
1.31 albertel 2599: $r->print('<option value="none"></option>');
2600: foreach (sort({$a <=> $b} keys(%sone))) {
2601: $r->print('<option value="'.$_.'">Column '.($_+1).'</option>');
2602: }
2603: $r->print('</select></td></tr>'."\n");
2604: $i++;
2605: }
2606: $i--;
2607: return $i;
2608: }
1.56 matthew 2609:
1.144 matthew 2610: ######################################################
2611: ######################################################
2612:
1.56 matthew 2613: =pod
1.31 albertel 2614:
1.112 bowersj2 2615: =item * csv_samples_select_table($r,$records,$d)
1.41 ng 2616:
2617: Prints a table of sample values from the upload and can make associate samples to internal names.
2618:
2619: $r is an Apache Request ref,
2620: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
2621: $d is an array of 2 element arrays (internal name, displayed name)
2622:
2623: =cut
2624:
1.144 matthew 2625: ######################################################
2626: ######################################################
1.31 albertel 2627: sub csv_samples_select_table {
2628: my ($r,$records,$d) = @_;
2629: my %sone; my %stwo; my %sthree;
2630: my $i=0;
1.144 matthew 2631: #
2632: $r->print('<table border=2><tr><th>'.
2633: &mt('Field').'</th><th>'.&mt('Samples').'</th></tr>');
1.31 albertel 2634: %sone=&record_sep($$records[0]);
2635: if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
2636: if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
1.144 matthew 2637: #
1.31 albertel 2638: foreach (sort keys %sone) {
1.144 matthew 2639: $r->print('<tr><td><select name="f'.$i.'"'.
1.32 matthew 2640: ' onchange="javascript:flip(this.form,'.$i.');">');
1.31 albertel 2641: foreach (@$d) {
2642: my ($value,$display)=@{ $_ };
1.144 matthew 2643: $r->print('<option value="'.$value.'">'.$display.'</option>');
1.31 albertel 2644: }
2645: $r->print('</select></td><td>');
2646: if (defined($sone{$_})) { $r->print($sone{$_}."</br>\n"); }
2647: if (defined($stwo{$_})) { $r->print($stwo{$_}."</br>\n"); }
2648: if (defined($sthree{$_})) { $r->print($sthree{$_}."</br>\n"); }
2649: $r->print('</td></tr>');
2650: $i++;
2651: }
2652: $i--;
2653: return($i);
1.115 matthew 2654: }
2655:
1.144 matthew 2656: ######################################################
2657: ######################################################
2658:
1.115 matthew 2659: =pod
2660:
2661: =item clean_excel_name($name)
2662:
2663: Returns a replacement for $name which does not contain any illegal characters.
2664:
2665: =cut
2666:
1.144 matthew 2667: ######################################################
2668: ######################################################
1.115 matthew 2669: sub clean_excel_name {
2670: my ($name) = @_;
2671: $name =~ s/[:\*\?\/\\]//g;
2672: if (length($name) > 31) {
2673: $name = substr($name,0,31);
2674: }
2675: return $name;
1.25 albertel 2676: }
1.84 albertel 2677:
1.85 albertel 2678: =pod
2679:
1.112 bowersj2 2680: =item * check_if_partid_hidden($id,$symb,$udom,$uname)
1.85 albertel 2681:
2682: Returns either 1 or undef
2683:
2684: 1 if the part is to be hidden, undef if it is to be shown
2685:
2686: Arguments are:
2687:
2688: $id the id of the part to be checked
2689: $symb, optional the symb of the resource to check
2690: $udom, optional the domain of the user to check for
2691: $uname, optional the username of the user to check for
2692:
2693: =cut
1.84 albertel 2694:
2695: sub check_if_partid_hidden {
2696: my ($id,$symb,$udom,$uname) = @_;
1.133 albertel 2697: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84 albertel 2698: $symb,$udom,$uname);
1.141 albertel 2699: my $truth=1;
2700: #if the string starts with !, then the list is the list to show not hide
2701: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84 albertel 2702: my @hiddenlist=split(/,/,$hiddenparts);
2703: foreach my $checkid (@hiddenlist) {
1.141 albertel 2704: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84 albertel 2705: }
1.141 albertel 2706: return !$truth;
1.84 albertel 2707: }
1.127 matthew 2708:
1.138 matthew 2709:
2710: ############################################################
2711: ############################################################
2712:
2713: =pod
2714:
1.157 matthew 2715: =back
2716:
1.138 matthew 2717: =head1 cgi-bin script and graphing routines
2718:
1.157 matthew 2719: =over 4
2720:
1.138 matthew 2721: =item get_cgi_id
2722:
2723: Inputs: none
2724:
2725: Returns an id which can be used to pass environment variables
2726: to various cgi-bin scripts. These environment variables will
2727: be removed from the users environment after a given time by
2728: the routine &Apache::lonnet::transfer_profile_to_env.
2729:
2730: =cut
2731:
2732: ############################################################
2733: ############################################################
1.152 albertel 2734: my $uniq=0;
1.136 matthew 2735: sub get_cgi_id {
1.154 albertel 2736: $uniq=($uniq+1)%100000;
1.152 albertel 2737: return (time.'_'.$uniq);
1.136 matthew 2738: }
2739:
1.127 matthew 2740: ############################################################
2741: ############################################################
2742:
2743: =pod
2744:
1.134 matthew 2745: =item DrawBarGraph
1.127 matthew 2746:
1.138 matthew 2747: Facilitates the plotting of data in a (stacked) bar graph.
2748: Puts plot definition data into the users environment in order for
2749: graph.png to plot it. Returns an <img> tag for the plot.
2750: The bars on the plot are labeled '1','2',...,'n'.
2751:
2752: Inputs:
2753:
2754: =over 4
2755:
2756: =item $Title: string, the title of the plot
2757:
2758: =item $xlabel: string, text describing the X-axis of the plot
2759:
2760: =item $ylabel: string, text describing the Y-axis of the plot
2761:
2762: =item $Max: scalar, the maximum Y value to use in the plot
2763: If $Max is < any data point, the graph will not be rendered.
2764:
1.140 matthew 2765: =item $colors: array ref holding the colors to be used for the data sets when
1.138 matthew 2766: they are plotted. If undefined, default values will be used.
2767:
2768: =item @Values: An array of array references. Each array reference holds data
2769: to be plotted in a stacked bar chart.
2770:
2771: =back
2772:
2773: Returns:
2774:
2775: An <img> tag which references graph.png and the appropriate identifying
2776: information for the plot.
2777:
1.127 matthew 2778: =cut
2779:
2780: ############################################################
2781: ############################################################
1.134 matthew 2782: sub DrawBarGraph {
1.129 matthew 2783: my ($Title,$xlabel,$ylabel,$Max,$colors,@Values)=@_;
1.134 matthew 2784: #
2785: if (! defined($colors)) {
2786: $colors = ['#33ff00',
2787: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
2788: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
2789: ];
2790: }
1.127 matthew 2791: #
1.136 matthew 2792: my $identifier = &get_cgi_id();
2793: my $id = 'cgi.'.$identifier;
1.129 matthew 2794: if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127 matthew 2795: return '';
2796: }
1.129 matthew 2797: my $NumBars = scalar(@{$Values[0]});
2798: my %ValuesHash;
2799: my $NumSets=1;
2800: foreach my $array (@Values) {
2801: next if (! ref($array));
1.136 matthew 2802: $ValuesHash{$id.'.data.'.$NumSets++} =
1.132 matthew 2803: join(',',@$array);
1.129 matthew 2804: }
1.127 matthew 2805: #
1.136 matthew 2806: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
2807: if ($NumBars < 10) {
2808: $width = 120+$NumBars*15;
2809: $xskip = 1;
2810: $bar_width = 15;
2811: } elsif ($NumBars <= 25) {
2812: $width = 120+$NumBars*11;
2813: $xskip = 5;
2814: $bar_width = 8;
2815: } elsif ($NumBars <= 50) {
2816: $width = 120+$NumBars*8;
2817: $xskip = 5;
2818: $bar_width = 4;
2819: } else {
2820: $width = 120+$NumBars*8;
2821: $xskip = 5;
2822: $bar_width = 4;
2823: }
2824: #
2825: my @Labels;
2826: for (my $i=0;$i<@{$Values[0]};$i++) {
2827: push (@Labels,$i+1);
2828: }
2829: #
1.137 matthew 2830: $Max = 1 if ($Max < 1);
2831: if ( int($Max) < $Max ) {
2832: $Max++;
2833: $Max = int($Max);
2834: }
1.127 matthew 2835: $Title = '' if (! defined($Title));
2836: $xlabel = '' if (! defined($xlabel));
2837: $ylabel = '' if (! defined($ylabel));
1.136 matthew 2838: $ValuesHash{$id.'.title'} = &Apache::lonnet::escape($Title);
2839: $ValuesHash{$id.'.xlabel'} = &Apache::lonnet::escape($xlabel);
2840: $ValuesHash{$id.'.ylabel'} = &Apache::lonnet::escape($ylabel);
1.137 matthew 2841: $ValuesHash{$id.'.y_max_value'} = $Max;
1.136 matthew 2842: $ValuesHash{$id.'.NumBars'} = $NumBars;
2843: $ValuesHash{$id.'.NumSets'} = $NumSets;
2844: $ValuesHash{$id.'.PlotType'} = 'bar';
2845: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
2846: $ValuesHash{$id.'.height'} = $height;
2847: $ValuesHash{$id.'.width'} = $width;
2848: $ValuesHash{$id.'.xskip'} = $xskip;
2849: $ValuesHash{$id.'.bar_width'} = $bar_width;
2850: $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127 matthew 2851: #
1.137 matthew 2852: &Apache::lonnet::appenv(%ValuesHash);
2853: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
2854: }
2855:
2856: ############################################################
2857: ############################################################
2858:
2859: =pod
2860:
2861: =item DrawXYGraph
2862:
1.138 matthew 2863: Facilitates the plotting of data in an XY graph.
2864: Puts plot definition data into the users environment in order for
2865: graph.png to plot it. Returns an <img> tag for the plot.
2866:
2867: Inputs:
2868:
2869: =over 4
2870:
2871: =item $Title: string, the title of the plot
2872:
2873: =item $xlabel: string, text describing the X-axis of the plot
2874:
2875: =item $ylabel: string, text describing the Y-axis of the plot
2876:
2877: =item $Max: scalar, the maximum Y value to use in the plot
2878: If $Max is < any data point, the graph will not be rendered.
2879:
2880: =item $colors: Array ref containing the hex color codes for the data to be
2881: plotted in. If undefined, default values will be used.
2882:
2883: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
2884:
2885: =item $Ydata: Array ref containing Array refs.
2886: Each of the contained arrays will be plotted as a seperate curve.
2887:
2888: =item %Values: hash indicating or overriding any default values which are
2889: passed to graph.png.
2890: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
2891:
2892: =back
2893:
2894: Returns:
2895:
2896: An <img> tag which references graph.png and the appropriate identifying
2897: information for the plot.
2898:
1.137 matthew 2899: =cut
2900:
2901: ############################################################
2902: ############################################################
2903: sub DrawXYGraph {
2904: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
2905: #
2906: # Create the identifier for the graph
2907: my $identifier = &get_cgi_id();
2908: my $id = 'cgi.'.$identifier;
2909: #
2910: $Title = '' if (! defined($Title));
2911: $xlabel = '' if (! defined($xlabel));
2912: $ylabel = '' if (! defined($ylabel));
2913: my %ValuesHash =
2914: (
2915: $id.'.title' => &Apache::lonnet::escape($Title),
2916: $id.'.xlabel' => &Apache::lonnet::escape($xlabel),
2917: $id.'.ylabel' => &Apache::lonnet::escape($ylabel),
2918: $id.'.y_max_value'=> $Max,
2919: $id.'.labels' => join(',',@$Xlabels),
2920: $id.'.PlotType' => 'XY',
2921: );
2922: #
2923: if (defined($colors) && ref($colors) eq 'ARRAY') {
2924: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
2925: }
2926: #
2927: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
2928: return '';
2929: }
2930: my $NumSets=1;
1.138 matthew 2931: foreach my $array (@{$Ydata}){
1.137 matthew 2932: next if (! ref($array));
2933: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
2934: }
1.138 matthew 2935: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137 matthew 2936: #
2937: # Deal with other parameters
2938: while (my ($key,$value) = each(%Values)) {
2939: $ValuesHash{$id.'.'.$key} = $value;
1.127 matthew 2940: }
2941: #
1.136 matthew 2942: &Apache::lonnet::appenv(%ValuesHash);
2943: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
2944: }
2945:
2946: ############################################################
2947: ############################################################
2948:
2949: =pod
2950:
1.138 matthew 2951: =item DrawXYYGraph
2952:
2953: Facilitates the plotting of data in an XY graph with two Y axes.
2954: Puts plot definition data into the users environment in order for
2955: graph.png to plot it. Returns an <img> tag for the plot.
2956:
2957: Inputs:
2958:
2959: =over 4
2960:
2961: =item $Title: string, the title of the plot
2962:
2963: =item $xlabel: string, text describing the X-axis of the plot
2964:
2965: =item $ylabel: string, text describing the Y-axis of the plot
2966:
2967: =item $colors: Array ref containing the hex color codes for the data to be
2968: plotted in. If undefined, default values will be used.
2969:
2970: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
2971:
2972: =item $Ydata1: The first data set
2973:
2974: =item $Min1: The minimum value of the left Y-axis
2975:
2976: =item $Max1: The maximum value of the left Y-axis
2977:
2978: =item $Ydata2: The second data set
2979:
2980: =item $Min2: The minimum value of the right Y-axis
2981:
2982: =item $Max2: The maximum value of the left Y-axis
2983:
2984: =item %Values: hash indicating or overriding any default values which are
2985: passed to graph.png.
2986: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
2987:
2988: =back
2989:
2990: Returns:
2991:
2992: An <img> tag which references graph.png and the appropriate identifying
2993: information for the plot.
1.136 matthew 2994:
2995: =cut
2996:
2997: ############################################################
2998: ############################################################
1.137 matthew 2999: sub DrawXYYGraph {
3000: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
3001: $Ydata2,$Min2,$Max2,%Values)=@_;
1.136 matthew 3002: #
3003: # Create the identifier for the graph
3004: my $identifier = &get_cgi_id();
3005: my $id = 'cgi.'.$identifier;
3006: #
3007: $Title = '' if (! defined($Title));
3008: $xlabel = '' if (! defined($xlabel));
3009: $ylabel = '' if (! defined($ylabel));
3010: my %ValuesHash =
3011: (
3012: $id.'.title' => &Apache::lonnet::escape($Title),
3013: $id.'.xlabel' => &Apache::lonnet::escape($xlabel),
3014: $id.'.ylabel' => &Apache::lonnet::escape($ylabel),
3015: $id.'.labels' => join(',',@$Xlabels),
3016: $id.'.PlotType' => 'XY',
3017: $id.'.NumSets' => 2,
1.137 matthew 3018: $id.'.two_axes' => 1,
3019: $id.'.y1_max_value' => $Max1,
3020: $id.'.y1_min_value' => $Min1,
3021: $id.'.y2_max_value' => $Max2,
3022: $id.'.y2_min_value' => $Min2,
1.136 matthew 3023: );
3024: #
1.137 matthew 3025: if (defined($colors) && ref($colors) eq 'ARRAY') {
3026: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
3027: }
3028: #
3029: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
3030: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136 matthew 3031: return '';
3032: }
3033: my $NumSets=1;
1.137 matthew 3034: foreach my $array ($Ydata1,$Ydata2){
1.136 matthew 3035: next if (! ref($array));
3036: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137 matthew 3037: }
3038: #
3039: # Deal with other parameters
3040: while (my ($key,$value) = each(%Values)) {
3041: $ValuesHash{$id.'.'.$key} = $value;
1.136 matthew 3042: }
3043: #
3044: &Apache::lonnet::appenv(%ValuesHash);
1.130 albertel 3045: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139 matthew 3046: }
3047:
3048: ############################################################
3049: ############################################################
3050:
3051: =pod
3052:
1.157 matthew 3053: =back
3054:
1.139 matthew 3055: =head1 Statistics helper routines?
3056:
3057: Bad place for them but what the hell.
3058:
1.157 matthew 3059: =over 4
3060:
1.139 matthew 3061: =item &chartlink
3062:
3063: Returns a link to the chart for a specific student.
3064:
3065: Inputs:
3066:
3067: =over 4
3068:
3069: =item $linktext: The text of the link
3070:
3071: =item $sname: The students username
3072:
3073: =item $sdomain: The students domain
3074:
3075: =back
3076:
1.157 matthew 3077: =back
3078:
1.139 matthew 3079: =cut
3080:
3081: ############################################################
3082: ############################################################
3083: sub chartlink {
3084: my ($linktext, $sname, $sdomain) = @_;
3085: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
3086: '&SelectedStudent='.&Apache::lonnet::escape($sname.':'.$sdomain).
3087: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
3088: '">'.$linktext.'</a>';
1.153 matthew 3089: }
3090:
3091: #######################################################
3092: #######################################################
3093:
3094: =pod
3095:
3096: =head1 Course Environment Routines
1.157 matthew 3097:
3098: =over 4
1.153 matthew 3099:
3100: =item &restore_course_settings
3101:
3102: =item &store_course_settings
3103:
3104: Restores/Store indicated form parameters from the course environment.
3105: Will not overwrite existing values of the form parameters.
3106:
3107: Inputs:
3108: a scalar describing the data (e.g. 'chart', 'problem_analysis')
3109:
3110: a hash ref describing the data to be stored. For example:
3111:
3112: %Save_Parameters = ('Status' => 'scalar',
3113: 'chartoutputmode' => 'scalar',
3114: 'chartoutputdata' => 'scalar',
3115: 'Section' => 'array',
3116: 'StudentData' => 'array',
3117: 'Maps' => 'array');
3118:
3119: Returns: both routines return nothing
3120:
3121: =cut
3122:
3123: #######################################################
3124: #######################################################
3125: sub store_course_settings {
3126: # save to the environment
3127: # appenv the same items, just to be safe
3128: my $courseid = $ENV{'request.course.id'};
3129: my $coursedom = $ENV{'course.'.$courseid.'.domain'};
3130: my ($prefix,$Settings) = @_;
3131: my %SaveHash;
3132: my %AppHash;
3133: while (my ($setting,$type) = each(%$Settings)) {
3134: my $basename = 'env.internal.'.$prefix.'.'.$setting;
3135: my $envname = 'course.'.$courseid.'.'.$basename;
3136: if (exists($ENV{'form.'.$setting})) {
3137: # Save this value away
3138: if ($type eq 'scalar' &&
3139: (! exists($ENV{$envname}) ||
3140: $ENV{$envname} ne $ENV{'form.'.$setting})) {
3141: $SaveHash{$basename} = $ENV{'form.'.$setting};
3142: $AppHash{$envname} = $ENV{'form.'.$setting};
3143: } elsif ($type eq 'array') {
3144: my $stored_form;
3145: if (ref($ENV{'form.'.$setting})) {
3146: $stored_form = join(',',
3147: map {
3148: &Apache::lonnet::escape($_);
3149: } sort(@{$ENV{'form.'.$setting}}));
3150: } else {
3151: $stored_form =
3152: &Apache::lonnet::escape($ENV{'form.'.$setting});
3153: }
3154: # Determine if the array contents are the same.
3155: if ($stored_form ne $ENV{$envname}) {
3156: $SaveHash{$basename} = $stored_form;
3157: $AppHash{$envname} = $stored_form;
3158: }
3159: }
3160: }
3161: }
3162: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
3163: $coursedom,
3164: $ENV{'course.'.$courseid.'.num'});
3165: if ($put_result !~ /^(ok|delayed)/) {
3166: &Apache::lonnet::logthis('unable to save form parameters, '.
3167: 'got error:'.$put_result);
3168: }
3169: # Make sure these settings stick around in this session, too
3170: &Apache::lonnet::appenv(%AppHash);
3171: return;
3172: }
3173:
3174: sub restore_course_settings {
3175: my $courseid = $ENV{'request.course.id'};
3176: my ($prefix,$Settings) = @_;
3177: while (my ($setting,$type) = each(%$Settings)) {
3178: next if (exists($ENV{'form.'.$setting}));
3179: my $envname = 'course.'.$courseid.'.env.internal.'.$prefix.
3180: '.'.$setting;
3181: if (exists($ENV{$envname})) {
3182: if ($type eq 'scalar') {
3183: $ENV{'form.'.$setting} = $ENV{$envname};
3184: } elsif ($type eq 'array') {
3185: $ENV{'form.'.$setting} = [
3186: map {
3187: &Apache::lonnet::unescape($_);
3188: } split(',',$ENV{$envname})
3189: ];
3190: }
3191: }
3192: }
1.127 matthew 3193: }
3194:
3195: ############################################################
3196: ############################################################
1.154 albertel 3197:
3198: sub propath {
3199: my ($udom,$uname)=@_;
3200: $udom=~s/\W//g;
3201: $uname=~s/\W//g;
3202: my $subdir=$uname.'__';
3203: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
3204: my $proname="$Apache::lonnet::perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
3205: return $proname;
1.156 albertel 3206: }
3207:
3208: sub icon {
3209: my ($file)=@_;
3210: my @file_ext = split(/\./,$file);
3211: my $curfext = $file_ext[-1];
3212: my $iconname="unknown.gif";
3213: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
3214: # The unless conditional that follows is a bit of overkill
3215: $iconname = $curfext.".gif" unless
3216: (!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn');
3217: return $Apache::lonnet::perlvar{'lonIconsURL'}."/$iconname";
1.154 albertel 3218: }
1.84 albertel 3219:
1.41 ng 3220: =pod
3221:
3222: =back
3223:
1.112 bowersj2 3224: =cut
1.41 ng 3225:
1.112 bowersj2 3226: 1;
3227: __END__;
1.41 ng 3228:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>