Annotation of loncom/interface/loncommon.pm, revision 1.182

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

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>