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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.492   ! albertel    4: # $Id: loncommon.pm,v 1.491 2006/12/11 21:16:32 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.82      www        61: use Apache::lonmenu();
1.117     www        62: use Apache::lonlocal;
1.139     matthew    63: use HTML::Entities;
1.334     albertel   64: use Apache::lonhtmlcommon();
                     65: use Apache::loncoursedata();
1.344     albertel   66: use Apache::lontexconvert();
1.444     albertel   67: use Apache::lonclonecourse();
1.479     albertel   68: use LONCAPA qw(:DEFAULT :match);
1.117     www        69: 
1.22      www        70: my $readit;
                     71: 
1.157     matthew    72: ##
                     73: ## Global Variables
                     74: ##
1.46      matthew    75: 
1.20      www        76: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41   77: my %language;
1.124     www        78: my %supported_language;
1.12      harris41   79: my %cprtag;
1.192     taceyjo1   80: my %scprtag;
1.351     www        81: my %fe; my %fd; my %fm;
1.41      ng         82: my %category_extensions;
1.12      harris41   83: 
1.63      www        84: # ---------------------------------------------- Designs
                     85: 
                     86: my %designhash;
                     87: 
1.46      matthew    88: # ---------------------------------------------- Thesaurus variables
1.144     matthew    89: #
                     90: # %Keywords:
                     91: #      A hash used by &keyword to determine if a word is considered a keyword.
                     92: # $thesaurus_db_file 
                     93: #      Scalar containing the full path to the thesaurus database.
1.46      matthew    94: 
                     95: my %Keywords;
                     96: my $thesaurus_db_file;
                     97: 
1.144     matthew    98: #
                     99: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    100: # thesaurus.tab, and filecategories.tab.
                    101: #
1.18      www       102: BEGIN {
1.46      matthew   103:     # Variable initialization
                    104:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    105:     #
1.22      www       106:     unless ($readit) {
1.12      harris41  107: # ------------------------------------------------------------------- languages
                    108:     {
1.158     raeburn   109:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    110:                                    '/language.tab';
                    111:         if ( open(my $fh,"<$langtabfile") ) {
1.356     albertel  112:             while (my $line = <$fh>) {
                    113:                 next if ($line=~/^\#/);
                    114:                 chomp($line);
                    115:                 my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
1.158     raeburn   116:                 $language{$key}=$val.' - '.$enc;
                    117:                 if ($sup) {
                    118:                     $supported_language{$key}=$sup;
                    119:                 }
                    120:             }
                    121:             close($fh);
                    122:         }
1.12      harris41  123:     }
                    124: # ------------------------------------------------------------------ copyrights
                    125:     {
1.158     raeburn   126:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    127:                                   '/copyright.tab';
                    128:         if ( open (my $fh,"<$copyrightfile") ) {
1.356     albertel  129:             while (my $line = <$fh>) {
                    130:                 next if ($line=~/^\#/);
                    131:                 chomp($line);
                    132:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   133:                 $cprtag{$key}=$val;
                    134:             }
                    135:             close($fh);
                    136:         }
1.12      harris41  137:     }
1.351     www       138: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  139:     {
                    140:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    141:                                   '/source_copyright.tab';
                    142:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
1.356     albertel  143:             while (my $line = <$fh>) {
                    144:                 next if ($line =~ /^\#/);
                    145:                 chomp($line);
                    146:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  147:                 $scprtag{$key}=$val;
                    148:             }
                    149:             close($fh);
                    150:         }
                    151:     }
1.63      www       152: 
                    153: # -------------------------------------------------------------- domain designs
                    154: 
                    155:     my $filename;
                    156:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                    157:     opendir(DIR,$designdir);
                    158:     while ($filename=readdir(DIR)) {
1.271     albertel  159: 	if ($filename!~/\.tab$/) { next; }
1.479     albertel  160: 	my ($domain)=($filename=~/^($match_domain)\./);
1.271     albertel  161: 	{
                    162: 	    my $designfile = $designdir.'/'.$filename;
                    163: 	    if ( open (my $fh,"<$designfile") ) {
1.356     albertel  164: 		while (my $line = <$fh>) {
                    165: 		    next if ($line =~ /^\#/);
                    166: 		    chomp($line);
                    167: 		    my ($key,$val)=(split(/\=/,$line));
1.271     albertel  168: 		    if ($val) { $designhash{$domain.'.'.$key}=$val; }
                    169: 		}
                    170: 		close($fh);
                    171: 	    }
                    172: 	}
1.63      www       173: 
                    174:     }
                    175:     closedir(DIR);
                    176: 
                    177: 
1.15      harris41  178: # ------------------------------------------------------------- file categories
                    179:     {
1.158     raeburn   180:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    181:                                   '/filecategories.tab';
                    182:         if ( open (my $fh,"<$categoryfile") ) {
1.356     albertel  183: 	    while (my $line = <$fh>) {
                    184: 		next if ($line =~ /^\#/);
                    185: 		chomp($line);
                    186:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.158     raeburn   187:                 push @{$category_extensions{lc($category)}},$extension;
                    188:             }
                    189:             close($fh);
                    190:         }
                    191: 
1.15      harris41  192:     }
1.12      harris41  193: # ------------------------------------------------------------------ file types
                    194:     {
1.158     raeburn   195:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    196:                '/filetypes.tab';
                    197:         if ( open (my $fh,"<$typesfile") ) {
1.356     albertel  198:             while (my $line = <$fh>) {
                    199: 		next if ($line =~ /^\#/);
                    200: 		chomp($line);
                    201:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   202:                 if ($descr ne '') {
                    203:                     $fe{$ending}=lc($emb);
                    204:                     $fd{$ending}=$descr;
1.351     www       205:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   206:                 }
                    207:             }
                    208:             close($fh);
                    209:         }
1.12      harris41  210:     }
1.22      www       211:     &Apache::lonnet::logthis(
1.46      matthew   212:               "<font color=yellow>INFO: Read file types</font>");
1.22      www       213:     $readit=1;
1.46      matthew   214:     }  # end of unless($readit) 
1.32      matthew   215:     
                    216: }
1.112     bowersj2  217: 
1.42      matthew   218: ###############################################################
                    219: ##           HTML and Javascript Helper Functions            ##
                    220: ###############################################################
                    221: 
                    222: =pod 
                    223: 
1.112     bowersj2  224: =head1 HTML and Javascript Functions
1.42      matthew   225: 
1.112     bowersj2  226: =over 4
                    227: 
                    228: =item * browser_and_searcher_javascript ()
                    229: 
                    230: X<browsing, javascript>X<searching, javascript>Returns a string
                    231: containing javascript with two functions, C<openbrowser> and
                    232: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    233: tags.
1.42      matthew   234: 
1.112     bowersj2  235: =item * openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   236: 
                    237: inputs: formname, elementname, only, omit
                    238: 
                    239: formname and elementname indicate the name of the html form and name of
                    240: the element that the results of the browsing selection are to be placed in. 
                    241: 
                    242: Specifying 'only' will restrict the browser to displaying only files
1.185     www       243: with the given extension.  Can be a comma separated list.
1.42      matthew   244: 
                    245: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       246: with the given extension.  Can be a comma separated list.
1.42      matthew   247: 
1.112     bowersj2  248: =item * opensearcher(formname, elementname) [javascript]
1.42      matthew   249: 
                    250: Inputs: formname, elementname
                    251: 
                    252: formname and elementname specify the name of the html form and the name
                    253: of the element the selection from the search results will be placed in.
                    254: 
                    255: =cut
                    256: 
                    257: sub browser_and_searcher_javascript {
1.199     albertel  258:     my ($mode)=@_;
                    259:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  260:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   261:     return <<END;
1.219     albertel  262: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   263:     var editbrowser = null;
1.135     albertel  264:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       265:         var url = '$resurl/?';
1.42      matthew   266:         if (editbrowser == null) {
                    267:             url += 'launch=1&';
                    268:         }
                    269:         url += 'catalogmode=interactive&';
1.199     albertel  270:         url += 'mode=$mode&';
1.42      matthew   271:         url += 'form=' + formname + '&';
                    272:         if (only != null) {
                    273:             url += 'only=' + only + '&';
1.217     albertel  274:         } else {
                    275:             url += 'only=&';
                    276: 	}
1.42      matthew   277:         if (omit != null) {
                    278:             url += 'omit=' + omit + '&';
1.217     albertel  279:         } else {
                    280:             url += 'omit=&';
                    281: 	}
1.135     albertel  282:         if (titleelement != null) {
                    283:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  284:         } else {
                    285: 	    url += 'titleelement=&';
                    286: 	}
1.42      matthew   287:         url += 'element=' + elementname + '';
                    288:         var title = 'Browser';
1.435     albertel  289:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   290:         options += ',width=700,height=600';
                    291:         editbrowser = open(url,title,options,'1');
                    292:         editbrowser.focus();
                    293:     }
                    294:     var editsearcher;
1.135     albertel  295:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   296:         var url = '/adm/searchcat?';
                    297:         if (editsearcher == null) {
                    298:             url += 'launch=1&';
                    299:         }
                    300:         url += 'catalogmode=interactive&';
1.199     albertel  301:         url += 'mode=$mode&';
1.42      matthew   302:         url += 'form=' + formname + '&';
1.135     albertel  303:         if (titleelement != null) {
                    304:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  305:         } else {
                    306: 	    url += 'titleelement=&';
                    307: 	}
1.42      matthew   308:         url += 'element=' + elementname + '';
                    309:         var title = 'Search';
1.435     albertel  310:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   311:         options += ',width=700,height=600';
                    312:         editsearcher = open(url,title,options,'1');
                    313:         editsearcher.focus();
                    314:     }
1.219     albertel  315: // END LON-CAPA Internal -->
1.42      matthew   316: END
1.170     www       317: }
                    318: 
                    319: sub lastresurl {
1.258     albertel  320:     if ($env{'environment.lastresurl'}) {
                    321: 	return $env{'environment.lastresurl'}
1.170     www       322:     } else {
                    323: 	return '/res';
                    324:     }
                    325: }
                    326: 
                    327: sub storeresurl {
                    328:     my $resurl=&Apache::lonnet::clutter(shift);
                    329:     unless ($resurl=~/^\/res/) { return 0; }
                    330:     $resurl=~s/\/$//;
                    331:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
                    332:     &Apache::lonnet::appenv('environment.lastresurl' => $resurl);
                    333:     return 1;
1.42      matthew   334: }
                    335: 
1.74      www       336: sub studentbrowser_javascript {
1.111     www       337:    unless (
1.258     albertel  338:             (($env{'request.course.id'}) && 
1.302     albertel  339:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    340: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    341: 					  '/'.$env{'request.course.sec'})
                    342: 	      ))
1.258     albertel  343:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       344:           ) { return ''; }  
1.74      www       345:    return (<<'ENDSTDBRW');
                    346: <script type="text/javascript" language="Javascript" >
                    347:     var stdeditbrowser;
1.111     www       348:     function openstdbrowser(formname,uname,udom,roleflag) {
1.74      www       349:         var url = '/adm/pickstudent?';
                    350:         var filter;
                    351:         eval('filter=document.'+formname+'.'+uname+'.value;');
                    352:         if (filter != null) {
                    353:            if (filter != '') {
                    354:                url += 'filter='+filter+'&';
                    355: 	   }
                    356:         }
                    357:         url += 'form=' + formname + '&unameelement='+uname+
                    358:                                     '&udomelement='+udom;
1.111     www       359: 	if (roleflag) { url+="&roles=1"; }
1.102     www       360:         var title = 'Student_Browser';
1.74      www       361:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    362:         options += ',width=700,height=600';
                    363:         stdeditbrowser = open(url,title,options,'1');
                    364:         stdeditbrowser.focus();
                    365:     }
                    366: </script>
                    367: ENDSTDBRW
                    368: }
1.42      matthew   369: 
1.74      www       370: sub selectstudent_link {
1.111     www       371:    my ($form,$unameele,$udomele)=@_;
1.258     albertel  372:    if ($env{'request.course.id'}) {  
1.302     albertel  373:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    374: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    375: 					'/'.$env{'request.course.sec'})) {
1.111     www       376: 	   return '';
                    377:        }
                    378:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
1.119     www       379:         '","'.$udomele.'");'."'>".&mt('Select User')."</a>";
1.74      www       380:    }
1.258     albertel  381:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.111     www       382:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
1.119     www       383:         '","'.$udomele.'",1);'."'>".&mt('Select User')."</a>";
1.111     www       384:    }
                    385:    return '';
1.91      www       386: }
                    387: 
                    388: sub coursebrowser_javascript {
1.468     raeburn   389:     my ($domainfilter,$sec_element,$formname)=@_;
1.377     raeburn   390:     my $crs_or_grp_alert = &mt('Please select the type of LON-CAPA entity - Course or Group - for which you wish to add/modify a user role');
1.468     raeburn   391:    my $output = '
1.91      www       392: <script type="text/javascript" language="Javascript" >
1.468     raeburn   393:     var stdeditbrowser;'."\n";
                    394:    $output .= <<"ENDSTDBRW";
1.377     raeburn   395:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,crstype) {
1.91      www       396:         var url = '/adm/pickcourse?';
1.468     raeburn   397:         var domainfilter = '';
                    398:         var formid = getFormIdByName(formname);
                    399:         if (formid > -1) {
                    400:             var domid = getIndexByName(formid,udom);
                    401:             if (domid > -1) {
                    402:                 if (document.forms[formid].elements[domid].type == 'select-one') {
                    403:                     domainfilter=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    404:                 }
                    405:                 if (document.forms[formid].elements[domid].type == 'hidden') {
                    406:                     domainfilter=document.forms[formid].elements[domid].value;
                    407:                 }
                    408:             }
1.91      www       409:         }
1.128     albertel  410:         if (domainfilter != null) {
                    411:            if (domainfilter != '') {
                    412:                url += 'domainfilter='+domainfilter+'&';
                    413: 	   }
                    414:         }
1.91      www       415:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  416: 	                            '&cdomelement='+udom+
                    417:                                     '&cnameelement='+desc;
1.468     raeburn   418:         if (extra_element !=null && extra_element != '') {
                    419:             if (formname == 'rolechoice') {
                    420:                 url += '&roleelement='+extra_element;
                    421:                 if (domainfilter == null || domainfilter == '') {
                    422:                     url += '&domainfilter='+extra_element;
                    423:                 }
1.234     raeburn   424:             }
1.468     raeburn   425:             else {
                    426:                 if (formname == 'portform') {
                    427:                     url += '&setroles='+extra_element;
                    428:                 }
                    429:             }     
1.230     raeburn   430:         }
1.293     raeburn   431:         if (multflag !=null && multflag != '') {
                    432:             url += '&multiple='+multflag;
                    433:         }
1.377     raeburn   434:         if (crstype == 'Course/Group') {
                    435:             if (formname == 'cu') {
                    436:                 crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value; 
                    437:                 if (crstype == "") {
                    438:                     alert("$crs_or_grp_alert");
                    439:                     return;
                    440:                 }
                    441:             }
                    442:         }
                    443:         if (crstype !=null && crstype != '') {
                    444:             url += '&type='+crstype;
                    445:         }
1.102     www       446:         var title = 'Course_Browser';
1.91      www       447:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    448:         options += ',width=700,height=600';
                    449:         stdeditbrowser = open(url,title,options,'1');
                    450:         stdeditbrowser.focus();
                    451:     }
1.468     raeburn   452: 
                    453:     function getFormIdByName(formname) {
                    454:         for (var i=0;i<document.forms.length;i++) {
                    455:             if (document.forms[i].name == formname) {
                    456:                 return i;
                    457:             }
                    458:         }
                    459:         return -1; 
                    460:     }
                    461: 
                    462:     function getIndexByName(formid,item) {
                    463:         for (var i=0;i<document.forms[formid].elements.length;i++) {
                    464:             if (document.forms[formid].elements[i].name == item) {
                    465:                 return i;
                    466:             }
                    467:         }
                    468:         return -1;
                    469:     }
1.91      www       470: ENDSTDBRW
1.468     raeburn   471:     if ($sec_element ne '') {
                    472:         $output .= &setsec_javascript($sec_element,$formname);
                    473:     }
                    474:     $output .= '
                    475: </script>';
                    476:     return $output;
                    477: }
                    478: 
                    479: sub setsec_javascript {
                    480:     my ($sec_element,$formname) = @_;
                    481:     my $setsections = qq|
                    482: function setSect(sectionlist) {
                    483:     var sectionsArray = sectionlist.split(",");
                    484:     var numSections = sectionsArray.length;
                    485:     document.$formname.$sec_element.length = 0;
                    486:     if (numSections == 0) {
                    487:         document.$formname.$sec_element.multiple=false;
                    488:         document.$formname.$sec_element.size=1;
                    489:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    490:     } else {
                    491:         if (numSections == 1) {
                    492:             document.$formname.$sec_element.multiple=false;
                    493:             document.$formname.$sec_element.size=1;
                    494:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    495:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    496:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    497:         } else {
                    498:             for (var i=0; i<numSections; i++) {
                    499:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    500:             }
                    501:             document.$formname.$sec_element.multiple=true
                    502:             if (numSections < 3) {
                    503:                 document.$formname.$sec_element.size=numSections;
                    504:             } else {
                    505:                 document.$formname.$sec_element.size=3;
                    506:             }
                    507:             document.$formname.$sec_element.options[0].selected = false
                    508:         }
                    509:     }
1.91      www       510: }
1.468     raeburn   511: |;
                    512:     return $setsections;
                    513: }
                    514: 
1.91      www       515: 
                    516: sub selectcourse_link {
1.377     raeburn   517:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
1.492   ! albertel  518:    return "<a href='".'javascript:opencrsbrowser("'.$form.'","'.$unameele.
        !           519:         '","'.$udomele.'","'.$desc.'","'.$extra_element.'","'.$multflag.'","'.$selecttype.'");'."'>".&mt('Select Course')."</a>";
1.74      www       520: }
1.42      matthew   521: 
1.273     raeburn   522: sub check_uncheck_jscript {
                    523:     my $jscript = <<"ENDSCRT";
                    524: function checkAll(field) {
                    525:     if (field.length > 0) {
                    526:         for (i = 0; i < field.length; i++) {
                    527:             field[i].checked = true ;
                    528:         }
                    529:     } else {
                    530:         field.checked = true
                    531:     }
                    532: }
                    533:  
                    534: function uncheckAll(field) {
                    535:     if (field.length > 0) {
                    536:         for (i = 0; i < field.length; i++) {
                    537:             field[i].checked = false ;
                    538:         }     } else {
                    539:         field.checked = false ;
                    540:     }
                    541: }
                    542: ENDSCRT
                    543:     return $jscript;
                    544: }
                    545: 
                    546: 
1.42      matthew   547: =pod
1.36      matthew   548: 
1.112     bowersj2  549: =item * linked_select_forms(...)
1.36      matthew   550: 
                    551: linked_select_forms returns a string containing a <script></script> block
                    552: and html for two <select> menus.  The select menus will be linked in that
                    553: changing the value of the first menu will result in new values being placed
                    554: in the second menu.  The values in the select menu will appear in alphabetical
                    555: order.
                    556: 
                    557: linked_select_forms takes the following ordered inputs:
                    558: 
                    559: =over 4
                    560: 
1.112     bowersj2  561: =item * $formname, the name of the <form> tag
1.36      matthew   562: 
1.112     bowersj2  563: =item * $middletext, the text which appears between the <select> tags
1.36      matthew   564: 
1.112     bowersj2  565: =item * $firstdefault, the default value for the first menu
1.36      matthew   566: 
1.112     bowersj2  567: =item * $firstselectname, the name of the first <select> tag
1.36      matthew   568: 
1.112     bowersj2  569: =item * $secondselectname, the name of the second <select> tag
1.36      matthew   570: 
1.112     bowersj2  571: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew   572: 
1.41      ng        573: =back 
                    574: 
1.36      matthew   575: Below is an example of such a hash.  Only the 'text', 'default', and 
                    576: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                    577: values for the first select menu.  The text that coincides with the 
1.41      ng        578: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew   579: and text for the second menu are given in the hash pointed to by 
                    580: $menu{$choice1}->{'select2'}.  
                    581: 
1.112     bowersj2  582:  my %menu = ( A1 => { text =>"Choice A1" ,
                    583:                        default => "B3",
                    584:                        select2 => { 
                    585:                            B1 => "Choice B1",
                    586:                            B2 => "Choice B2",
                    587:                            B3 => "Choice B3",
                    588:                            B4 => "Choice B4"
                    589:                            }
                    590:                    },
                    591:                A2 => { text =>"Choice A2" ,
                    592:                        default => "C2",
                    593:                        select2 => { 
                    594:                            C1 => "Choice C1",
                    595:                            C2 => "Choice C2",
                    596:                            C3 => "Choice C3"
                    597:                            }
                    598:                    },
                    599:                A3 => { text =>"Choice A3" ,
                    600:                        default => "D6",
                    601:                        select2 => { 
                    602:                            D1 => "Choice D1",
                    603:                            D2 => "Choice D2",
                    604:                            D3 => "Choice D3",
                    605:                            D4 => "Choice D4",
                    606:                            D5 => "Choice D5",
                    607:                            D6 => "Choice D6",
                    608:                            D7 => "Choice D7"
                    609:                            }
                    610:                    }
                    611:                );
1.36      matthew   612: 
                    613: =cut
                    614: 
                    615: sub linked_select_forms {
                    616:     my ($formname,
                    617:         $middletext,
                    618:         $firstdefault,
                    619:         $firstselectname,
                    620:         $secondselectname, 
                    621:         $hashref
                    622:         ) = @_;
                    623:     my $second = "document.$formname.$secondselectname";
                    624:     my $first = "document.$formname.$firstselectname";
                    625:     # output the javascript to do the changing
                    626:     my $result = '';
1.219     albertel  627:     $result.="<script type=\"text/javascript\">\n";
1.36      matthew   628:     $result.="var select2data = new Object();\n";
                    629:     $" = '","';
                    630:     my $debug = '';
                    631:     foreach my $s1 (sort(keys(%$hashref))) {
                    632:         $result.="select2data.d_$s1 = new Object();\n";        
                    633:         $result.="select2data.d_$s1.def = new String('".
                    634:             $hashref->{$s1}->{'default'}."');\n";
                    635:         $result.="select2data.d_$s1.values = new Array(";        
                    636:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
                    637:         $result.="\"@s2values\");\n";
                    638:         $result.="select2data.d_$s1.texts = new Array(";        
                    639:         my @s2texts;
                    640:         foreach my $value (@s2values) {
                    641:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
                    642:         }
                    643:         $result.="\"@s2texts\");\n";
                    644:     }
                    645:     $"=' ';
                    646:     $result.= <<"END";
                    647: 
                    648: function select1_changed() {
                    649:     // Determine new choice
                    650:     var newvalue = "d_" + $first.value;
                    651:     // update select2
                    652:     var values     = select2data[newvalue].values;
                    653:     var texts      = select2data[newvalue].texts;
                    654:     var select2def = select2data[newvalue].def;
                    655:     var i;
                    656:     // out with the old
                    657:     for (i = 0; i < $second.options.length; i++) {
                    658:         $second.options[i] = null;
                    659:     }
                    660:     // in with the nuclear
                    661:     for (i=0;i<values.length; i++) {
                    662:         $second.options[i] = new Option(values[i]);
1.143     matthew   663:         $second.options[i].value = values[i];
1.36      matthew   664:         $second.options[i].text = texts[i];
                    665:         if (values[i] == select2def) {
                    666:             $second.options[i].selected = true;
                    667:         }
                    668:     }
                    669: }
                    670: </script>
                    671: END
                    672:     # output the initial values for the selection lists
                    673:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
                    674:     foreach my $value (sort(keys(%$hashref))) {
                    675:         $result.="    <option value=\"$value\" ";
1.253     albertel  676:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www       677:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew   678:     }
                    679:     $result .= "</select>\n";
                    680:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                    681:     $result .= $middletext;
                    682:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
                    683:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
                    684:     foreach my $value (sort(keys(%select2))) {
                    685:         $result.="    <option value=\"$value\" ";        
1.253     albertel  686:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www       687:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew   688:     }
                    689:     $result .= "</select>\n";
                    690:     #    return $debug;
                    691:     return $result;
                    692: }   #  end of sub linked_select_forms {
                    693: 
1.45      matthew   694: =pod
1.44      bowersj2  695: 
1.112     bowersj2  696: =item * help_open_topic($topic, $text, $stayOnPage, $width, $height)
1.44      bowersj2  697: 
1.112     bowersj2  698: Returns a string corresponding to an HTML link to the given help
                    699: $topic, where $topic corresponds to the name of a .tex file in
                    700: /home/httpd/html/adm/help/tex, with underscores replaced by
                    701: spaces. 
                    702: 
                    703: $text will optionally be linked to the same topic, allowing you to
                    704: link text in addition to the graphic. If you do not want to link
                    705: text, but wish to specify one of the later parameters, pass an
                    706: empty string. 
                    707: 
                    708: $stayOnPage is a value that will be interpreted as a boolean. If true,
                    709: the link will not open a new window. If false, the link will open
                    710: a new window using Javascript. (Default is false.) 
                    711: 
                    712: $width and $height are optional numerical parameters that will
                    713: override the width and height of the popped up window, which may
                    714: be useful for certain help topics with big pictures included. 
1.44      bowersj2  715: 
                    716: =cut
                    717: 
                    718: sub help_open_topic {
1.48      bowersj2  719:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
                    720:     $text = "" if (not defined $text);
1.44      bowersj2  721:     $stayOnPage = 0 if (not defined $stayOnPage);
1.258     albertel  722:     if ($env{'browser.interface'} eq 'textual' ||
                    723: 	$env{'environment.remote'} eq 'off' ) {
1.79      www       724: 	$stayOnPage=1;
                    725:     }
1.44      bowersj2  726:     $width = 350 if (not defined $width);
                    727:     $height = 400 if (not defined $height);
                    728:     my $filename = $topic;
                    729:     $filename =~ s/ /_/g;
                    730: 
1.48      bowersj2  731:     my $template = "";
                    732:     my $link;
1.159     www       733: 
                    734:     $topic=~s/\W/\_/g;
1.44      bowersj2  735: 
                    736:     if (!$stayOnPage)
                    737:     {
1.72      bowersj2  738: 	$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  739:     }
                    740:     else
                    741:     {
1.48      bowersj2  742: 	$link = "/adm/help/${filename}.hlp";
                    743:     }
                    744: 
                    745:     # Add the text
                    746:     if ($text ne "")
                    747:     {
1.77      www       748: 	$template .= 
                    749:   "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
1.436     albertel  750:   "<td bgcolor='#5555FF'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
1.48      bowersj2  751:     }
                    752: 
                    753:     # Add the graphic
1.179     matthew   754:     my $title = &mt('Online Help');
1.215     albertel  755:     my $helpicon=&lonhttpdurl("/adm/help/gif/smallHelp.gif");
1.48      bowersj2  756:     $template .= <<"ENDTEMPLATE";
1.436     albertel  757:  <a target="_top" href="$link" title="$title"><img src="$helpicon" border="0" alt="(Help: $topic)" /></a>
1.44      bowersj2  758: ENDTEMPLATE
1.78      www       759:     if ($text ne '') { $template.='</td></tr></table>' };
1.44      bowersj2  760:     return $template;
                    761: 
1.106     bowersj2  762: }
                    763: 
                    764: # This is a quicky function for Latex cheatsheet editing, since it 
                    765: # appears in at least four places
                    766: sub helpLatexCheatsheet {
                    767:     my $other = shift;
                    768:     my $addOther = '';
                    769:     if ($other) {
                    770: 	$addOther = Apache::loncommon::help_open_topic($other, shift,
                    771: 						       undef, undef, 600) .
                    772: 							   '</td><td>';
                    773:     }
                    774:     return '<table><tr><td>'.
                    775: 	$addOther .
                    776: 	&Apache::loncommon::help_open_topic("Greek_Symbols",'Greek Symbols',
                    777: 					    undef,undef,600)
                    778: 	.'</td><td>'.
                    779: 	&Apache::loncommon::help_open_topic("Other_Symbols",'Other Symbols',
                    780: 					    undef,undef,600)
                    781: 	.'</td></tr></table>';
1.172     www       782: }
                    783: 
1.430     albertel  784: sub general_help {
                    785:     my $helptopic='Student_Intro';
                    786:     if ($env{'request.role'}=~/^(ca|au)/) {
                    787: 	$helptopic='Authoring_Intro';
                    788:     } elsif ($env{'request.role'}=~/^cc/) {
                    789: 	$helptopic='Course_Coordination_Intro';
                    790:     }
                    791:     return $helptopic;
                    792: }
                    793: 
                    794: sub update_help_link {
                    795:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                    796:     my $origurl = $ENV{'REQUEST_URI'};
                    797:     $origurl=~s|^/~|/priv/|;
                    798:     my $timestamp = time;
                    799:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                    800:         $$datum = &escape($$datum);
                    801:     }
                    802: 
                    803:     my $banner_link = "/adm/helpmenu?page=banner&amp;topic=$topic&amp;component_help=$component_help&amp;faq=$faq&amp;bug=$bug&amp;origurl=$origurl&amp;stamp=$timestamp&amp;stayonpage=$stayOnPage";
                    804:     my $output .= <<"ENDOUTPUT";
                    805: <script type="text/javascript">
                    806: banner_link = '$banner_link';
                    807: </script>
                    808: ENDOUTPUT
                    809:     return $output;
                    810: }
                    811: 
                    812: # now just updates the help link and generates a blue icon
1.193     raeburn   813: sub help_open_menu {
1.430     albertel  814:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
                    815: 	= @_;
                    816:     
                    817:     $stayOnPage = 0 if (not defined $stayOnPage);
                    818:     if ($env{'browser.interface'} eq 'textual' ||
                    819: 	$env{'environment.remote'} eq 'off' ) {
                    820: 	$stayOnPage=1;
                    821:     }
                    822:     my $output;
                    823:     if ($component_help) {
                    824: 	if (!$text) {
                    825: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                    826: 				       $width,$height);
                    827: 	} else {
                    828: 	    my $help_text;
                    829: 	    $help_text=&unescape($topic);
                    830: 	    $output='<table><tr><td>'.
                    831: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                    832: 				 $width,$height).'</td></tr></table>';
                    833: 	}
                    834:     }
                    835:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                    836:     return $output.$banner_link;
                    837: }
                    838: 
                    839: sub top_nav_help {
                    840:     my ($text) = @_;
                    841: 
1.436     albertel  842:     $text = &mt($text);
                    843: 
                    844:     my $stayOnPage = 
                    845: 	($env{'browser.interface'}  eq 'textual' ||
                    846: 	 $env{'environment.remote'} eq 'off' );
                    847:     my $link=  ($stayOnPage) ? "javascript:helpMenu('display')"
                    848: 	                     : "javascript:helpMenu('open')";
                    849:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stayOnPage);
                    850: 
