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

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

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