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

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

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