1.201     raeburn   851:     my $title = &mt('Get help');
1.436     albertel  852: 
                    853:     return <<"END";
                    854: $banner_link
                    855:  <a href="$link" title="$title">$text</a>
                    856: END
                    857: }
                    858: 
                    859: sub help_menu_js {
                    860:     my ($text) = @_;
                    861: 
                    862:     my $stayOnPage = 
                    863: 	($env{'browser.interface'}  eq 'textual' ||
                    864: 	 $env{'environment.remote'} eq 'off' );
                    865: 
                    866:     my $width = 620;
                    867:     my $height = 600;
1.430     albertel  868:     my $helptopic=&general_help();
                    869:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
1.261     albertel  870:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel  871:     my $start_page =
                    872:         &Apache::loncommon::start_page('Help Menu', undef,
                    873: 				       {'frameset'    => 1,
                    874: 					'js_ready'    => 1,
                    875: 					'add_entries' => {
                    876: 					    'border' => '0',
                    877: 					    'rows'   => "105,*",},});
                    878:     my $end_page =
                    879:         &Apache::loncommon::end_page({'frameset' => 1,
                    880: 				      'js_ready' => 1,});
                    881: 
1.436     albertel  882:     my $template .= <<"ENDTEMPLATE";
                    883: <script type="text/javascript">
1.253     albertel  884: // <!-- BEGIN LON-CAPA Internal
                    885: // <![CDATA[
1.430     albertel  886: var banner_link = '';
1.243     raeburn   887: function helpMenu(target) {
                    888:     var caller = this;
                    889:     if (target == 'open') {
                    890:         var newWindow = null;
                    891:         try {
1.262     albertel  892:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn   893:         }
                    894:         catch(error) {
                    895:             writeHelp(caller);
                    896:             return;
                    897:         }
                    898:         if (newWindow) {
                    899:             caller = newWindow;
                    900:         }
1.193     raeburn   901:     }
1.243     raeburn   902:     writeHelp(caller);
                    903:     return;
                    904: }
                    905: function writeHelp(caller) {
1.430     albertel  906:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
1.243     raeburn   907:     caller.document.close()
                    908:     caller.focus()
1.193     raeburn   909: }
1.253     albertel  910: // ]]>
1.219     albertel  911: // END LON-CAPA Internal -->
1.436     albertel  912: </script>
1.193     raeburn   913: ENDTEMPLATE
                    914:     return $template;
                    915: }
                    916: 
1.172     www       917: sub help_open_bug {
                    918:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel  919:     unless ($env{'user.adv'}) { return ''; }
1.172     www       920:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                    921:     $text = "" if (not defined $text);
                    922:     $stayOnPage = 0 if (not defined $stayOnPage);
1.258     albertel  923:     if ($env{'browser.interface'} eq 'textual' ||
                    924: 	$env{'environment.remote'} eq 'off' ) {
1.172     www       925: 	$stayOnPage=1;
                    926:     }
1.184     albertel  927:     $width = 600 if (not defined $width);
                    928:     $height = 600 if (not defined $height);
1.172     www       929: 
                    930:     $topic=~s/\W+/\+/g;
                    931:     my $link='';
                    932:     my $template='';
1.379     albertel  933:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                    934: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www       935:     if (!$stayOnPage)
                    936:     {
                    937: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                    938:     }
                    939:     else
                    940:     {
                    941: 	$link = $url;
                    942:     }
                    943:     # Add the text
                    944:     if ($text ne "")
                    945:     {
                    946: 	$template .= 
                    947:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.436     albertel  948:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
1.172     www       949:     }
                    950: 
                    951:     # Add the graphic
1.179     matthew   952:     my $title = &mt('Report a Bug');
1.215     albertel  953:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www       954:     $template .= <<"ENDTEMPLATE";
1.436     albertel  955:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www       956: ENDTEMPLATE
                    957:     if ($text ne '') { $template.='</td></tr></table>' };
                    958:     return $template;
                    959: 
                    960: }
                    961: 
                    962: sub help_open_faq {
                    963:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel  964:     unless ($env{'user.adv'}) { return ''; }
1.172     www       965:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                    966:     $text = "" if (not defined $text);
                    967:     $stayOnPage = 0 if (not defined $stayOnPage);
1.258     albertel  968:     if ($env{'browser.interface'} eq 'textual' ||
                    969: 	$env{'environment.remote'} eq 'off' ) {
1.172     www       970: 	$stayOnPage=1;
                    971:     }
                    972:     $width = 350 if (not defined $width);
                    973:     $height = 400 if (not defined $height);
                    974: 
                    975:     $topic=~s/\W+/\+/g;
                    976:     my $link='';
                    977:     my $template='';
                    978:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                    979:     if (!$stayOnPage)
                    980:     {
                    981: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                    982:     }
                    983:     else
                    984:     {
                    985: 	$link = $url;
                    986:     }
                    987: 
                    988:     # Add the text
                    989:     if ($text ne "")
                    990:     {
                    991: 	$template .= 
1.173     www       992:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.436     albertel  993:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
1.172     www       994:     }
                    995: 
                    996:     # Add the graphic
1.179     matthew   997:     my $title = &mt('View the FAQ');
1.215     albertel  998:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www       999:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1000:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1001: ENDTEMPLATE
                   1002:     if ($text ne '') { $template.='</td></tr></table>' };
                   1003:     return $template;
                   1004: 
1.44      bowersj2 1005: }
1.37      matthew  1006: 
1.180     matthew  1007: ###############################################################
                   1008: ###############################################################
                   1009: 
1.45      matthew  1010: =pod
                   1011: 
1.256     matthew  1012: =item * change_content_javascript():
                   1013: 
                   1014: This and the next function allow you to create small sections of an
                   1015: otherwise static HTML page that you can update on the fly with
                   1016: Javascript, even in Netscape 4.
                   1017: 
                   1018: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1019: must be written to the HTML page once. It will prove the Javascript
                   1020: function "change(name, content)". Calling the change function with the
                   1021: name of the section 
                   1022: you want to update, matching the name passed to C<changable_area>, and
                   1023: the new content you want to put in there, will put the content into
                   1024: that area.
                   1025: 
                   1026: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1027: to contain room for the original contents. You need to "make space"
                   1028: for whatever changes you wish to make, and be B<sure> to check your
                   1029: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1030: it's adequate for updating a one-line status display, but little more.
                   1031: This script will set the space to 100% width, so you only need to
                   1032: worry about height in Netscape 4.
                   1033: 
                   1034: Modern browsers are much less limiting, and if you can commit to the
                   1035: user not using Netscape 4, this feature may be used freely with
                   1036: pretty much any HTML.
                   1037: 
                   1038: =cut
                   1039: 
                   1040: sub change_content_javascript {
                   1041:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1042:     if ($env{'browser.type'} eq 'netscape' &&
                   1043: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1044: 	return (<<NETSCAPE4);
                   1045: 	function change(name, content) {
                   1046: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1047: 	    doc.open();
                   1048: 	    doc.write(content);
                   1049: 	    doc.close();
                   1050: 	}
                   1051: NETSCAPE4
                   1052:     } else {
                   1053: 	# Otherwise, we need to use semi-standards-compliant code
                   1054: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1055: 	# is really scary, and every useful browser supports it
                   1056: 	return (<<DOMBASED);
                   1057: 	function change(name, content) {
                   1058: 	    element = document.getElementById(name);
                   1059: 	    element.innerHTML = content;
                   1060: 	}
                   1061: DOMBASED
                   1062:     }
                   1063: }
                   1064: 
                   1065: =pod
                   1066: 
                   1067: =item * changable_area($name, $origContent):
                   1068: 
                   1069: This provides a "changable area" that can be modified on the fly via
                   1070: the Javascript code provided in C<change_content_javascript>. $name is
                   1071: the name you will use to reference the area later; do not repeat the
                   1072: same name on a given HTML page more then once. $origContent is what
                   1073: the area will originally contain, which can be left blank.
                   1074: 
                   1075: =cut
                   1076: 
                   1077: sub changable_area {
                   1078:     my ($name, $origContent) = @_;
                   1079: 
1.258     albertel 1080:     if ($env{'browser.type'} eq 'netscape' &&
                   1081: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1082: 	# If this is netscape 4, we need to use the Layer tag
                   1083: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1084:     } else {
                   1085: 	return "<span id='$name'>$origContent</span>";
                   1086:     }
                   1087: }
                   1088: 
                   1089: =pod
                   1090: 
                   1091: =back
                   1092: 
                   1093: =head1 Excel and CSV file utility routines
                   1094: 
                   1095: =over 4
                   1096: 
                   1097: =cut
                   1098: 
                   1099: ###############################################################
                   1100: ###############################################################
                   1101: 
                   1102: =pod
                   1103: 
1.112     bowersj2 1104: =item * csv_translate($text) 
1.37      matthew  1105: 
1.185     www      1106: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  1107: format.
                   1108: 
                   1109: =cut
                   1110: 
1.180     matthew  1111: ###############################################################
                   1112: ###############################################################
1.37      matthew  1113: sub csv_translate {
                   1114:     my $text = shift;
                   1115:     $text =~ s/\"/\"\"/g;
1.209     albertel 1116:     $text =~ s/\n/ /g;
1.37      matthew  1117:     return $text;
                   1118: }
1.180     matthew  1119: 
                   1120: ###############################################################
                   1121: ###############################################################
                   1122: 
                   1123: =pod
                   1124: 
                   1125: =item * define_excel_formats
                   1126: 
                   1127: Define some commonly used Excel cell formats.
                   1128: 
                   1129: Currently supported formats:
                   1130: 
                   1131: =over 4
                   1132: 
                   1133: =item header
                   1134: 
                   1135: =item bold
                   1136: 
                   1137: =item h1
                   1138: 
                   1139: =item h2
                   1140: 
                   1141: =item h3
                   1142: 
1.256     matthew  1143: =item h4
                   1144: 
                   1145: =item i
                   1146: 
1.180     matthew  1147: =item date
                   1148: 
                   1149: =back
                   1150: 
                   1151: Inputs: $workbook
                   1152: 
                   1153: Returns: $format, a hash reference.
                   1154: 
                   1155: =cut
                   1156: 
                   1157: ###############################################################
                   1158: ###############################################################
                   1159: sub define_excel_formats {
                   1160:     my ($workbook) = @_;
                   1161:     my $format;
                   1162:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   1163:                                                 bottom    => 1,
                   1164:                                                 align     => 'center');
                   1165:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   1166:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   1167:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   1168:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  1169:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  1170:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  1171:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  1172:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  1173:     return $format;
                   1174: }
                   1175: 
                   1176: ###############################################################
                   1177: ###############################################################
1.113     bowersj2 1178: 
                   1179: =pod
                   1180: 
1.256     matthew  1181: =item * create_workbook
1.255     matthew  1182: 
                   1183: Create an Excel worksheet.  If it fails, output message on the
                   1184: request object and return undefs.
                   1185: 
                   1186: Inputs: Apache request object
                   1187: 
                   1188: Returns (undef) on failure, 
                   1189:     Excel worksheet object, scalar with filename, and formats 
                   1190:     from &Apache::loncommon::define_excel_formats on success
                   1191: 
                   1192: =cut
                   1193: 
                   1194: ###############################################################
                   1195: ###############################################################
                   1196: sub create_workbook {
                   1197:     my ($r) = @_;
                   1198:         #
                   1199:     # Create the excel spreadsheet
                   1200:     my $filename = '/prtspool/'.
1.258     albertel 1201:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  1202:         time.'_'.rand(1000000000).'.xls';
                   1203:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   1204:     if (! defined($workbook)) {
                   1205:         $r->log_error("Error creating excel spreadsheet $filename: $!");
                   1206:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
                   1207:                             "This error has been logged.  ".
                   1208:                             "Please alert your LON-CAPA administrator").
                   1209:                   '</p>');
                   1210:         return (undef);
                   1211:     }
                   1212:     #
                   1213:     $workbook->set_tempdir('/home/httpd/perl/tmp');
                   1214:     #
                   1215:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   1216:     return ($workbook,$filename,$format);
                   1217: }
                   1218: 
                   1219: ###############################################################
                   1220: ###############################################################
                   1221: 
                   1222: =pod
                   1223: 
1.256     matthew  1224: =item * create_text_file
1.113     bowersj2 1225: 
1.256     matthew  1226: Create a file to write to and eventually make available to the usre.
                   1227: If file creation fails, outputs an error message on the request object and 
                   1228: return undefs.
1.113     bowersj2 1229: 
1.256     matthew  1230: Inputs: Apache request object, and file suffix
1.113     bowersj2 1231: 
1.256     matthew  1232: Returns (undef) on failure, 
                   1233:     Filehandle and filename on success.
1.113     bowersj2 1234: 
                   1235: =cut
                   1236: 
1.256     matthew  1237: ###############################################################
                   1238: ###############################################################
                   1239: sub create_text_file {
                   1240:     my ($r,$suffix) = @_;
                   1241:     if (! defined($suffix)) { $suffix = 'txt'; };
                   1242:     my $fh;
                   1243:     my $filename = '/prtspool/'.
1.258     albertel 1244:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  1245:         time.'_'.rand(1000000000).'.'.$suffix;
                   1246:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   1247:     if (! defined($fh)) {
                   1248:         $r->log_error("Couldn't open $filename for output $!");
                   1249:         $r->print("Problems occured in creating the output file.  ".
                   1250:                   "This error has been logged.  ".
                   1251:                   "Please alert your LON-CAPA administrator.");
1.113     bowersj2 1252:     }
1.256     matthew  1253:     return ($fh,$filename)
1.113     bowersj2 1254: }
                   1255: 
                   1256: 
1.256     matthew  1257: =pod 
1.113     bowersj2 1258: 
                   1259: =back
                   1260: 
                   1261: =cut
1.37      matthew  1262: 
                   1263: ###############################################################
1.33      matthew  1264: ##        Home server <option> list generating code          ##
                   1265: ###############################################################
1.35      matthew  1266: 
1.45      matthew  1267: =pod
                   1268: 
1.112     bowersj2 1269: =head1 Home Server option list generating code
                   1270: 
                   1271: =over 4
                   1272: 
                   1273: =item * get_domains()
1.35      matthew  1274: 
                   1275: Returns an array containing each of the domains listed in the hosts.tab
                   1276: file.
                   1277: 
                   1278: =cut
                   1279: 
                   1280: #-------------------------------------------
1.34      matthew  1281: sub get_domains {
                   1282:     # The code below was stolen from "The Perl Cookbook", p 102, 1st ed.
                   1283:     my @domains;
                   1284:     my %seen;
1.356     albertel 1285:     foreach my $dom (sort(values(%Apache::lonnet::hostdom))) {
                   1286: 	push(@domains,$dom) unless $seen{$dom}++;
1.34      matthew  1287:     }
                   1288:     return @domains;
                   1289: }
1.88      www      1290: 
1.169     www      1291: # ------------------------------------------
                   1292: 
                   1293: sub domain_select {
                   1294:     my ($name,$value,$multiple)=@_;
                   1295:     my %domains=map { 
                   1296: 	$_ => $_.' '.$Apache::lonnet::domaindescription{$_} 
                   1297:     } &get_domains;
                   1298:     if ($multiple) {
                   1299: 	$domains{''}=&mt('Any domain');
1.287     albertel 1300: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      1301:     } else {
                   1302: 	return &select_form($name,$value,%domains);
                   1303:     }
                   1304: }
                   1305: 
1.282     albertel 1306: #-------------------------------------------
                   1307: 
                   1308: =pod
                   1309: 
1.287     albertel 1310: =item * multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 1311: 
                   1312: Returns a string containing a <select> element int multiple mode
                   1313: 
                   1314: 
                   1315: Args:
                   1316:   $name - name of the <select> element
                   1317:   $value - sclara or array ref of values that should already be selected
                   1318:   $size - number of rows long the select element is
1.283     albertel 1319:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 1320:           (shown text should already have been &mt())
1.284     albertel 1321:   $order - (optional) array ref of the order to show the elments in
1.283     albertel 1322: 
1.282     albertel 1323: =cut
                   1324: 
                   1325: #-------------------------------------------
1.169     www      1326: sub multiple_select_form {
1.284     albertel 1327:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      1328:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   1329:     my $output='';
1.191     matthew  1330:     if (! defined($size)) {
                   1331:         $size = 4;
1.283     albertel 1332:         if (scalar(keys(%$hash))<4) {
                   1333:             $size = scalar(keys(%$hash));
1.191     matthew  1334:         }
                   1335:     }
1.169     www      1336:     $output.="\n<select name='$name' size='$size' multiple='1'>";
1.286     banghart 1337:     my @order = ref($order) ? @$order
1.284     albertel 1338:                             : sort(keys(%$hash));
                   1339:     foreach my $key (@order) {
1.356     albertel 1340:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 1341:         $output.='selected="selected" ' if ($selected{$key});
                   1342:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      1343:     }
                   1344:     $output.="</select>\n";
                   1345:     return $output;
                   1346: }
                   1347: 
1.88      www      1348: #-------------------------------------------
                   1349: 
                   1350: =pod
                   1351: 
1.112     bowersj2 1352: =item * select_form($defdom,$name,%hash)
1.88      www      1353: 
                   1354: Returns a string containing a <select name='$name' size='1'> form to 
                   1355: allow a user to select options from a hash option_name => displayed text.  
                   1356: See lonrights.pm for an example invocation and use.
                   1357: 
                   1358: =cut
                   1359: 
                   1360: #-------------------------------------------
                   1361: sub select_form {
                   1362:     my ($def,$name,%hash) = @_;
                   1363:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
1.128     albertel 1364:     my @keys;
                   1365:     if (exists($hash{'select_form_order'})) {
                   1366: 	@keys=@{$hash{'select_form_order'}};
                   1367:     } else {
                   1368: 	@keys=sort(keys(%hash));
                   1369:     }
1.356     albertel 1370:     foreach my $key (@keys) {
                   1371:         $selectform.=
                   1372: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   1373:             ($key eq $def ? 'selected="selected" ' : '').
                   1374:                 ">".&mt($hash{$key})."</option>\n";
1.88      www      1375:     }
                   1376:     $selectform.="</select>";
                   1377:     return $selectform;
                   1378: }
                   1379: 
1.475     www      1380: # For display filters
                   1381: 
                   1382: sub display_filter {
                   1383:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      1384:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.475     www      1385:     return '<nobr><label>'.&mt('Records [_1]',
                   1386: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   1387: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.478     www      1388: 	   '</label></nobr> <nobr>'.
1.475     www      1389:            &mt('Filter [_1]',
1.477     www      1390: 	   &select_form($env{'form.displayfilter'},
                   1391: 			'displayfilter',
                   1392: 			('currentfolder' => 'Current folder/page',
                   1393: 			 'containing' => 'Containing phrase',
                   1394: 			 'none' => 'None'))).
1.478     www      1395: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></nobr>';
1.475     www      1396: }
                   1397: 
1.167     www      1398: sub gradeleveldescription {
                   1399:     my $gradelevel=shift;
                   1400:     my %gradelevels=(0 => 'Not specified',
                   1401: 		     1 => 'Grade 1',
                   1402: 		     2 => 'Grade 2',
                   1403: 		     3 => 'Grade 3',
                   1404: 		     4 => 'Grade 4',
                   1405: 		     5 => 'Grade 5',
                   1406: 		     6 => 'Grade 6',
                   1407: 		     7 => 'Grade 7',
                   1408: 		     8 => 'Grade 8',
                   1409: 		     9 => 'Grade 9',
                   1410: 		     10 => 'Grade 10',
                   1411: 		     11 => 'Grade 11',
                   1412: 		     12 => 'Grade 12',
                   1413: 		     13 => 'Grade 13',
                   1414: 		     14 => '100 Level',
                   1415: 		     15 => '200 Level',
                   1416: 		     16 => '300 Level',
                   1417: 		     17 => '400 Level',
                   1418: 		     18 => 'Graduate Level');
                   1419:     return &mt($gradelevels{$gradelevel});
                   1420: }
                   1421: 
1.163     www      1422: sub select_level_form {
                   1423:     my ($deflevel,$name)=@_;
                   1424:     unless ($deflevel) { $deflevel=0; }
1.167     www      1425:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   1426:     for (my $i=0; $i<=18; $i++) {
                   1427:         $selectform.="<option value=\"$i\" ".
1.253     albertel 1428:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      1429:                 ">".&gradeleveldescription($i)."</option>\n";
                   1430:     }
                   1431:     $selectform.="</select>";
                   1432:     return $selectform;
1.163     www      1433: }
1.167     www      1434: 
1.35      matthew  1435: #-------------------------------------------
                   1436: 
1.45      matthew  1437: =pod
                   1438: 
1.112     bowersj2 1439: =item * select_dom_form($defdom,$name,$includeempty)
1.35      matthew  1440: 
                   1441: Returns a string containing a <select name='$name' size='1'> form to 
                   1442: allow a user to select the domain to preform an operation in.  
                   1443: See loncreateuser.pm for an example invocation and use.
                   1444: 
1.90      www      1445: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   1446: selected");
                   1447: 
1.35      matthew  1448: =cut
                   1449: 
                   1450: #-------------------------------------------
1.34      matthew  1451: sub select_dom_form {
1.90      www      1452:     my ($defdom,$name,$includeempty) = @_;
1.34      matthew  1453:     my @domains = get_domains();
1.90      www      1454:     if ($includeempty) { @domains=('',@domains); }
1.34      matthew  1455:     my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
1.356     albertel 1456:     foreach my $dom (@domains) {
                   1457:         $selectdomain.="<option value=\"$dom\" ".
                   1458:             ($dom eq $defdom ? 'selected="selected" ' : '').
                   1459:                 ">$dom</option>\n";
1.34      matthew  1460:     }
                   1461:     $selectdomain.="</select>";
                   1462:     return $selectdomain;
                   1463: }
                   1464: 
1.35      matthew  1465: #-------------------------------------------
                   1466: 
1.45      matthew  1467: =pod
                   1468: 
1.112     bowersj2 1469: =item * get_library_servers($domain)
1.35      matthew  1470: 
                   1471: Returns a hash which contains keys like '103l3' and values like 
                   1472: 'kirk.lite.msu.edu'.  All of the keys will be for machines in the
                   1473: given $domain.
                   1474: 
                   1475: =cut
                   1476: 
                   1477: #-------------------------------------------
1.52      matthew  1478: sub get_library_servers {
1.33      matthew  1479:     my $domain = shift;
1.52      matthew  1480:     my %library_servers;
1.356     albertel 1481:     foreach my $hostid (keys(%Apache::lonnet::libserv)) {
                   1482:         if ($Apache::lonnet::hostdom{$hostid} eq $domain) {
                   1483:             $library_servers{$hostid} = $Apache::lonnet::hostname{$hostid};
1.33      matthew  1484:         }
                   1485:     }
1.52      matthew  1486:     return %library_servers;
1.33      matthew  1487: }
                   1488: 
1.35      matthew  1489: #-------------------------------------------
                   1490: 
1.45      matthew  1491: =pod
                   1492: 
1.112     bowersj2 1493: =item * home_server_option_list($domain)
1.35      matthew  1494: 
                   1495: returns a string which contains an <option> list to be used in a 
                   1496: <select> form input.  See loncreateuser.pm for an example.
                   1497: 
                   1498: =cut
                   1499: 
                   1500: #-------------------------------------------
1.33      matthew  1501: sub home_server_option_list {
                   1502:     my $domain = shift;
1.52      matthew  1503:     my %servers = &get_library_servers($domain);
1.33      matthew  1504:     my $result = '';
1.356     albertel 1505:     foreach my $hostid (sort(keys(%servers))) {
1.33      matthew  1506:         $result.=
1.356     albertel 1507:             '<option value="'.$hostid.'">'.
                   1508: 	    $hostid.' '.$servers{$hostid}."</option>\n";
1.33      matthew  1509:     }
                   1510:     return $result;
                   1511: }
1.112     bowersj2 1512: 
                   1513: =pod
                   1514: 
                   1515: =back
                   1516: 
                   1517: =cut
1.87      matthew  1518: 
                   1519: ###############################################################
1.112     bowersj2 1520: ##                  Decoding User Agent                      ##
1.87      matthew  1521: ###############################################################
                   1522: 
                   1523: =pod
                   1524: 
1.112     bowersj2 1525: =head1 Decoding the User Agent
                   1526: 
                   1527: =over 4
                   1528: 
                   1529: =item * &decode_user_agent()
1.87      matthew  1530: 
                   1531: Inputs: $r
                   1532: 
                   1533: Outputs:
                   1534: 
                   1535: =over 4
                   1536: 
1.112     bowersj2 1537: =item * $httpbrowser
1.87      matthew  1538: 
1.112     bowersj2 1539: =item * $clientbrowser
1.87      matthew  1540: 
1.112     bowersj2 1541: =item * $clientversion
1.87      matthew  1542: 
1.112     bowersj2 1543: =item * $clientmathml
1.87      matthew  1544: 
1.112     bowersj2 1545: =item * $clientunicode
1.87      matthew  1546: 
1.112     bowersj2 1547: =item * $clientos
1.87      matthew  1548: 
                   1549: =back
                   1550: 
1.157     matthew  1551: =back 
                   1552: 
1.87      matthew  1553: =cut
                   1554: 
                   1555: ###############################################################
                   1556: ###############################################################
                   1557: sub decode_user_agent {
1.247     albertel 1558:     my ($r)=@_;
1.87      matthew  1559:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   1560:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   1561:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 1562:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  1563:     my $clientbrowser='unknown';
                   1564:     my $clientversion='0';
                   1565:     my $clientmathml='';
                   1566:     my $clientunicode='0';
                   1567:     for (my $i=0;$i<=$#browsertype;$i++) {
                   1568:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
                   1569: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   1570: 	    $clientbrowser=$bname;
                   1571:             $httpbrowser=~/$vreg/i;
                   1572: 	    $clientversion=$1;
                   1573:             $clientmathml=($clientversion>=$minv);
                   1574:             $clientunicode=($clientversion>=$univ);
                   1575: 	}
                   1576:     }
                   1577:     my $clientos='unknown';
                   1578:     if (($httpbrowser=~/linux/i) ||
                   1579:         ($httpbrowser=~/unix/i) ||
                   1580:         ($httpbrowser=~/ux/i) ||
                   1581:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   1582:     if (($httpbrowser=~/vax/i) ||
                   1583:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   1584:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   1585:     if (($httpbrowser=~/mac/i) ||
                   1586:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
                   1587:     if ($httpbrowser=~/win/i) { $clientos='win'; }
                   1588:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
                   1589:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
                   1590:             $clientunicode,$clientos,);
                   1591: }
                   1592: 
1.32      matthew  1593: ###############################################################
                   1594: ##    Authentication changing form generation subroutines    ##
                   1595: ###############################################################
                   1596: ##
                   1597: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   1598: ## hash, and have reasonable default values.
                   1599: ##
                   1600: ##    formname = the name given in the <form> tag.
1.35      matthew  1601: #-------------------------------------------
                   1602: 
1.45      matthew  1603: =pod
                   1604: 
1.112     bowersj2 1605: =head1 Authentication Routines
                   1606: 
                   1607: =over 4
                   1608: 
                   1609: =item * authform_xxxxxx
1.35      matthew  1610: 
                   1611: The authform_xxxxxx subroutines provide javascript and html forms which 
                   1612: handle some of the conveniences required for authentication forms.  
                   1613: This is not an optimal method, but it works.  
                   1614: 
                   1615: See loncreateuser.pm for invocation and use examples.
                   1616: 
                   1617: =over 4
                   1618: 
1.112     bowersj2 1619: =item * authform_header
1.35      matthew  1620: 
1.112     bowersj2 1621: =item * authform_authorwarning
1.35      matthew  1622: 
1.112     bowersj2 1623: =item * authform_nochange
1.35      matthew  1624: 
1.112     bowersj2 1625: =item * authform_kerberos
1.35      matthew  1626: 
1.112     bowersj2 1627: =item * authform_internal
1.35      matthew  1628: 
1.112     bowersj2 1629: =item * authform_filesystem
1.35      matthew  1630: 
                   1631: =back
                   1632: 
1.157     matthew  1633: =back 
                   1634: 
1.35      matthew  1635: =cut
                   1636: 
                   1637: #-------------------------------------------
1.32      matthew  1638: sub authform_header{  
                   1639:     my %in = (
                   1640:         formname => 'cu',
1.80      albertel 1641:         kerb_def_dom => '',
1.32      matthew  1642:         @_,
                   1643:     );
                   1644:     $in{'formname'} = 'document.' . $in{'formname'};
                   1645:     my $result='';
1.80      albertel 1646: 
                   1647: #---------------------------------------------- Code for upper case translation
                   1648:     my $Javascript_toUpperCase;
                   1649:     unless ($in{kerb_def_dom}) {
                   1650:         $Javascript_toUpperCase =<<"END";
                   1651:         switch (choice) {
                   1652:            case 'krb': currentform.elements[choicearg].value =
                   1653:                currentform.elements[choicearg].value.toUpperCase();
                   1654:                break;
                   1655:            default:
                   1656:         }
                   1657: END
                   1658:     } else {
                   1659:         $Javascript_toUpperCase = "";
                   1660:     }
                   1661: 
1.165     raeburn  1662:     my $radioval = "'nochange'";
1.174     matthew  1663:     if (exists($in{'curr_authtype'}) &&
                   1664:         defined($in{'curr_authtype'}) &&
                   1665:         $in{'curr_authtype'} ne '') {
                   1666:         $radioval = "'$in{'curr_authtype'}arg'";
                   1667:     }
1.165     raeburn  1668:     my $argfield = 'null';
                   1669:     if ( grep/^mode$/,(keys %in) ) {
                   1670:         if ($in{'mode'} eq 'modifycourse')  {
                   1671:             if ( grep/^curr_authtype$/,(keys %in) ) {
                   1672:                 $radioval = "'$in{'curr_authtype'}'";
                   1673:             }
                   1674:             if ( grep/^curr_autharg$/,(keys %in) ) {
                   1675:                 unless ($in{'curr_autharg'} eq '') {
                   1676:                     $argfield = "'$in{'curr_autharg'}'";
                   1677:                 }
                   1678:             }
                   1679:         }
                   1680:     }
                   1681: 
1.32      matthew  1682:     $result.=<<"END";
                   1683: var current = new Object();
1.165     raeburn  1684: current.radiovalue = $radioval;
                   1685: current.argfield = $argfield;
1.32      matthew  1686: 
                   1687: function changed_radio(choice,currentform) {
                   1688:     var choicearg = choice + 'arg';
                   1689:     // If a radio button in changed, we need to change the argfield
                   1690:     if (current.radiovalue != choice) {
                   1691:         current.radiovalue = choice;
                   1692:         if (current.argfield != null) {
                   1693:             currentform.elements[current.argfield].value = '';
                   1694:         }
                   1695:         if (choice == 'nochange') {
                   1696:             current.argfield = null;
                   1697:         } else {
                   1698:             current.argfield = choicearg;
                   1699:             switch(choice) {
                   1700:                 case 'krb': 
                   1701:                     currentform.elements[current.argfield].value = 
                   1702:                         "$in{'kerb_def_dom'}";
                   1703:                 break;
                   1704:               default:
                   1705:                 break;
                   1706:             }
                   1707:         }
                   1708:     }
                   1709:     return;
                   1710: }
1.22      www      1711: 
1.32      matthew  1712: function changed_text(choice,currentform) {
                   1713:     var choicearg = choice + 'arg';
                   1714:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 1715:         $Javascript_toUpperCase
1.32      matthew  1716:         // clear old field
                   1717:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   1718:             currentform.elements[current.argfield].value = '';
                   1719:         }
                   1720:         current.argfield = choicearg;
                   1721:     }
                   1722:     set_auth_radio_buttons(choice,currentform);
                   1723:     return;
1.20      www      1724: }
1.32      matthew  1725: 
                   1726: function set_auth_radio_buttons(newvalue,currentform) {
                   1727:     var i=0;
                   1728:     while (i < currentform.login.length) {
                   1729:         if (currentform.login[i].value == newvalue) { break; }
                   1730:         i++;
                   1731:     }
                   1732:     if (i == currentform.login.length) {
                   1733:         return;
                   1734:     }
                   1735:     current.radiovalue = newvalue;
                   1736:     currentform.login[i].checked = true;
                   1737:     return;
                   1738: }
                   1739: END
                   1740:     return $result;
                   1741: }
                   1742: 
                   1743: sub authform_authorwarning{
                   1744:     my $result='';
1.144     matthew  1745:     $result='<i>'.
                   1746:         &mt('As a general rule, only authors or co-authors should be '.
                   1747:             'filesystem authenticated '.
                   1748:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  1749:     return $result;
                   1750: }
                   1751: 
                   1752: sub authform_nochange{  
                   1753:     my %in = (
                   1754:               formname => 'document.cu',
                   1755:               kerb_def_dom => 'MSU.EDU',
                   1756:               @_,
                   1757:           );
1.281     albertel 1758:     my $result = '<label>'.&mt('[_1] Do not change login data',
1.144     matthew  1759:                      '<input type="radio" name="login" value="nochange" '.
                   1760:                      'checked="checked" onclick="'.
1.281     albertel 1761:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   1762: 	    '</label>';
1.32      matthew  1763:     return $result;
                   1764: }
                   1765: 
                   1766: sub authform_kerberos{  
                   1767:     my %in = (
                   1768:               formname => 'document.cu',
                   1769:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 1770:               kerb_def_auth => 'krb4',
1.32      matthew  1771:               @_,
                   1772:               );
1.165     raeburn  1773:     my ($check4,$check5,$krbarg);
1.80      albertel 1774:     if ($in{'kerb_def_auth'} eq 'krb5') {
                   1775:        $check5 = " checked=\"on\"";
                   1776:     } else {
                   1777:        $check4 = " checked=\"on\"";
                   1778:     }
1.165     raeburn  1779:     $krbarg = $in{'kerb_def_dom'};
                   1780: 
                   1781:     my $krbcheck = "";
                   1782:     if ( grep/^curr_authtype$/,(keys %in) ) {
                   1783:         if ($in{'curr_authtype'} =~ m/^krb/) {
                   1784:             $krbcheck = " checked=\"on\"";
                   1785:             if ( grep/^curr_autharg$/,(keys %in) ) {
                   1786:                 $krbarg = $in{'curr_autharg'};
                   1787:             }
                   1788:         }
                   1789:     }
                   1790: 
1.144     matthew  1791:     my $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   1792:     my $result .= &mt
                   1793:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 1794:          '[_3] Version 4 [_4] Version 5 [_5]',
                   1795:          '<label><input type="radio" name="login" value="krb" '.
1.165     raeburn  1796:              'onclick="'.$jscall.'" onchange="'.$jscall.'"'.$krbcheck.' />',
1.281     albertel 1797:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  1798:              'value="'.$krbarg.'" '.
1.144     matthew  1799:              'onchange="'.$jscall.'" />',
1.281     albertel 1800:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
                   1801:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
                   1802: 	 '</label>');
1.32      matthew  1803:     return $result;
                   1804: }
                   1805: 
                   1806: sub authform_internal{  
                   1807:     my %args = (
                   1808:                 formname => 'document.cu',
                   1809:                 kerb_def_dom => 'MSU.EDU',
                   1810:                 @_,
                   1811:                 );
1.165     raeburn  1812: 
                   1813:     my $intcheck = "";
                   1814:     my $intarg = 'value=""';
                   1815:     if ( grep/^curr_authtype$/,(keys %args) ) {
                   1816:         if ($args{'curr_authtype'} eq 'int') {
                   1817:             $intcheck = " checked=\"on\"";
                   1818:             if ( grep/^curr_autharg$/,(keys %args) ) {
                   1819:                 $intarg = "value=\"$args{'curr_autharg'}\"";
                   1820:             }
                   1821:         }
                   1822:     }
                   1823: 
1.144     matthew  1824:     my $jscall = "javascript:changed_radio('int',$args{'formname'});";
                   1825:     my $result.=&mt
                   1826:         ('[_1] Internally authenticated (with initial password [_2])',
1.281     albertel 1827:          '<label><input type="radio" name="login" value="int" '.$intcheck.
1.165     raeburn  1828:              ' onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1.281     albertel 1829:          '</label><input type="text" size="10" name="intarg" '.$intarg.
1.165     raeburn  1830:              ' onchange="'.$jscall.'" />');
1.32      matthew  1831:     return $result;
                   1832: }
                   1833: 
                   1834: sub authform_local{  
                   1835:     my %in = (
                   1836:               formname => 'document.cu',
                   1837:               kerb_def_dom => 'MSU.EDU',
                   1838:               @_,
                   1839:               );
1.165     raeburn  1840: 
                   1841:     my $loccheck = "";
                   1842:     my $locarg = 'value=""';
                   1843:     if ( grep/^curr_authtype$/,(keys %in) ) {
                   1844:         if ($in{'curr_authtype'} eq 'loc') {
                   1845:             $loccheck = " checked=\"on\"";
                   1846:             if ( grep/^curr_autharg$/,(keys %in) ) {
                   1847:                 $locarg = "value=\"$in{'curr_autharg'}\"";
                   1848:             }
                   1849:         }
                   1850:     }
                   1851: 
1.144     matthew  1852:     my $jscall = "javascript:changed_radio('loc',$in{'formname'});";
1.160     matthew  1853:     my $result.=&mt('[_1] Local Authentication with argument [_2]',
1.281     albertel 1854:                     '<label><input type="radio" name="login" value="loc" '.$loccheck.
1.165     raeburn  1855:                         ' onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1.281     albertel 1856:                     '</label><input type="text" size="10" name="locarg" '.$locarg.
1.165     raeburn  1857:                         ' onchange="'.$jscall.'" />');
1.32      matthew  1858:     return $result;
                   1859: }
                   1860: 
                   1861: sub authform_filesystem{  
                   1862:     my %in = (
                   1863:               formname => 'document.cu',
                   1864:               kerb_def_dom => 'MSU.EDU',
                   1865:               @_,
                   1866:               );
1.144     matthew  1867:     my $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   1868:     my $result.= &mt
                   1869:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 1870:          '<label><input type="radio" name="login" value="fsys" '.
1.144     matthew  1871:          'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1.281     albertel 1872:          '</label><input type="text" size="10" name="fsysarg" value="" '.
1.144     matthew  1873:                   'onchange="'.$jscall.'" />');
1.32      matthew  1874:     return $result;
                   1875: }
                   1876: 
