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