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

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

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