1.80      albertel 1877: ###############################################################
                   1878: ##    Get Authentication Defaults for Domain                 ##
                   1879: ###############################################################
                   1880: 
                   1881: =pod
                   1882: 
1.112     bowersj2 1883: =head1 Domains and Authentication
                   1884: 
                   1885: Returns default authentication type and an associated argument as
                   1886: listed in file 'domain.tab'.
                   1887: 
                   1888: =over 4
                   1889: 
                   1890: =item * get_auth_defaults
1.80      albertel 1891: 
                   1892: get_auth_defaults($target_domain) returns the default authentication
                   1893: type and an associated argument (initial password or a kerberos domain).
                   1894: These values are stored in lonTabs/domain.tab
                   1895: 
                   1896: ($def_auth, $def_arg) = &get_auth_defaults($target_domain);
                   1897: 
                   1898: If target_domain is not found in domain.tab, returns nothing ('').
                   1899: 
                   1900: =cut
                   1901: 
                   1902: #-------------------------------------------
                   1903: sub get_auth_defaults {
                   1904:     my $domain=shift;
                   1905:     return ($Apache::lonnet::domain_auth_def{$domain},$Apache::lonnet::domain_auth_arg_def{$domain});
                   1906: }
                   1907: ###############################################################
                   1908: ##   End Get Authentication Defaults for Domain              ##
                   1909: ###############################################################
                   1910: 
                   1911: ###############################################################
                   1912: ##    Get Kerberos Defaults for Domain                 ##
                   1913: ###############################################################
                   1914: ##
                   1915: ## Returns default kerberos version and an associated argument
                   1916: ## as listed in file domain.tab. If not listed, provides
                   1917: ## appropriate default domain and kerberos version.
                   1918: ##
                   1919: #-------------------------------------------
                   1920: 
                   1921: =pod
                   1922: 
1.112     bowersj2 1923: =item * get_kerberos_defaults
1.80      albertel 1924: 
                   1925: get_kerberos_defaults($target_domain) returns the default kerberos
                   1926: version and domain. If not found in domain.tabs, it defaults to
                   1927: version 4 and the domain of the server.
                   1928: 
                   1929: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   1930: 
                   1931: =cut
                   1932: 
                   1933: #-------------------------------------------
                   1934: sub get_kerberos_defaults {
                   1935:     my $domain=shift;
                   1936:     my ($krbdef,$krbdefdom) =
                   1937:         &Apache::loncommon::get_auth_defaults($domain);
                   1938:     unless ($krbdef =~/^krb/ && $krbdefdom) {
                   1939:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   1940:         my $krbdefdom=$1;
                   1941:         $krbdefdom=~tr/a-z/A-Z/;
                   1942:         $krbdef = "krb4";
                   1943:     }
                   1944:     return ($krbdef,$krbdefdom);
                   1945: }
1.112     bowersj2 1946: 
                   1947: =pod
                   1948: 
                   1949: =back
                   1950: 
                   1951: =cut
1.32      matthew  1952: 
1.46      matthew  1953: ###############################################################
                   1954: ##                Thesaurus Functions                        ##
                   1955: ###############################################################
1.20      www      1956: 
1.46      matthew  1957: =pod
1.20      www      1958: 
1.112     bowersj2 1959: =head1 Thesaurus Functions
                   1960: 
                   1961: =over 4
                   1962: 
                   1963: =item * initialize_keywords
1.46      matthew  1964: 
                   1965: Initializes the package variable %Keywords if it is empty.  Uses the
                   1966: package variable $thesaurus_db_file.
                   1967: 
                   1968: =cut
                   1969: 
                   1970: ###################################################
                   1971: 
                   1972: sub initialize_keywords {
                   1973:     return 1 if (scalar keys(%Keywords));
                   1974:     # If we are here, %Keywords is empty, so fill it up
                   1975:     #   Make sure the file we need exists...
                   1976:     if (! -e $thesaurus_db_file) {
                   1977:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   1978:                                  " failed because it does not exist");
                   1979:         return 0;
                   1980:     }
                   1981:     #   Set up the hash as a database
                   1982:     my %thesaurus_db;
                   1983:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 1984:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  1985:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   1986:                                  $thesaurus_db_file);
                   1987:         return 0;
                   1988:     } 
                   1989:     #  Get the average number of appearances of a word.
                   1990:     my $avecount = $thesaurus_db{'average.count'};
                   1991:     #  Put keywords (those that appear > average) into %Keywords
                   1992:     while (my ($word,$data)=each (%thesaurus_db)) {
                   1993:         my ($count,undef) = split /:/,$data;
                   1994:         $Keywords{$word}++ if ($count > $avecount);
                   1995:     }
                   1996:     untie %thesaurus_db;
                   1997:     # Remove special values from %Keywords.
1.356     albertel 1998:     foreach my $value ('total.count','average.count') {
                   1999:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.46      matthew  2000:     }
                   2001:     return 1;
                   2002: }
                   2003: 
                   2004: ###################################################
                   2005: 
                   2006: =pod
                   2007: 
1.112     bowersj2 2008: =item * keyword($word)
1.46      matthew  2009: 
                   2010: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   2011: than the average number of times in the thesaurus database.  Calls 
                   2012: &initialize_keywords
                   2013: 
                   2014: =cut
                   2015: 
                   2016: ###################################################
1.20      www      2017: 
                   2018: sub keyword {
1.46      matthew  2019:     return if (!&initialize_keywords());
                   2020:     my $word=lc(shift());
                   2021:     $word=~s/\W//g;
                   2022:     return exists($Keywords{$word});
1.20      www      2023: }
1.46      matthew  2024: 
                   2025: ###############################################################
                   2026: 
                   2027: =pod 
1.20      www      2028: 
1.112     bowersj2 2029: =item * get_related_words
1.46      matthew  2030: 
1.160     matthew  2031: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  2032: an array of words.  If the keyword is not in the thesaurus, an empty array
                   2033: will be returned.  The order of the words returned is determined by the
                   2034: database which holds them.
                   2035: 
                   2036: Uses global $thesaurus_db_file.
                   2037: 
                   2038: =cut
                   2039: 
                   2040: ###############################################################
                   2041: sub get_related_words {
                   2042:     my $keyword = shift;
                   2043:     my %thesaurus_db;
                   2044:     if (! -e $thesaurus_db_file) {
                   2045:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   2046:                                  "failed because the file does not exist");
                   2047:         return ();
                   2048:     }
                   2049:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 2050:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  2051:         return ();
                   2052:     } 
                   2053:     my @Words=();
1.429     www      2054:     my $count=0;
1.46      matthew  2055:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 2056: 	# The first element is the number of times
                   2057: 	# the word appears.  We do not need it now.
1.429     www      2058: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   2059: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   2060: 	my $threshold=$mostfrequentcount/10;
                   2061:         foreach my $possibleword (@RelatedWords) {
                   2062:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   2063:             if ($wordcount>$threshold) {
                   2064: 		push(@Words,$word);
                   2065:                 $count++;
                   2066:                 if ($count>10) { last; }
                   2067: 	    }
1.20      www      2068:         }
                   2069:     }
1.46      matthew  2070:     untie %thesaurus_db;
                   2071:     return @Words;
1.14      harris41 2072: }
1.46      matthew  2073: 
1.112     bowersj2 2074: =pod
                   2075: 
                   2076: =back
                   2077: 
                   2078: =cut
1.61      www      2079: 
                   2080: # -------------------------------------------------------------- Plaintext name
1.81      albertel 2081: =pod
                   2082: 
1.112     bowersj2 2083: =head1 User Name Functions
                   2084: 
                   2085: =over 4
                   2086: 
1.226     albertel 2087: =item * plainname($uname,$udom,$first)
1.81      albertel 2088: 
1.112     bowersj2 2089: Takes a users logon name and returns it as a string in
1.226     albertel 2090: "first middle last generation" form 
                   2091: if $first is set to 'lastname' then it returns it as
                   2092: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 2093: 
                   2094: =cut
1.61      www      2095: 
1.295     www      2096: 
1.81      albertel 2097: ###############################################################
1.61      www      2098: sub plainname {
1.226     albertel 2099:     my ($uname,$udom,$first)=@_;
1.295     www      2100:     my %names=&getnames($uname,$udom);
1.226     albertel 2101:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   2102: 					  $names{'middlename'},
                   2103: 					  $names{'lastname'},
                   2104: 					  $names{'generation'},$first);
                   2105:     $name=~s/^\s+//;
1.62      www      2106:     $name=~s/\s+$//;
                   2107:     $name=~s/\s+/ /g;
1.353     albertel 2108:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      2109:     return $name;
1.61      www      2110: }
1.66      www      2111: 
                   2112: # -------------------------------------------------------------------- Nickname
1.81      albertel 2113: =pod
                   2114: 
1.112     bowersj2 2115: =item * nickname($uname,$udom)
1.81      albertel 2116: 
                   2117: Gets a users name and returns it as a string as
                   2118: 
                   2119: "&quot;nickname&quot;"
1.66      www      2120: 
1.81      albertel 2121: if the user has a nickname or
                   2122: 
                   2123: "first middle last generation"
                   2124: 
                   2125: if the user does not
                   2126: 
                   2127: =cut
1.66      www      2128: 
                   2129: sub nickname {
                   2130:     my ($uname,$udom)=@_;
1.295     www      2131:     my %names=&getnames($uname,$udom);
1.68      albertel 2132:     my $name=$names{'nickname'};
1.66      www      2133:     if ($name) {
                   2134:        $name='&quot;'.$name.'&quot;'; 
                   2135:     } else {
                   2136:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   2137: 	     $names{'lastname'}.' '.$names{'generation'};
                   2138:        $name=~s/\s+$//;
                   2139:        $name=~s/\s+/ /g;
                   2140:     }
                   2141:     return $name;
                   2142: }
                   2143: 
1.295     www      2144: sub getnames {
                   2145:     my ($uname,$udom)=@_;
1.433     albertel 2146:     if ($udom eq 'public' && $uname eq 'public') {
                   2147: 	return ('lastname' => &mt('Public'));
                   2148:     }
1.295     www      2149:     my $id=$uname.':'.$udom;
                   2150:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   2151:     if ($cached) {
                   2152: 	return %{$names};
                   2153:     } else {
                   2154: 	my %loadnames=&Apache::lonnet::get('environment',
                   2155:                     ['firstname','middlename','lastname','generation','nickname'],
                   2156: 					 $udom,$uname);
                   2157: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   2158: 	return %loadnames;
                   2159:     }
                   2160: }
1.61      www      2161: 
1.466     albertel 2162: sub getemails {
                   2163:     my ($uname,$udom)=@_;
                   2164:     if ($udom eq 'public' && $uname eq 'public') {
                   2165: 	return;
                   2166:     }
1.467     www      2167:     if (!$udom) { $udom=$env{'user.domain'}; }
                   2168:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 2169:     my $id=$uname.':'.$udom;
                   2170:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   2171:     if ($cached) {
                   2172: 	return %{$names};
                   2173:     } else {
                   2174: 	my %loadnames=&Apache::lonnet::get('environment',
                   2175:                     			   ['notification','critnotification',
                   2176: 					    'permanentemail'],
                   2177: 					   $udom,$uname);
                   2178: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   2179: 	return %loadnames;
                   2180:     }
                   2181: }
                   2182: 
1.61      www      2183: # ------------------------------------------------------------------ Screenname
1.81      albertel 2184: 
                   2185: =pod
                   2186: 
1.112     bowersj2 2187: =item * screenname($uname,$udom)
1.81      albertel 2188: 
                   2189: Gets a users screenname and returns it as a string
                   2190: 
                   2191: =cut
1.61      www      2192: 
                   2193: sub screenname {
                   2194:     my ($uname,$udom)=@_;
1.258     albertel 2195:     if ($uname eq $env{'user.name'} &&
                   2196: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 2197:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 2198:     return $names{'screenname'};
1.62      www      2199: }
                   2200: 
1.212     albertel 2201: 
1.62      www      2202: # ------------------------------------------------------------- Message Wrapper
                   2203: 
                   2204: sub messagewrapper {
1.369     www      2205:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      2206:     return 
1.441     albertel 2207:         '<a href="/adm/email?compose=individual&amp;'.
                   2208:         'recname='.$username.'&amp;recdom='.$domain.
                   2209: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  2210:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      2211: }
                   2212: # --------------------------------------------------------------- Notes Wrapper
                   2213: 
                   2214: sub noteswrapper {
                   2215:     my ($link,$un,$do)=@_;
                   2216:     return 
                   2217: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
1.62      www      2218: }
                   2219: # ------------------------------------------------------------- Aboutme Wrapper
                   2220: 
                   2221: sub aboutmewrapper {
1.166     www      2222:     my ($link,$username,$domain,$target)=@_;
1.447     raeburn  2223:     if (!defined($username)  && !defined($domain)) {
                   2224:         return;
                   2225:     }
1.205     www      2226:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.454     banghart 2227: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal page").'">'.$link.'</a>';
1.62      www      2228: }
                   2229: 
                   2230: # ------------------------------------------------------------ Syllabus Wrapper
                   2231: 
                   2232: 
                   2233: sub syllabuswrapper {
1.109     matthew  2234:     my ($linktext,$coursedir,$domain,$fontcolor)=@_;
                   2235:     if ($fontcolor) { 
                   2236:         $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>'; 
                   2237:     }
1.208     matthew  2238:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      2239: }
1.14      harris41 2240: 
1.208     matthew  2241: sub track_student_link {
1.268     albertel 2242:     my ($linktext,$sname,$sdom,$target,$start) = @_;
                   2243:     my $link ="/adm/trackstudent?";
1.208     matthew  2244:     my $title = 'View recent activity';
                   2245:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   2246:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 2247:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  2248:         $title .= ' of this student';
1.268     albertel 2249:     } 
1.208     matthew  2250:     if (defined($target) && $target !~ /^\s*$/) {
                   2251:         $target = qq{target="$target"};
                   2252:     } else {
                   2253:         $target = '';
                   2254:     }
1.268     albertel 2255:     if ($start) { $link.='&amp;start='.$start; }
1.448     albertel 2256:     
                   2257:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   2258: 	&help_open_topic('View_recent_activity');
1.208     matthew  2259: }
                   2260: 
1.112     bowersj2 2261: =pod
                   2262: 
                   2263: =back
                   2264: 
                   2265: =head1 Access .tab File Data
                   2266: 
                   2267: =over 4
                   2268: 
                   2269: =item * languageids() 
                   2270: 
                   2271: returns list of all language ids
                   2272: 
                   2273: =cut
                   2274: 
1.14      harris41 2275: sub languageids {
1.16      harris41 2276:     return sort(keys(%language));
1.14      harris41 2277: }
                   2278: 
1.112     bowersj2 2279: =pod
                   2280: 
                   2281: =item * languagedescription() 
                   2282: 
                   2283: returns description of a specified language id
                   2284: 
                   2285: =cut
                   2286: 
1.14      harris41 2287: sub languagedescription {
1.125     www      2288:     my $code=shift;
                   2289:     return  ($supported_language{$code}?'* ':'').
                   2290:             $language{$code}.
1.126     www      2291: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      2292: }
                   2293: 
                   2294: sub plainlanguagedescription {
                   2295:     my $code=shift;
                   2296:     return $language{$code};
                   2297: }
                   2298: 
                   2299: sub supportedlanguagecode {
                   2300:     my $code=shift;
                   2301:     return $supported_language{$code};
1.97      www      2302: }
                   2303: 
1.112     bowersj2 2304: =pod
                   2305: 
                   2306: =item * copyrightids() 
                   2307: 
                   2308: returns list of all copyrights
                   2309: 
                   2310: =cut
                   2311: 
                   2312: sub copyrightids {
                   2313:     return sort(keys(%cprtag));
                   2314: }
                   2315: 
                   2316: =pod
                   2317: 
                   2318: =item * copyrightdescription() 
                   2319: 
                   2320: returns description of a specified copyright id
                   2321: 
                   2322: =cut
                   2323: 
                   2324: sub copyrightdescription {
1.166     www      2325:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 2326: }
1.197     matthew  2327: 
                   2328: =pod
                   2329: 
1.192     taceyjo1 2330: =item * source_copyrightids() 
                   2331: 
                   2332: returns list of all source copyrights
                   2333: 
                   2334: =cut
                   2335: 
                   2336: sub source_copyrightids {
                   2337:     return sort(keys(%scprtag));
                   2338: }
                   2339: 
                   2340: =pod
                   2341: 
                   2342: =item * source_copyrightdescription() 
                   2343: 
                   2344: returns description of a specified source copyright id
                   2345: 
                   2346: =cut
                   2347: 
                   2348: sub source_copyrightdescription {
                   2349:     return &mt($scprtag{shift(@_)});
                   2350: }
1.112     bowersj2 2351: 
                   2352: =pod
                   2353: 
                   2354: =item * filecategories() 
                   2355: 
                   2356: returns list of all file categories
                   2357: 
                   2358: =cut
                   2359: 
                   2360: sub filecategories {
                   2361:     return sort(keys(%category_extensions));
                   2362: }
                   2363: 
                   2364: =pod
                   2365: 
                   2366: =item * filecategorytypes() 
                   2367: 
                   2368: returns list of file types belonging to a given file
                   2369: category
                   2370: 
                   2371: =cut
                   2372: 
                   2373: sub filecategorytypes {
1.356     albertel 2374:     my ($cat) = @_;
                   2375:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 2376: }
                   2377: 
                   2378: =pod
                   2379: 
                   2380: =item * fileembstyle() 
                   2381: 
                   2382: returns embedding style for a specified file type
                   2383: 
                   2384: =cut
                   2385: 
                   2386: sub fileembstyle {
                   2387:     return $fe{lc(shift(@_))};
1.169     www      2388: }
                   2389: 
1.351     www      2390: sub filemimetype {
                   2391:     return $fm{lc(shift(@_))};
                   2392: }
                   2393: 
1.169     www      2394: 
                   2395: sub filecategoryselect {
                   2396:     my ($name,$value)=@_;
1.189     matthew  2397:     return &select_form($value,$name,
1.169     www      2398: 			'' => &mt('Any category'),
                   2399: 			map { $_,$_ } sort(keys(%category_extensions)));
1.112     bowersj2 2400: }
                   2401: 
                   2402: =pod
                   2403: 
                   2404: =item * filedescription() 
                   2405: 
                   2406: returns description for a specified file type
                   2407: 
                   2408: =cut
                   2409: 
                   2410: sub filedescription {
1.188     matthew  2411:     my $file_description = $fd{lc(shift())};
                   2412:     $file_description =~ s:([\[\]]):~$1:g;
                   2413:     return &mt($file_description);
1.112     bowersj2 2414: }
                   2415: 
                   2416: =pod
                   2417: 
                   2418: =item * filedescriptionex() 
                   2419: 
                   2420: returns description for a specified file type with
                   2421: extra formatting
                   2422: 
                   2423: =cut
                   2424: 
                   2425: sub filedescriptionex {
                   2426:     my $ex=shift;
1.188     matthew  2427:     my $file_description = $fd{lc($ex)};
                   2428:     $file_description =~ s:([\[\]]):~$1:g;
                   2429:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 2430: }
                   2431: 
                   2432: # End of .tab access
                   2433: =pod
                   2434: 
                   2435: =back
                   2436: 
                   2437: =cut
                   2438: 
                   2439: # ------------------------------------------------------------------ File Types
                   2440: sub fileextensions {
                   2441:     return sort(keys(%fe));
                   2442: }
                   2443: 
1.97      www      2444: # ----------------------------------------------------------- Display Languages
                   2445: # returns a hash with all desired display languages
                   2446: #
                   2447: 
                   2448: sub display_languages {
                   2449:     my %languages=();
1.356     albertel 2450:     foreach my $lang (&preferred_languages()) {
                   2451: 	$languages{$lang}=1;
1.97      www      2452:     }
                   2453:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 2454:     if ($env{'form.displaylanguage'}) {
1.356     albertel 2455: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   2456: 	    $languages{$lang}=1;
1.97      www      2457:         }
                   2458:     }
                   2459:     return %languages;
1.14      harris41 2460: }
                   2461: 
1.117     www      2462: sub preferred_languages {
                   2463:     my @languages=();
1.258     albertel 2464:     if ($env{'course.'.$env{'request.course.id'}.'.languages'}) {
1.117     www      2465: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,
1.258     albertel 2466: 	         $env{'course.'.$env{'request.course.id'}.'.languages'}));
1.177     www      2467:     }
1.258     albertel 2468:     if ($env{'environment.languages'}) {
1.459     albertel 2469: 	@languages=(@languages,
                   2470: 		    split(/\s*(\,|\;|\:)\s*/,$env{'environment.languages'}));
1.118     www      2471:     }
1.162     www      2472:     my $browser=(split(/\;/,$ENV{'HTTP_ACCEPT_LANGUAGE'}))[0];
                   2473:     if ($browser) {
                   2474: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,$browser));
                   2475:     }
1.258     albertel 2476:     if ($Apache::lonnet::domain_lang_def{$env{'user.domain'}}) {
1.118     www      2477: 	@languages=(@languages,
1.258     albertel 2478: 		$Apache::lonnet::domain_lang_def{$env{'user.domain'}});
1.118     www      2479:     }
1.258     albertel 2480:     if ($Apache::lonnet::domain_lang_def{$env{'request.role.domain'}}) {
1.118     www      2481: 	@languages=(@languages,
1.258     albertel 2482: 		$Apache::lonnet::domain_lang_def{$env{'request.role.domain'}});
1.118     www      2483:     }
                   2484:     if ($Apache::lonnet::domain_lang_def{
                   2485: 	                          $Apache::lonnet::perlvar{'lonDefDomain'}}) {
                   2486: 	@languages=(@languages,
                   2487: 		$Apache::lonnet::domain_lang_def{
                   2488:                                   $Apache::lonnet::perlvar{'lonDefDomain'}});
                   2489:     }
                   2490: # turn "en-ca" into "en-ca,en"
                   2491:     my @genlanguages;
1.356     albertel 2492:     foreach my $lang (@languages) {
                   2493: 	unless ($lang=~/\w/) { next; }
                   2494: 	push (@genlanguages,$lang);
                   2495: 	if ($lang=~/(\-|\_)/) {
                   2496: 	    push(@genlanguages,(split(/(\-|\_)/,$lang))[0]);
1.118     www      2497: 	}
                   2498:     }
                   2499:     return @genlanguages;
1.117     www      2500: }
                   2501: 
1.112     bowersj2 2502: ###############################################################
                   2503: ##               Student Answer Attempts                     ##
                   2504: ###############################################################
                   2505: 
                   2506: =pod
                   2507: 
                   2508: =head1 Alternate Problem Views
                   2509: 
                   2510: =over 4
                   2511: 
                   2512: =item * get_previous_attempt($symb, $username, $domain, $course,
                   2513:     $getattempt, $regexp, $gradesub)
                   2514: 
                   2515: Return string with previous attempt on problem. Arguments:
                   2516: 
                   2517: =over 4
                   2518: 
                   2519: =item * $symb: Problem, including path
                   2520: 
                   2521: =item * $username: username of the desired student
                   2522: 
                   2523: =item * $domain: domain of the desired student
1.14      harris41 2524: 
1.112     bowersj2 2525: =item * $course: Course ID
1.14      harris41 2526: 
1.112     bowersj2 2527: =item * $getattempt: Leave blank for all attempts, otherwise put
                   2528:     something
1.14      harris41 2529: 
1.112     bowersj2 2530: =item * $regexp: if string matches this regexp, the string will be
                   2531:     sent to $gradesub
1.14      harris41 2532: 
1.112     bowersj2 2533: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 2534: 
1.112     bowersj2 2535: =back
1.14      harris41 2536: 
1.112     bowersj2 2537: The output string is a table containing all desired attempts, if any.
1.16      harris41 2538: 
1.112     bowersj2 2539: =cut
1.1       albertel 2540: 
                   2541: sub get_previous_attempt {
1.43      ng       2542:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
1.1       albertel 2543:   my $prevattempts='';
1.43      ng       2544:   no strict 'refs';
1.1       albertel 2545:   if ($symb) {
1.3       albertel 2546:     my (%returnhash)=
                   2547:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 2548:     if ($returnhash{'version'}) {
                   2549:       my %lasthash=();
                   2550:       my $version;
                   2551:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.356     albertel 2552:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   2553: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
1.19      harris41 2554:         }
1.1       albertel 2555:       }
1.43      ng       2556:       $prevattempts='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1.40      ng       2557:       $prevattempts.='<table border="0" width="100%"><tr bgcolor="#e6ffff"><td>History</td>';
1.356     albertel 2558:       foreach my $key (sort(keys(%lasthash))) {
                   2559: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       2560: 	if ($#parts > 0) {
1.31      albertel 2561: 	  my $data=$parts[-1];
                   2562: 	  pop(@parts);
1.40      ng       2563: 	  $prevattempts.='<td>Part '.join('.',@parts).'<br />'.$data.'&nbsp;</td>';
1.31      albertel 2564: 	} else {
1.41      ng       2565: 	  if ($#parts == 0) {
                   2566: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   2567: 	  } else {
                   2568: 	    $prevattempts.='<th>'.$ign.'</th>';
                   2569: 	  }
1.31      albertel 2570: 	}
1.16      harris41 2571:       }
1.40      ng       2572:       if ($getattempt eq '') {
                   2573: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
                   2574: 	  $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Transaction '.$version.'</td>';
1.356     albertel 2575: 	    foreach my $key (sort(keys(%lasthash))) {
1.40      ng       2576: 	       my $value;
1.356     albertel 2577: 	       if ($key =~ /timestamp/) {
                   2578: 		  $value=scalar(localtime($returnhash{$version.':'.$key}));
1.40      ng       2579: 	       } else {
1.356     albertel 2580: 		  $value=$returnhash{$version.':'.$key};
1.40      ng       2581: 	       }
1.369     www      2582: 	       $prevattempts.='<td>'.&unescape($value).'&nbsp;</td>';   
1.40      ng       2583: 	    }
                   2584: 	 }
1.1       albertel 2585:       }
1.40      ng       2586:       $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Current</td>';
1.356     albertel 2587:       foreach my $key (sort(keys(%lasthash))) {
1.5       albertel 2588: 	my $value;
1.356     albertel 2589: 	if ($key =~ /timestamp/) {
                   2590: 	  $value=scalar(localtime($lasthash{$key}));
1.5       albertel 2591: 	} else {
1.356     albertel 2592: 	  $value=$lasthash{$key};
1.5       albertel 2593: 	}
1.369     www      2594: 	$value=&unescape($value);
1.356     albertel 2595: 	if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
1.40      ng       2596: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
1.16      harris41 2597:       }
1.40      ng       2598:       $prevattempts.='</tr></table></td></tr></table>';
1.1       albertel 2599:     } else {
                   2600:       $prevattempts='Nothing submitted - no attempts.';
                   2601:     }
                   2602:   } else {
                   2603:     $prevattempts='No data.';
                   2604:   }
