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

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

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