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

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

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