1.10      albertel 2605: }
                   2606: 
1.107     albertel 2607: sub relative_to_absolute {
                   2608:     my ($url,$output)=@_;
                   2609:     my $parser=HTML::TokeParser->new(\$output);
                   2610:     my $token;
                   2611:     my $thisdir=$url;
                   2612:     my @rlinks=();
                   2613:     while ($token=$parser->get_token) {
                   2614: 	if ($token->[0] eq 'S') {
                   2615: 	    if ($token->[1] eq 'a') {
                   2616: 		if ($token->[2]->{'href'}) {
                   2617: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   2618: 		}
                   2619: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   2620: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   2621: 	    } elsif ($token->[1] eq 'base') {
                   2622: 		$thisdir=$token->[2]->{'href'};
                   2623: 	    }
                   2624: 	}
                   2625:     }
                   2626:     $thisdir=~s-/[^/]*$--;
1.356     albertel 2627:     foreach my $link (@rlinks) {
                   2628: 	unless (($link=~/^http:\/\//i) ||
                   2629: 		($link=~/^\//) ||
                   2630: 		($link=~/^javascript:/i) ||
                   2631: 		($link=~/^mailto:/i) ||
                   2632: 		($link=~/^\#/)) {
                   2633: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   2634: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 2635: 	}
                   2636:     }
                   2637: # -------------------------------------------------- Deal with Applet codebases
                   2638:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   2639:     return $output;
                   2640: }
                   2641: 
1.112     bowersj2 2642: =pod
                   2643: 
                   2644: =item * get_student_view
                   2645: 
                   2646: show a snapshot of what student was looking at
                   2647: 
                   2648: =cut
                   2649: 
1.10      albertel 2650: sub get_student_view {
1.186     albertel 2651:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      2652:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 2653:   my (%form);
1.10      albertel 2654:   my @elements=('symb','courseid','domain','username');
                   2655:   foreach my $element (@elements) {
1.186     albertel 2656:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 2657:   }
1.186     albertel 2658:   if (defined($moreenv)) {
                   2659:       %form=(%form,%{$moreenv});
                   2660:   }
1.236     albertel 2661:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 2662:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.186     albertel 2663:   my $userview=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 2664:   $userview=~s/\<body[^\>]*\>//gi;
                   2665:   $userview=~s/\<\/body\>//gi;
                   2666:   $userview=~s/\<html\>//gi;
                   2667:   $userview=~s/\<\/html\>//gi;
                   2668:   $userview=~s/\<head\>//gi;
                   2669:   $userview=~s/\<\/head\>//gi;
                   2670:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 2671:   $userview=&relative_to_absolute($feedurl,$userview);
1.11      albertel 2672:   return $userview;
                   2673: }
                   2674: 
1.112     bowersj2 2675: =pod
                   2676: 
                   2677: =item * get_student_answers() 
                   2678: 
                   2679: show a snapshot of how student was answering problem
                   2680: 
                   2681: =cut
                   2682: 
1.11      albertel 2683: sub get_student_answers {
1.100     sakharuk 2684:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      2685:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 2686:   my (%moreenv);
1.11      albertel 2687:   my @elements=('symb','courseid','domain','username');
                   2688:   foreach my $element (@elements) {
1.186     albertel 2689:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 2690:   }
1.186     albertel 2691:   $moreenv{'grade_target'}='answer';
                   2692:   %moreenv=(%form,%moreenv);
                   2693:   my $userview=&Apache::lonnet::ssi('/res/'.$feedurl,%moreenv);
1.10      albertel 2694:   return $userview;
1.1       albertel 2695: }
1.116     albertel 2696: 
                   2697: =pod
                   2698: 
                   2699: =item * &submlink()
                   2700: 
1.242     albertel 2701: Inputs: $text $uname $udom $symb $target
1.116     albertel 2702: 
                   2703: Returns: A link to grades.pm such as to see the SUBM view of a student
                   2704: 
                   2705: =cut
                   2706: 
                   2707: ###############################################
                   2708: sub submlink {
1.242     albertel 2709:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 2710:     if (!($uname && $udom)) {
                   2711: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 2712: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 2713: 	if (!$symb) { $symb=$cursymb; }
                   2714:     }
1.254     matthew  2715:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      2716:     $symb=&escape($symb);
1.242     albertel 2717:     if ($target) { $target="target=\"$target\""; }
                   2718:     return '<a href="/adm/grades?&command=submission&'.
                   2719: 	'symb='.$symb.'&student='.$uname.
                   2720: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
                   2721: }
                   2722: ##############################################
                   2723: 
                   2724: =pod
                   2725: 
                   2726: =item * &pgrdlink()
                   2727: 
                   2728: Inputs: $text $uname $udom $symb $target
                   2729: 
                   2730: Returns: A link to grades.pm such as to see the PGRD view of a student
                   2731: 
                   2732: =cut
                   2733: 
                   2734: ###############################################
                   2735: sub pgrdlink {
                   2736:     my $link=&submlink(@_);
                   2737:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   2738:     return $link;
                   2739: }
                   2740: ##############################################
                   2741: 
                   2742: =pod
                   2743: 
                   2744: =item * &pprmlink()
                   2745: 
                   2746: Inputs: $text $uname $udom $symb $target
                   2747: 
                   2748: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 2749: student and a specific resource
1.242     albertel 2750: 
                   2751: =cut
                   2752: 
                   2753: ###############################################
                   2754: sub pprmlink {
                   2755:     my ($text,$uname,$udom,$symb,$target)=@_;
                   2756:     if (!($uname && $udom)) {
                   2757: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 2758: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 2759: 	if (!$symb) { $symb=$cursymb; }
                   2760:     }
1.254     matthew  2761:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      2762:     $symb=&escape($symb);
1.242     albertel 2763:     if ($target) { $target="target=\"$target\""; }
                   2764:     return '<a href="/adm/parmset?&command=set&'.
                   2765: 	'symb='.$symb.'&uname='.$uname.
                   2766: 	'&udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 2767: }
                   2768: ##############################################
1.37      matthew  2769: 
1.112     bowersj2 2770: =pod
                   2771: 
                   2772: =back
                   2773: 
                   2774: =cut
                   2775: 
1.37      matthew  2776: ###############################################
1.51      www      2777: 
                   2778: 
                   2779: sub timehash {
                   2780:     my @ltime=localtime(shift);
                   2781:     return ( 'seconds' => $ltime[0],
                   2782:              'minutes' => $ltime[1],
                   2783:              'hours'   => $ltime[2],
                   2784:              'day'     => $ltime[3],
                   2785:              'month'   => $ltime[4]+1,
                   2786:              'year'    => $ltime[5]+1900,
                   2787:              'weekday' => $ltime[6],
                   2788:              'dayyear' => $ltime[7]+1,
                   2789:              'dlsav'   => $ltime[8] );
                   2790: }
                   2791: 
1.370     www      2792: sub utc_string {
                   2793:     my ($date)=@_;
1.371     www      2794:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      2795: }
                   2796: 
1.51      www      2797: sub maketime {
                   2798:     my %th=@_;
                   2799:     return POSIX::mktime(
                   2800:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      2801:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      2802: }
                   2803: 
                   2804: #########################################
1.51      www      2805: 
                   2806: sub findallcourses {
1.482     raeburn  2807:     my ($roles,$uname,$udom) = @_;
1.355     albertel 2808:     my %roles;
                   2809:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 2810:     my %courses;
1.51      www      2811:     my $now=time;
1.482     raeburn  2812:     if (!defined($uname)) {
                   2813:         $uname = $env{'user.name'};
                   2814:     }
                   2815:     if (!defined($udom)) {
                   2816:         $udom = $env{'user.domain'};
                   2817:     }
                   2818:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   2819:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
                   2820:         if (!%roles) {
                   2821:             %roles = (
                   2822:                        cc => 1,
                   2823:                        in => 1,
                   2824:                        ep => 1,
                   2825:                        ta => 1,
                   2826:                        cr => 1,
                   2827:                        st => 1,
                   2828:              );
                   2829:         }
                   2830:         foreach my $entry (keys(%roleshash)) {
                   2831:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   2832:             if ($trole =~ /^cr/) { 
                   2833:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   2834:             } else {
                   2835:                 next if (!exists($roles{$trole}));
                   2836:             }
                   2837:             if ($tend) {
                   2838:                 next if ($tend < $now);
                   2839:             }
                   2840:             if ($tstart) {
                   2841:                 next if ($tstart > $now);
                   2842:             }
                   2843:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
                   2844:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
                   2845:             if ($secpart eq '') {
                   2846:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   2847:                 $sec = 'none';
                   2848:                 $realsec = '';
                   2849:             } else {
                   2850:                 $cnum = $cnumpart;
                   2851:                 ($sec,$role) = split(/_/,$secpart);
                   2852:                 $realsec = $sec;
1.490     raeburn  2853:             }
1.482     raeburn  2854:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
                   2855:         }
                   2856:     } else {
                   2857:         foreach my $key (keys(%env)) {
1.483     albertel 2858: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   2859:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  2860: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   2861: 	        next if ($role eq 'ca' || $role eq 'aa');
                   2862: 	        next if (%roles && !exists($roles{$role}));
                   2863: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   2864:                 my $active=1;
                   2865:                 if ($starttime) {
                   2866: 		    if ($now<$starttime) { $active=0; }
                   2867:                 }
                   2868:                 if ($endtime) {
                   2869:                     if ($now>$endtime) { $active=0; }
                   2870:                 }
                   2871:                 if ($active) {
                   2872:                     if ($sec eq '') {
                   2873:                         $sec = 'none';
                   2874:                     }
                   2875:                     $courses{$cdom.'_'.$cnum}{$sec} = 
                   2876:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
1.474     raeburn  2877:                 }
                   2878:             }
1.51      www      2879:         }
                   2880:     }
1.474     raeburn  2881:     return %courses;
1.51      www      2882: }
1.37      matthew  2883: 
1.54      www      2884: ###############################################
1.474     raeburn  2885: 
                   2886: sub blockcheck {
1.482     raeburn  2887:     my ($setters,$activity,$uname,$udom) = @_;
1.490     raeburn  2888: 
                   2889:     if (!defined($udom)) {
                   2890:         $udom = $env{'user.domain'};
                   2891:     }
                   2892:     if (!defined($uname)) {
                   2893:         $uname = $env{'user.name'};
                   2894:     }
                   2895: 
                   2896:     my ($startblock,$endblock);
                   2897: 
                   2898:     # If uname and udom are for a course, check for blocks in the course.
                   2899: 
                   2900:     if (&Apache::lonnet::is_course($udom,$uname)) {
                   2901:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
                   2902:         ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
                   2903:         return ($startblock,$endblock);
                   2904:     }
1.474     raeburn  2905: 
1.482     raeburn  2906:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  2907: 
1.490     raeburn  2908:     # If uname is for a user, and activity is course-specific, i.e.,
                   2909:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  2910: 
1.490     raeburn  2911:     if (($activity eq 'boards' || $activity eq 'chat' ||
                   2912:          $activity eq 'groups') && ($env{'request.course.id'})) {
                   2913:         foreach my $key (keys(%live_courses)) {
                   2914:             if ($key ne $env{'request.course.id'}) {
                   2915:                 delete($live_courses{$key});
                   2916:             }
                   2917:         }
                   2918:     }
                   2919: 
                   2920:     my $otheruser = 0;
                   2921:     my %own_courses;
                   2922:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   2923:         # Resource belongs to user other than current user.
                   2924:         $otheruser = 1;
                   2925:         # Gather courses for current user
                   2926:         %own_courses = 
                   2927:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   2928:     }
                   2929: 
                   2930:     # Gather active course roles - course coordinator, instructor, 
                   2931:     # exam proctor, ta, student, or custom role.
1.474     raeburn  2932: 
                   2933:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  2934:         my ($cdom,$cnum);
                   2935:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   2936:             $cdom = $env{'course.'.$course.'.domain'};
                   2937:             $cnum = $env{'course.'.$course.'.num'};
                   2938:         } else {
1.490     raeburn  2939:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  2940:         }
                   2941:         my $no_ownblock = 0;
                   2942:         my $no_userblock = 0;
1.490     raeburn  2943:         if ($otheruser) {
                   2944:             # Check if current user has 'evb' priv for this
                   2945:             if (defined($own_courses{$course})) {
                   2946:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   2947:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   2948:                     if ($sec ne 'none') {
                   2949:                         $checkrole .= '/'.$sec;
                   2950:                     }
                   2951:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   2952:                         $no_ownblock = 1;
                   2953:                         last;
                   2954:                     }
                   2955:                 }
                   2956:             }
                   2957:             # if they have 'evb' priv and are currently not playing student
                   2958:             next if (($no_ownblock) &&
                   2959:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   2960:         }
1.474     raeburn  2961:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  2962:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  2963:             if ($sec ne 'none') {
1.482     raeburn  2964:                 $checkrole .= '/'.$sec;
1.474     raeburn  2965:             }
1.490     raeburn  2966:             # Resource belongs to user other than current user.
                   2967:             # Assemble privs for that user, and check for 'evb' priv.  
                   2968:             if ($otheruser) {
                   2969:                 # Resource belongs to user other than current user.
                   2970:                 # Assemble privs for that user, and check for 'evb' priv.
1.482     raeburn  2971:                 my ($trole,$tdom,$tnum,$tsec);
                   2972:                 my $entry = $live_courses{$course}{$sec};
                   2973:                 if ($entry =~ /^cr/) {
                   2974:                     ($trole,$tdom,$tnum,$tsec) = 
                   2975:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   2976:                 } else {
                   2977:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   2978:                 }
                   2979:                 my ($spec,$area,$trest,%allroles,%userroles);
                   2980:                 $area = '/'.$tdom.'/'.$tnum;
                   2981:                 $trest = $tnum;
                   2982:                 if ($tsec ne '') {
                   2983:                     $area .= '/'.$tsec;
                   2984:                     $trest .= '/'.$tsec;
                   2985:                 }
                   2986:                 $spec = $trole.'.'.$area;
                   2987:                 if ($trole =~ /^cr/) {
                   2988:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   2989:                                                       $tdom,$spec,$trest,$area);
                   2990:                 } else {
                   2991:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   2992:                                                        $tdom,$spec,$trest,$area);
                   2993:                 }
                   2994:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.486     raeburn  2995:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   2996:                     if ($1) {
                   2997:                         $no_userblock = 1;
                   2998:                         last;
                   2999:                     }
                   3000:                 }
1.490     raeburn  3001:             } else {
                   3002:                 # Resource belongs to current user
                   3003:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  3004:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   3005:                     $no_ownblock = 1;
                   3006:                     last;
                   3007:                 }
1.474     raeburn  3008:             }
                   3009:         }
                   3010:         # if they have the evb priv and are currently not playing student
1.482     raeburn  3011:         next if (($no_ownblock) &&
1.491     albertel 3012:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  3013:         next if ($no_userblock);
1.474     raeburn  3014: 
1.490     raeburn  3015:         # Retrieve blocking times and identity of blocker for course
                   3016:         # of specified user, unless user has 'evb' privilege.
                   3017: 
                   3018:         ($startblock,$endblock)=&get_blocks($setters,$activity,$cdom,$cnum);
                   3019:     }
                   3020:     return ($startblock,$endblock);
                   3021: }
                   3022: 
                   3023: sub get_blocks {
                   3024:     my ($setters,$activity,$cdom,$cnum) = @_;
                   3025:     my $startblock = 0;
                   3026:     my $endblock = 0;
                   3027:     my $course = $cdom.'_'.$cnum;
                   3028:     $setters->{$course} = {};
                   3029:     $setters->{$course}{'staff'} = [];
                   3030:     $setters->{$course}{'times'} = [];
                   3031:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   3032:     foreach my $record (keys(%records)) {
                   3033:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
                   3034:         if ($start <= time && $end >= time) {
                   3035:             my ($staff_name,$staff_dom,$title,$blocks) =
                   3036:                 &parse_block_record($records{$record});
                   3037:             if ($blocks->{$activity} eq 'on') {
                   3038:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   3039:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
1.491     albertel 3040:                 if ( ($startblock == 0) || ($startblock > $start) ) {
                   3041:                     $startblock = $start;
1.490     raeburn  3042:                 }
1.491     albertel 3043:                 if ( ($endblock == 0) || ($endblock < $end) ) {
                   3044:                     $endblock = $end;
1.474     raeburn  3045:                 }
                   3046:             }
                   3047:         }
                   3048:     }
                   3049:     return ($startblock,$endblock);
                   3050: }
                   3051: 
                   3052: sub parse_block_record {
                   3053:     my ($record) = @_;
                   3054:     my ($setuname,$setudom,$title,$blocks);
                   3055:     if (ref($record) eq 'HASH') {
                   3056:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   3057:         $title = &unescape($record->{'event'});
                   3058:         $blocks = $record->{'blocks'};
                   3059:     } else {
                   3060:         my @data = split(/:/,$record,3);
                   3061:         if (scalar(@data) eq 2) {
                   3062:             $title = $data[1];
                   3063:             ($setuname,$setudom) = split(/@/,$data[0]);
                   3064:         } else {
                   3065:             ($setuname,$setudom,$title) = @data;
                   3066:         }
                   3067:         $blocks = { 'com' => 'on' };
                   3068:     }
                   3069:     return ($setuname,$setudom,$title,$blocks);
                   3070: }
                   3071: 
                   3072: sub build_block_table {
                   3073:     my ($startblock,$endblock,$setters) = @_;
                   3074:     my %lt = &Apache::lonlocal::texthash(
                   3075:         'cacb' => 'Currently active communication blocks',
                   3076:         'cour' => 'Course',
                   3077:         'dura' => 'Duration',
                   3078:         'blse' => 'Block set by'
                   3079:     );
                   3080:     my $output;
1.476     raeburn  3081:     $output = '<br />'.$lt{'cacb'}.':<br />';
1.474     raeburn  3082:     $output .= &start_data_table();
                   3083:     $output .= '
                   3084: <tr>
                   3085:  <th>'.$lt{'cour'}.'</th>
                   3086:  <th>'.$lt{'dura'}.'</th>
                   3087:  <th>'.$lt{'blse'}.'</th>
                   3088: </tr>
                   3089: ';
                   3090:     foreach my $course (keys(%{$setters})) {
                   3091:         my %courseinfo=&Apache::lonnet::coursedescription($course);
                   3092:         for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
                   3093:             my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
1.490     raeburn  3094:             my $fullname = &plainname($uname,$udom);
                   3095:             if (defined($env{'user.name'}) && defined($env{'user.domain'})
                   3096:                 && $env{'user.name'} ne 'public' 
                   3097:                 && $env{'user.domain'} ne 'public') {
                   3098:                 $fullname = &aboutmewrapper($fullname,$uname,$udom);
                   3099:             }
1.474     raeburn  3100:             my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
                   3101:             $openblock = &Apache::lonlocal::locallocaltime($openblock);
                   3102:             $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
                   3103:             $output .= &Apache::loncommon::start_data_table_row().
                   3104:                        '<td>'.$courseinfo{'description'}.'</td>'.
                   3105:                        '<td>'.$openblock.' to '.$closeblock.'</td>'.
1.490     raeburn  3106:                        '<td>'.$fullname.'</td>'.
1.474     raeburn  3107:                         &Apache::loncommon::end_data_table_row();
                   3108:         }
                   3109:     }
                   3110:     $output .= &end_data_table();
                   3111: }
                   3112: 
1.490     raeburn  3113: sub blocking_status {
                   3114:     my ($activity,$uname,$udom) = @_;
                   3115:     my %setters;
                   3116:     my ($blocked,$output,$ownitem,$is_course);
                   3117:     my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
                   3118:     if ($startblock && $endblock) {
                   3119:         $blocked = 1;
                   3120:         if (wantarray) {
                   3121:             my $category;
                   3122:             if ($activity eq 'boards') {
                   3123:                 $category = 'Discussion posts in this course';
                   3124:             } elsif ($activity eq 'blogs') {
                   3125:                 $category = 'Blogs';
                   3126:             } elsif ($activity eq 'port') {
                   3127:                 if (defined($uname) && defined($udom)) {
                   3128:                     if ($uname eq $env{'user.name'} &&
                   3129:                         $udom eq $env{'user.domain'}) {
                   3130:                         $ownitem = 1;
                   3131:                     }
                   3132:                 }
                   3133:                 $is_course = &Apache::lonnet::is_course($udom,$uname);
                   3134:                 if ($ownitem) { 
                   3135:                     $category = 'Your portfolio files';  
                   3136:                 } elsif ($is_course) {
                   3137:                     my $coursedesc;
                   3138:                     foreach my $course (keys(%setters)) {
                   3139:                         my %courseinfo =
                   3140:                              &Apache::lonnet::coursedescription($course);
                   3141:                         $coursedesc = $courseinfo{'description'};
                   3142:                     }
                   3143:                     $category = "Group files in the course '$coursedesc'";
                   3144:                 } else {
                   3145:                     $category = 'Portfolio files belonging to ';
                   3146:                     if ($env{'user.name'} eq 'public' && 
                   3147:                         $env{'user.domain'} eq 'public') {
                   3148:                         $category .= &plainname($uname,$udom);
                   3149:                     } else {
                   3150:                         $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);  
                   3151:                     }
                   3152:                 }
                   3153:             } elsif ($activity eq 'groups') {
                   3154:                 $category = 'Groups in this course';
                   3155:             }
                   3156:             my $showstart = &Apache::lonlocal::locallocaltime($startblock);
                   3157:             my $showend = &Apache::lonlocal::locallocaltime($endblock);
                   3158:             $output = '<br />'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'<br />';
                   3159:             if (!($activity eq 'port' && !($ownitem) && !($is_course))) { 
                   3160:                 $output .= &build_block_table($startblock,$endblock,\%setters);
                   3161:             }
                   3162:         }
                   3163:     }
                   3164:     if (wantarray) {
                   3165:         return ($blocked,$output);
                   3166:     } else {
                   3167:         return $blocked;
                   3168:     }
                   3169: }
                   3170: 
1.60      matthew  3171: ###############################################
                   3172: 
                   3173: =pod
                   3174: 
1.112     bowersj2 3175: =head1 Domain Template Functions
                   3176: 
                   3177: =over 4
                   3178: 
                   3179: =item * &determinedomain()
1.60      matthew  3180: 
                   3181: Inputs: $domain (usually will be undef)
                   3182: 
1.63      www      3183: Returns: Determines which domain should be used for designs
1.60      matthew  3184: 
                   3185: =cut
1.54      www      3186: 
1.60      matthew  3187: ###############################################
1.63      www      3188: sub determinedomain {
                   3189:     my $domain=shift;
                   3190:    if (! $domain) {
1.60      matthew  3191:         # Determine domain if we have not been given one
                   3192:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
1.258     albertel 3193:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   3194:         if ($env{'request.role.domain'}) { 
                   3195:             $domain=$env{'request.role.domain'}; 
1.60      matthew  3196:         }
                   3197:     }
1.63      www      3198:     return $domain;
                   3199: }
                   3200: ###############################################
                   3201: =pod
                   3202: 
1.112     bowersj2 3203: =item * &domainlogo()
1.63      www      3204: 
                   3205: Inputs: $domain (usually will be undef)
                   3206: 
                   3207: Returns: A link to a domain logo, if the domain logo exists.
                   3208: If the domain logo does not exist, a description of the domain.
                   3209: 
                   3210: =cut
1.112     bowersj2 3211: 
1.63      www      3212: ###############################################
                   3213: sub domainlogo {
                   3214:     my $domain = &determinedomain(shift);    
                   3215:      # See if there is a logo
1.59      www      3216:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$domain.'.gif') {
1.215     albertel 3217: 	my $logo=&lonhttpdurl("/adm/lonDomLogos/$domain.gif");
                   3218:         return '<img src="'.$logo.'" alt="'.$domain.'" />';
1.60      matthew  3219:     } elsif(exists($Apache::lonnet::domaindescription{$domain})) {
                   3220:         return $Apache::lonnet::domaindescription{$domain};
1.59      www      3221:     } else {
1.60      matthew  3222:         return '';
1.59      www      3223:     }
                   3224: }
1.63      www      3225: ##############################################
                   3226: 
                   3227: =pod
                   3228: 
1.112     bowersj2 3229: =item * &designparm()
1.63      www      3230: 
                   3231: Inputs: $which parameter; $domain (usually will be undef)
                   3232: 
                   3233: Returns: value of designparamter $which
                   3234: 
                   3235: =cut
1.112     bowersj2 3236: 
1.397     albertel 3237: 
1.400     albertel 3238: ##############################################
1.397     albertel 3239: sub designparm {
                   3240:     my ($which,$domain)=@_;
1.258     albertel 3241:     if ($env{'browser.blackwhite'} eq 'on') {
1.110     www      3242: 	if ($which=~/\.(font|alink|vlink|link)$/) {
                   3243: 	    return '#000000';
                   3244: 	}
                   3245: 	if ($which=~/\.(pgbg|sidebg)$/) {
                   3246: 	    return '#FFFFFF';
                   3247: 	}
                   3248: 	if ($which=~/\.tabbg$/) {
                   3249: 	    return '#CCCCCC';
                   3250: 	}
                   3251:     }
1.397     albertel 3252:     if (exists($env{'environment.color.'.$which})) {
1.258     albertel 3253: 	return $env{'environment.color.'.$which};
1.96      www      3254:     }
1.63      www      3255:     $domain=&determinedomain($domain);
1.397     albertel 3256:     if (exists($designhash{$domain.'.'.$which})) {
1.63      www      3257: 	return $designhash{$domain.'.'.$which};
                   3258:     } else {
                   3259:         return $designhash{'default.'.$which};
                   3260:     }
                   3261: }
1.59      www      3262: 
1.60      matthew  3263: ###############################################
                   3264: ###############################################
                   3265: 
                   3266: =pod
                   3267: 
1.112     bowersj2 3268: =back
                   3269: 
                   3270: =head1 HTTP Helpers
                   3271: 
                   3272: =over 4
                   3273: 
                   3274: =item * &bodytag()
1.60      matthew  3275: 
                   3276: Returns a uniform header for LON-CAPA web pages.
                   3277: 
                   3278: Inputs: 
                   3279: 
1.112     bowersj2 3280: =over 4
                   3281: 
                   3282: =item * $title, A title to be displayed on the page.
                   3283: 
                   3284: =item * $function, the current role (can be undef).
                   3285: 
                   3286: =item * $addentries, extra parameters for the <body> tag.
                   3287: 
                   3288: =item * $bodyonly, if defined, only return the <body> tag.
                   3289: 
                   3290: =item * $domain, if defined, force a given domain.
                   3291: 
                   3292: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      3293:             text interface only)
1.60      matthew  3294: 
1.326     albertel 3295: =item * $customtitle, alternate text to use instead of $title
                   3296:                       in the title box that appears, this text
                   3297:                       is not auto translated like the $title is
1.309     albertel 3298: 
                   3299: =item * $notopbar, if true, keep the 'what is this' info but remove the
                   3300:                    navigational links
1.317     albertel 3301: 
1.338     albertel 3302: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   3303: 
                   3304: =item * $notitle, if true keep the nav controls, but remove the title bar
                   3305: 
1.361     albertel 3306: =item * $no_inline_link, if true and in remote mode, don't show the 
                   3307:          'Switch To Inline Menu' link
                   3308: 
1.460     albertel 3309: =item * $args, optional argument valid values are
                   3310:             no_auto_mt_title -> prevents &mt()ing the title arg
                   3311: 
1.112     bowersj2 3312: =back
                   3313: 
1.60      matthew  3314: Returns: A uniform header for LON-CAPA web pages.  
                   3315: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   3316: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   3317: other decorations will be returned.
                   3318: 
                   3319: =cut
                   3320: 
1.54      www      3321: sub bodytag {
1.309     albertel 3322:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
1.460     albertel 3323: 	$notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
1.339     albertel 3324: 
1.460     albertel 3325:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.339     albertel 3326: 
1.183     matthew  3327:     $function = &get_users_function() if (!$function);
1.339     albertel 3328:     my $img =    &designparm($function.'.img',$domain);
                   3329:     my $font =   &designparm($function.'.font',$domain);
                   3330:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   3331: 
                   3332:     my %design = ( 'style'   => 'margin-top: 0px',
                   3333: 		   'bgcolor' => $pgbg,
                   3334: 		   'text'    => $font,
                   3335:                    'alink'   => &designparm($function.'.alink',$domain),
                   3336: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   3337: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 3338:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 3339: 
1.63      www      3340:  # role and realm
1.378     raeburn  3341:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
                   3342:     if ($role  eq 'ca') {
1.479     albertel 3343:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.378     raeburn  3344:         $realm = &plainname($rname,$rdom).':'.$rdom;
                   3345:     } 
1.55      www      3346: # realm
1.258     albertel 3347:     if ($env{'request.course.id'}) {
1.378     raeburn  3348:         if ($env{'request.role'} !~ /^cr/) {
                   3349:             $role = &Apache::lonnet::plaintext($role,&course_type());
                   3350:         }
1.359     albertel 3351: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  3352:     } else {
                   3353:         $role = &Apache::lonnet::plaintext($role);
1.54      www      3354:     }
1.433     albertel 3355: 
1.359     albertel 3356:     if (!$realm) { $realm='&nbsp;'; }
1.55      www      3357: # Set messages
1.60      matthew  3358:     my $messages=&domainlogo($domain);
1.101     www      3359: # Port for miniserver
1.83      albertel 3360:     my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
                   3361:     if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
1.330     albertel 3362: 
1.438     albertel 3363:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 3364: 
1.101     www      3365: # construct main body tag
1.359     albertel 3366:     my $bodytag = "<body $extra_body_attr>".
                   3367: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 3368: 
1.332     albertel 3369:     if ($bodyonly 
                   3370: 	|| ($env{'request.state'} eq 'construct' 
                   3371: 	    && $env{'environment.remote'} ne 'off' )) {
1.60      matthew  3372:         return $bodytag;
1.258     albertel 3373:     } elsif ($env{'browser.interface'} eq 'textual') {
1.95      www      3374: # Accessibility
1.224     raeburn  3375:           
1.337     albertel 3376: 	$bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
1.338     albertel 3377: 	if (!$notitle) {
1.337     albertel 3378: 	    $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
                   3379: 	}
                   3380: 	return $bodytag;
1.359     albertel 3381:     }
                   3382: 
1.410     albertel 3383:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
1.433     albertel 3384:     if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3385: 	undef($role);
1.434     albertel 3386:     } else {
                   3387: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
1.433     albertel 3388:     }
1.359     albertel 3389:     
                   3390:     my $roleinfo=(<<ENDROLE);
                   3391: <td class="LC_title_bar_who">
                   3392: <div class="LC_title_bar_name">
1.410     albertel 3393:     $name
1.361     albertel 3394:     &nbsp;
1.359     albertel 3395: </div>
                   3396: <div class="LC_title_bar_role">
1.361     albertel 3397: $role&nbsp;
1.359     albertel 3398: </div>
                   3399: <div class="LC_title_bar_realm">
1.361     albertel 3400: $realm&nbsp;
1.359     albertel 3401: </div>
1.206     albertel 3402: </td>
                   3403: ENDROLE
1.235     raeburn  3404: 
1.359     albertel 3405:     my $titleinfo = '<span class="LC_title_bar_title">'.$title.'</span>';
                   3406:     if ($customtitle) {
                   3407:         $titleinfo = $customtitle;
                   3408:     }
                   3409:     #
                   3410:     # Extra info if you are the DC
                   3411:     my $dc_info = '';
                   3412:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   3413:                         $env{'course.'.$env{'request.course.id'}.
                   3414:                                  '.domain'}.'/'})) {
                   3415:         my $cid = $env{'request.course.id'};
                   3416:         $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      3417:         $dc_info =~ s/\s+$//;
1.359     albertel 3418:         $dc_info = '('.$dc_info.')';
                   3419:     }
                   3420: 
                   3421:     if ($env{'environment.remote'} eq 'off') {
                   3422:         # No Remote
1.258     albertel 3423: 	if ($env{'request.state'} eq 'construct') {
1.359     albertel 3424: 	    $forcereg=1;
                   3425: 	}
                   3426: 
                   3427: 	if (!$customtitle && $env{'request.state'} eq 'construct') {
                   3428: 	    # this is for resources; directories have customtitle, and crumbs
                   3429:             # and select recent are created in lonpubdir.pm  
1.229     albertel 3430: 	    my ($uname,$thisdisfn)=
1.258     albertel 3431: 		($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
1.229     albertel 3432: 	    my $formaction='/priv/'.$uname.'/'.$thisdisfn;
                   3433: 	    $formaction=~s/\/+/\//g;
                   3434: 
1.359     albertel 3435: 	    my $parentpath = '';
                   3436: 	    my $lastitem = '';
                   3437: 	    if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   3438: 		$parentpath = $1;
                   3439: 		$lastitem = $2;
                   3440: 	    } else {
                   3441: 		$lastitem = $thisdisfn;
                   3442: 	    }
                   3443: 	    $titleinfo = 
1.401     albertel 3444: 		&Apache::loncommon::help_open_menu('','',3,'Authoring').
1.359     albertel 3445: 		'<b>Construction Space</b>:&nbsp;'. 
                   3446: 		'<form name="dirs" method="post" action="'.$formaction
                   3447: 		.'" target="_top"><tt><b>'
                   3448: 		.&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<font size=\"+1\">$lastitem</font></b></tt><br />"
                   3449: 		.&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   3450: 		.'</form>'
                   3451: 		.&Apache::lonmenu::constspaceform();
1.235     raeburn  3452:         }
1.359     albertel 3453: 
1.337     albertel 3454:         my $titletable;
1.338     albertel 3455: 	if (!$notitle) {
1.337     albertel 3456: 	    $titletable =
1.359     albertel 3457: 		'<table id="LC_title_bar">'.
                   3458:                          "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
                   3459: 			 '</tr></table>';
1.337     albertel 3460: 	}
1.359     albertel 3461: 	if ($notopbar) {
                   3462: 	    $bodytag .= $titletable;
                   3463: 	} else {
                   3464: 	    if ($env{'request.state'} eq 'construct') {
1.337     albertel 3465:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
                   3466: 							  $titletable);
1.272     raeburn  3467:             } else {
1.336     albertel 3468:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
1.359     albertel 3469: 		    $titletable;
1.272     raeburn  3470:             }
1.235     raeburn  3471:         }
                   3472:         return $bodytag;
1.94      www      3473:     }
1.95      www      3474: 
1.93      www      3475: #
1.95      www      3476: # Top frame rendering, Remote is up
1.93      www      3477: #
1.359     albertel 3478: 
                   3479:     my $upperleft='<img src="http://'.$ENV{'HTTP_HOST'}.':'.
                   3480:         $lonhttpdPort.$img.'" alt="'.$function.'" />';
                   3481: 
1.305     www      3482:     # Explicit link to get inline menu
1.361     albertel 3483:     my $menu= ($no_inline_link?''
                   3484: 	       :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
1.245     matthew  3485:     #
1.338     albertel 3486:     if ($notitle) {
1.337     albertel 3487: 	return $bodytag;
                   3488:     }
1.94      www      3489:     return(<<ENDBODY);
1.60      matthew  3490: $bodytag
1.359     albertel 3491: <table id="LC_title_bar" class="LC_with_remote">
1.368     albertel 3492: <tr><td class="LC_title_bar_role_logo">$upperleft</td>
1.359     albertel 3493:     <td class="LC_title_bar_domain_logo">$messages&nbsp;</td>
1.54      www      3494: </tr>
1.359     albertel 3495: <tr><td>$titleinfo $dc_info $menu</td>
                   3496: $roleinfo
1.368     albertel 3497: </tr>
1.356     albertel 3498: </table>
1.54      www      3499: ENDBODY
1.182     matthew  3500: }
                   3501: 
1.330     albertel 3502: sub make_attr_string {
                   3503:     my ($register,$attr_ref) = @_;
                   3504: 
                   3505:     if ($attr_ref && !ref($attr_ref)) {
                   3506: 	die("addentries Must be a hash ref ".
                   3507: 	    join(':',caller(1))." ".
                   3508: 	    join(':',caller(0))." ");
                   3509:     }
                   3510: 
                   3511:     if ($register) {
1.339     albertel 3512: 	my ($on_load,$on_unload);
                   3513: 	foreach my $key (keys(%{$attr_ref})) {
                   3514: 	    if      (lc($key) eq 'onload') {
                   3515: 		$on_load.=$attr_ref->{$key}.';';
                   3516: 		delete($attr_ref->{$key});
                   3517: 
                   3518: 	    } elsif (lc($key) eq 'onunload') {
                   3519: 		$on_unload.=$attr_ref->{$key}.';';
                   3520: 		delete($attr_ref->{$key});
                   3521: 	    }
                   3522: 	}
                   3523: 	$attr_ref->{'onload'}  =
                   3524: 	    &Apache::lonmenu::loadevents().  $on_load;
                   3525: 	$attr_ref->{'onunload'}=
                   3526: 	    &Apache::lonmenu::unloadevents().$on_unload;
                   3527:     }
                   3528: 
                   3529: # Accessibility font enhance
                   3530:     if ($env{'browser.fontenhance'} eq 'on') {
                   3531: 	my $style;
                   3532: 	foreach my $key (keys(%{$attr_ref})) {
                   3533: 	    if (lc($key) eq 'style') {
                   3534: 		$style.=$attr_ref->{$key}.';';
                   3535: 		delete($attr_ref->{$key});
                   3536: 	    }
                   3537: 	}
                   3538: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
1.330     albertel 3539:     }
1.339     albertel 3540: 
                   3541:     if ($env{'browser.blackwhite'} eq 'on') {
                   3542: 	delete($attr_ref->{'font'});
                   3543: 	delete($attr_ref->{'link'});
                   3544: 	delete($attr_ref->{'alink'});
                   3545: 	delete($attr_ref->{'vlink'});
                   3546: 	delete($attr_ref->{'bgcolor'});
                   3547: 	delete($attr_ref->{'background'});
                   3548:     }
                   3549: 
1.330     albertel 3550:     my $attr_string;
                   3551:     foreach my $attr (keys(%$attr_ref)) {
                   3552: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   3553:     }
                   3554:     return $attr_string;
                   3555: }
                   3556: 
                   3557: 
1.182     matthew  3558: ###############################################
1.251     albertel 3559: ###############################################
                   3560: 
                   3561: =pod
                   3562: 
                   3563: =back
                   3564: 
1.306     albertel 3565: =head1 HTML Helpers
1.251     albertel 3566: 
                   3567: =over 4
                   3568: 
                   3569: =item * &endbodytag()
                   3570: 
                   3571: Returns a uniform footer for LON-CAPA web pages.
                   3572: 
1.306     albertel 3573: Inputs: none
1.251     albertel 3574: 
                   3575: =back
                   3576: 
                   3577: =cut
                   3578: 
                   3579: sub endbodytag {
                   3580:     my $endbodytag='</body>';
1.269     albertel 3581:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
1.315     albertel 3582:     if ( exists( $env{'internal.head.redirect'} ) ) {
                   3583: 	$endbodytag=
                   3584: 	    "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   3585: 	    &mt('Continue').'</a>'.
                   3586: 	    $endbodytag;
                   3587:     }
1.251     albertel 3588:     return $endbodytag;
                   3589: }
                   3590: 
1.352     albertel 3591: =pod
                   3592: 
                   3593: =over 4
                   3594: 
                   3595: =item * &standard_css()
                   3596: 
                   3597: Returns a style sheet
                   3598: 
                   3599: Inputs: (all optional)
                   3600:             domain         -> force to color decorate a page for a specific
                   3601:                                domain
                   3602:             function       -> force usage of a specific rolish color scheme
                   3603:             bgcolor        -> override the default page bgcolor
                   3604: 
                   3605: =back
                   3606: 
                   3607: =cut
                   3608: 
1.343     albertel 3609: sub standard_css {
1.345     albertel 3610:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 3611:     $function  = &get_users_function() if (!$function);
                   3612:     my $img    = &designparm($function.'.img',   $domain);
                   3613:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   3614:     my $font   = &designparm($function.'.font',  $domain);
1.345     albertel 3615:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 3616:     my $pgbg_or_bgcolor =
                   3617: 	         $bgcolor ||
1.352     albertel 3618: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 3619:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 3620:     my $alink  = &designparm($function.'.alink', $domain);
                   3621:     my $vlink  = &designparm($function.'.vlink', $domain);
                   3622:     my $link   = &designparm($function.'.link',  $domain);
                   3623: 
                   3624:     my $sans                 = 'Arial,Helvetica,sans-serif';
1.395     albertel 3625:     my $mono                 = 'monospace';
1.352     albertel 3626:     my $data_table_head      = $tabbg;
                   3627:     my $data_table_light     = '#EEEEEE';
1.470     banghart 3628:     my $data_table_dark      = '#DDDDDD';
                   3629:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 3630:     my $data_table_highlight = '#FFFF00';
1.352     albertel 3631:     my $mail_new             = '#FFBB77';
                   3632:     my $mail_new_hover       = '#DD9955';
                   3633:     my $mail_read            = '#BBBB77';
                   3634:     my $mail_read_hover      = '#999944';
                   3635:     my $mail_replied         = '#AAAA88';
                   3636:     my $mail_replied_hover   = '#888855';
                   3637:     my $mail_other           = '#99BBBB';
                   3638:     my $mail_other_hover     = '#669999';
1.391     albertel 3639:     my $table_header         = '#DDDDDD';
1.489     raeburn  3640:     my $feedback_link_bg     = '#BBBBBB';
1.392     albertel 3641: 
                   3642:     my $border = ($env{'browser.type'} eq 'explorer') ? '0px 2px 0px 2px'
                   3643: 	                                              : '0px 3px 0px 4px';
1.448     albertel 3644: 
1.343     albertel 3645:     return <<END;
1.345     albertel 3646: h1, h2, h3, th { font-family: $sans }
1.343     albertel 3647: a:focus { color: red; background: yellow } 
                   3648: table.thinborder { border-collapse: collapse; }
1.426     albertel 3649: table.thinborder tr th {  border-style: solid; border-width: 1px; background: $tabbg;}
                   3650: table.thinborder tr td { border-style: solid; border-width: 1px}
                   3651: 
1.343     albertel 3652: form, .inline { display: inline; }
                   3653: .center { text-align: center; }
1.395     albertel 3654: .LC_filename {font-family: $mono;}
1.350     albertel 3655: .LC_error {
                   3656:   color: red;
                   3657:   font-size: larger;
                   3658: }
1.457     albertel 3659: .LC_warning,
                   3660: .LC_diff_removed {
1.394     albertel 3661:   color: red;
                   3662: }
1.457     albertel 3663: .LC_success,
                   3664: .LC_diff_added {
1.350     albertel 3665:   color: green;
                   3666: }
1.440     albertel 3667: .LC_icon {
                   3668:   border: 0px;
                   3669: }
1.346     albertel 3670: 
1.458     albertel 3671: table.LC_pastsubmission {
                   3672:   border: 1px solid black;
                   3673:   margin: 2px;
                   3674: }
                   3675: 
1.392     albertel 3676: table#LC_top_nav, table#LC_menubuttons {
1.345     albertel 3677:   width: 100%;
                   3678:   background: $pgbg;
1.392     albertel 3679:   border: 2px;
1.402     albertel 3680:   border-collapse: separate;
1.403     albertel 3681:   padding: 0px;
1.345     albertel 3682: }
1.392     albertel 3683: 
1.409     albertel 3684: table#LC_title_bar, table.LC_breadcrumbs, table#LC_nav_location,
1.393     albertel 3685: table#LC_title_bar.LC_with_remote {
1.359     albertel 3686:   width: 100%;
1.392     albertel 3687:   border-color: $pgbg;
                   3688:   border-style: solid;
                   3689:   border-width: $border;
                   3690: 
1.379     albertel 3691:   background: $pgbg;
                   3692:   font-family: $sans;
1.392     albertel 3693:   border-collapse: collapse;
1.403     albertel 3694:   padding: 0px;
1.359     albertel 3695: }
1.392     albertel 3696: 
1.409     albertel 3697: table.LC_docs_path {
                   3698:   width: 100%;
                   3699:   border: 0;
                   3700:   background: $pgbg;
                   3701:   font-family: $sans;
                   3702:   border-collapse: collapse;
                   3703:   padding: 0px;
                   3704: }
                   3705: 
1.359     albertel 3706: table#LC_title_bar td {
                   3707:   background: $tabbg;
                   3708: }
                   3709: table#LC_title_bar td.LC_title_bar_who {
                   3710:   background: $tabbg;
                   3711:   color: $font;
1.427     albertel 3712:   font: small $sans;
1.359     albertel 3713:   text-align: right;
                   3714: }
1.469     banghart 3715: span.LC_metadata {
                   3716:     font-family: $sans;
                   3717: }
1.359     albertel 3718: span.LC_title_bar_title {
1.416     albertel 3719:   font: bold x-large $sans;
1.359     albertel 3720: }
                   3721: table#LC_title_bar td.LC_title_bar_domain_logo {
                   3722:   background: $sidebg;
                   3723:   text-align: right;
1.368     albertel 3724:   padding: 0px;
                   3725: }
                   3726: table#LC_title_bar td.LC_title_bar_role_logo {
                   3727:   background: $sidebg;
                   3728:   padding: 0px;
1.359     albertel 3729: }
                   3730: 
1.346     albertel 3731: table#LC_menubuttons_mainmenu {
                   3732:   background: $pgbg;
                   3733:   border: 0px;
                   3734:   border-spacing: 1px;
1.372     albertel 3735:   padding: 0px 1px;
1.346     albertel 3736:   margin: 0px;
                   3737:   border-collapse: separate;
                   3738: }
                   3739: table#LC_menubuttons img, table#LC_menubuttons_mainmenu img {
                   3740:   border: 0px;
                   3741: }
1.345     albertel 3742: table#LC_top_nav td {
                   3743:   background: $tabbg;
1.392     albertel 3744:   border: 0px;
1.407     albertel 3745:   font-size: small;
1.345     albertel 3746: }
                   3747: table#LC_top_nav td a, div#LC_top_nav a {
                   3748:   color: $font;
                   3749:   font-family: $sans;
                   3750: }
1.364     albertel 3751: table#LC_top_nav td.LC_top_nav_logo {
                   3752:   background: $tabbg;
1.432     albertel 3753:   text-align: left;
1.408     albertel 3754:   white-space: nowrap;
1.432     albertel 3755:   width: 31px;
1.408     albertel 3756: }
                   3757: table#LC_top_nav td.LC_top_nav_logo img {
1.432     albertel 3758:   border: 0px;
1.408     albertel 3759:   vertical-align: bottom;
1.364     albertel 3760: }
1.432     albertel 3761: table#LC_top_nav td.LC_top_nav_exit,
                   3762: table#LC_top_nav td.LC_top_nav_help {
                   3763:   width: 2.0em;
                   3764: }
1.442     albertel 3765: table#LC_top_nav td.LC_top_nav_login {
                   3766:   width: 4.0em;
                   3767:   text-align: center;
                   3768: }
1.409     albertel 3769: table.LC_breadcrumbs td, table.LC_docs_path td  {
1.357     albertel 3770:   background: $tabbg;
                   3771:   color: $font;
                   3772:   font-family: $sans;
1.358     albertel 3773:   font-size: smaller;
1.357     albertel 3774: }
1.411     albertel 3775: table.LC_breadcrumbs td.LC_breadcrumbs_component,
1.409     albertel 3776: table.LC_docs_path td.LC_docs_path_component {
1.357     albertel 3777:   background: $tabbg;
                   3778:   color: $font;
                   3779:   font-family: $sans;
                   3780:   font-size: larger;
                   3781:   text-align: right;
                   3782: }
1.383     albertel 3783: td.LC_table_cell_checkbox {
                   3784:   text-align: center;
                   3785: }
                   3786: 
1.346     albertel 3787: .LC_menubuttons_inline_text {
                   3788:   color: $font;
                   3789:   font-family: $sans;
                   3790:   font-size: smaller;
                   3791: }
                   3792: 
                   3793: td.LC_menubuttons_text {
                   3794:   color: $font;
                   3795:   font-family: $sans;
                   3796: }
                   3797: td.LC_menubuttons_img {
                   3798:   background: $tabbg;
                   3799: }
                   3800: .LC_current_location {
                   3801:   font-family: $sans;
                   3802:   background: $tabbg;
                   3803: }
                   3804: .LC_new_mail {
                   3805:   font-family: $sans;
                   3806:   font-weight: bold;
                   3807: }
1.347     albertel 3808: 
1.440     albertel 3809: table.LC_aboutme_port {
                   3810:   border: 0px;
                   3811:   border-collapse: collapse;
                   3812:   border-spacing: 0px;
                   3813: }
1.349     albertel 3814: table.LC_data_table, table.LC_mail_list {
1.347     albertel 3815:   border: 1px solid #000000;
1.402     albertel 3816:   border-collapse: separate;
1.426     albertel 3817:   border-spacing: 1px;
1.347     albertel 3818: }
1.422     albertel 3819: .LC_data_table_dense {
                   3820:   font-size: small;
                   3821: }
1.349     albertel 3822: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th {
                   3823:   font-weight: bold;
                   3824:   background-color: $data_table_head;
1.421     albertel 3825:   font-size: smaller;
1.347     albertel 3826: }
1.440     albertel 3827: table.LC_data_table tr td, 
                   3828: table.LC_aboutme_port tr td {
1.349     albertel 3829:   background-color: $data_table_light;
1.425     albertel 3830:   padding: 2px;
1.347     albertel 3831: }
1.440     albertel 3832: table.LC_data_table tr.LC_even_row td,
                   3833: table.LC_aboutme_port tr.LC_even_row td {
1.349     albertel 3834:   background-color: $data_table_dark;
1.347     albertel 3835: }
1.425     albertel 3836: table.LC_data_table tr.LC_data_table_highlight td {
                   3837:   background-color: $data_table_darker;
                   3838: }
1.451     albertel 3839: table.LC_data_table tr.LC_empty_row td,
1.452     albertel 3840: table.LC_whatsnew tr.LC_empty_row td {
1.347     albertel 3841:   background-color: #FFFFFF;
1.421     albertel 3842:   font-weight: bold;
                   3843:   font-style: italic;
                   3844:   text-align: center;
                   3845:   padding: 8px;
1.347     albertel 3846: }
1.465     albertel 3847: table.LC_whatsnew tr.LC_empty_row td {
                   3848:   padding: 4ex
                   3849: }
1.451     albertel 3850: table.LC_whatsnew {
                   3851: }
                   3852: 
                   3853: table.LC_whatsnew tr th,
                   3854: table.LC_whatsnew tr.LC_info_row td {
                   3855:   background-color: #CCC;
                   3856:   font-weight: bold;
                   3857:   font-size: small;
                   3858:   text-align: right;
                   3859: }
                   3860: table.LC_whatsnew tr td {
                   3861:   background-color: #FFF;
                   3862:   font-size: small;
                   3863:   text-align: right;
                   3864: }
                   3865: table.LC_whatsnew tr td.LC_first_item {
                   3866:   text-align: left;
                   3867: }
                   3868: 
                   3869: table.LC_whatsnew tr.LC_odd_row td {
                   3870:   background-color: #EEE;
                   3871: }
                   3872: 
1.473     raeburn  3873: table.LC_createuser {
                   3874: }
                   3875: 
                   3876: table.LC_createuser tr.LC_section_row td {
                   3877:   font-size: smaller;
                   3878: }
                   3879: 
                   3880: table.LC_createuser tr.LC_info_row td  {
                   3881:   background-color: #CCC;
                   3882:   font-weight: bold;
                   3883:   text-align: center;
                   3884: }
                   3885: 
1.349     albertel 3886: table.LC_calendar {
                   3887:   border: 1px solid #000000;
                   3888:   border-collapse: collapse;
                   3889: }
                   3890: table.LC_calendar_pickdate {
                   3891:   font-size: xx-small;
                   3892: }
                   3893: table.LC_calendar tr td {
                   3894:   border: 1px solid #000000;
                   3895:   vertical-align: top;
                   3896: }
                   3897: table.LC_calendar tr td.LC_calendar_day_empty {
                   3898:   background-color: $data_table_dark;
                   3899: }
                   3900: table.LC_calendar tr td.LC_calendar_day_current {
                   3901:   background-color: $data_table_highlight;
                   3902: }
                   3903: 
                   3904: table.LC_mail_list tr.LC_mail_new {
                   3905:   background-color: $mail_new;
                   3906: }
                   3907: table.LC_mail_list tr.LC_mail_new:hover {
                   3908:   background-color: $mail_new_hover;
                   3909: }
                   3910: table.LC_mail_list tr.LC_mail_read {
                   3911:   background-color: $mail_read;
                   3912: }
                   3913: table.LC_mail_list tr.LC_mail_read:hover {
                   3914:   background-color: $mail_read_hover;
                   3915: }
                   3916: table.LC_mail_list tr.LC_mail_replied {
                   3917:   background-color: $mail_replied;
                   3918: }
                   3919: table.LC_mail_list tr.LC_mail_replied:hover {
                   3920:   background-color: $mail_replied_hover;
                   3921: }
                   3922: table.LC_mail_list tr.LC_mail_other {
                   3923:   background-color: $mail_other;
                   3924: }
                   3925: table.LC_mail_list tr.LC_mail_other:hover {
                   3926:   background-color: $mail_other_hover;
                   3927: }
1.385     albertel 3928: 
1.386     albertel 3929: table#LC_portfolio_actions {
                   3930:   width: auto;
                   3931:   background: $pgbg;
                   3932:   border: 0px;
                   3933:   border-spacing: 2px 2px;
                   3934:   padding: 0px;
                   3935:   margin: 0px;
                   3936:   border-collapse: separate;
                   3937: }
                   3938: table#LC_portfolio_actions td.LC_label {
                   3939:   background: $tabbg;
                   3940:   text-align: right;
                   3941: }
                   3942: table#LC_portfolio_actions td.LC_value {
                   3943:   background: $tabbg;
                   3944: }
1.385     albertel 3945: 
1.391     albertel 3946: table#LC_cstr_controls {
                   3947:   width: 100%;
                   3948:   border-collapse: collapse;
                   3949: }
                   3950: table#LC_cstr_controls tr td {
                   3951:   border: 4px solid $pgbg;
                   3952:   padding: 4px;
                   3953:   text-align: center;
                   3954:   background: $tabbg;
                   3955: }
                   3956: table#LC_cstr_controls tr th {
                   3957:   border: 4px solid $pgbg;
                   3958:   background: $table_header;
                   3959:   text-align: center;
                   3960:   font-family: $sans;
                   3961:   font-size: smaller;
                   3962: }
                   3963: 
1.389     albertel 3964: table#LC_browser {
                   3965:  
                   3966: }
                   3967: table#LC_browser tr th {
1.391     albertel 3968:   background: $table_header;
1.389     albertel 3969: }
1.390     albertel 3970: table#LC_browser tr td {
                   3971:   padding: 2px;
                   3972: }
1.389     albertel 3973: table#LC_browser tr.LC_browser_file,
                   3974: table#LC_browser tr.LC_browser_file_published {
                   3975:   background: #CCFF88;
                   3976: }
                   3977: table#LC_browser tr.LC_browser_file_locked,
                   3978: table#LC_browser tr.LC_browser_file_unpublished {
                   3979:   background: #FFAA99;
1.387     albertel 3980: }
1.389     albertel 3981: table#LC_browser tr.LC_browser_file_obsolete {
                   3982:   background: #AAAAAA;
1.387     albertel 3983: }
1.455     albertel 3984: table#LC_browser tr.LC_browser_file_modified,
                   3985: table#LC_browser tr.LC_browser_file_metamodified {
1.389     albertel 3986:   background: #FFFF77;
1.387     albertel 3987: }
1.389     albertel 3988: table#LC_browser tr.LC_browser_folder {
                   3989:   background: #CCCCFF;
1.387     albertel 3990: }
1.388     albertel 3991: span.LC_current_location {
                   3992:   font-size: x-large;
                   3993:   background: $pgbg;
                   3994: }
1.387     albertel 3995: 
1.395     albertel 3996: span.LC_parm_menu_item {
                   3997:   font-size: larger;
                   3998:   font-family: $sans;
                   3999: }
                   4000: span.LC_parm_scope_all {
                   4001:   color: red;
                   4002: }
                   4003: span.LC_parm_scope_folder {
                   4004:   color: green;
                   4005: }
                   4006: span.LC_parm_scope_resource {
                   4007:   color: orange;
                   4008: }
                   4009: span.LC_parm_part {
                   4010:   color: blue;
                   4011: }
                   4012: span.LC_parm_folder, span.LC_parm_symb {
                   4013:   font-size: x-small;
                   4014:   font-family: $mono;
                   4015:   color: #AAAAAA;
                   4016: }
                   4017: 
1.396     albertel 4018: td.LC_parm_overview_level_menu, td.LC_parm_overview_map_menu,
                   4019: td.LC_parm_overview_parm_selectors, td.LC_parm_overview_parm_restrictions {
                   4020:   border: 1px solid black;
                   4021:   border-collapse: collapse;
                   4022: }
                   4023: table.LC_parm_overview_restrictions td {
                   4024:   border-width: 1px 4px 1px 4px;
                   4025:   border-style: solid;
                   4026:   border-color: $pgbg;
                   4027:   text-align: center;
                   4028: }
                   4029: table.LC_parm_overview_restrictions th {
                   4030:   background: $tabbg;
                   4031:   border-width: 1px 4px 1px 4px;
                   4032:   border-style: solid;
                   4033:   border-color: $pgbg;
                   4034: }
1.398     albertel 4035: table#LC_helpmenu {
                   4036:   border: 0px;
                   4037:   height: 55px;
                   4038:   border-spacing: 0px;
                   4039: }
                   4040: 
                   4041: table#LC_helpmenu fieldset legend {
                   4042:   font-size: larger;
                   4043:   font-weight: bold;
                   4044: }
1.397     albertel 4045: table#LC_helpmenu_links {
                   4046:   width: 100%;
                   4047:   border: 1px solid black;
                   4048:   background: $pgbg;
                   4049:   padding: 0px;
                   4050:   border-spacing: 1px;
                   4051: }
                   4052: table#LC_helpmenu_links tr td {
                   4053:   padding: 1px;
                   4054:   background: $tabbg;
1.399     albertel 4055:   text-align: center;
                   4056:   font-weight: bold;
1.397     albertel 4057: }
1.396     albertel 4058: 
1.397     albertel 4059: table#LC_helpmenu_links a:link, table#LC_helpmenu_links a:visited,
                   4060: table#LC_helpmenu_links a:active {
                   4061:   text-decoration: none;
                   4062:   color: $font;
                   4063: }
                   4064: table#LC_helpmenu_links a:hover {
                   4065:   text-decoration: underline;
                   4066:   color: $vlink;
                   4067: }
1.396     albertel 4068: 
1.417     albertel 4069: .LC_chrt_popup_exists {
                   4070:   border: 1px solid #339933;
                   4071:   margin: -1px;
                   4072: }
                   4073: .LC_chrt_popup_up {
                   4074:   border: 1px solid yellow;
                   4075:   margin: -1px;
                   4076: }
                   4077: .LC_chrt_popup {
                   4078:   border: 1px solid #8888FF;
                   4079:   background: #CCCCFF;
                   4080: }
                   4081: 
1.421     albertel 4082: table.LC_pick_box {
                   4083:   width: 100%;
                   4084:   border-collapse: separate;
                   4085:   background: white;
                   4086:   border: 1px solid black;
                   4087:   border-spacing: 1px;
                   4088: }
                   4089: table.LC_pick_box td.LC_pick_box_title {
                   4090:   background: $tabbg;
                   4091:   font-weight: bold;
                   4092:   text-align: right;
                   4093:   width: 184px;
                   4094:   padding: 8px;
                   4095: }
1.424     albertel 4096: table.LC_pick_box td.LC_pick_box_separator {
1.421     albertel 4097:   padding: 0px;
                   4098:   height: 1px;
                   4099:   background: black;
                   4100: }
                   4101: table.LC_pick_box td.LC_pick_box_submit {
                   4102:   text-align: right;
                   4103: }
                   4104: 
1.424     albertel 4105: table.LC_group_priv_box {
                   4106:   background: white;
                   4107:   border: 1px solid black;
                   4108:   border-spacing: 1px;
                   4109: }
                   4110: table.LC_group_priv_box td.LC_pick_box_title {
                   4111:   background: $tabbg;
                   4112:   font-weight: bold;
                   4113:   text-align: right;
                   4114:   width: 184px;
                   4115: }
                   4116: table.LC_group_priv_box td.LC_groups_fixed {
                   4117:   background: $data_table_light;
                   4118:   text-align: center;
                   4119: }
                   4120: table.LC_group_priv_box td.LC_groups_optional {
                   4121:   background: $data_table_dark;
                   4122:   text-align: center;
                   4123: }
                   4124: table.LC_group_priv_box td.LC_groups_functionality {
                   4125:   background: $data_table_darker;
                   4126:   text-align: center;
                   4127:   font-weight: bold;
                   4128: }
                   4129: table.LC_group_priv td {
                   4130:   text-align: left;
                   4131:   padding: 0px;
                   4132: }
                   4133: 
1.421     albertel 4134: table.LC_notify_front_page {
                   4135:   background: white;
                   4136:   border: 1px solid black;
                   4137:   padding: 8px;
                   4138: }
                   4139: table.LC_notify_front_page td {
                   4140:   padding: 8px;
                   4141: }
1.424     albertel 4142: .LC_navbuttons {
                   4143:   margin: 2ex 0ex 2ex 0ex;
                   4144: }
1.423     albertel 4145: .LC_topic_bar {
                   4146:   font-family: $sans;
                   4147:   font-weight: bold;
                   4148:   width: 100%;
                   4149:   background: $tabbg;
                   4150:   vertical-align: middle;
                   4151:   margin: 2ex 0ex 2ex 0ex;
                   4152: }
                   4153: .LC_topic_bar span {
                   4154:   vertical-align: middle;
                   4155: }
                   4156: .LC_topic_bar img {
                   4157:   vertical-align: bottom;
                   4158: }
                   4159: table.LC_course_group_status {
                   4160:   margin: 20px;
                   4161: }
                   4162: table.LC_status_selector td {
                   4163:   vertical-align: top;
                   4164:   text-align: center;
1.424     albertel 4165:   padding: 4px;
                   4166: }
                   4167: table.LC_descriptive_input td.LC_description {
                   4168:   vertical-align: top;
                   4169:   text-align: right;
                   4170:   font-weight: bold;
1.423     albertel 4171: }
1.489     raeburn  4172: table.LC_feedback_link {
                   4173:     background: $feedback_link_bg;
                   4174: }
                   4175: span.LC_feedback_link {
                   4176:     background: $feedback_link_bg;
                   4177:     font-size: larger;
                   4178: }
1.421     albertel 4179: 
1.343     albertel 4180: END
                   4181: }
                   4182: 
1.306     albertel 4183: =pod
                   4184: 
                   4185: =over 4
                   4186: 
                   4187: =item * &headtag()
                   4188: 
                   4189: Returns a uniform footer for LON-CAPA web pages.
                   4190: 
1.307     albertel 4191: Inputs: $title - optional title for the head
                   4192:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 4193:         $args - optional arguments
1.319     albertel 4194:             force_register - if is true call registerurl so the remote is 
                   4195:                              informed
1.415     albertel 4196:             redirect       -> array ref of
                   4197:                                    1- seconds before redirect occurs
                   4198:                                    2- url to redirect to
                   4199:                                    3- whether the side effect should occur
1.315     albertel 4200:                            (side effect of setting 
                   4201:                                $env{'internal.head.redirect'} to the url 
                   4202:                                redirected too)
1.352     albertel 4203:             domain         -> force to color decorate a page for a specific
                   4204:                                domain
                   4205:             function       -> force usage of a specific rolish color scheme
                   4206:             bgcolor        -> override the default page bgcolor
1.460     albertel 4207:             no_auto_mt_title
                   4208:                            -> prevent &mt()ing the title arg
1.464     albertel 4209: 
1.306     albertel 4210: =back
                   4211: 
                   4212: =cut
                   4213: 
                   4214: sub headtag {
1.313     albertel 4215:     my ($title,$head_extra,$args) = @_;
1.306     albertel 4216:     
1.363     albertel 4217:     my $function = $args->{'function'} || &get_users_function();
                   4218:     my $domain   = $args->{'domain'}   || &determinedomain();
                   4219:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.418     albertel 4220:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 4221: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.418     albertel 4222: 		   #time(),
                   4223: 		   $env{'environment.color.timestamp'},
1.363     albertel 4224: 		   $function,$domain,$bgcolor);
                   4225: 
1.369     www      4226:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 4227: 
1.308     albertel 4228:     my $result =
                   4229: 	'<head>'.
1.461     albertel 4230: 	&font_settings();
1.319     albertel 4231: 
1.461     albertel 4232:     if (!$args->{'frameset'}) {
                   4233: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   4234:     }
1.319     albertel 4235:     if ($args->{'force_register'}) {
                   4236: 	$result .= &Apache::lonmenu::registerurl(1);
                   4237:     }
1.436     albertel 4238:     if (!$args->{'no_nav_bar'} 
                   4239: 	&& !$args->{'only_body'}
                   4240: 	&& !$args->{'frameset'}) {
                   4241: 	$result .= &help_menu_js();
                   4242:     }
1.319     albertel 4243: 
1.314     albertel 4244:     if (ref($args->{'redirect'})) {
1.414     albertel 4245: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 4246: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 4247: 	if (!$inhibit_continue) {
                   4248: 	    $env{'internal.head.redirect'} = $url;
                   4249: 	}
1.313     albertel 4250: 	$result.=<<ADDMETA
                   4251: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 4252: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 4253: ADDMETA
                   4254:     }
1.306     albertel 4255:     if (!defined($title)) {
                   4256: 	$title = 'The LearningOnline Network with CAPA';
                   4257:     }
1.460     albertel 4258:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   4259:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.414     albertel 4260: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
                   4261: 	.$head_extra;
1.306     albertel 4262:     return $result;
                   4263: }
                   4264: 
                   4265: =pod
                   4266: 
                   4267: =over 4
                   4268: 
1.340     albertel 4269: =item * &font_settings()
                   4270: 
                   4271: Returns neccessary <meta> to set the proper encoding
                   4272: 
                   4273: Inputs: none
                   4274: 
                   4275: =back
                   4276: 
                   4277: =cut
                   4278: 
                   4279: sub font_settings {
                   4280:     my $headerstring='';
                   4281:     if (($env{'browser.os'} eq 'mac') && (!$env{'browser.mathml'})) { 
                   4282: 	$headerstring.=
                   4283: 	    '<meta Content-Type="text/html; charset=x-mac-roman" />';
                   4284:     } elsif (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
                   4285: 	$headerstring.=
                   4286: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
                   4287:     }
                   4288:     return $headerstring;
                   4289: }
                   4290: 
1.341     albertel 4291: =pod
                   4292: 
                   4293: =over 4
                   4294: 
                   4295: =item * &xml_begin()
                   4296: 
                   4297: Returns the needed doctype and <html>
                   4298: 
                   4299: Inputs: none
                   4300: 
                   4301: =back
                   4302: 
                   4303: =cut
                   4304: 
                   4305: sub xml_begin {
                   4306:     my $output='';
                   4307: 
1.342     albertel 4308:     &Apache::lonhtmlcommon::init_htmlareafields();
                   4309: 
1.341     albertel 4310:     if ($env{'browser.mathml'}) {
                   4311: 	$output='<?xml version="1.0"?>'
                   4312:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   4313: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   4314:             
                   4315: #	    .'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" [<!ENTITY mathns "http://www.w3.org/1998/Math/MathML">] >'
                   4316: 	    .'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">'
                   4317:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   4318: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
                   4319:     } else {
                   4320: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
                   4321:     }
                   4322:     return $output;
                   4323: }
1.340     albertel 4324: 
                   4325: =pod
                   4326: 
                   4327: =over 4
                   4328: 
1.306     albertel 4329: =item * &endheadtag()
                   4330: 
                   4331: Returns a uniform </head> for LON-CAPA web pages.
                   4332: 
                   4333: Inputs: none
                   4334: 
                   4335: =back
                   4336: 
                   4337: =cut
                   4338: 
                   4339: sub endheadtag {
                   4340:     return '</head>';
                   4341: }
                   4342: 
                   4343: =pod
                   4344: 
                   4345: =over 4
                   4346: 
                   4347: =item * &head()
                   4348: 
                   4349: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
                   4350: 
                   4351: Inputs: $title - optional title for the page
1.307     albertel 4352:         $head_extra - optional extra HTML to put inside the <head>
1.405     albertel 4353: 
1.306     albertel 4354: =back
                   4355: 
                   4356: =cut
                   4357: 
                   4358: sub head {
1.325     albertel 4359:     my ($title,$head_extra,$args) = @_;
                   4360:     return &headtag($title,$head_extra,$args).&endheadtag();
1.306     albertel 4361: }
                   4362: 
                   4363: =pod
                   4364: 
                   4365: =over 4
                   4366: 
                   4367: =item * &start_page()
                   4368: 
                   4369: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   4370: 
                   4371: Inputs: $title - optional title for the page
                   4372:         $head_extra - optional extra HTML to incude inside the <head>
1.315     albertel 4373:         $args - additional optional args supported are:
1.317     albertel 4374:                   only_body      -> is true will set &bodytag() onlybodytag
                   4375:                                     arg on
                   4376:                   no_nav_bar     -> is true will set &bodytag() notopbar arg on
                   4377:                   add_entries    -> additional attributes to add to the  <body>
                   4378:                   domain         -> force to color decorate a page for a 
                   4379:                                     specific domain
                   4380:                   function       -> force usage of a specific rolish color
                   4381:                                     scheme
                   4382:                   redirect       -> see &headtag()
                   4383:                   bgcolor        -> override the default page bg color
                   4384:                   js_ready       -> return a string ready for being used in 
                   4385:                                     a javascript writeln
1.320     albertel 4386:                   html_encode    -> return a string ready for being used in 
                   4387:                                     a html attribute
1.317     albertel 4388:                   force_register -> if is true will turn on the &bodytag()
                   4389:                                     $forcereg arg
1.326     albertel 4390:                   body_title     -> alternate text to use instead of $title
                   4391:                                     in the title box that appears, this text
                   4392:                                     is not auto translated like the $title is
1.330     albertel 4393:                   frameset       -> if true will start with a <frameset>
                   4394:                                     rather than <body>
1.338     albertel 4395:                   no_title       -> if true the title bar won't be shown
                   4396:                   skip_phases    -> hash ref of 
                   4397:                                     head -> skip the <html><head> generation
                   4398:                                     body -> skip all <body> generation
1.337     albertel 4399: 
1.361     albertel 4400:                   no_inline_link -> if true and in remote mode, don't show the 
                   4401:                                     'Switch To Inline Menu' link
                   4402: 
1.460     albertel 4403:                   no_auto_mt_title -> prevent &mt()ing the title arg
                   4404: 
1.306     albertel 4405: =back
                   4406: 
                   4407: =cut
                   4408: 
                   4409: sub start_page {
1.309     albertel 4410:     my ($title,$head_extra,$args) = @_;
1.318     albertel 4411:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.313     albertel 4412:     my %head_args;
1.352     albertel 4413:     foreach my $arg ('redirect','force_register','domain','function',
1.460     albertel 4414: 		     'bgcolor','frameset','no_nav_bar','only_body',
                   4415: 		     'no_auto_mt_title') {
1.319     albertel 4416: 	if (defined($args->{$arg})) {
1.324     raeburn  4417: 	    $head_args{$arg} = $args->{$arg};
1.319     albertel 4418: 	}
1.313     albertel 4419:     }
1.319     albertel 4420: 
1.315     albertel 4421:     $env{'internal.start_page'}++;
1.338     albertel 4422:     my $result;
                   4423:     if (! exists($args->{'skip_phases'}{'head'}) ) {
                   4424: 	$result.=
1.341     albertel 4425: 	    &xml_begin().
1.338     albertel 4426: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
                   4427:     }
                   4428:     
                   4429:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   4430: 	if ($args->{'frameset'}) {
                   4431: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   4432: 						$args->{'add_entries'});
                   4433: 	    $result .= "\n<frameset $attr_string>\n";
                   4434: 	} else {
                   4435: 	    $result .=
                   4436: 		&bodytag($title, 
                   4437: 			 $args->{'function'},       $args->{'add_entries'},
                   4438: 			 $args->{'only_body'},      $args->{'domain'},
                   4439: 			 $args->{'force_register'}, $args->{'body_title'},
                   4440: 			 $args->{'no_nav_bar'},     $args->{'bgcolor'},
1.460     albertel 4441: 			 $args->{'no_title'},       $args->{'no_inline_link'},
                   4442: 			 $args);
1.338     albertel 4443: 	}
1.330     albertel 4444:     }
1.338     albertel 4445: 
1.315     albertel 4446:     if ($args->{'js_ready'}) {
1.317     albertel 4447: 	$result = &js_ready($result);
1.315     albertel 4448:     }
1.320     albertel 4449:     if ($args->{'html_encode'}) {
                   4450: 	$result = &html_encode($result);
                   4451:     }
1.315     albertel 4452:     return $result;
1.306     albertel 4453: }
                   4454: 
1.330     albertel 4455: 
1.306     albertel 4456: =pod
                   4457: 
                   4458: =over 4
                   4459: 
                   4460: =item * &head()
                   4461: 
                   4462: Returns a complete </body></html> section for LON-CAPA web pages.
                   4463: 
1.315     albertel 4464: Inputs:         $args - additional optional args supported are:
                   4465:                  js_ready     -> return a string ready for being used in 
                   4466:                                  a javascript writeln
1.320     albertel 4467:                  html_encode  -> return a string ready for being used in 
                   4468:                                  a html attribute
1.330     albertel 4469:                  frameset     -> if true will start with a <frameset>
                   4470:                                  rather than <body>
1.306     albertel 4471: 
                   4472: =cut
                   4473: 
                   4474: sub end_page {
1.315     albertel 4475:     my ($args) = @_;
                   4476:     $env{'internal.end_page'}++;
1.330     albertel 4477:     my $result;
1.335     albertel 4478:     if ($args->{'discussion'}) {
                   4479: 	my ($target,$parser);
                   4480: 	if (ref($args->{'discussion'})) {
                   4481: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   4482: 				$args->{'discussion'}{'parser'});
                   4483: 	}
                   4484: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   4485:     }
                   4486: 
1.330     albertel 4487:     if ($args->{'frameset'}) {
                   4488: 	$result .= '</frameset>';
                   4489:     } else {
                   4490: 	$result .= &endbodytag();
                   4491:     }
                   4492:     $result .= "\n</html>";
                   4493: 
1.315     albertel 4494:     if ($args->{'js_ready'}) {
1.317     albertel 4495: 	$result = &js_ready($result);
1.315     albertel 4496:     }
1.335     albertel 4497: 
1.320     albertel 4498:     if ($args->{'html_encode'}) {
                   4499: 	$result = &html_encode($result);
                   4500:     }
1.335     albertel 4501: 
1.315     albertel 4502:     return $result;
                   4503: }
                   4504: 
1.320     albertel 4505: sub html_encode {
                   4506:     my ($result) = @_;
                   4507: 
1.322     albertel 4508:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 4509:     
                   4510:     return $result;
                   4511: }
1.317     albertel 4512: sub js_ready {
                   4513:     my ($result) = @_;
                   4514: 
1.323     albertel 4515:     $result =~ s/[\n\r]/ /xmsg;
                   4516:     $result =~ s/\\/\\\\/xmsg;
                   4517:     $result =~ s/'/\\'/xmsg;
1.372     albertel 4518:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 4519:     
                   4520:     return $result;
                   4521: }
                   4522: 
1.315     albertel 4523: sub validate_page {
                   4524:     if (  exists($env{'internal.start_page'})
1.316     albertel 4525: 	  &&     $env{'internal.start_page'} > 1) {
                   4526: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 4527: 				 $env{'internal.start_page'}.' '.
1.316     albertel 4528: 				 $ENV{'request.filename'});
1.315     albertel 4529:     }
                   4530:     if (  exists($env{'internal.end_page'})
1.316     albertel 4531: 	  &&     $env{'internal.end_page'} > 1) {
                   4532: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 4533: 				 $env{'internal.end_page'}.' '.
1.316     albertel 4534: 				 $env{'request.filename'});
1.315     albertel 4535:     }
                   4536:     if (     exists($env{'internal.start_page'})
                   4537: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 4538: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   4539: 				 $env{'request.filename'});
1.315     albertel 4540:     }
                   4541:     if (   ! exists($env{'internal.start_page'})
                   4542: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 4543: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   4544: 				 $env{'request.filename'});
1.315     albertel 4545:     }
1.306     albertel 4546: }
1.315     albertel 4547: 
1.318     albertel 4548: sub simple_error_page {
                   4549:     my ($r,$title,$msg) = @_;
                   4550:     my $page =
                   4551: 	&Apache::loncommon::start_page($title).
                   4552: 	&mt($msg).
                   4553: 	&Apache::loncommon::end_page();
                   4554:     if (ref($r)) {
                   4555: 	$r->print($page);
1.327     albertel 4556: 	return;
1.318     albertel 4557:     }
                   4558:     return $page;
                   4559: }
1.347     albertel 4560: 
                   4561: {
                   4562:     my $row_count;
                   4563:     sub start_data_table {
1.422     albertel 4564: 	my ($add_class) = @_;
                   4565: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.347     albertel 4566: 	undef($row_count);
1.422     albertel 4567: 	return '<table class="'.$css_class.'">'."\n";
1.347     albertel 4568:     }
                   4569: 
                   4570:     sub end_data_table {
                   4571: 	undef($row_count);
1.389     albertel 4572: 	return '</table>'."\n";;
1.347     albertel 4573:     }
                   4574: 
                   4575:     sub start_data_table_row {
1.422     albertel 4576: 	my ($add_class) = @_;
1.347     albertel 4577: 	$row_count++;
1.422     albertel 4578: 	my $css_class = ($row_count % 2)?'':'LC_even_row';
1.428     albertel 4579: 	$css_class = (join(' ',$css_class,$add_class));
1.422     albertel 4580: 	return  '<tr class="'.$css_class.'">'."\n";;
1.347     albertel 4581:     }
1.471     banghart 4582:     
                   4583:     sub continue_data_table_row {
                   4584: 	my ($add_class) = @_;
                   4585: 	my $css_class = ($row_count % 2)?'':'LC_even_row';
                   4586: 	$css_class = (join(' ',$css_class,$add_class));
                   4587: 	return  '<tr class="'.$css_class.'">'."\n";;
                   4588:     }
1.347     albertel 4589: 
                   4590:     sub end_data_table_row {
1.389     albertel 4591: 	return '</tr>'."\n";;
1.347     albertel 4592:     }
1.367     www      4593: 
1.421     albertel 4594:     sub start_data_table_empty_row {
                   4595: 	$row_count++;
                   4596: 	return  '<tr class="LC_empty_row" >'."\n";;
                   4597:     }
                   4598: 
                   4599:     sub end_data_table_empty_row {
                   4600: 	return '</tr>'."\n";;
                   4601:     }
                   4602: 
1.367     www      4603:     sub start_data_table_header_row {
1.389     albertel 4604: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      4605:     }
                   4606: 
                   4607:     sub end_data_table_header_row {
1.389     albertel 4608: 	return '</tr>'."\n";;
1.367     www      4609:     }
1.347     albertel 4610: }
                   4611: 
1.251     albertel 4612: ###############################################
1.182     matthew  4613: 
                   4614: =pod
                   4615: 
1.405     albertel 4616: =item * &get_users_function()
1.182     matthew  4617: 
                   4618: Used by &bodytag to determine the current users primary role.
                   4619: Returns either 'student','coordinator','admin', or 'author'.
                   4620: 
                   4621: =cut
                   4622: 
                   4623: ###############################################
                   4624: sub get_users_function {
                   4625:     my $function = 'student';
1.258     albertel 4626:     if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
1.182     matthew  4627:         $function='coordinator';
                   4628:     }
1.258     albertel 4629:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  4630:         $function='admin';
                   4631:     }
1.258     albertel 4632:     if (($env{'request.role'}=~/^(au|ca)/) ||
1.182     matthew  4633:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
                   4634:         $function='author';
                   4635:     }
                   4636:     return $function;
1.54      www      4637: }
1.99      www      4638: 
                   4639: ###############################################
                   4640: 
1.233     raeburn  4641: =pod
                   4642: 
1.405     albertel 4643: =item * &check_user_status
1.274     raeburn  4644: 
                   4645: Determines current status of supplied role for a
                   4646: specific user. Roles can be active, previous or future.
                   4647: 
                   4648: Inputs: 
                   4649: user's domain, user's username, course's domain,
1.375     raeburn  4650: course's number, optional section ID.
1.274     raeburn  4651: 
                   4652: Outputs:
                   4653: role status: active, previous or future. 
                   4654: 
                   4655: =cut
                   4656: 
                   4657: sub check_user_status {
1.412     raeburn  4658:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.274     raeburn  4659:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
                   4660:     my @uroles = keys %userinfo;
                   4661:     my $srchstr;
                   4662:     my $active_chk = 'none';
1.412     raeburn  4663:     my $now = time;
1.274     raeburn  4664:     if (@uroles > 0) {
1.412     raeburn  4665:         if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  4666:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   4667:         } else {
1.412     raeburn  4668:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   4669:         }
                   4670:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  4671:             my $role_end = 0;
                   4672:             my $role_start = 0;
                   4673:             $active_chk = 'active';
1.412     raeburn  4674:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   4675:                 $role_end = $1;
                   4676:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   4677:                     $role_start = $1;
1.274     raeburn  4678:                 }
                   4679:             }
                   4680:             if ($role_start > 0) {
1.412     raeburn  4681:                 if ($now < $role_start) {
1.274     raeburn  4682:                     $active_chk = 'future';
                   4683:                 }
                   4684:             }
                   4685:             if ($role_end > 0) {
1.412     raeburn  4686:                 if ($now > $role_end) {
1.274     raeburn  4687:                     $active_chk = 'previous';
                   4688:                 }
                   4689:             }
                   4690:         }
                   4691:     }
                   4692:     return $active_chk;
                   4693: }
                   4694: 
                   4695: ###############################################
                   4696: 
                   4697: =pod
                   4698: 
1.405     albertel 4699: =item * &get_sections()
1.233     raeburn  4700: 
                   4701: Determines all the sections for a course including
                   4702: sections with students and sections containing other roles.
1.419     raeburn  4703: Incoming parameters: 
                   4704: 
                   4705: 1. domain
                   4706: 2. course number 
                   4707: 3. reference to array containing roles for which sections should 
                   4708: be gathered (optional).
                   4709: 4. reference to array containing status types for which sections 
                   4710: should be gathered (optional).
                   4711: 
                   4712: If the third argument is undefined, sections are gathered for any role. 
                   4713: If the fourth argument is undefined, sections are gathered for any status.
                   4714: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  4715:  
1.374     raeburn  4716: Returns section hash (keys are section IDs, values are
                   4717: number of users in each section), subject to the
1.419     raeburn  4718: optional roles filter, optional status filter 
1.233     raeburn  4719: 
                   4720: =cut
                   4721: 
                   4722: ###############################################
                   4723: sub get_sections {
1.419     raeburn  4724:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 4725:     if (!defined($cdom) || !defined($cnum)) {
                   4726:         my $cid =  $env{'request.course.id'};
                   4727: 
                   4728: 	return if (!defined($cid));
                   4729: 
                   4730:         $cdom = $env{'course.'.$cid.'.domain'};
                   4731:         $cnum = $env{'course.'.$cid.'.num'};
                   4732:     }
                   4733: 
                   4734:     my %sectioncount;
1.419     raeburn  4735:     my $now = time;
1.240     albertel 4736: 
1.366     albertel 4737:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
1.276     albertel 4738: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 4739: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   4740: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  4741:         my $start_index = &Apache::loncoursedata::CL_START();
                   4742:         my $end_index = &Apache::loncoursedata::CL_END();
                   4743:         my $status;
1.366     albertel 4744: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  4745: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   4746: 				                     $data->[$status_index],
                   4747:                                                      $data->[$start_index],
                   4748:                                                      $data->[$end_index]);
                   4749:             if ($stu_status eq 'Active') {
                   4750:                 $status = 'active';
                   4751:             } elsif ($end < $now) {
                   4752:                 $status = 'previous';
                   4753:             } elsif ($start > $now) {
                   4754:                 $status = 'future';
                   4755:             } 
                   4756: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   4757:                 if ((!defined($possible_status)) || (($status ne '') && 
                   4758:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   4759: 		    $sectioncount{$section}++;
                   4760:                 }
1.240     albertel 4761: 	    }
                   4762: 	}
                   4763:     }
                   4764:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   4765:     foreach my $user (sort(keys(%courseroles))) {
                   4766: 	if ($user !~ /^(\w{2})/) { next; }
                   4767: 	my ($role) = ($user =~ /^(\w{2})/);
                   4768: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  4769: 	my ($section,$status);
1.240     albertel 4770: 	if ($role eq 'cr' &&
                   4771: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   4772: 	    $section=$1;
                   4773: 	}
                   4774: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   4775: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  4776:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   4777:         if ($end == -1 && $start == -1) {
                   4778:             next; #deleted role
                   4779:         }
                   4780:         if (!defined($possible_status)) { 
                   4781:             $sectioncount{$section}++;
                   4782:         } else {
                   4783:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   4784:                 $status = 'active';
                   4785:             } elsif ($end < $now) {
                   4786:                 $status = 'future';
                   4787:             } elsif ($start > $now) {
                   4788:                 $status = 'previous';
                   4789:             }
                   4790:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   4791:                 $sectioncount{$section}++;
                   4792:             }
                   4793:         }
1.233     raeburn  4794:     }
1.366     albertel 4795:     return %sectioncount;
1.233     raeburn  4796: }
                   4797: 
1.274     raeburn  4798: ###############################################
1.294     raeburn  4799: 
                   4800: =pod
1.405     albertel 4801: 
                   4802: =item * &get_course_users()
                   4803: 
1.275     raeburn  4804: Retrieves usernames:domains for users in the specified course
                   4805: with specific role(s), and access status. 
                   4806: 
                   4807: Incoming parameters:
1.277     albertel 4808: 1. course domain
                   4809: 2. course number
                   4810: 3. access status: users must have - either active, 
1.275     raeburn  4811: previous, future, or all.
1.277     albertel 4812: 4. reference to array of permissible roles
1.288     raeburn  4813: 5. reference to array of section restrictions (optional)
                   4814: 6. reference to results object (hash of hashes).
                   4815: 7. reference to optional userdata hash
1.275     raeburn  4816: Keys of top level hash are roles.
                   4817: Keys of inner hashes are username:domain, with 
                   4818: values set to access type.
1.288     raeburn  4819: Optional userdata hash returns an array with arguments in the 
                   4820: same order as loncoursedata::get_classlist() for student data.
                   4821: 
                   4822: Entries for end, start, section and status are blank because
                   4823: of the possibility of multiple values for non-student roles.
                   4824: 
1.275     raeburn  4825: =cut
1.405     albertel 4826: 
1.275     raeburn  4827: ###############################################
1.405     albertel 4828: 
1.275     raeburn  4829: sub get_course_users {
1.288     raeburn  4830:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata) = @_;
                   4831:     my %idx = ();
1.419     raeburn  4832:     my %seclists;
1.288     raeburn  4833: 
                   4834:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   4835:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   4836:     $idx{end} = &Apache::loncoursedata::CL_END();
                   4837:     $idx{start} = &Apache::loncoursedata::CL_START();
                   4838:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   4839:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   4840:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   4841:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   4842: 
1.290     albertel 4843:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 4844:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  4845:         my $now = time;
1.277     albertel 4846:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  4847:             my $match = 0;
1.412     raeburn  4848:             my $secmatch = 0;
1.419     raeburn  4849:             my $section = $$classlist{$student}[$idx{section}];
                   4850:             if ($section eq '') {
                   4851:                 $section = 'none';
                   4852:             }
1.291     albertel 4853:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 4854:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  4855:                     $secmatch = 1;
                   4856:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 4857:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  4858:                         $secmatch = 1;
                   4859:                     }
                   4860:                 } else {  
1.419     raeburn  4861: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  4862: 		        $secmatch = 1;
                   4863:                     }
1.290     albertel 4864: 		}
1.412     raeburn  4865:                 if (!$secmatch) {
                   4866:                     next;
                   4867:                 }
1.419     raeburn  4868:             }
1.420     albertel 4869:             push(@{$seclists{$student}},$section); 
1.275     raeburn  4870:             if (defined($$types{'active'})) {
1.288     raeburn  4871:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  4872:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  4873:                     $match = 1;
1.275     raeburn  4874:                 }
                   4875:             }
                   4876:             if (defined($$types{'previous'})) {
1.288     raeburn  4877:                 if ($$classlist{$student}[$idx{end}] <= $now) {
1.275     raeburn  4878:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  4879:                     $match = 1;
1.275     raeburn  4880:                 }
                   4881:             }
                   4882:             if (defined($$types{'future'})) {
1.288     raeburn  4883:                 if (($$classlist{$student}[$idx{start}] > $now) && ($$classlist{$student}[$idx{end}] > $now) || ($$classlist{$student}[$idx{end}] == 0) || ($$classlist{$student}[$idx{end}] eq '')) {
1.275     raeburn  4884:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  4885:                     $match = 1;
1.275     raeburn  4886:                 }
                   4887:             }
1.412     raeburn  4888:             if ($match && ref($userdata) eq 'HASH') {
1.288     raeburn  4889:                 $$userdata{$student} = $$classlist{$student};
                   4890:             }
1.275     raeburn  4891:         }
                   4892:     }
1.412     raeburn  4893:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  4894:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   4895:         my $now = time;
                   4896:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  4897:             my $match = 0;
1.412     raeburn  4898:             my $secmatch = 0;
1.439     raeburn  4899:             my $status;
1.412     raeburn  4900:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  4901:             $user =~ s/:$//;
1.439     raeburn  4902:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   4903:             if ($end == -1 || $start == -1) {
                   4904:                 next;
                   4905:             }
                   4906:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   4907:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  4908:                 my ($uname,$udom) = split(/:/,$user);
                   4909:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 4910:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  4911:                         $secmatch = 1;
                   4912:                     } elsif ($usec eq '') {
1.420     albertel 4913:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  4914:                             $secmatch = 1;
                   4915:                         }
                   4916:                     } else {
                   4917:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   4918:                             $secmatch = 1;
                   4919:                         }
                   4920:                     }
                   4921:                     if (!$secmatch) {
                   4922:                         next;
                   4923:                     }
1.288     raeburn  4924:                 }
1.419     raeburn  4925:                 if ($usec eq '') {
                   4926:                     $usec = 'none';
                   4927:                 }
1.275     raeburn  4928:                 if ($uname ne '' && $udom ne '') {
1.439     raeburn  4929:                     if ($end < $now) {
                   4930:                         $status = 'previous';
                   4931:                     } elsif ($start > $now) {
                   4932:                         $status = 'future';
                   4933:                     } else {
                   4934:                         $status = 'active';
                   4935:                     }
1.277     albertel 4936:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  4937:                         if ($status eq $type) {
1.420     albertel 4938:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  4939:                                 push(@{$$users{$role}{$user}},$type);
                   4940:                             }
1.288     raeburn  4941:                             $match = 1;
                   4942:                         }
                   4943:                     }
1.419     raeburn  4944:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   4945:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   4946: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   4947:                         }
1.420     albertel 4948:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  4949:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   4950:                         }
1.275     raeburn  4951:                     }
                   4952:                 }
                   4953:             }
                   4954:         }
1.290     albertel 4955:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  4956:             if ((defined($cdom)) && (defined($cnum))) {
                   4957:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   4958:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   4959:                     my $owner = $csettings{'internal.courseowner'};
1.439     raeburn  4960:                     if ($owner !~ /^[^:]+:[^:]+$/) {
                   4961:                         $owner = $owner.':'.$cdom;
                   4962:                     }
                   4963:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 4964:                     if (defined($userdata) && 
                   4965: 			!exists($$userdata{$owner.':'.$cdom})) {
                   4966: 			&get_user_info($cdom,$owner,\%idx,$userdata);
1.420     albertel 4967:                         if (!grep(/^none$/,@{$seclists{$owner.':'.$cdom}})) {
1.419     raeburn  4968:                             push(@{$seclists{$owner.':'.$cdom}},'none');
                   4969:                         }
1.290     albertel 4970: 		    }
1.279     raeburn  4971:                 }
                   4972:             }
                   4973:         }
1.419     raeburn  4974:         foreach my $user (keys(%seclists)) {
                   4975:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   4976:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   4977:         }
1.275     raeburn  4978:     }
                   4979:     return;
                   4980: }
                   4981: 
1.288     raeburn  4982: sub get_user_info {
                   4983:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 4984:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   4985: 	&plainname($uname,$udom,'lastname');
1.291     albertel 4986:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  4987:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.288     raeburn  4988:     return;
                   4989: }
1.275     raeburn  4990: 
1.472     raeburn  4991: ###############################################
                   4992: 
                   4993: =pod
                   4994: 
                   4995: =item * &get_user_quota()
                   4996: 
                   4997: Retrieves quota assigned for storage of portfolio files for a user  
                   4998: 
                   4999: Incoming parameters:
                   5000: 1. user's username
                   5001: 2. user's domain
                   5002: 
                   5003: Returns:
                   5004: 1. Disk quota (in Mb) assigned to student. 
                   5005: 
                   5006: If a value has been stored in the user's environment, 
                   5007: it will return that, otherwise it returns the default
                   5008: for users in the domain.
                   5009: 
                   5010: =cut
                   5011: 
                   5012: ###############################################
                   5013: 
                   5014: 
                   5015: sub get_user_quota {
                   5016:     my ($uname,$udom) = @_;
                   5017:     my $quota;
                   5018:     if (!defined($udom)) {
                   5019:         $udom = $env{'user.domain'};
                   5020:     }
                   5021:     if (!defined($uname)) {
                   5022:         $uname = $env{'user.name'};
                   5023:     }
                   5024:     if (($udom eq '' || $uname eq '') ||
                   5025:         ($udom eq 'public') && ($uname eq 'public')) {
                   5026:         $quota = 0;
                   5027:     } else {
                   5028:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   5029:             $quota = $env{'environment.portfolioquota'};
                   5030:         } else {
                   5031:             my %userenv = &Apache::lonnet::dump('environment',$udom,$uname);
                   5032:             my ($tmp) = keys(%userenv);
                   5033:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   5034:                 $quota = $userenv{'portfolioquota'};
                   5035:             } else {
                   5036:                 undef(%userenv);
                   5037:             }
                   5038:         }
                   5039:         if ($quota eq '') {
                   5040:             $quota = &default_quota($udom);
                   5041:         }
                   5042:     }
                   5043:     return $quota;
                   5044: }
                   5045: 
                   5046: ###############################################
                   5047: 
                   5048: =pod
                   5049: 
                   5050: =item * &default_quota()
                   5051: 
                   5052: Retrieves default quota assigned for storage of user portfolio files
                   5053: 
                   5054: Incoming parameters:
                   5055: 1. domain
                   5056: 
                   5057: Returns:
                   5058: 1. Default disk quota (in Mb) for user portfolios in the domain.
                   5059: 
                   5060: If a value has been stored in the domain's configuration db,
                   5061: it will return that, otherwise it returns 20 (for backwards 
                   5062: compatibility with domains which have not set up a configuration
                   5063: db file; the original statically defined portfolio quota was 20 Mb). 
                   5064: 
                   5065: =cut
                   5066: 
                   5067: ###############################################
                   5068: 
                   5069: 
                   5070: sub default_quota {
                   5071:     my ($udom) = @_;
                   5072:     my %defaults = &Apache::lonnet::get_dom('configuration',
                   5073:                                             ['portfolioquota'],$udom);
                   5074:     if ($defaults{'portfolioquota'} ne '') {
                   5075:         return $defaults{'portfolioquota'};
                   5076:     } else {
                   5077:         return '20';
                   5078:     }
                   5079: }
                   5080: 
1.384     raeburn  5081: sub get_secgrprole_info {
                   5082:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   5083:     my %sections_count = &get_sections($cdom,$cnum);
                   5084:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   5085:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   5086:     my @groups = sort(keys(%curr_groups));
                   5087:     my $allroles = [];
                   5088:     my $rolehash;
                   5089:     my $accesshash = {
                   5090:                      active => 'Currently has access',
                   5091:                      future => 'Will have future access',
                   5092:                      previous => 'Previously had access',
                   5093:                   };
                   5094:     if ($needroles) {
                   5095:         $rolehash = {'all' => 'all'};
1.385     albertel 5096:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   5097: 	if (&Apache::lonnet::error(%user_roles)) {
                   5098: 	    undef(%user_roles);
                   5099: 	}
                   5100:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  5101:             my ($role)=split(/\:/,$item,2);
                   5102:             if ($role eq 'cr') { next; }
                   5103:             if ($role =~ /^cr/) {
                   5104:                 $$rolehash{$role} = (split('/',$role))[3];
                   5105:             } else {
                   5106:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   5107:             }
                   5108:         }
                   5109:         foreach my $key (sort(keys(%{$rolehash}))) {
                   5110:             push(@{$allroles},$key);
                   5111:         }
                   5112:         push (@{$allroles},'st');
                   5113:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   5114:     }
                   5115:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   5116: }
                   5117: 
1.112     bowersj2 5118: =pod
                   5119: 
                   5120: =item * get_unprocessed_cgi($query,$possible_names)
                   5121: 
1.258     albertel 5122: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 5123: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 5124: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 5125: 
                   5126: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   5127: $possible_names is an ref to an array of form element names.  As an example:
                   5128: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 5129: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 5130: 
                   5131: =cut
1.1       albertel 5132: 
1.6       albertel 5133: sub get_unprocessed_cgi {
1.25      albertel 5134:   my ($query,$possible_names)= @_;
1.26      matthew  5135:   # $Apache::lonxml::debug=1;
1.356     albertel 5136:   foreach my $pair (split(/&/,$query)) {
                   5137:     my ($name, $value) = split(/=/,$pair);
1.369     www      5138:     $name = &unescape($name);
1.25      albertel 5139:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   5140:       $value =~ tr/+/ /;
                   5141:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 5142:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 5143:     }
1.16      harris41 5144:   }
1.6       albertel 5145: }
                   5146: 
1.112     bowersj2 5147: =pod
                   5148: 
                   5149: =item * cacheheader() 
                   5150: 
                   5151: returns cache-controlling header code
                   5152: 
                   5153: =cut
                   5154: 
1.7       albertel 5155: sub cacheheader {
1.258     albertel 5156:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 5157:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   5158:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 5159:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   5160:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 5161:     return $output;
1.7       albertel 5162: }
                   5163: 
1.112     bowersj2 5164: =pod
                   5165: 
                   5166: =item * no_cache($r) 
                   5167: 
                   5168: specifies header code to not have cache
                   5169: 
                   5170: =cut
                   5171: 
1.9       albertel 5172: sub no_cache {
1.216     albertel 5173:     my ($r) = @_;
                   5174:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 5175: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 5176:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   5177:     $r->no_cache(1);
                   5178:     $r->header_out("Expires" => $date);
                   5179:     $r->header_out("Pragma" => "no-cache");
1.123     www      5180: }
                   5181: 
                   5182: sub content_type {
1.181     albertel 5183:     my ($r,$type,$charset) = @_;
1.299     foxr     5184:     if ($r) {
                   5185: 	#  Note that printout.pl calls this with undef for $r.
                   5186: 	&no_cache($r);
                   5187:     }
1.258     albertel 5188:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 5189:     unless ($charset) {
                   5190: 	$charset=&Apache::lonlocal::current_encoding;
                   5191:     }
                   5192:     if ($charset) { $type.='; charset='.$charset; }
                   5193:     if ($r) {
                   5194: 	$r->content_type($type);
                   5195:     } else {
                   5196: 	print("Content-type: $type\n\n");
                   5197:     }
1.9       albertel 5198: }
1.25      albertel 5199: 
1.112     bowersj2 5200: =pod
                   5201: 
                   5202: =item * add_to_env($name,$value) 
                   5203: 
1.258     albertel 5204: adds $name to the %env hash with value
1.112     bowersj2 5205: $value, if $name already exists, the entry is converted to an array
                   5206: reference and $value is added to the array.
                   5207: 
                   5208: =cut
                   5209: 
1.25      albertel 5210: sub add_to_env {
                   5211:   my ($name,$value)=@_;
1.258     albertel 5212:   if (defined($env{$name})) {
                   5213:     if (ref($env{$name})) {
1.25      albertel 5214:       #already have multiple values
1.258     albertel 5215:       push(@{ $env{$name} },$value);
1.25      albertel 5216:     } else {
                   5217:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 5218:       my $first=$env{$name};
                   5219:       undef($env{$name});
                   5220:       push(@{ $env{$name} },$first,$value);
1.25      albertel 5221:     }
                   5222:   } else {
1.258     albertel 5223:     $env{$name}=$value;
1.25      albertel 5224:   }
1.31      albertel 5225: }
1.149     albertel 5226: 
                   5227: =pod
                   5228: 
                   5229: =item * get_env_multiple($name) 
                   5230: 
1.258     albertel 5231: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 5232: values may be defined and end up as an array ref.
                   5233: 
                   5234: returns an array of values
                   5235: 
                   5236: =cut
                   5237: 
                   5238: sub get_env_multiple {
                   5239:     my ($name) = @_;
                   5240:     my @values;
1.258     albertel 5241:     if (defined($env{$name})) {
1.149     albertel 5242:         # exists is it an array
1.258     albertel 5243:         if (ref($env{$name})) {
                   5244:             @values=@{ $env{$name} };
1.149     albertel 5245:         } else {
1.258     albertel 5246:             $values[0]=$env{$name};
1.149     albertel 5247:         }
                   5248:     }
                   5249:     return(@values);
                   5250: }
                   5251: 
1.31      albertel 5252: 
1.41      ng       5253: =pod
1.45      matthew  5254: 
1.464     albertel 5255: =back
1.41      ng       5256: 
1.112     bowersj2 5257: =head1 CSV Upload/Handling functions
1.38      albertel 5258: 
1.41      ng       5259: =over 4
                   5260: 
1.112     bowersj2 5261: =item * upfile_store($r)
1.41      ng       5262: 
                   5263: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 5264: needs $env{'form.upfile'}
1.41      ng       5265: returns $datatoken to be put into hidden field
                   5266: 
                   5267: =cut
1.31      albertel 5268: 
                   5269: sub upfile_store {
                   5270:     my $r=shift;
1.258     albertel 5271:     $env{'form.upfile'}=~s/\r/\n/gs;
                   5272:     $env{'form.upfile'}=~s/\f/\n/gs;
                   5273:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   5274:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 5275: 
1.258     albertel 5276:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   5277: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 5278:     {
1.158     raeburn  5279:         my $datafile = $r->dir_config('lonDaemons').
                   5280:                            '/tmp/'.$datatoken.'.tmp';
                   5281:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 5282:             print $fh $env{'form.upfile'};
1.158     raeburn  5283:             close($fh);
                   5284:         }
1.31      albertel 5285:     }
                   5286:     return $datatoken;
                   5287: }
                   5288: 
1.56      matthew  5289: =pod
                   5290: 
1.112     bowersj2 5291: =item * load_tmp_file($r)
1.41      ng       5292: 
                   5293: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 5294: needs $env{'form.datatoken'},
                   5295: sets $env{'form.upfile'} to the contents of the file
1.41      ng       5296: 
                   5297: =cut
1.31      albertel 5298: 
                   5299: sub load_tmp_file {
                   5300:     my $r=shift;
                   5301:     my @studentdata=();
                   5302:     {
1.158     raeburn  5303:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 5304:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  5305:         if ( open(my $fh,"<$studentfile") ) {
                   5306:             @studentdata=<$fh>;
                   5307:             close($fh);
                   5308:         }
1.31      albertel 5309:     }
1.258     albertel 5310:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 5311: }
                   5312: 
1.56      matthew  5313: =pod
                   5314: 
1.112     bowersj2 5315: =item * upfile_record_sep()
1.41      ng       5316: 
                   5317: Separate uploaded file into records
                   5318: returns array of records,
1.258     albertel 5319: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       5320: 
                   5321: =cut
1.31      albertel 5322: 
                   5323: sub upfile_record_sep {
1.258     albertel 5324:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 5325:     } else {
1.248     albertel 5326: 	my @records;
1.258     albertel 5327: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 5328: 	    if ($line=~/^\s*$/) { next; }
                   5329: 	    push(@records,$line);
                   5330: 	}
                   5331: 	return @records;
1.31      albertel 5332:     }
                   5333: }
                   5334: 
1.56      matthew  5335: =pod
                   5336: 
1.112     bowersj2 5337: =item * record_sep($record)
1.41      ng       5338: 
1.258     albertel 5339: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       5340: 
                   5341: =cut
                   5342: 
1.263     www      5343: sub takeleft {
                   5344:     my $index=shift;
                   5345:     return substr('0000'.$index,-4,4);
                   5346: }
                   5347: 
1.31      albertel 5348: sub record_sep {
                   5349:     my $record=shift;
                   5350:     my %components=();
1.258     albertel 5351:     if ($env{'form.upfiletype'} eq 'xml') {
                   5352:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 5353:         my $i=0;
1.356     albertel 5354:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 5355:             $field=~s/^(\"|\')//;
                   5356:             $field=~s/(\"|\')$//;
1.263     www      5357:             $components{&takeleft($i)}=$field;
1.31      albertel 5358:             $i++;
                   5359:         }
1.258     albertel 5360:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 5361:         my $i=0;
1.356     albertel 5362:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 5363:             $field=~s/^(\"|\')//;
                   5364:             $field=~s/(\"|\')$//;
1.263     www      5365:             $components{&takeleft($i)}=$field;
1.31      albertel 5366:             $i++;
                   5367:         }
                   5368:     } else {
1.480     banghart 5369:         my @allfields;
                   5370:         if ($env{'form.upfiletype'} eq 'semisv') {
                   5371:             @allfields=split(/;/,$record);
                   5372:         } else {
                   5373:             @allfields=split(/\,/,$record);
                   5374:         }
1.31      albertel 5375:         my $i=0;
                   5376:         my $j;
                   5377:         for ($j=0;$j<=$#allfields;$j++) {
                   5378:             my $field=$allfields[$j];
                   5379:             if ($field=~/^\s*(\"|\')/) {
                   5380: 		my $delimiter=$1;
                   5381:                 while (($field!~/$delimiter$/) && ($j<$#allfields)) {
                   5382: 		    $j++;
                   5383: 		    $field.=','.$allfields[$j];
                   5384: 		}
                   5385:                 $field=~s/^\s*$delimiter//;
                   5386:                 $field=~s/$delimiter\s*$//;
                   5387:             }
1.263     www      5388:             $components{&takeleft($i)}=$field;
1.31      albertel 5389: 	    $i++;
                   5390:         }
                   5391:     }
                   5392:     return %components;
                   5393: }
                   5394: 
1.144     matthew  5395: ######################################################
                   5396: ######################################################
                   5397: 
1.56      matthew  5398: =pod
                   5399: 
1.112     bowersj2 5400: =item * upfile_select_html()
1.41      ng       5401: 
1.144     matthew  5402: Return HTML code to select a file from the users machine and specify 
                   5403: the file type.
1.41      ng       5404: 
                   5405: =cut
                   5406: 
1.144     matthew  5407: ######################################################
                   5408: ######################################################
1.31      albertel 5409: sub upfile_select_html {
1.144     matthew  5410:     my %Types = (
                   5411:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 5412:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  5413:                  space => &mt('Space separated'),
                   5414:                  tab   => &mt('Tabulator separated'),
                   5415: #                 xml   => &mt('HTML/XML'),
                   5416:                  );
                   5417:     my $Str = '<input type="file" name="upfile" size="50" />'.
                   5418:         '<br />Type: <select name="upfiletype">';
                   5419:     foreach my $type (sort(keys(%Types))) {
                   5420:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   5421:     }
                   5422:     $Str .= "</select>\n";
                   5423:     return $Str;
1.31      albertel 5424: }
                   5425: 
1.301     albertel 5426: sub get_samples {
                   5427:     my ($records,$toget) = @_;
                   5428:     my @samples=({});
                   5429:     my $got=0;
                   5430:     foreach my $rec (@$records) {
                   5431: 	my %temp = &record_sep($rec);
                   5432: 	if (! grep(/\S/, values(%temp))) { next; }
                   5433: 	if (%temp) {
                   5434: 	    $samples[$got]=\%temp;
                   5435: 	    $got++;
                   5436: 	    if ($got == $toget) { last; }
                   5437: 	}
                   5438:     }
                   5439:     return \@samples;
                   5440: }
                   5441: 
1.144     matthew  5442: ######################################################
                   5443: ######################################################
                   5444: 
1.56      matthew  5445: =pod
                   5446: 
1.112     bowersj2 5447: =item * csv_print_samples($r,$records)
1.41      ng       5448: 
                   5449: Prints a table of sample values from each column uploaded $r is an
                   5450: Apache Request ref, $records is an arrayref from
                   5451: &Apache::loncommon::upfile_record_sep
                   5452: 
                   5453: =cut
                   5454: 
1.144     matthew  5455: ######################################################
                   5456: ######################################################
1.31      albertel 5457: sub csv_print_samples {
                   5458:     my ($r,$records) = @_;
1.301     albertel 5459:     my $samples = &get_samples($records,3);
                   5460: 
1.144     matthew  5461:     $r->print(&mt('Samples').'<br /><table border="2"><tr>');
1.356     albertel 5462:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
                   5463:         $r->print('<th>'.&mt('Column&nbsp;[_1]',($sample+1)).'</th>'); }
1.31      albertel 5464:     $r->print('</tr>');
1.301     albertel 5465:     foreach my $hash (@$samples) {
1.31      albertel 5466: 	$r->print('<tr>');
1.356     albertel 5467: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 5468: 	    $r->print('<td>');
1.356     albertel 5469: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 5470: 	    $r->print('</td>');
                   5471: 	}
                   5472: 	$r->print('</tr>');
                   5473:     }
                   5474:     $r->print('</tr></table><br />'."\n");
                   5475: }
                   5476: 
1.144     matthew  5477: ######################################################
                   5478: ######################################################
                   5479: 
1.56      matthew  5480: =pod
                   5481: 
1.112     bowersj2 5482: =item * csv_print_select_table($r,$records,$d)
1.41      ng       5483: 
                   5484: Prints a table to create associations between values and table columns.
1.144     matthew  5485: 
1.41      ng       5486: $r is an Apache Request ref,
                   5487: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  5488: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       5489: 
                   5490: =cut
                   5491: 
1.144     matthew  5492: ######################################################
                   5493: ######################################################
1.31      albertel 5494: sub csv_print_select_table {
                   5495:     my ($r,$records,$d) = @_;
1.301     albertel 5496:     my $i=0;
                   5497:     my $samples = &get_samples($records,1);
1.144     matthew  5498:     $r->print(&mt('Associate columns with student attributes.')."\n".
                   5499: 	     '<table border="2"><tr>'.
                   5500:               '<th>'.&mt('Attribute').'</th>'.
                   5501:               '<th>'.&mt('Column').'</th></tr>'."\n");
1.356     albertel 5502:     foreach my $array_ref (@$d) {
                   5503: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.31      albertel 5504: 	$r->print('<tr><td>'.$display.'</td>');
                   5505: 
                   5506: 	$r->print('<td><select name=f'.$i.
1.32      matthew  5507: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 5508: 	$r->print('<option value="none"></option>');
1.356     albertel 5509: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   5510: 	    $r->print('<option value="'.$sample.'"'.
                   5511:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
                   5512:                       '>Column '.($sample+1).'</option>');
1.31      albertel 5513: 	}
                   5514: 	$r->print('</select></td></tr>'."\n");
                   5515: 	$i++;
                   5516:     }
                   5517:     $i--;
                   5518:     return $i;
                   5519: }
1.56      matthew  5520: 
1.144     matthew  5521: ######################################################
                   5522: ######################################################
                   5523: 
1.56      matthew  5524: =pod
1.31      albertel 5525: 
1.112     bowersj2 5526: =item * csv_samples_select_table($r,$records,$d)
1.41      ng       5527: 
                   5528: Prints a table of sample values from the upload and can make associate samples to internal names.
                   5529: 
                   5530: $r is an Apache Request ref,
                   5531: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   5532: $d is an array of 2 element arrays (internal name, displayed name)
                   5533: 
                   5534: =cut
                   5535: 
1.144     matthew  5536: ######################################################
                   5537: ######################################################
1.31      albertel 5538: sub csv_samples_select_table {
                   5539:     my ($r,$records,$d) = @_;
                   5540:     my $i=0;
1.144     matthew  5541:     #
1.301     albertel 5542:     my $samples = &get_samples($records,3);
1.144     matthew  5543:     $r->print('<table border=2><tr><th>'.
                   5544:               &mt('Field').'</th><th>'.&mt('Samples').'</th></tr>');
1.301     albertel 5545: 
                   5546:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.144     matthew  5547: 	$r->print('<tr><td><select name="f'.$i.'"'.
1.32      matthew  5548: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 5549: 	foreach my $option (@$d) {
                   5550: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  5551: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 5552:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  5553:                       $display.'</option>');
1.31      albertel 5554: 	}
                   5555: 	$r->print('</select></td><td>');
1.301     albertel 5556: 	foreach my $line (0..2) {
                   5557: 	    if (defined($samples->[$line]{$key})) { 
                   5558: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   5559: 	    }
                   5560: 	}
1.31      albertel 5561: 	$r->print('</td></tr>');
                   5562: 	$i++;
                   5563:     }
                   5564:     $i--;
                   5565:     return($i);
1.115     matthew  5566: }
                   5567: 
1.144     matthew  5568: ######################################################
                   5569: ######################################################
                   5570: 
1.115     matthew  5571: =pod
                   5572: 
                   5573: =item clean_excel_name($name)
                   5574: 
                   5575: Returns a replacement for $name which does not contain any illegal characters.
                   5576: 
                   5577: =cut
                   5578: 
1.144     matthew  5579: ######################################################
                   5580: ######################################################
1.115     matthew  5581: sub clean_excel_name {
                   5582:     my ($name) = @_;
                   5583:     $name =~ s/[:\*\?\/\\]//g;
                   5584:     if (length($name) > 31) {
                   5585:         $name = substr($name,0,31);
                   5586:     }
                   5587:     return $name;
1.25      albertel 5588: }
1.84      albertel 5589: 
1.85      albertel 5590: =pod
                   5591: 
1.112     bowersj2 5592: =item * check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 5593: 
                   5594: Returns either 1 or undef
                   5595: 
                   5596: 1 if the part is to be hidden, undef if it is to be shown
                   5597: 
                   5598: Arguments are:
                   5599: 
                   5600: $id the id of the part to be checked
                   5601: $symb, optional the symb of the resource to check
                   5602: $udom, optional the domain of the user to check for
                   5603: $uname, optional the username of the user to check for
                   5604: 
                   5605: =cut
1.84      albertel 5606: 
                   5607: sub check_if_partid_hidden {
                   5608:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 5609:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 5610: 					 $symb,$udom,$uname);
1.141     albertel 5611:     my $truth=1;
                   5612:     #if the string starts with !, then the list is the list to show not hide
                   5613:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 5614:     my @hiddenlist=split(/,/,$hiddenparts);
                   5615:     foreach my $checkid (@hiddenlist) {
1.141     albertel 5616: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 5617:     }
1.141     albertel 5618:     return !$truth;
1.84      albertel 5619: }
1.127     matthew  5620: 
1.138     matthew  5621: 
                   5622: ############################################################
                   5623: ############################################################
                   5624: 
                   5625: =pod
                   5626: 
1.157     matthew  5627: =back 
                   5628: 
1.138     matthew  5629: =head1 cgi-bin script and graphing routines
                   5630: 
1.157     matthew  5631: =over 4
                   5632: 
1.138     matthew  5633: =item get_cgi_id
                   5634: 
                   5635: Inputs: none
                   5636: 
                   5637: Returns an id which can be used to pass environment variables
                   5638: to various cgi-bin scripts.  These environment variables will
                   5639: be removed from the users environment after a given time by
                   5640: the routine &Apache::lonnet::transfer_profile_to_env.
                   5641: 
                   5642: =cut
                   5643: 
                   5644: ############################################################
                   5645: ############################################################
1.152     albertel 5646: my $uniq=0;
1.136     matthew  5647: sub get_cgi_id {
1.154     albertel 5648:     $uniq=($uniq+1)%100000;
1.280     albertel 5649:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  5650: }
                   5651: 
1.127     matthew  5652: ############################################################
                   5653: ############################################################
                   5654: 
                   5655: =pod
                   5656: 
1.134     matthew  5657: =item DrawBarGraph
1.127     matthew  5658: 
1.138     matthew  5659: Facilitates the plotting of data in a (stacked) bar graph.
                   5660: Puts plot definition data into the users environment in order for 
                   5661: graph.png to plot it.  Returns an <img> tag for the plot.
                   5662: The bars on the plot are labeled '1','2',...,'n'.
                   5663: 
                   5664: Inputs:
                   5665: 
                   5666: =over 4
                   5667: 
                   5668: =item $Title: string, the title of the plot
                   5669: 
                   5670: =item $xlabel: string, text describing the X-axis of the plot
                   5671: 
                   5672: =item $ylabel: string, text describing the Y-axis of the plot
                   5673: 
                   5674: =item $Max: scalar, the maximum Y value to use in the plot
                   5675: If $Max is < any data point, the graph will not be rendered.
                   5676: 
1.140     matthew  5677: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  5678: they are plotted.  If undefined, default values will be used.
                   5679: 
1.178     matthew  5680: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   5681: 
1.138     matthew  5682: =item @Values: An array of array references.  Each array reference holds data
                   5683: to be plotted in a stacked bar chart.
                   5684: 
1.239     matthew  5685: =item If the final element of @Values is a hash reference the key/value
                   5686: pairs will be added to the graph definition.
                   5687: 
1.138     matthew  5688: =back
                   5689: 
                   5690: Returns:
                   5691: 
                   5692: An <img> tag which references graph.png and the appropriate identifying
                   5693: information for the plot.
                   5694: 
1.127     matthew  5695: =cut
                   5696: 
                   5697: ############################################################
                   5698: ############################################################
1.134     matthew  5699: sub DrawBarGraph {
1.178     matthew  5700:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  5701:     #
                   5702:     if (! defined($colors)) {
                   5703:         $colors = ['#33ff00', 
                   5704:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   5705:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   5706:                   ]; 
                   5707:     }
1.228     matthew  5708:     my $extra_settings = {};
                   5709:     if (ref($Values[-1]) eq 'HASH') {
                   5710:         $extra_settings = pop(@Values);
                   5711:     }
1.127     matthew  5712:     #
1.136     matthew  5713:     my $identifier = &get_cgi_id();
                   5714:     my $id = 'cgi.'.$identifier;        
1.129     matthew  5715:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  5716:         return '';
                   5717:     }
1.225     matthew  5718:     #
                   5719:     my @Labels;
                   5720:     if (defined($labels)) {
                   5721:         @Labels = @$labels;
                   5722:     } else {
                   5723:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   5724:             push (@Labels,$i+1);
                   5725:         }
                   5726:     }
                   5727:     #
1.129     matthew  5728:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  5729:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  5730:     my %ValuesHash;
                   5731:     my $NumSets=1;
                   5732:     foreach my $array (@Values) {
                   5733:         next if (! ref($array));
1.136     matthew  5734:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  5735:             join(',',@$array);
1.129     matthew  5736:     }
1.127     matthew  5737:     #
1.136     matthew  5738:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  5739:     if ($NumBars < 3) {
                   5740:         $width = 120+$NumBars*32;
1.220     matthew  5741:         $xskip = 1;
1.225     matthew  5742:         $bar_width = 30;
                   5743:     } elsif ($NumBars < 5) {
                   5744:         $width = 120+$NumBars*20;
                   5745:         $xskip = 1;
                   5746:         $bar_width = 20;
1.220     matthew  5747:     } elsif ($NumBars < 10) {
1.136     matthew  5748:         $width = 120+$NumBars*15;
                   5749:         $xskip = 1;
                   5750:         $bar_width = 15;
                   5751:     } elsif ($NumBars <= 25) {
                   5752:         $width = 120+$NumBars*11;
                   5753:         $xskip = 5;
                   5754:         $bar_width = 8;
                   5755:     } elsif ($NumBars <= 50) {
                   5756:         $width = 120+$NumBars*8;
                   5757:         $xskip = 5;
                   5758:         $bar_width = 4;
                   5759:     } else {
                   5760:         $width = 120+$NumBars*8;
                   5761:         $xskip = 5;
                   5762:         $bar_width = 4;
                   5763:     }
                   5764:     #
1.137     matthew  5765:     $Max = 1 if ($Max < 1);
                   5766:     if ( int($Max) < $Max ) {
                   5767:         $Max++;
                   5768:         $Max = int($Max);
                   5769:     }
1.127     matthew  5770:     $Title  = '' if (! defined($Title));
                   5771:     $xlabel = '' if (! defined($xlabel));
                   5772:     $ylabel = '' if (! defined($ylabel));
1.369     www      5773:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   5774:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   5775:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  5776:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  5777:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   5778:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   5779:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   5780:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   5781:     $ValuesHash{$id.'.height'}   = $height;
                   5782:     $ValuesHash{$id.'.width'}    = $width;
                   5783:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   5784:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   5785:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  5786:     #
1.228     matthew  5787:     # Deal with other parameters
                   5788:     while (my ($key,$value) = each(%$extra_settings)) {
                   5789:         $ValuesHash{$id.'.'.$key} = $value;
                   5790:     }
                   5791:     #
1.137     matthew  5792:     &Apache::lonnet::appenv(%ValuesHash);
                   5793:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   5794: }
                   5795: 
                   5796: ############################################################
                   5797: ############################################################
                   5798: 
                   5799: =pod
                   5800: 
                   5801: =item DrawXYGraph
                   5802: 
1.138     matthew  5803: Facilitates the plotting of data in an XY graph.
                   5804: Puts plot definition data into the users environment in order for 
                   5805: graph.png to plot it.  Returns an <img> tag for the plot.
                   5806: 
                   5807: Inputs:
                   5808: 
                   5809: =over 4
                   5810: 
                   5811: =item $Title: string, the title of the plot
                   5812: 
                   5813: =item $xlabel: string, text describing the X-axis of the plot
                   5814: 
                   5815: =item $ylabel: string, text describing the Y-axis of the plot
                   5816: 
                   5817: =item $Max: scalar, the maximum Y value to use in the plot
                   5818: If $Max is < any data point, the graph will not be rendered.
                   5819: 
                   5820: =item $colors: Array ref containing the hex color codes for the data to be 
                   5821: plotted in.  If undefined, default values will be used.
                   5822: 
                   5823: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   5824: 
                   5825: =item $Ydata: Array ref containing Array refs.  
1.185     www      5826: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  5827: 
                   5828: =item %Values: hash indicating or overriding any default values which are 
                   5829: passed to graph.png.  
                   5830: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   5831: 
                   5832: =back
                   5833: 
                   5834: Returns:
                   5835: 
                   5836: An <img> tag which references graph.png and the appropriate identifying
                   5837: information for the plot.
                   5838: 
1.137     matthew  5839: =cut
                   5840: 
                   5841: ############################################################
                   5842: ############################################################
                   5843: sub DrawXYGraph {
                   5844:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   5845:     #
                   5846:     # Create the identifier for the graph
                   5847:     my $identifier = &get_cgi_id();
                   5848:     my $id = 'cgi.'.$identifier;
                   5849:     #
                   5850:     $Title  = '' if (! defined($Title));
                   5851:     $xlabel = '' if (! defined($xlabel));
                   5852:     $ylabel = '' if (! defined($ylabel));
                   5853:     my %ValuesHash = 
                   5854:         (
1.369     www      5855:          $id.'.title'  => &escape($Title),
                   5856:          $id.'.xlabel' => &escape($xlabel),
                   5857:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  5858:          $id.'.y_max_value'=> $Max,
                   5859:          $id.'.labels'     => join(',',@$Xlabels),
                   5860:          $id.'.PlotType'   => 'XY',
                   5861:          );
                   5862:     #
                   5863:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   5864:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   5865:     }
                   5866:     #
                   5867:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   5868:         return '';
                   5869:     }
                   5870:     my $NumSets=1;
1.138     matthew  5871:     foreach my $array (@{$Ydata}){
1.137     matthew  5872:         next if (! ref($array));
                   5873:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   5874:     }
1.138     matthew  5875:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  5876:     #
                   5877:     # Deal with other parameters
                   5878:     while (my ($key,$value) = each(%Values)) {
                   5879:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  5880:     }
                   5881:     #
1.136     matthew  5882:     &Apache::lonnet::appenv(%ValuesHash);
                   5883:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   5884: }
                   5885: 
                   5886: ############################################################
                   5887: ############################################################
                   5888: 
                   5889: =pod
                   5890: 
1.138     matthew  5891: =item DrawXYYGraph
                   5892: 
                   5893: Facilitates the plotting of data in an XY graph with two Y axes.
                   5894: Puts plot definition data into the users environment in order for 
                   5895: graph.png to plot it.  Returns an <img> tag for the plot.
                   5896: 
                   5897: Inputs:
                   5898: 
                   5899: =over 4
                   5900: 
                   5901: =item $Title: string, the title of the plot
                   5902: 
                   5903: =item $xlabel: string, text describing the X-axis of the plot
                   5904: 
                   5905: =item $ylabel: string, text describing the Y-axis of the plot
                   5906: 
                   5907: =item $colors: Array ref containing the hex color codes for the data to be 
                   5908: plotted in.  If undefined, default values will be used.
                   5909: 
                   5910: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   5911: 
                   5912: =item $Ydata1: The first data set
                   5913: 
                   5914: =item $Min1: The minimum value of the left Y-axis
                   5915: 
                   5916: =item $Max1: The maximum value of the left Y-axis
                   5917: 
                   5918: =item $Ydata2: The second data set
                   5919: 
                   5920: =item $Min2: The minimum value of the right Y-axis
                   5921: 
                   5922: =item $Max2: The maximum value of the left Y-axis
                   5923: 
                   5924: =item %Values: hash indicating or overriding any default values which are 
                   5925: passed to graph.png.  
                   5926: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   5927: 
                   5928: =back
                   5929: 
                   5930: Returns:
                   5931: 
                   5932: An <img> tag which references graph.png and the appropriate identifying
                   5933: information for the plot.
1.136     matthew  5934: 
                   5935: =cut
                   5936: 
                   5937: ############################################################
                   5938: ############################################################
1.137     matthew  5939: sub DrawXYYGraph {
                   5940:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   5941:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  5942:     #
                   5943:     # Create the identifier for the graph
                   5944:     my $identifier = &get_cgi_id();
                   5945:     my $id = 'cgi.'.$identifier;
                   5946:     #
                   5947:     $Title  = '' if (! defined($Title));
                   5948:     $xlabel = '' if (! defined($xlabel));
                   5949:     $ylabel = '' if (! defined($ylabel));
                   5950:     my %ValuesHash = 
                   5951:         (
1.369     www      5952:          $id.'.title'  => &escape($Title),
                   5953:          $id.'.xlabel' => &escape($xlabel),
                   5954:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  5955:          $id.'.labels' => join(',',@$Xlabels),
                   5956:          $id.'.PlotType' => 'XY',
                   5957:          $id.'.NumSets' => 2,
1.137     matthew  5958:          $id.'.two_axes' => 1,
                   5959:          $id.'.y1_max_value' => $Max1,
                   5960:          $id.'.y1_min_value' => $Min1,
                   5961:          $id.'.y2_max_value' => $Max2,
                   5962:          $id.'.y2_min_value' => $Min2,
1.136     matthew  5963:          );
                   5964:     #
1.137     matthew  5965:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   5966:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   5967:     }
                   5968:     #
                   5969:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   5970:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  5971:         return '';
                   5972:     }
                   5973:     my $NumSets=1;
1.137     matthew  5974:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  5975:         next if (! ref($array));
                   5976:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  5977:     }
                   5978:     #
                   5979:     # Deal with other parameters
                   5980:     while (my ($key,$value) = each(%Values)) {
                   5981:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  5982:     }
                   5983:     #
                   5984:     &Apache::lonnet::appenv(%ValuesHash);
1.130     albertel 5985:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  5986: }
                   5987: 
                   5988: ############################################################
                   5989: ############################################################
                   5990: 
                   5991: =pod
                   5992: 
1.157     matthew  5993: =back 
                   5994: 
1.139     matthew  5995: =head1 Statistics helper routines?  
                   5996: 
                   5997: Bad place for them but what the hell.
                   5998: 
1.157     matthew  5999: =over 4
                   6000: 
1.139     matthew  6001: =item &chartlink
                   6002: 
                   6003: Returns a link to the chart for a specific student.  
                   6004: 
                   6005: Inputs:
                   6006: 
                   6007: =over 4
                   6008: 
                   6009: =item $linktext: The text of the link
                   6010: 
                   6011: =item $sname: The students username
                   6012: 
                   6013: =item $sdomain: The students domain
                   6014: 
                   6015: =back
                   6016: 
1.157     matthew  6017: =back
                   6018: 
1.139     matthew  6019: =cut
                   6020: 
                   6021: ############################################################
                   6022: ############################################################
                   6023: sub chartlink {
                   6024:     my ($linktext, $sname, $sdomain) = @_;
                   6025:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      6026:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 6027:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  6028:        '">'.$linktext.'</a>';
1.153     matthew  6029: }
                   6030: 
                   6031: #######################################################
                   6032: #######################################################
                   6033: 
                   6034: =pod
                   6035: 
                   6036: =head1 Course Environment Routines
1.157     matthew  6037: 
                   6038: =over 4
1.153     matthew  6039: 
                   6040: =item &restore_course_settings 
                   6041: 
                   6042: =item &store_course_settings
                   6043: 
                   6044: Restores/Store indicated form parameters from the course environment.
                   6045: Will not overwrite existing values of the form parameters.
                   6046: 
                   6047: Inputs: 
                   6048: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   6049: 
                   6050: a hash ref describing the data to be stored.  For example:
                   6051:    
                   6052: %Save_Parameters = ('Status' => 'scalar',
                   6053:     'chartoutputmode' => 'scalar',
                   6054:     'chartoutputdata' => 'scalar',
                   6055:     'Section' => 'array',
1.373     raeburn  6056:     'Group' => 'array',
1.153     matthew  6057:     'StudentData' => 'array',
                   6058:     'Maps' => 'array');
                   6059: 
                   6060: Returns: both routines return nothing
                   6061: 
                   6062: =cut
                   6063: 
                   6064: #######################################################
                   6065: #######################################################
                   6066: sub store_course_settings {
                   6067:     # save to the environment
                   6068:     # appenv the same items, just to be safe
1.258     albertel 6069:     my $courseid = $env{'request.course.id'};
1.300     albertel 6070:     my $udom  = $env{'user.domain'};
                   6071:     my $uname = $env{'user.name'};
1.153     matthew  6072:     my ($prefix,$Settings) = @_;
                   6073:     my %SaveHash;
                   6074:     my %AppHash;
                   6075:     while (my ($setting,$type) = each(%$Settings)) {
1.300     albertel 6076:         my $basename = join('.','internal',$courseid,$prefix,$setting);
                   6077:         my $envname = 'environment.'.$basename;
1.258     albertel 6078:         if (exists($env{'form.'.$setting})) {
1.153     matthew  6079:             # Save this value away
                   6080:             if ($type eq 'scalar' &&
1.258     albertel 6081:                 (! exists($env{$envname}) || 
                   6082:                  $env{$envname} ne $env{'form.'.$setting})) {
                   6083:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   6084:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  6085:             } elsif ($type eq 'array') {
                   6086:                 my $stored_form;
1.258     albertel 6087:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  6088:                     $stored_form = join(',',
                   6089:                                         map {
1.369     www      6090:                                             &escape($_);
1.258     albertel 6091:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  6092:                 } else {
                   6093:                     $stored_form = 
1.369     www      6094:                         &escape($env{'form.'.$setting});
1.153     matthew  6095:                 }
                   6096:                 # Determine if the array contents are the same.
1.258     albertel 6097:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  6098:                     $SaveHash{$basename} = $stored_form;
                   6099:                     $AppHash{$envname}   = $stored_form;
                   6100:                 }
                   6101:             }
                   6102:         }
                   6103:     }
                   6104:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 6105:                                           $udom,$uname);
1.153     matthew  6106:     if ($put_result !~ /^(ok|delayed)/) {
                   6107:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   6108:                                  'got error:'.$put_result);
                   6109:     }
                   6110:     # Make sure these settings stick around in this session, too
                   6111:     &Apache::lonnet::appenv(%AppHash);
                   6112:     return;
                   6113: }
                   6114: 
                   6115: sub restore_course_settings {
1.258     albertel 6116:     my $courseid = $env{'request.course.id'};
1.153     matthew  6117:     my ($prefix,$Settings) = @_;
                   6118:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 6119:         next if (exists($env{'form.'.$setting}));
1.300     albertel 6120:         my $envname = 'environment.internal.'.$courseid.'.'.$prefix.
1.153     matthew  6121:             '.'.$setting;
1.258     albertel 6122:         if (exists($env{$envname})) {
1.153     matthew  6123:             if ($type eq 'scalar') {
1.258     albertel 6124:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  6125:             } elsif ($type eq 'array') {
1.258     albertel 6126:                 $env{'form.'.$setting} = [ 
1.153     matthew  6127:                                            map { 
1.369     www      6128:                                                &unescape($_); 
1.258     albertel 6129:                                            } split(',',$env{$envname})
1.153     matthew  6130:                                            ];
                   6131:             }
                   6132:         }
                   6133:     }
1.127     matthew  6134: }
                   6135: 
                   6136: ############################################################
                   6137: ############################################################
1.154     albertel 6138: 
1.443     albertel 6139: sub commit_customrole {
                   6140:     my ($udom,$uname,$url,$three,$four,$five,$start,$end) = @_;
                   6141:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.'@'.$three.' in '.$url.
                   6142:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   6143:                          ($end?', ending '.localtime($end):'').': <b>'.
                   6144:               &Apache::lonnet::assigncustomrole(
                   6145:                  $udom,$uname,$url,$three,$four,$five,$end,$start).
                   6146:                  '</b><br />';
                   6147:     return $output;
                   6148: }
                   6149: 
                   6150: sub commit_standardrole {
                   6151:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec) = @_;
                   6152:     my $output;
                   6153:     my $logmsg;
                   6154:     if ($three eq 'st') {
                   6155:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec);
                   6156:         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course')) {
                   6157:             $output = "Error: $result\n"; 
                   6158:         } else {
                   6159:             $output = &mt('Assigning').' '.$three.' in '.$url.
                   6160:                ($start?', '.&mt('starting').' '.localtime($start):'').
                   6161:                ($end?', '.&mt('ending').' '.localtime($end):'').
                   6162:                ': <b>'.$result.'</b><br />'.
                   6163:                &mt('Add to classlist').': <b>ok</b><br />';
                   6164:         }
                   6165:     } else {
                   6166:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   6167:                ($start?', '.&mt('starting').' '.localtime($start):'').
                   6168:                ($end?', '.&mt('ending').' '.localtime($end):'').': <b>'.
                   6169:                &Apache::lonnet::assignrole(
                   6170:                    $udom,$uname,$url,$three,$end,$start).
                   6171:                    '</b><br />';
                   6172:     }
                   6173:     return $output;
                   6174: }
                   6175: 
                   6176: sub commit_studentrole {
                   6177:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec) = @_;
                   6178:     my $linefeed =  '<br />'."\n";
                   6179:     my $result;
                   6180:     if (defined($one) && defined($two)) {
                   6181:         my $cid=$one.'_'.$two;
                   6182:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   6183:         my $secchange = 0;
                   6184:         my $expire_role_result;
                   6185:         my $modify_section_result;
                   6186:         unless ($oldsec eq '-1') {
                   6187:             unless ($sec eq $oldsec) {
                   6188:                 $secchange = 1;
                   6189:                 my $uurl='/'.$cid;
                   6190:                 $uurl=~s/\_/\//g;
                   6191:                 if ($oldsec) {
                   6192:                     $uurl.='/'.$oldsec;
                   6193:                 }
                   6194:                 $expire_role_result = &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',time);
                   6195:                 $result = $expire_role_result;
                   6196:             }
                   6197:         }
                   6198:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
                   6199:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid);
                   6200:             if ($modify_section_result =~ /^ok/) {
                   6201:                 if ($secchange == 1) {
                   6202:                     $$logmsg .= "Section for $uname switched from old section: $oldsec to new section: $sec".$linefeed;
                   6203:                 } elsif ($oldsec eq '-1') {
                   6204:                     $$logmsg .= "New student role for $uname in section $sec in course $cid".$linefeed;
                   6205:                 } else {
                   6206:                     $$logmsg .= "Student $uname assigned to unchanged section $sec in course $cid".$linefeed;
                   6207:                 }
                   6208:             } else {
                   6209:                 $$logmsg .= "Error when attempting section change for $uname from old section $oldsec to new section: $sec in course $cid -error: $modify_section_result".$linefeed;
                   6210:             }
                   6211:             $result = $modify_section_result;
                   6212:         } elsif ($secchange == 1) {
                   6213:             $$logmsg .= "Error when attempting to expire role for $uname in old section $oldsec in course $cid -error: $expire_role_result".$linefeed;
                   6214:         }
                   6215:     } else {
                   6216:         $$logmsg .= "Incomplete course id defined.  Addition of user $uname from domain $udom to course $one\_$two, section $sec not completed.$linefeed";
                   6217:         $result = "error: incomplete course id\n";
                   6218:     }
                   6219:     return $result;
                   6220: }
                   6221: 
                   6222: ############################################################
                   6223: ############################################################
                   6224: 
1.444     albertel 6225: sub construct_course {
                   6226:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname) = @_;
                   6227:     my $outcome;
                   6228: 
                   6229: #
                   6230: # Open course
                   6231: #
                   6232:     my $crstype = lc($args->{'crstype'});
                   6233:     my %cenv=();
                   6234:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   6235:                                              $args->{'cdescr'},
                   6236:                                              $args->{'curl'},
                   6237:                                              $args->{'course_home'},
                   6238:                                              $args->{'nonstandard'},
                   6239:                                              $args->{'crscode'},
                   6240:                                              $args->{'ccuname'}.':'.
                   6241:                                              $args->{'ccdomain'},
                   6242:                                              $args->{'crstype'});
                   6243: 
                   6244:     # Note: The testing routines depend on this being output; see 
                   6245:     # Utils::Course. This needs to at least be output as a comment
                   6246:     # if anyone ever decides to not show this, and Utils::Course::new
                   6247:     # will need to be suitably modified.
                   6248:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]<br />',$crstype,$$courseid);
                   6249: #
                   6250: # Check if created correctly
                   6251: #
1.479     albertel 6252:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 6253:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
                   6254:     $outcome .= &mt('Created on').': '.$crsuhome.'<br>';
                   6255: #
                   6256: # Are we cloning?
                   6257: #
                   6258:     my $cloneid='';
                   6259:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
                   6260: 	$cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
1.479     albertel 6261:         my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
1.444     albertel 6262: 	my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   6263: 	if ($clonehome eq 'no_host') {
                   6264: 	    $outcome .=
                   6265:     '<br /><font color="red">'.&mt('Attempting to clone non-existing [_1]',$crstype).' '.$cloneid.'</font>';
                   6266: 	} else {
                   6267: 	    $outcome .= 
                   6268:     '<br /><font color="green">'.&mt('Cloning [_1] from [_2]',$crstype,$clonehome).'</font>';
                   6269: 	    my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
                   6270: # Copy all files
                   6271: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid);
                   6272: # Restore URL
                   6273: 	    $cenv{'url'}=$oldcenv{'url'};
                   6274: # Restore title
                   6275: 	    $cenv{'description'}=$oldcenv{'description'};
                   6276: # restore grading mode
                   6277: 	    if (defined($oldcenv{'grading'})) {
                   6278: 		$cenv{'grading'}=$oldcenv{'grading'};
                   6279: 	    }
                   6280: # Mark as cloned
                   6281: 	    $cenv{'clonedfrom'}=$cloneid;
                   6282: 	    delete($cenv{'default_enrollment_start_date'});
                   6283: 	    delete($cenv{'default_enrollment_end_date'});
                   6284: 	}
                   6285:     }
                   6286: #
                   6287: # Set environment (will override cloned, if existing)
                   6288: #
                   6289:     my @sections = ();
                   6290:     my @xlists = ();
                   6291:     if ($args->{'crstype'}) {
                   6292:         $cenv{'type'}=$args->{'crstype'};
                   6293:     }
                   6294:     if ($args->{'crsid'}) {
                   6295:         $cenv{'courseid'}=$args->{'crsid'};
                   6296:     }
                   6297:     if ($args->{'crscode'}) {
                   6298:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   6299:     }
                   6300:     if ($args->{'crsquota'} ne '') {
                   6301:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   6302:     } else {
                   6303:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   6304:     }
                   6305:     if ($args->{'ccuname'}) {
                   6306:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   6307:                                         ':'.$args->{'ccdomain'};
                   6308:     } else {
                   6309:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   6310:     }
                   6311: 
                   6312:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   6313:     if ($args->{'crssections'}) {
                   6314:         $cenv{'internal.sectionnums'} = '';
                   6315:         if ($args->{'crssections'} =~ m/,/) {
                   6316:             @sections = split/,/,$args->{'crssections'};
                   6317:         } else {
                   6318:             $sections[0] = $args->{'crssections'};
                   6319:         }
                   6320:         if (@sections > 0) {
                   6321:             foreach my $item (@sections) {
                   6322:                 my ($sec,$gp) = split/:/,$item;
                   6323:                 my $class = $args->{'crscode'}.$sec;
                   6324:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   6325:                 $cenv{'internal.sectionnums'} .= $item.',';
                   6326:                 unless ($addcheck eq 'ok') {
                   6327:                     push @badclasses, $class;
                   6328:                 }
                   6329:             }
                   6330:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   6331:         }
                   6332:     }
                   6333: # do not hide course coordinator from staff listing, 
                   6334: # even if privileged
                   6335:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   6336: # add crosslistings
                   6337:     if ($args->{'crsxlist'}) {
                   6338:         $cenv{'internal.crosslistings'}='';
                   6339:         if ($args->{'crsxlist'} =~ m/,/) {
                   6340:             @xlists = split/,/,$args->{'crsxlist'};
                   6341:         } else {
                   6342:             $xlists[0] = $args->{'crsxlist'};
                   6343:         }
                   6344:         if (@xlists > 0) {
                   6345:             foreach my $item (@xlists) {
                   6346:                 my ($xl,$gp) = split/:/,$item;
                   6347:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   6348:                 $cenv{'internal.crosslistings'} .= $item.',';
                   6349:                 unless ($addcheck eq 'ok') {
                   6350:                     push @badclasses, $xl;
                   6351:                 }
                   6352:             }
                   6353:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   6354:         }
                   6355:     }
                   6356:     if ($args->{'autoadds'}) {
                   6357:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   6358:     }
                   6359:     if ($args->{'autodrops'}) {
                   6360:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   6361:     }
                   6362: # check for notification of enrollment changes
                   6363:     my @notified = ();
                   6364:     if ($args->{'notify_owner'}) {
                   6365:         if ($args->{'ccuname'} ne '') {
                   6366:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   6367:         }
                   6368:     }
                   6369:     if ($args->{'notify_dc'}) {
                   6370:         if ($uname ne '') { 
                   6371:             push(@notified,$uname.'@'.$udom);
                   6372:         }
                   6373:     }
                   6374:     if (@notified > 0) {
                   6375:         my $notifylist;
                   6376:         if (@notified > 1) {
                   6377:             $notifylist = join(',',@notified);
                   6378:         } else {
                   6379:             $notifylist = $notified[0];
                   6380:         }
                   6381:         $cenv{'internal.notifylist'} = $notifylist;
                   6382:     }
                   6383:     if (@badclasses > 0) {
                   6384:         my %lt=&Apache::lonlocal::texthash(
                   6385:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.  However, if automated course roster updates are enabled for this class, these particular sections/crosslistings will not contribute towards enrollment, because the user identified as the course owner for this LON-CAPA course',
                   6386:                 'dnhr' => 'does not have rights to access enrollment in these classes',
                   6387:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
                   6388:         );
                   6389:         $outcome .= '<font color="red">'.$lt{'tclb'}.' ('.$cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.' ('.$lt{'adby'}.').<br /><ul>'."\n";
                   6390:         foreach (@badclasses) {
                   6391:             $outcome .= "<li>$_</li>\n";
                   6392:         }
                   6393:         $outcome .= "</ul><br /><br /></font>\n";
                   6394:     }
                   6395:     if ($args->{'no_end_date'}) {
                   6396:         $args->{'endaccess'} = 0;
                   6397:     }
                   6398:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   6399:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   6400:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   6401:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   6402:     if ($args->{'showphotos'}) {
                   6403:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   6404:     }
                   6405:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   6406:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   6407:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   6408:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
                   6409:             $outcome .= '<font color="red" size="+1">'.
                   6410:                       &mt('As you did not include the default Kerberos domain to be used for authentication in this class, the institutional data used by the automated enrollment process must include the Kerberos domain for each new student').'</font></p>';
                   6411:         }
                   6412:     }
                   6413:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   6414:        if ($args->{'setpolicy'}) {
                   6415:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   6416:        }
                   6417:        if ($args->{'setcontent'}) {
                   6418:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   6419:        }
                   6420:     }
                   6421:     if ($args->{'reshome'}) {
                   6422: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   6423: 	$cenv{'reshome'}=~s/\/+$/\//;
                   6424:     }
                   6425: #
                   6426: # course has keyed access
                   6427: #
                   6428:     if ($args->{'setkeys'}) {
                   6429:        $cenv{'keyaccess'}='yes';
                   6430:     }
                   6431: # if specified, key authority is not course, but user
                   6432: # only active if keyaccess is yes
                   6433:     if ($args->{'keyauth'}) {
1.487     albertel 6434: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   6435: 	$user = &LONCAPA::clean_username($user);
                   6436: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     6437: 	if ($user ne '' && $domain ne '') {
1.487     albertel 6438: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 6439: 	}
                   6440:     }
                   6441: 
                   6442:     if ($args->{'disresdis'}) {
                   6443:         $cenv{'pch.roles.denied'}='st';
                   6444:     }
                   6445:     if ($args->{'disablechat'}) {
                   6446:         $cenv{'plc.roles.denied'}='st';
                   6447:     }
                   6448: 
                   6449:     # Record we've not yet viewed the Course Initialization Helper for this 
                   6450:     # course
                   6451:     $cenv{'course.helper.not.run'} = 1;
                   6452:     #
                   6453:     # Use new Randomseed
                   6454:     #
                   6455:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   6456:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   6457:     #
                   6458:     # The encryption code and receipt prefix for this course
                   6459:     #
                   6460:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   6461:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   6462:     #
                   6463:     # By default, use standard grading
                   6464:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   6465: 
                   6466:     $outcome .= ('<br />'.&mt('Setting environment').': '.                 
                   6467:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).'<br>');
                   6468: #
                   6469: # Open all assignments
                   6470: #
                   6471:     if ($args->{'openall'}) {
                   6472:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   6473:        my %storecontent = ($storeunder         => time,
                   6474:                            $storeunder.'.type' => 'date_start');
                   6475:        
                   6476:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
                   6477:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).'<br>';
                   6478:    }
                   6479: #
                   6480: # Set first page
                   6481: #
                   6482:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   6483: 	    || ($cloneid)) {
1.445     albertel 6484: 	use LONCAPA::map;
1.444     albertel 6485: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 6486: 
                   6487: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   6488:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   6489: 
1.444     albertel 6490:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   6491:         my $title; my $url;
                   6492:         if ($args->{'firstres'} eq 'syl') {
                   6493: 	    $title='Syllabus';
                   6494:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   6495:         } else {
                   6496:             $title='Navigate Contents';
                   6497:             $url='/adm/navmaps';
                   6498:         }
1.445     albertel 6499: 
                   6500:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   6501: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   6502: 
                   6503: 	if ($errtext) { $fatal=2; }
                   6504:         $outcome .= ($fatal?$errtext:'write ok').'<br />';
1.444     albertel 6505:     }
                   6506:     return $outcome;
                   6507: }
                   6508: 
                   6509: ############################################################
                   6510: ############################################################
                   6511: 
1.378     raeburn  6512: sub course_type {
                   6513:     my ($cid) = @_;
                   6514:     if (!defined($cid)) {
                   6515:         $cid = $env{'request.course.id'};
                   6516:     }
1.404     albertel 6517:     if (defined($env{'course.'.$cid.'.type'})) {
                   6518:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  6519:     } else {
                   6520:         return 'Course';
1.377     raeburn  6521:     }
                   6522: }
1.156     albertel 6523: 
1.406     raeburn  6524: sub group_term {
                   6525:     my $crstype = &course_type();
                   6526:     my %names = (
                   6527:                   'Course' => 'group',
                   6528:                   'Group' => 'team',
                   6529:                 );
                   6530:     return $names{$crstype};
                   6531: }
                   6532: 
1.156     albertel 6533: sub icon {
                   6534:     my ($file)=@_;
1.168     albertel 6535:     my $curfext = (split(/\./,$file))[-1];
                   6536:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 6537:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 6538:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   6539: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   6540: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   6541: 	            $curfext.".gif") {
                   6542: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   6543: 		$curfext.".gif";
                   6544: 	}
                   6545:     }
1.249     albertel 6546:     return &lonhttpdurl($iconname);
1.154     albertel 6547: } 
1.84      albertel 6548: 
1.215     albertel 6549: sub lonhttpdurl {
                   6550:     my ($url)=@_;
                   6551:     my $lonhttpd_port=$Apache::lonnet::perlvar{'lonhttpdPort'};
                   6552:     if (!defined($lonhttpd_port)) { $lonhttpd_port='8080'; }
                   6553:     return 'http://'.$ENV{'SERVER_NAME'}.':'.$lonhttpd_port.$url;
                   6554: }
                   6555: 
1.213     albertel 6556: sub connection_aborted {
                   6557:     my ($r)=@_;
                   6558:     $r->print(" ");$r->rflush();
                   6559:     my $c = $r->connection;
                   6560:     return $c->aborted();
                   6561: }
                   6562: 
1.221     foxr     6563: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     6564: #    strings as 'strings'.
                   6565: sub escape_single {
1.221     foxr     6566:     my ($input) = @_;
1.223     albertel 6567:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     6568:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   6569:     return $input;
                   6570: }
1.223     albertel 6571: 
1.222     foxr     6572: #  Same as escape_single, but escape's "'s  This 
                   6573: #  can be used for  "strings"
                   6574: sub escape_double {
                   6575:     my ($input) = @_;
                   6576:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   6577:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   6578:     return $input;
                   6579: }
1.223     albertel 6580:  
1.222     foxr     6581: #   Escapes the last element of a full URL.
                   6582: sub escape_url {
                   6583:     my ($url)   = @_;
1.238     raeburn  6584:     my @urlslices = split(/\//, $url,-1);
1.369     www      6585:     my $lastitem = &escape(pop(@urlslices));
1.223     albertel 6586:     return join('/',@urlslices).'/'.$lastitem;
1.222     foxr     6587: }
1.462     albertel 6588: 
                   6589: # -------------------------------------------------------- Initliaze user login
                   6590: sub init_user_environment {
1.463     albertel 6591:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 6592:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   6593: 
                   6594:     my $public=($username eq 'public' && $domain eq 'public');
                   6595: 
                   6596: # See if old ID present, if so, remove
                   6597: 
                   6598:     my ($filename,$cookie,$userroles);
                   6599:     my $now=time;
                   6600: 
                   6601:     if ($public) {
                   6602: 	my $max_public=100;
                   6603: 	my $oldest;
                   6604: 	my $oldest_time=0;
                   6605: 	for(my $next=1;$next<=$max_public;$next++) {
                   6606: 	    if (-e $lonids."/publicuser_$next.id") {
                   6607: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   6608: 		if ($mtime<$oldest_time || !$oldest_time) {
                   6609: 		    $oldest_time=$mtime;
                   6610: 		    $oldest=$next;
                   6611: 		}
                   6612: 	    } else {
                   6613: 		$cookie="publicuser_$next";
                   6614: 		last;
                   6615: 	    }
                   6616: 	}
                   6617: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   6618:     } else {
1.463     albertel 6619: 	# if this isn't a robot, kill any existing non-robot sessions
                   6620: 	if (!$args->{'robot'}) {
                   6621: 	    opendir(DIR,$lonids);
                   6622: 	    while ($filename=readdir(DIR)) {
                   6623: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   6624: 		    unlink($lonids.'/'.$filename);
                   6625: 		}
1.462     albertel 6626: 	    }
1.463     albertel 6627: 	    closedir(DIR);
1.462     albertel 6628: 	}
                   6629: # Give them a new cookie
1.463     albertel 6630: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
                   6631: 		                   : $now);
                   6632: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 6633:     
                   6634: # Initialize roles
                   6635: 
                   6636: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
                   6637:     }
                   6638: # ------------------------------------ Check browser type and MathML capability
                   6639: 
                   6640:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
                   6641:         $clientunicode,$clientos) = &decode_user_agent($r);
                   6642: 
                   6643: # -------------------------------------- Any accessibility options to remember?
                   6644:     if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
                   6645: 	foreach my $option ('imagesuppress','appletsuppress',
                   6646: 			    'embedsuppress','fontenhance','blackwhite') {
                   6647: 	    if ($form->{$option} eq 'true') {
                   6648: 		&Apache::lonnet::put('environment',{$option => 'on'},
                   6649: 				     $domain,$username);
                   6650: 	    } else {
                   6651: 		&Apache::lonnet::del('environment',[$option],
                   6652: 				     $domain,$username);
                   6653: 	    }
                   6654: 	}
                   6655:     }
                   6656: # ------------------------------------------------------------- Get environment
                   6657: 
                   6658:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   6659:     my ($tmp) = keys(%userenv);
                   6660:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   6661: 	# default remote control to off
                   6662: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
                   6663:     } else {
                   6664: 	undef(%userenv);
                   6665:     }
                   6666:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   6667: 	$form->{'interface'}=$userenv{'interface'};
                   6668:     }
                   6669:     $env{'environment.remote'}=$userenv{'remote'};
                   6670:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   6671: 
                   6672: # --------------- Do not trust query string to be put directly into environment
                   6673:     foreach my $option ('imagesuppress','appletsuppress',
                   6674: 			'embedsuppress','fontenhance','blackwhite',
                   6675: 			'interface','localpath','localres') {
                   6676: 	$form->{$option}=~s/[\n\r\=]//gs;
                   6677:     }
                   6678: # --------------------------------------------------------- Write first profile
                   6679: 
                   6680:     {
                   6681: 	my %initial_env = 
                   6682: 	    ("user.name"          => $username,
                   6683: 	     "user.domain"        => $domain,
                   6684: 	     "user.home"          => $authhost,
                   6685: 	     "browser.type"       => $clientbrowser,
                   6686: 	     "browser.version"    => $clientversion,
                   6687: 	     "browser.mathml"     => $clientmathml,
                   6688: 	     "browser.unicode"    => $clientunicode,
                   6689: 	     "browser.os"         => $clientos,
                   6690: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   6691: 	     "request.course.fn"  => '',
                   6692: 	     "request.course.uri" => '',
                   6693: 	     "request.course.sec" => '',
                   6694: 	     "request.role"       => 'cm',
                   6695: 	     "request.role.adv"   => $env{'user.adv'},
                   6696: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   6697: 
                   6698:         if ($form->{'localpath'}) {
                   6699: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   6700: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   6701:         }
                   6702: 	
                   6703: 	if ($public) {
                   6704: 	    $initial_env{"environment.remote"} = "off";
                   6705: 	}
                   6706: 	if ($form->{'interface'}) {
                   6707: 	    $form->{'interface'}=~s/\W//gs;
                   6708: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   6709: 	    $env{'browser.interface'}=$form->{'interface'};
                   6710: 	    foreach my $option ('imagesuppress','appletsuppress',
                   6711: 				'embedsuppress','fontenhance','blackwhite') {
                   6712: 		if (($form->{$option} eq 'true') ||
                   6713: 		    ($userenv{$option} eq 'on')) {
                   6714: 		    $initial_env{"browser.$option"} = "on";
                   6715: 		}
                   6716: 	    }
                   6717: 	}
                   6718: 
                   6719: 	$env{'user.environment'} = "$lonids/$cookie.id";
                   6720: 	
                   6721: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   6722: 		 &GDBM_WRCREAT(),0640)) {
                   6723: 	    &_add_to_env(\%disk_env,\%initial_env);
                   6724: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   6725: 	    &_add_to_env(\%disk_env,$userroles);
1.463     albertel 6726: 	    if (ref($args->{'extra_env'})) {
                   6727: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   6728: 	    }
1.462     albertel 6729: 	    untie(%disk_env);
                   6730: 	} else {
                   6731: 	    &Apache::lonnet::logthis("<font color=\"blue\">WARNING: ".
                   6732: 			   'Could not create environment storage in lonauth: '.$!.'</font>');
                   6733: 	    return 'error: '.$!;
                   6734: 	}
                   6735:     }
                   6736:     $env{'request.role'}='cm';
                   6737:     $env{'request.role.adv'}=$env{'user.adv'};
                   6738:     $env{'browser.type'}=$clientbrowser;
                   6739: 
                   6740:     return $cookie;
                   6741: 
                   6742: }
                   6743: 
                   6744: sub _add_to_env {
                   6745:     my ($idf,$env_data,$prefix) = @_;
                   6746:     while (my ($key,$value) = each(%$env_data)) {
                   6747: 	$idf->{$prefix.$key} = $value;
                   6748: 	$env{$prefix.$key}   = $value;
                   6749:     }
                   6750: }
                   6751: 
                   6752: 
1.41      ng       6753: =pod
                   6754: 
                   6755: =back
                   6756: 
1.112     bowersj2 6757: =cut
1.41      ng       6758: 
1.112     bowersj2 6759: 1;
                   6760: __END__;
1.41      ng       6761: 

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