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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.679.2.6! raeburn     4: # $Id: loncommon.pm,v 1.679.2.5 2008/09/19 23:09:29 raeburn Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.139     matthew    64: use HTML::Entities;
1.334     albertel   65: use Apache::lonhtmlcommon();
                     66: use Apache::loncoursedata();
1.344     albertel   67: use Apache::lontexconvert();
1.444     albertel   68: use Apache::lonclonecourse();
1.479     albertel   69: use LONCAPA qw(:DEFAULT :match);
1.657     raeburn    70: use DateTime::TimeZone;
1.117     www        71: 
1.517     raeburn    72: # ---------------------------------------------- Designs
                     73: use vars qw(%defaultdesign);
                     74: 
1.22      www        75: my $readit;
                     76: 
1.517     raeburn    77: 
1.157     matthew    78: ##
                     79: ## Global Variables
                     80: ##
1.46      matthew    81: 
1.643     foxr       82: 
                     83: # ----------------------------------------------- SSI with retries:
                     84: #
                     85: 
                     86: =pod
                     87: 
1.648     raeburn    88: =head1 Server Side include with retries:
1.643     foxr       89: 
                     90: =over 4
                     91: 
1.648     raeburn    92: =item * &ssi_with_retries(resource,retries form)
1.643     foxr       93: 
                     94: Performs an ssi with some number of retries.  Retries continue either
                     95: until the result is ok or until the retry count supplied by the
                     96: caller is exhausted.  
                     97: 
                     98: Inputs:
1.648     raeburn    99: 
                    100: =over 4
                    101: 
1.643     foxr      102: resource   - Identifies the resource to insert.
1.648     raeburn   103: 
1.643     foxr      104: retries    - Count of the number of retries allowed.
1.648     raeburn   105: 
1.643     foxr      106: form       - Hash that identifies the rendering options.
                    107: 
1.648     raeburn   108: =back
                    109: 
                    110: Returns:
                    111: 
                    112: =over 4
                    113: 
1.643     foxr      114: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   115: 
1.643     foxr      116: response   - The response from the last attempt (which may or may not have been successful.
                    117: 
1.648     raeburn   118: =back
                    119: 
                    120: =back
                    121: 
1.643     foxr      122: =cut
                    123: 
                    124: sub ssi_with_retries {
                    125:     my ($resource, $retries, %form) = @_;
                    126: 
                    127: 
                    128:     my $ok = 0;			# True if we got a good response.
                    129:     my $content;
                    130:     my $response;
                    131: 
                    132:     # Try to get the ssi done. within the retries count:
                    133: 
                    134:     do {
                    135: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    136: 	$ok      = $response->is_success;
1.650     www       137:         if (!$ok) {
                    138:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    139:         }
1.643     foxr      140: 	$retries--;
                    141:     } while (!$ok && ($retries > 0));
                    142: 
                    143:     if (!$ok) {
                    144: 	$content = '';		# On error return an empty content.
                    145:     }
                    146:     return ($content, $response);
                    147: 
                    148: }
                    149: 
                    150: 
                    151: 
1.20      www       152: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  153: my %language;
1.124     www       154: my %supported_language;
1.12      harris41  155: my %cprtag;
1.192     taceyjo1  156: my %scprtag;
1.351     www       157: my %fe; my %fd; my %fm;
1.41      ng        158: my %category_extensions;
1.12      harris41  159: 
1.46      matthew   160: # ---------------------------------------------- Thesaurus variables
1.144     matthew   161: #
                    162: # %Keywords:
                    163: #      A hash used by &keyword to determine if a word is considered a keyword.
                    164: # $thesaurus_db_file 
                    165: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   166: 
                    167: my %Keywords;
                    168: my $thesaurus_db_file;
                    169: 
1.144     matthew   170: #
                    171: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    172: # thesaurus.tab, and filecategories.tab.
                    173: #
1.18      www       174: BEGIN {
1.46      matthew   175:     # Variable initialization
                    176:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    177:     #
1.22      www       178:     unless ($readit) {
1.12      harris41  179: # ------------------------------------------------------------------- languages
                    180:     {
1.158     raeburn   181:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    182:                                    '/language.tab';
                    183:         if ( open(my $fh,"<$langtabfile") ) {
1.356     albertel  184:             while (my $line = <$fh>) {
                    185:                 next if ($line=~/^\#/);
                    186:                 chomp($line);
                    187:                 my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
1.158     raeburn   188:                 $language{$key}=$val.' - '.$enc;
                    189:                 if ($sup) {
                    190:                     $supported_language{$key}=$sup;
                    191:                 }
                    192:             }
                    193:             close($fh);
                    194:         }
1.12      harris41  195:     }
                    196: # ------------------------------------------------------------------ copyrights
                    197:     {
1.158     raeburn   198:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    199:                                   '/copyright.tab';
                    200:         if ( open (my $fh,"<$copyrightfile") ) {
1.356     albertel  201:             while (my $line = <$fh>) {
                    202:                 next if ($line=~/^\#/);
                    203:                 chomp($line);
                    204:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   205:                 $cprtag{$key}=$val;
                    206:             }
                    207:             close($fh);
                    208:         }
1.12      harris41  209:     }
1.351     www       210: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  211:     {
                    212:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    213:                                   '/source_copyright.tab';
                    214:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
1.356     albertel  215:             while (my $line = <$fh>) {
                    216:                 next if ($line =~ /^\#/);
                    217:                 chomp($line);
                    218:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  219:                 $scprtag{$key}=$val;
                    220:             }
                    221:             close($fh);
                    222:         }
                    223:     }
1.63      www       224: 
1.517     raeburn   225: # -------------------------------------------------------------- default domain designs
1.63      www       226:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   227:     my $designfile = $designdir.'/default.tab';
                    228:     if ( open (my $fh,"<$designfile") ) {
                    229:         while (my $line = <$fh>) {
                    230:             next if ($line =~ /^\#/);
                    231:             chomp($line);
                    232:             my ($key,$val)=(split(/\=/,$line));
                    233:             if ($val) { $defaultdesign{$key}=$val; }
                    234:         }
                    235:         close($fh);
1.63      www       236:     }
                    237: 
1.15      harris41  238: # ------------------------------------------------------------- file categories
                    239:     {
1.158     raeburn   240:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    241:                                   '/filecategories.tab';
                    242:         if ( open (my $fh,"<$categoryfile") ) {
1.356     albertel  243: 	    while (my $line = <$fh>) {
                    244: 		next if ($line =~ /^\#/);
                    245: 		chomp($line);
                    246:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.158     raeburn   247:                 push @{$category_extensions{lc($category)}},$extension;
                    248:             }
                    249:             close($fh);
                    250:         }
                    251: 
1.15      harris41  252:     }
1.12      harris41  253: # ------------------------------------------------------------------ file types
                    254:     {
1.158     raeburn   255:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    256:                '/filetypes.tab';
                    257:         if ( open (my $fh,"<$typesfile") ) {
1.356     albertel  258:             while (my $line = <$fh>) {
                    259: 		next if ($line =~ /^\#/);
                    260: 		chomp($line);
                    261:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   262:                 if ($descr ne '') {
                    263:                     $fe{$ending}=lc($emb);
                    264:                     $fd{$ending}=$descr;
1.351     www       265:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   266:                 }
                    267:             }
                    268:             close($fh);
                    269:         }
1.12      harris41  270:     }
1.22      www       271:     &Apache::lonnet::logthis(
1.46      matthew   272:               "<font color=yellow>INFO: Read file types</font>");
1.22      www       273:     $readit=1;
1.46      matthew   274:     }  # end of unless($readit) 
1.32      matthew   275:     
                    276: }
1.112     bowersj2  277: 
1.42      matthew   278: ###############################################################
                    279: ##           HTML and Javascript Helper Functions            ##
                    280: ###############################################################
                    281: 
                    282: =pod 
                    283: 
1.112     bowersj2  284: =head1 HTML and Javascript Functions
1.42      matthew   285: 
1.112     bowersj2  286: =over 4
                    287: 
1.648     raeburn   288: =item * &browser_and_searcher_javascript()
1.112     bowersj2  289: 
                    290: X<browsing, javascript>X<searching, javascript>Returns a string
                    291: containing javascript with two functions, C<openbrowser> and
                    292: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    293: tags.
1.42      matthew   294: 
1.648     raeburn   295: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   296: 
                    297: inputs: formname, elementname, only, omit
                    298: 
                    299: formname and elementname indicate the name of the html form and name of
                    300: the element that the results of the browsing selection are to be placed in. 
                    301: 
                    302: Specifying 'only' will restrict the browser to displaying only files
1.185     www       303: with the given extension.  Can be a comma separated list.
1.42      matthew   304: 
                    305: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       306: with the given extension.  Can be a comma separated list.
1.42      matthew   307: 
1.648     raeburn   308: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   309: 
                    310: Inputs: formname, elementname
                    311: 
                    312: formname and elementname specify the name of the html form and the name
                    313: of the element the selection from the search results will be placed in.
1.542     raeburn   314: 
1.42      matthew   315: =cut
                    316: 
                    317: sub browser_and_searcher_javascript {
1.199     albertel  318:     my ($mode)=@_;
                    319:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  320:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   321:     return <<END;
1.219     albertel  322: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   323:     var editbrowser = null;
1.135     albertel  324:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       325:         var url = '$resurl/?';
1.42      matthew   326:         if (editbrowser == null) {
                    327:             url += 'launch=1&';
                    328:         }
                    329:         url += 'catalogmode=interactive&';
1.199     albertel  330:         url += 'mode=$mode&';
1.611     albertel  331:         url += 'inhibitmenu=yes&';
1.42      matthew   332:         url += 'form=' + formname + '&';
                    333:         if (only != null) {
                    334:             url += 'only=' + only + '&';
1.217     albertel  335:         } else {
                    336:             url += 'only=&';
                    337: 	}
1.42      matthew   338:         if (omit != null) {
                    339:             url += 'omit=' + omit + '&';
1.217     albertel  340:         } else {
                    341:             url += 'omit=&';
                    342: 	}
1.135     albertel  343:         if (titleelement != null) {
                    344:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  345:         } else {
                    346: 	    url += 'titleelement=&';
                    347: 	}
1.42      matthew   348:         url += 'element=' + elementname + '';
                    349:         var title = 'Browser';
1.435     albertel  350:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   351:         options += ',width=700,height=600';
                    352:         editbrowser = open(url,title,options,'1');
                    353:         editbrowser.focus();
                    354:     }
                    355:     var editsearcher;
1.135     albertel  356:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   357:         var url = '/adm/searchcat?';
                    358:         if (editsearcher == null) {
                    359:             url += 'launch=1&';
                    360:         }
                    361:         url += 'catalogmode=interactive&';
1.199     albertel  362:         url += 'mode=$mode&';
1.42      matthew   363:         url += 'form=' + formname + '&';
1.135     albertel  364:         if (titleelement != null) {
                    365:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  366:         } else {
                    367: 	    url += 'titleelement=&';
                    368: 	}
1.42      matthew   369:         url += 'element=' + elementname + '';
                    370:         var title = 'Search';
1.435     albertel  371:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   372:         options += ',width=700,height=600';
                    373:         editsearcher = open(url,title,options,'1');
                    374:         editsearcher.focus();
                    375:     }
1.219     albertel  376: // END LON-CAPA Internal -->
1.42      matthew   377: END
1.170     www       378: }
                    379: 
                    380: sub lastresurl {
1.258     albertel  381:     if ($env{'environment.lastresurl'}) {
                    382: 	return $env{'environment.lastresurl'}
1.170     www       383:     } else {
                    384: 	return '/res';
                    385:     }
                    386: }
                    387: 
                    388: sub storeresurl {
                    389:     my $resurl=&Apache::lonnet::clutter(shift);
                    390:     unless ($resurl=~/^\/res/) { return 0; }
                    391:     $resurl=~s/\/$//;
                    392:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   393:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       394:     return 1;
1.42      matthew   395: }
                    396: 
1.74      www       397: sub studentbrowser_javascript {
1.111     www       398:    unless (
1.258     albertel  399:             (($env{'request.course.id'}) && 
1.302     albertel  400:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    401: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    402: 					  '/'.$env{'request.course.sec'})
                    403: 	      ))
1.258     albertel  404:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       405:           ) { return ''; }  
1.74      www       406:    return (<<'ENDSTDBRW');
                    407: <script type="text/javascript" language="Javascript" >
                    408:     var stdeditbrowser;
1.558     albertel  409:     function openstdbrowser(formname,uname,udom,roleflag,ignorefilter) {
1.74      www       410:         var url = '/adm/pickstudent?';
                    411:         var filter;
1.558     albertel  412: 	if (!ignorefilter) {
                    413: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    414: 	}
1.74      www       415:         if (filter != null) {
                    416:            if (filter != '') {
                    417:                url += 'filter='+filter+'&';
                    418: 	   }
                    419:         }
                    420:         url += 'form=' + formname + '&unameelement='+uname+
                    421:                                     '&udomelement='+udom;
1.111     www       422: 	if (roleflag) { url+="&roles=1"; }
1.102     www       423:         var title = 'Student_Browser';
1.74      www       424:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    425:         options += ',width=700,height=600';
                    426:         stdeditbrowser = open(url,title,options,'1');
                    427:         stdeditbrowser.focus();
                    428:     }
                    429: </script>
                    430: ENDSTDBRW
                    431: }
1.42      matthew   432: 
1.74      www       433: sub selectstudent_link {
1.111     www       434:    my ($form,$unameele,$udomele)=@_;
1.258     albertel  435:    if ($env{'request.course.id'}) {  
1.302     albertel  436:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    437: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    438: 					'/'.$env{'request.course.sec'})) {
1.111     www       439: 	   return '';
                    440:        }
                    441:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
1.607     albertel  442:         '","'.$udomele.'");'."'>".&mt('Select User')."</a>";
1.74      www       443:    }
1.258     albertel  444:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.111     www       445:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
1.119     www       446:         '","'.$udomele.'",1);'."'>".&mt('Select User')."</a>";
1.111     www       447:    }
                    448:    return '';
1.91      www       449: }
                    450: 
1.653     raeburn   451: sub authorbrowser_javascript {
                    452:     return <<"ENDAUTHORBRW";
                    453: <script type="text/javascript">
                    454: var stdeditbrowser;
                    455: 
                    456: function openauthorbrowser(formname,udom) {
                    457:     var url = '/adm/pickauthor?';
                    458:     url += 'form='+formname+'&roledom='+udom;
                    459:     var title = 'Author_Browser';
                    460:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    461:     options += ',width=700,height=600';
                    462:     stdeditbrowser = open(url,title,options,'1');
                    463:     stdeditbrowser.focus();
                    464: }
                    465: 
                    466: </script>
                    467: ENDAUTHORBRW
                    468: }
                    469: 
1.91      www       470: sub coursebrowser_javascript {
1.468     raeburn   471:     my ($domainfilter,$sec_element,$formname)=@_;
1.377     raeburn   472:     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   473:    my $output = '
1.538     albertel  474: <script type="text/javascript">
1.468     raeburn   475:     var stdeditbrowser;'."\n";
                    476:    $output .= <<"ENDSTDBRW";
1.377     raeburn   477:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,crstype) {
1.91      www       478:         var url = '/adm/pickcourse?';
1.468     raeburn   479:         var domainfilter = '';
                    480:         var formid = getFormIdByName(formname);
                    481:         if (formid > -1) {
                    482:             var domid = getIndexByName(formid,udom);
                    483:             if (domid > -1) {
                    484:                 if (document.forms[formid].elements[domid].type == 'select-one') {
                    485:                     domainfilter=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    486:                 }
                    487:                 if (document.forms[formid].elements[domid].type == 'hidden') {
                    488:                     domainfilter=document.forms[formid].elements[domid].value;
                    489:                 }
                    490:             }
1.91      www       491:         }
1.128     albertel  492:         if (domainfilter != null) {
                    493:            if (domainfilter != '') {
                    494:                url += 'domainfilter='+domainfilter+'&';
                    495: 	   }
                    496:         }
1.91      www       497:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  498: 	                            '&cdomelement='+udom+
                    499:                                     '&cnameelement='+desc;
1.468     raeburn   500:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   501:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   502:                 url += '&roleelement='+extra_element;
                    503:                 if (domainfilter == null || domainfilter == '') {
                    504:                     url += '&domainfilter='+extra_element;
                    505:                 }
1.234     raeburn   506:             }
1.468     raeburn   507:             else {
                    508:                 if (formname == 'portform') {
                    509:                     url += '&setroles='+extra_element;
                    510:                 }
                    511:             }     
1.230     raeburn   512:         }
1.293     raeburn   513:         if (multflag !=null && multflag != '') {
                    514:             url += '&multiple='+multflag;
                    515:         }
1.377     raeburn   516:         if (crstype == 'Course/Group') {
                    517:             if (formname == 'cu') {
                    518:                 crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value; 
                    519:                 if (crstype == "") {
                    520:                     alert("$crs_or_grp_alert");
                    521:                     return;
                    522:                 }
                    523:             }
                    524:         }
                    525:         if (crstype !=null && crstype != '') {
                    526:             url += '&type='+crstype;
                    527:         }
1.102     www       528:         var title = 'Course_Browser';
1.91      www       529:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    530:         options += ',width=700,height=600';
                    531:         stdeditbrowser = open(url,title,options,'1');
                    532:         stdeditbrowser.focus();
                    533:     }
1.468     raeburn   534: 
                    535:     function getFormIdByName(formname) {
                    536:         for (var i=0;i<document.forms.length;i++) {
                    537:             if (document.forms[i].name == formname) {
                    538:                 return i;
                    539:             }
                    540:         }
                    541:         return -1; 
                    542:     }
                    543: 
                    544:     function getIndexByName(formid,item) {
                    545:         for (var i=0;i<document.forms[formid].elements.length;i++) {
                    546:             if (document.forms[formid].elements[i].name == item) {
                    547:                 return i;
                    548:             }
                    549:         }
                    550:         return -1;
                    551:     }
1.91      www       552: ENDSTDBRW
1.468     raeburn   553:     if ($sec_element ne '') {
                    554:         $output .= &setsec_javascript($sec_element,$formname);
                    555:     }
                    556:     $output .= '
                    557: </script>';
                    558:     return $output;
                    559: }
                    560: 
                    561: sub setsec_javascript {
                    562:     my ($sec_element,$formname) = @_;
                    563:     my $setsections = qq|
                    564: function setSect(sectionlist) {
1.629     raeburn   565:     var sectionsArray = new Array();
                    566:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    567:         sectionsArray = sectionlist.split(",");
                    568:     }
1.468     raeburn   569:     var numSections = sectionsArray.length;
                    570:     document.$formname.$sec_element.length = 0;
                    571:     if (numSections == 0) {
                    572:         document.$formname.$sec_element.multiple=false;
                    573:         document.$formname.$sec_element.size=1;
                    574:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    575:     } else {
                    576:         if (numSections == 1) {
                    577:             document.$formname.$sec_element.multiple=false;
                    578:             document.$formname.$sec_element.size=1;
                    579:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    580:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    581:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    582:         } else {
                    583:             for (var i=0; i<numSections; i++) {
                    584:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    585:             }
                    586:             document.$formname.$sec_element.multiple=true
                    587:             if (numSections < 3) {
                    588:                 document.$formname.$sec_element.size=numSections;
                    589:             } else {
                    590:                 document.$formname.$sec_element.size=3;
                    591:             }
                    592:             document.$formname.$sec_element.options[0].selected = false
                    593:         }
                    594:     }
1.91      www       595: }
1.468     raeburn   596: |;
                    597:     return $setsections;
                    598: }
                    599: 
1.91      www       600: 
                    601: sub selectcourse_link {
1.377     raeburn   602:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
1.492     albertel  603:    return "<a href='".'javascript:opencrsbrowser("'.$form.'","'.$unameele.
                    604:         '","'.$udomele.'","'.$desc.'","'.$extra_element.'","'.$multflag.'","'.$selecttype.'");'."'>".&mt('Select Course')."</a>";
1.74      www       605: }
1.42      matthew   606: 
1.653     raeburn   607: sub selectauthor_link {
                    608:    my ($form,$udom)=@_;
                    609:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    610:           &mt('Select Author').'</a>';
                    611: }
                    612: 
1.273     raeburn   613: sub check_uncheck_jscript {
                    614:     my $jscript = <<"ENDSCRT";
                    615: function checkAll(field) {
                    616:     if (field.length > 0) {
                    617:         for (i = 0; i < field.length; i++) {
                    618:             field[i].checked = true ;
                    619:         }
                    620:     } else {
                    621:         field.checked = true
                    622:     }
                    623: }
                    624:  
                    625: function uncheckAll(field) {
                    626:     if (field.length > 0) {
                    627:         for (i = 0; i < field.length; i++) {
                    628:             field[i].checked = false ;
1.543     albertel  629:         }
                    630:     } else {
1.273     raeburn   631:         field.checked = false ;
                    632:     }
                    633: }
                    634: ENDSCRT
                    635:     return $jscript;
                    636: }
                    637: 
1.656     www       638: sub select_timezone {
1.659     raeburn   639:    my ($name,$selected,$onchange,$includeempty)=@_;
                    640:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    641:    if ($includeempty) {
                    642:        $output .= '<option value=""';
                    643:        if (($selected eq '') || ($selected eq 'local')) {
                    644:            $output .= ' selected="selected" ';
                    645:        }
                    646:        $output .= '> </option>';
                    647:    }
1.657     raeburn   648:    my @timezones = DateTime::TimeZone->all_names;
                    649:    foreach my $tzone (@timezones) {
                    650:        $output.= '<option value="'.$tzone.'"';
                    651:        if ($tzone eq $selected) {
                    652:            $output.=' selected="selected"';
                    653:        }
                    654:        $output.=">$tzone</option>\n";
1.656     www       655:    }
                    656:    $output.="</select>";
                    657:    return $output;
                    658: }
1.273     raeburn   659: 
1.42      matthew   660: =pod
1.36      matthew   661: 
1.648     raeburn   662: =item * &linked_select_forms(...)
1.36      matthew   663: 
                    664: linked_select_forms returns a string containing a <script></script> block
                    665: and html for two <select> menus.  The select menus will be linked in that
                    666: changing the value of the first menu will result in new values being placed
                    667: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn   668: order unless a defined order is provided.
1.36      matthew   669: 
                    670: linked_select_forms takes the following ordered inputs:
                    671: 
                    672: =over 4
                    673: 
1.112     bowersj2  674: =item * $formname, the name of the <form> tag
1.36      matthew   675: 
1.112     bowersj2  676: =item * $middletext, the text which appears between the <select> tags
1.36      matthew   677: 
1.112     bowersj2  678: =item * $firstdefault, the default value for the first menu
1.36      matthew   679: 
1.112     bowersj2  680: =item * $firstselectname, the name of the first <select> tag
1.36      matthew   681: 
1.112     bowersj2  682: =item * $secondselectname, the name of the second <select> tag
1.36      matthew   683: 
1.112     bowersj2  684: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew   685: 
1.609     raeburn   686: =item * $menuorder, the order of values in the first menu
                    687: 
1.41      ng        688: =back 
                    689: 
1.36      matthew   690: Below is an example of such a hash.  Only the 'text', 'default', and 
                    691: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                    692: values for the first select menu.  The text that coincides with the 
1.41      ng        693: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew   694: and text for the second menu are given in the hash pointed to by 
                    695: $menu{$choice1}->{'select2'}.  
                    696: 
1.112     bowersj2  697:  my %menu = ( A1 => { text =>"Choice A1" ,
                    698:                        default => "B3",
                    699:                        select2 => { 
                    700:                            B1 => "Choice B1",
                    701:                            B2 => "Choice B2",
                    702:                            B3 => "Choice B3",
                    703:                            B4 => "Choice B4"
1.609     raeburn   704:                            },
                    705:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2  706:                    },
                    707:                A2 => { text =>"Choice A2" ,
                    708:                        default => "C2",
                    709:                        select2 => { 
                    710:                            C1 => "Choice C1",
                    711:                            C2 => "Choice C2",
                    712:                            C3 => "Choice C3"
1.609     raeburn   713:                            },
                    714:                        order => ['C2','C1','C3'],
1.112     bowersj2  715:                    },
                    716:                A3 => { text =>"Choice A3" ,
                    717:                        default => "D6",
                    718:                        select2 => { 
                    719:                            D1 => "Choice D1",
                    720:                            D2 => "Choice D2",
                    721:                            D3 => "Choice D3",
                    722:                            D4 => "Choice D4",
                    723:                            D5 => "Choice D5",
                    724:                            D6 => "Choice D6",
                    725:                            D7 => "Choice D7"
1.609     raeburn   726:                            },
                    727:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2  728:                    }
                    729:                );
1.36      matthew   730: 
                    731: =cut
                    732: 
                    733: sub linked_select_forms {
                    734:     my ($formname,
                    735:         $middletext,
                    736:         $firstdefault,
                    737:         $firstselectname,
                    738:         $secondselectname, 
1.609     raeburn   739:         $hashref,
                    740:         $menuorder,
1.36      matthew   741:         ) = @_;
                    742:     my $second = "document.$formname.$secondselectname";
                    743:     my $first = "document.$formname.$firstselectname";
                    744:     # output the javascript to do the changing
                    745:     my $result = '';
1.219     albertel  746:     $result.="<script type=\"text/javascript\">\n";
1.36      matthew   747:     $result.="var select2data = new Object();\n";
                    748:     $" = '","';
                    749:     my $debug = '';
                    750:     foreach my $s1 (sort(keys(%$hashref))) {
                    751:         $result.="select2data.d_$s1 = new Object();\n";        
                    752:         $result.="select2data.d_$s1.def = new String('".
                    753:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn   754:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew   755:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn   756:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                    757:             @s2values = @{$hashref->{$s1}->{'order'}};
                    758:         }
1.36      matthew   759:         $result.="\"@s2values\");\n";
                    760:         $result.="select2data.d_$s1.texts = new Array(";        
                    761:         my @s2texts;
                    762:         foreach my $value (@s2values) {
                    763:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
                    764:         }
                    765:         $result.="\"@s2texts\");\n";
                    766:     }
                    767:     $"=' ';
                    768:     $result.= <<"END";
                    769: 
                    770: function select1_changed() {
                    771:     // Determine new choice
                    772:     var newvalue = "d_" + $first.value;
                    773:     // update select2
                    774:     var values     = select2data[newvalue].values;
                    775:     var texts      = select2data[newvalue].texts;
                    776:     var select2def = select2data[newvalue].def;
                    777:     var i;
                    778:     // out with the old
                    779:     for (i = 0; i < $second.options.length; i++) {
                    780:         $second.options[i] = null;
                    781:     }
                    782:     // in with the nuclear
                    783:     for (i=0;i<values.length; i++) {
                    784:         $second.options[i] = new Option(values[i]);
1.143     matthew   785:         $second.options[i].value = values[i];
1.36      matthew   786:         $second.options[i].text = texts[i];
                    787:         if (values[i] == select2def) {
                    788:             $second.options[i].selected = true;
                    789:         }
                    790:     }
                    791: }
                    792: </script>
                    793: END
                    794:     # output the initial values for the selection lists
                    795:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
1.609     raeburn   796:     my @order = sort(keys(%{$hashref}));
                    797:     if (ref($menuorder) eq 'ARRAY') {
                    798:         @order = @{$menuorder};
                    799:     }
                    800:     foreach my $value (@order) {
1.36      matthew   801:         $result.="    <option value=\"$value\" ";
1.253     albertel  802:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www       803:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew   804:     }
                    805:     $result .= "</select>\n";
                    806:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                    807:     $result .= $middletext;
                    808:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
                    809:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn   810:     
                    811:     my @secondorder = sort(keys(%select2));
                    812:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                    813:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                    814:     }
                    815:     foreach my $value (@secondorder) {
1.36      matthew   816:         $result.="    <option value=\"$value\" ";        
1.253     albertel  817:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www       818:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew   819:     }
                    820:     $result .= "</select>\n";
                    821:     #    return $debug;
                    822:     return $result;
                    823: }   #  end of sub linked_select_forms {
                    824: 
1.45      matthew   825: =pod
1.44      bowersj2  826: 
1.648     raeburn   827: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height)
1.44      bowersj2  828: 
1.112     bowersj2  829: Returns a string corresponding to an HTML link to the given help
                    830: $topic, where $topic corresponds to the name of a .tex file in
                    831: /home/httpd/html/adm/help/tex, with underscores replaced by
                    832: spaces. 
                    833: 
                    834: $text will optionally be linked to the same topic, allowing you to
                    835: link text in addition to the graphic. If you do not want to link
                    836: text, but wish to specify one of the later parameters, pass an
                    837: empty string. 
                    838: 
                    839: $stayOnPage is a value that will be interpreted as a boolean. If true,
                    840: the link will not open a new window. If false, the link will open
                    841: a new window using Javascript. (Default is false.) 
                    842: 
                    843: $width and $height are optional numerical parameters that will
                    844: override the width and height of the popped up window, which may
                    845: be useful for certain help topics with big pictures included. 
1.44      bowersj2  846: 
                    847: =cut
                    848: 
                    849: sub help_open_topic {
1.48      bowersj2  850:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
                    851:     $text = "" if (not defined $text);
1.44      bowersj2  852:     $stayOnPage = 0 if (not defined $stayOnPage);
1.552     banghart  853:     if ($env{'browser.interface'} eq 'textual') {
1.79      www       854: 	$stayOnPage=1;
                    855:     }
1.44      bowersj2  856:     $width = 350 if (not defined $width);
                    857:     $height = 400 if (not defined $height);
                    858:     my $filename = $topic;
                    859:     $filename =~ s/ /_/g;
                    860: 
1.48      bowersj2  861:     my $template = "";
                    862:     my $link;
1.572     banghart  863:     
1.159     www       864:     $topic=~s/\W/\_/g;
1.44      bowersj2  865: 
1.572     banghart  866:     if (!$stayOnPage) {
1.72      bowersj2  867: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1.572     banghart  868:     } else {
1.48      bowersj2  869: 	$link = "/adm/help/${filename}.hlp";
                    870:     }
                    871: 
                    872:     # Add the text
1.572     banghart  873:     if ($text ne "") {
1.77      www       874: 	$template .= 
1.572     banghart  875:             "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
                    876:             "<td bgcolor='#5555FF'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
1.48      bowersj2  877:     }
                    878: 
                    879:     # Add the graphic
1.179     matthew   880:     my $title = &mt('Online Help');
1.667     raeburn   881:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.48      bowersj2  882:     $template .= <<"ENDTEMPLATE";
1.436     albertel  883:  <a target="_top" href="$link" title="$title"><img src="$helpicon" border="0" alt="(Help: $topic)" /></a>
1.44      bowersj2  884: ENDTEMPLATE
1.78      www       885:     if ($text ne '') { $template.='</td></tr></table>' };
1.44      bowersj2  886:     return $template;
                    887: 
1.106     bowersj2  888: }
                    889: 
                    890: # This is a quicky function for Latex cheatsheet editing, since it 
                    891: # appears in at least four places
                    892: sub helpLatexCheatsheet {
                    893:     my $other = shift;
                    894:     my $addOther = '';
                    895:     if ($other) {
                    896: 	$addOther = Apache::loncommon::help_open_topic($other, shift,
                    897: 						       undef, undef, 600) .
                    898: 							   '</td><td>';
                    899:     }
                    900:     return '<table><tr><td>'.
                    901: 	$addOther .
1.636     raeburn   902: 	&Apache::loncommon::help_open_topic("Greek_Symbols",&mt('Greek Symbols'),
1.106     bowersj2  903: 					    undef,undef,600)
                    904: 	.'</td><td>'.
1.636     raeburn   905: 	&Apache::loncommon::help_open_topic("Other_Symbols",&mt('Other Symbols'),
1.106     bowersj2  906: 					    undef,undef,600)
1.673     felicia   907: 	.'</td><td>'.
                    908: 	&Apache::loncommon::help_open_topic("Authoring_Output_Tags",&mt('Output Tags'),
                    909: 	                                    undef,undef,600)
1.106     bowersj2  910: 	.'</td></tr></table>';
1.172     www       911: }
                    912: 
1.430     albertel  913: sub general_help {
                    914:     my $helptopic='Student_Intro';
                    915:     if ($env{'request.role'}=~/^(ca|au)/) {
                    916: 	$helptopic='Authoring_Intro';
                    917:     } elsif ($env{'request.role'}=~/^cc/) {
                    918: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn   919:     } elsif ($env{'request.role'}=~/^dc/) {
                    920:         $helptopic='Domain_Coordination_Intro';
1.430     albertel  921:     }
                    922:     return $helptopic;
                    923: }
                    924: 
                    925: sub update_help_link {
                    926:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                    927:     my $origurl = $ENV{'REQUEST_URI'};
                    928:     $origurl=~s|^/~|/priv/|;
                    929:     my $timestamp = time;
                    930:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                    931:         $$datum = &escape($$datum);
                    932:     }
                    933: 
                    934:     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";
                    935:     my $output .= <<"ENDOUTPUT";
                    936: <script type="text/javascript">
                    937: banner_link = '$banner_link';
                    938: </script>
                    939: ENDOUTPUT
                    940:     return $output;
                    941: }
                    942: 
                    943: # now just updates the help link and generates a blue icon
1.193     raeburn   944: sub help_open_menu {
1.430     albertel  945:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart  946: 	= @_;    
1.430     albertel  947:     $stayOnPage = 0 if (not defined $stayOnPage);
1.572     banghart  948:     # only use pop-up help (stayOnPage == 0)
1.552     banghart  949:     # if environment.remote is on (using remote control UI)
1.572     banghart  950:     if ($env{'browser.interface'} eq 'textual' ||
                    951:     	$env{'environment.remote'} eq 'off' ) {
1.552     banghart  952:         $stayOnPage=1;
1.430     albertel  953:     }
                    954:     my $output;
                    955:     if ($component_help) {
                    956: 	if (!$text) {
                    957: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                    958: 				       $width,$height);
                    959: 	} else {
                    960: 	    my $help_text;
                    961: 	    $help_text=&unescape($topic);
                    962: 	    $output='<table><tr><td>'.
                    963: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                    964: 				 $width,$height).'</td></tr></table>';
                    965: 	}
                    966:     }
                    967:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                    968:     return $output.$banner_link;
                    969: }
                    970: 
                    971: sub top_nav_help {
                    972:     my ($text) = @_;
1.436     albertel  973:     $text = &mt($text);
1.572     banghart  974:     my $stay_on_page = 
1.436     albertel  975: 	($env{'browser.interface'}  eq 'textual' ||
                    976: 	 $env{'environment.remote'} eq 'off' );
1.572     banghart  977:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1.436     albertel  978: 	                     : "javascript:helpMenu('open')";
1.572     banghart  979:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1.436     albertel  980: 
1.201     raeburn   981:     my $title = &mt('Get help');
1.436     albertel  982: 
                    983:     return <<"END";
                    984: $banner_link
                    985:  <a href="$link" title="$title">$text</a>
                    986: END
                    987: }
                    988: 
                    989: sub help_menu_js {
                    990:     my ($text) = @_;
                    991: 
                    992:     my $stayOnPage = 
                    993: 	($env{'browser.interface'}  eq 'textual' ||
                    994: 	 $env{'environment.remote'} eq 'off' );
                    995: 
                    996:     my $width = 620;
                    997:     my $height = 600;
1.430     albertel  998:     my $helptopic=&general_help();
                    999:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1000:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1001:     my $start_page =
                   1002:         &Apache::loncommon::start_page('Help Menu', undef,
                   1003: 				       {'frameset'    => 1,
                   1004: 					'js_ready'    => 1,
                   1005: 					'add_entries' => {
                   1006: 					    'border' => '0',
1.579     raeburn  1007: 					    'rows'   => "110,*",},});
1.331     albertel 1008:     my $end_page =
                   1009:         &Apache::loncommon::end_page({'frameset' => 1,
                   1010: 				      'js_ready' => 1,});
                   1011: 
1.436     albertel 1012:     my $template .= <<"ENDTEMPLATE";
                   1013: <script type="text/javascript">
1.253     albertel 1014: // <!-- BEGIN LON-CAPA Internal
                   1015: // <![CDATA[
1.430     albertel 1016: var banner_link = '';
1.243     raeburn  1017: function helpMenu(target) {
                   1018:     var caller = this;
                   1019:     if (target == 'open') {
                   1020:         var newWindow = null;
                   1021:         try {
1.262     albertel 1022:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1023:         }
                   1024:         catch(error) {
                   1025:             writeHelp(caller);
                   1026:             return;
                   1027:         }
                   1028:         if (newWindow) {
                   1029:             caller = newWindow;
                   1030:         }
1.193     raeburn  1031:     }
1.243     raeburn  1032:     writeHelp(caller);
                   1033:     return;
                   1034: }
                   1035: function writeHelp(caller) {
1.430     albertel 1036:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
1.243     raeburn  1037:     caller.document.close()
                   1038:     caller.focus()
1.193     raeburn  1039: }
1.253     albertel 1040: // ]]>
1.219     albertel 1041: // END LON-CAPA Internal -->
1.436     albertel 1042: </script>
1.193     raeburn  1043: ENDTEMPLATE
                   1044:     return $template;
                   1045: }
                   1046: 
1.172     www      1047: sub help_open_bug {
                   1048:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1049:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1050:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1051:     $text = "" if (not defined $text);
                   1052:     $stayOnPage = 0 if (not defined $stayOnPage);
1.258     albertel 1053:     if ($env{'browser.interface'} eq 'textual' ||
                   1054: 	$env{'environment.remote'} eq 'off' ) {
1.172     www      1055: 	$stayOnPage=1;
                   1056:     }
1.184     albertel 1057:     $width = 600 if (not defined $width);
                   1058:     $height = 600 if (not defined $height);
1.172     www      1059: 
                   1060:     $topic=~s/\W+/\+/g;
                   1061:     my $link='';
                   1062:     my $template='';
1.379     albertel 1063:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1064: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1065:     if (!$stayOnPage)
                   1066:     {
                   1067: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1068:     }
                   1069:     else
                   1070:     {
                   1071: 	$link = $url;
                   1072:     }
                   1073:     # Add the text
                   1074:     if ($text ne "")
                   1075:     {
                   1076: 	$template .= 
                   1077:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.436     albertel 1078:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
1.172     www      1079:     }
                   1080: 
                   1081:     # Add the graphic
1.179     matthew  1082:     my $title = &mt('Report a Bug');
1.215     albertel 1083:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1084:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1085:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1086: ENDTEMPLATE
                   1087:     if ($text ne '') { $template.='</td></tr></table>' };
                   1088:     return $template;
                   1089: 
                   1090: }
                   1091: 
                   1092: sub help_open_faq {
                   1093:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1094:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1095:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1096:     $text = "" if (not defined $text);
                   1097:     $stayOnPage = 0 if (not defined $stayOnPage);
1.258     albertel 1098:     if ($env{'browser.interface'} eq 'textual' ||
                   1099: 	$env{'environment.remote'} eq 'off' ) {
1.172     www      1100: 	$stayOnPage=1;
                   1101:     }
                   1102:     $width = 350 if (not defined $width);
                   1103:     $height = 400 if (not defined $height);
                   1104: 
                   1105:     $topic=~s/\W+/\+/g;
                   1106:     my $link='';
                   1107:     my $template='';
                   1108:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1109:     if (!$stayOnPage)
                   1110:     {
                   1111: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1112:     }
                   1113:     else
                   1114:     {
                   1115: 	$link = $url;
                   1116:     }
                   1117: 
                   1118:     # Add the text
                   1119:     if ($text ne "")
                   1120:     {
                   1121: 	$template .= 
1.173     www      1122:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.436     albertel 1123:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
1.172     www      1124:     }
                   1125: 
                   1126:     # Add the graphic
1.179     matthew  1127:     my $title = &mt('View the FAQ');
1.215     albertel 1128:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1129:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1130:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1131: ENDTEMPLATE
                   1132:     if ($text ne '') { $template.='</td></tr></table>' };
                   1133:     return $template;
                   1134: 
1.44      bowersj2 1135: }
1.37      matthew  1136: 
1.180     matthew  1137: ###############################################################
                   1138: ###############################################################
                   1139: 
1.45      matthew  1140: =pod
                   1141: 
1.648     raeburn  1142: =item * &change_content_javascript():
1.256     matthew  1143: 
                   1144: This and the next function allow you to create small sections of an
                   1145: otherwise static HTML page that you can update on the fly with
                   1146: Javascript, even in Netscape 4.
                   1147: 
                   1148: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1149: must be written to the HTML page once. It will prove the Javascript
                   1150: function "change(name, content)". Calling the change function with the
                   1151: name of the section 
                   1152: you want to update, matching the name passed to C<changable_area>, and
                   1153: the new content you want to put in there, will put the content into
                   1154: that area.
                   1155: 
                   1156: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1157: to contain room for the original contents. You need to "make space"
                   1158: for whatever changes you wish to make, and be B<sure> to check your
                   1159: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1160: it's adequate for updating a one-line status display, but little more.
                   1161: This script will set the space to 100% width, so you only need to
                   1162: worry about height in Netscape 4.
                   1163: 
                   1164: Modern browsers are much less limiting, and if you can commit to the
                   1165: user not using Netscape 4, this feature may be used freely with
                   1166: pretty much any HTML.
                   1167: 
                   1168: =cut
                   1169: 
                   1170: sub change_content_javascript {
                   1171:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1172:     if ($env{'browser.type'} eq 'netscape' &&
                   1173: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1174: 	return (<<NETSCAPE4);
                   1175: 	function change(name, content) {
                   1176: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1177: 	    doc.open();
                   1178: 	    doc.write(content);
                   1179: 	    doc.close();
                   1180: 	}
                   1181: NETSCAPE4
                   1182:     } else {
                   1183: 	# Otherwise, we need to use semi-standards-compliant code
                   1184: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1185: 	# is really scary, and every useful browser supports it
                   1186: 	return (<<DOMBASED);
                   1187: 	function change(name, content) {
                   1188: 	    element = document.getElementById(name);
                   1189: 	    element.innerHTML = content;
                   1190: 	}
                   1191: DOMBASED
                   1192:     }
                   1193: }
                   1194: 
                   1195: =pod
                   1196: 
1.648     raeburn  1197: =item * &changable_area($name,$origContent):
1.256     matthew  1198: 
                   1199: This provides a "changable area" that can be modified on the fly via
                   1200: the Javascript code provided in C<change_content_javascript>. $name is
                   1201: the name you will use to reference the area later; do not repeat the
                   1202: same name on a given HTML page more then once. $origContent is what
                   1203: the area will originally contain, which can be left blank.
                   1204: 
                   1205: =cut
                   1206: 
                   1207: sub changable_area {
                   1208:     my ($name, $origContent) = @_;
                   1209: 
1.258     albertel 1210:     if ($env{'browser.type'} eq 'netscape' &&
                   1211: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1212: 	# If this is netscape 4, we need to use the Layer tag
                   1213: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1214:     } else {
                   1215: 	return "<span id='$name'>$origContent</span>";
                   1216:     }
                   1217: }
                   1218: 
                   1219: =pod
                   1220: 
1.648     raeburn  1221: =item * &viewport_geometry_js 
1.590     raeburn  1222: 
                   1223: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1224: 
                   1225: =cut
                   1226: 
                   1227: 
                   1228: sub viewport_geometry_js { 
                   1229:     return <<"GEOMETRY";
                   1230: var Geometry = {};
                   1231: function init_geometry() {
                   1232:     if (Geometry.init) { return };
                   1233:     Geometry.init=1;
                   1234:     if (window.innerHeight) {
                   1235:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1236:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1237:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1238:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1239:     }
                   1240:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1241:         Geometry.getViewportHeight =
                   1242:             function() { return document.documentElement.clientHeight; };
                   1243:         Geometry.getViewportWidth =
                   1244:             function() { return document.documentElement.clientWidth; };
                   1245: 
                   1246:         Geometry.getHorizontalScroll =
                   1247:             function() { return document.documentElement.scrollLeft; };
                   1248:         Geometry.getVerticalScroll =
                   1249:             function() { return document.documentElement.scrollTop; };
                   1250:     }
                   1251:     else if (document.body.clientHeight) {
                   1252:         Geometry.getViewportHeight =
                   1253:             function() { return document.body.clientHeight; };
                   1254:         Geometry.getViewportWidth =
                   1255:             function() { return document.body.clientWidth; };
                   1256:         Geometry.getHorizontalScroll =
                   1257:             function() { return document.body.scrollLeft; };
                   1258:         Geometry.getVerticalScroll =
                   1259:             function() { return document.body.scrollTop; };
                   1260:     }
                   1261: }
                   1262: 
                   1263: GEOMETRY
                   1264: }
                   1265: 
                   1266: =pod
                   1267: 
1.648     raeburn  1268: =item * &viewport_size_js()
1.590     raeburn  1269: 
                   1270: Provides a javascript function to set values of two form elements - width and height (elements are passed in as arguments to the javascript function) to the dimensions of the user's browser window. 
                   1271: 
                   1272: =cut
                   1273: 
                   1274: sub viewport_size_js {
                   1275:     my $geometry = &viewport_geometry_js();
                   1276:     return <<"DIMS";
                   1277: 
                   1278: $geometry
                   1279: 
                   1280: function getViewportDims(width,height) {
                   1281:     init_geometry();
                   1282:     width.value = Geometry.getViewportWidth();
                   1283:     height.value = Geometry.getViewportHeight();
                   1284:     return;
                   1285: }
                   1286: 
                   1287: DIMS
                   1288: }
                   1289: 
                   1290: =pod
                   1291: 
1.648     raeburn  1292: =item * &resize_textarea_js()
1.565     albertel 1293: 
                   1294: emits the needed javascript to resize a textarea to be as big as possible
                   1295: 
                   1296: creates a function resize_textrea that takes two IDs first should be
                   1297: the id of the element to resize, second should be the id of a div that
                   1298: surrounds everything that comes after the textarea, this routine needs
                   1299: to be attached to the <body> for the onload and onresize events.
                   1300: 
1.648     raeburn  1301: =back
1.565     albertel 1302: 
                   1303: =cut
                   1304: 
                   1305: sub resize_textarea_js {
1.590     raeburn  1306:     my $geometry = &viewport_geometry_js();
1.565     albertel 1307:     return <<"RESIZE";
                   1308:     <script type="text/javascript">
1.590     raeburn  1309: $geometry
1.565     albertel 1310: 
1.588     albertel 1311: function getX(element) {
                   1312:     var x = 0;
                   1313:     while (element) {
                   1314: 	x += element.offsetLeft;
                   1315: 	element = element.offsetParent;
                   1316:     }
                   1317:     return x;
                   1318: }
                   1319: function getY(element) {
                   1320:     var y = 0;
                   1321:     while (element) {
                   1322: 	y += element.offsetTop;
                   1323: 	element = element.offsetParent;
                   1324:     }
                   1325:     return y;
                   1326: }
                   1327: 
                   1328: 
1.565     albertel 1329: function resize_textarea(textarea_id,bottom_id) {
                   1330:     init_geometry();
                   1331:     var textarea        = document.getElementById(textarea_id);
                   1332:     //alert(textarea);
                   1333: 
1.588     albertel 1334:     var textarea_top    = getY(textarea);
1.565     albertel 1335:     var textarea_height = textarea.offsetHeight;
                   1336:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1337:     var bottom_top      = getY(bottom);
1.565     albertel 1338:     var bottom_height   = bottom.offsetHeight;
                   1339:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1340:     var fudge           = 23;
1.565     albertel 1341:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1342:     if (new_height < 300) {
                   1343: 	new_height = 300;
                   1344:     }
                   1345:     textarea.style.height=new_height+'px';
                   1346: }
                   1347: </script>
                   1348: RESIZE
                   1349: 
                   1350: }
                   1351: 
                   1352: =pod
                   1353: 
1.256     matthew  1354: =head1 Excel and CSV file utility routines
                   1355: 
                   1356: =over 4
                   1357: 
                   1358: =cut
                   1359: 
                   1360: ###############################################################
                   1361: ###############################################################
                   1362: 
                   1363: =pod
                   1364: 
1.648     raeburn  1365: =item * &csv_translate($text) 
1.37      matthew  1366: 
1.185     www      1367: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  1368: format.
                   1369: 
                   1370: =cut
                   1371: 
1.180     matthew  1372: ###############################################################
                   1373: ###############################################################
1.37      matthew  1374: sub csv_translate {
                   1375:     my $text = shift;
                   1376:     $text =~ s/\"/\"\"/g;
1.209     albertel 1377:     $text =~ s/\n/ /g;
1.37      matthew  1378:     return $text;
                   1379: }
1.180     matthew  1380: 
                   1381: ###############################################################
                   1382: ###############################################################
                   1383: 
                   1384: =pod
                   1385: 
1.648     raeburn  1386: =item * &define_excel_formats()
1.180     matthew  1387: 
                   1388: Define some commonly used Excel cell formats.
                   1389: 
                   1390: Currently supported formats:
                   1391: 
                   1392: =over 4
                   1393: 
                   1394: =item header
                   1395: 
                   1396: =item bold
                   1397: 
                   1398: =item h1
                   1399: 
                   1400: =item h2
                   1401: 
                   1402: =item h3
                   1403: 
1.256     matthew  1404: =item h4
                   1405: 
                   1406: =item i
                   1407: 
1.180     matthew  1408: =item date
                   1409: 
                   1410: =back
                   1411: 
                   1412: Inputs: $workbook
                   1413: 
                   1414: Returns: $format, a hash reference.
                   1415: 
                   1416: =cut
                   1417: 
                   1418: ###############################################################
                   1419: ###############################################################
                   1420: sub define_excel_formats {
                   1421:     my ($workbook) = @_;
                   1422:     my $format;
                   1423:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   1424:                                                 bottom    => 1,
                   1425:                                                 align     => 'center');
                   1426:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   1427:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   1428:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   1429:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  1430:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  1431:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  1432:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  1433:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  1434:     return $format;
                   1435: }
                   1436: 
                   1437: ###############################################################
                   1438: ###############################################################
1.113     bowersj2 1439: 
                   1440: =pod
                   1441: 
1.648     raeburn  1442: =item * &create_workbook()
1.255     matthew  1443: 
                   1444: Create an Excel worksheet.  If it fails, output message on the
                   1445: request object and return undefs.
                   1446: 
                   1447: Inputs: Apache request object
                   1448: 
                   1449: Returns (undef) on failure, 
                   1450:     Excel worksheet object, scalar with filename, and formats 
                   1451:     from &Apache::loncommon::define_excel_formats on success
                   1452: 
                   1453: =cut
                   1454: 
                   1455: ###############################################################
                   1456: ###############################################################
                   1457: sub create_workbook {
                   1458:     my ($r) = @_;
                   1459:         #
                   1460:     # Create the excel spreadsheet
                   1461:     my $filename = '/prtspool/'.
1.258     albertel 1462:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  1463:         time.'_'.rand(1000000000).'.xls';
                   1464:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   1465:     if (! defined($workbook)) {
                   1466:         $r->log_error("Error creating excel spreadsheet $filename: $!");
                   1467:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
                   1468:                             "This error has been logged.  ".
                   1469:                             "Please alert your LON-CAPA administrator").
                   1470:                   '</p>');
                   1471:         return (undef);
                   1472:     }
                   1473:     #
                   1474:     $workbook->set_tempdir('/home/httpd/perl/tmp');
                   1475:     #
                   1476:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   1477:     return ($workbook,$filename,$format);
                   1478: }
                   1479: 
                   1480: ###############################################################
                   1481: ###############################################################
                   1482: 
                   1483: =pod
                   1484: 
1.648     raeburn  1485: =item * &create_text_file()
1.113     bowersj2 1486: 
1.542     raeburn  1487: Create a file to write to and eventually make available to the user.
1.256     matthew  1488: If file creation fails, outputs an error message on the request object and 
                   1489: return undefs.
1.113     bowersj2 1490: 
1.256     matthew  1491: Inputs: Apache request object, and file suffix
1.113     bowersj2 1492: 
1.256     matthew  1493: Returns (undef) on failure, 
                   1494:     Filehandle and filename on success.
1.113     bowersj2 1495: 
                   1496: =cut
                   1497: 
1.256     matthew  1498: ###############################################################
                   1499: ###############################################################
                   1500: sub create_text_file {
                   1501:     my ($r,$suffix) = @_;
                   1502:     if (! defined($suffix)) { $suffix = 'txt'; };
                   1503:     my $fh;
                   1504:     my $filename = '/prtspool/'.
1.258     albertel 1505:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  1506:         time.'_'.rand(1000000000).'.'.$suffix;
                   1507:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   1508:     if (! defined($fh)) {
                   1509:         $r->log_error("Couldn't open $filename for output $!");
1.679.2.2  raeburn  1510:         $r->print(&mt('Problems occurred in creating the output file. '
                   1511:                      .'This error has been logged. '
                   1512:                      .'Please alert your LON-CAPA administrator.'));
1.113     bowersj2 1513:     }
1.256     matthew  1514:     return ($fh,$filename)
1.113     bowersj2 1515: }
                   1516: 
                   1517: 
1.256     matthew  1518: =pod 
1.113     bowersj2 1519: 
                   1520: =back
                   1521: 
                   1522: =cut
1.37      matthew  1523: 
                   1524: ###############################################################
1.33      matthew  1525: ##        Home server <option> list generating code          ##
                   1526: ###############################################################
1.35      matthew  1527: 
1.169     www      1528: # ------------------------------------------
                   1529: 
                   1530: sub domain_select {
                   1531:     my ($name,$value,$multiple)=@_;
                   1532:     my %domains=map { 
1.514     albertel 1533: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 1534:     } &Apache::lonnet::all_domains();
1.169     www      1535:     if ($multiple) {
                   1536: 	$domains{''}=&mt('Any domain');
1.550     albertel 1537: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 1538: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      1539:     } else {
1.550     albertel 1540: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.169     www      1541: 	return &select_form($name,$value,%domains);
                   1542:     }
                   1543: }
                   1544: 
1.282     albertel 1545: #-------------------------------------------
                   1546: 
                   1547: =pod
                   1548: 
1.519     raeburn  1549: =head1 Routines for form select boxes
                   1550: 
                   1551: =over 4
                   1552: 
1.648     raeburn  1553: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 1554: 
                   1555: Returns a string containing a <select> element int multiple mode
                   1556: 
                   1557: 
                   1558: Args:
                   1559:   $name - name of the <select> element
1.506     raeburn  1560:   $value - scalar or array ref of values that should already be selected
1.282     albertel 1561:   $size - number of rows long the select element is
1.283     albertel 1562:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 1563:           (shown text should already have been &mt())
1.506     raeburn  1564:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 1565: 
1.282     albertel 1566: =cut
                   1567: 
                   1568: #-------------------------------------------
1.169     www      1569: sub multiple_select_form {
1.284     albertel 1570:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      1571:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   1572:     my $output='';
1.191     matthew  1573:     if (! defined($size)) {
                   1574:         $size = 4;
1.283     albertel 1575:         if (scalar(keys(%$hash))<4) {
                   1576:             $size = scalar(keys(%$hash));
1.191     matthew  1577:         }
                   1578:     }
1.169     www      1579:     $output.="\n<select name='$name' size='$size' multiple='1'>";
1.501     banghart 1580:     my @order;
1.506     raeburn  1581:     if (ref($order) eq 'ARRAY')  {
                   1582:         @order = @{$order};
                   1583:     } else {
                   1584:         @order = sort(keys(%$hash));
1.501     banghart 1585:     }
                   1586:     if (exists($$hash{'select_form_order'})) {
                   1587:         @order = @{$$hash{'select_form_order'}};
                   1588:     }
                   1589:         
1.284     albertel 1590:     foreach my $key (@order) {
1.356     albertel 1591:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 1592:         $output.='selected="selected" ' if ($selected{$key});
                   1593:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      1594:     }
                   1595:     $output.="</select>\n";
                   1596:     return $output;
                   1597: }
                   1598: 
1.88      www      1599: #-------------------------------------------
                   1600: 
                   1601: =pod
                   1602: 
1.648     raeburn  1603: =item * &select_form($defdom,$name,%hash)
1.88      www      1604: 
                   1605: Returns a string containing a <select name='$name' size='1'> form to 
                   1606: allow a user to select options from a hash option_name => displayed text.  
                   1607: See lonrights.pm for an example invocation and use.
                   1608: 
                   1609: =cut
                   1610: 
                   1611: #-------------------------------------------
                   1612: sub select_form {
                   1613:     my ($def,$name,%hash) = @_;
                   1614:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
1.128     albertel 1615:     my @keys;
                   1616:     if (exists($hash{'select_form_order'})) {
                   1617: 	@keys=@{$hash{'select_form_order'}};
                   1618:     } else {
                   1619: 	@keys=sort(keys(%hash));
                   1620:     }
1.356     albertel 1621:     foreach my $key (@keys) {
                   1622:         $selectform.=
                   1623: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   1624:             ($key eq $def ? 'selected="selected" ' : '').
                   1625:                 ">".&mt($hash{$key})."</option>\n";
1.88      www      1626:     }
                   1627:     $selectform.="</select>";
                   1628:     return $selectform;
                   1629: }
                   1630: 
1.475     www      1631: # For display filters
                   1632: 
                   1633: sub display_filter {
                   1634:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      1635:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.475     www      1636:     return '<nobr><label>'.&mt('Records [_1]',
                   1637: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   1638: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.478     www      1639: 	   '</label></nobr> <nobr>'.
1.475     www      1640:            &mt('Filter [_1]',
1.477     www      1641: 	   &select_form($env{'form.displayfilter'},
                   1642: 			'displayfilter',
                   1643: 			('currentfolder' => 'Current folder/page',
                   1644: 			 'containing' => 'Containing phrase',
                   1645: 			 'none' => 'None'))).
1.478     www      1646: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></nobr>';
1.475     www      1647: }
                   1648: 
1.167     www      1649: sub gradeleveldescription {
                   1650:     my $gradelevel=shift;
                   1651:     my %gradelevels=(0 => 'Not specified',
                   1652: 		     1 => 'Grade 1',
                   1653: 		     2 => 'Grade 2',
                   1654: 		     3 => 'Grade 3',
                   1655: 		     4 => 'Grade 4',
                   1656: 		     5 => 'Grade 5',
                   1657: 		     6 => 'Grade 6',
                   1658: 		     7 => 'Grade 7',
                   1659: 		     8 => 'Grade 8',
                   1660: 		     9 => 'Grade 9',
                   1661: 		     10 => 'Grade 10',
                   1662: 		     11 => 'Grade 11',
                   1663: 		     12 => 'Grade 12',
                   1664: 		     13 => 'Grade 13',
                   1665: 		     14 => '100 Level',
                   1666: 		     15 => '200 Level',
                   1667: 		     16 => '300 Level',
                   1668: 		     17 => '400 Level',
                   1669: 		     18 => 'Graduate Level');
                   1670:     return &mt($gradelevels{$gradelevel});
                   1671: }
                   1672: 
1.163     www      1673: sub select_level_form {
                   1674:     my ($deflevel,$name)=@_;
                   1675:     unless ($deflevel) { $deflevel=0; }
1.167     www      1676:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   1677:     for (my $i=0; $i<=18; $i++) {
                   1678:         $selectform.="<option value=\"$i\" ".
1.253     albertel 1679:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      1680:                 ">".&gradeleveldescription($i)."</option>\n";
                   1681:     }
                   1682:     $selectform.="</select>";
                   1683:     return $selectform;
1.163     www      1684: }
1.167     www      1685: 
1.35      matthew  1686: #-------------------------------------------
                   1687: 
1.45      matthew  1688: =pod
                   1689: 
1.648     raeburn  1690: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc)
1.35      matthew  1691: 
                   1692: Returns a string containing a <select name='$name' size='1'> form to 
                   1693: allow a user to select the domain to preform an operation in.  
                   1694: See loncreateuser.pm for an example invocation and use.
                   1695: 
1.90      www      1696: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   1697: selected");
                   1698: 
1.563     raeburn  1699: If the $showdomdesc flag is set, the domain name is followed by the domain description. 
                   1700: 
1.35      matthew  1701: =cut
                   1702: 
                   1703: #-------------------------------------------
1.34      matthew  1704: sub select_dom_form {
1.563     raeburn  1705:     my ($defdom,$name,$includeempty,$showdomdesc) = @_;
1.550     albertel 1706:     my @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
1.90      www      1707:     if ($includeempty) { @domains=('',@domains); }
1.34      matthew  1708:     my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
1.356     albertel 1709:     foreach my $dom (@domains) {
                   1710:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  1711:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   1712:         if ($showdomdesc) {
                   1713:             if ($dom ne '') {
                   1714:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   1715:                 if ($domdesc ne '') {
                   1716:                     $selectdomain .= ' ('.$domdesc.')';
                   1717:                 }
                   1718:             } 
                   1719:         }
                   1720:         $selectdomain .= "</option>\n";
1.34      matthew  1721:     }
                   1722:     $selectdomain.="</select>";
                   1723:     return $selectdomain;
                   1724: }
                   1725: 
1.35      matthew  1726: #-------------------------------------------
                   1727: 
1.45      matthew  1728: =pod
                   1729: 
1.648     raeburn  1730: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  1731: 
1.586     raeburn  1732: input: 4 arguments (two required, two optional) - 
                   1733:     $domain - domain of new user
                   1734:     $name - name of form element
                   1735:     $default - Value of 'default' causes a default item to be first 
                   1736:                             option, and selected by default. 
                   1737:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   1738:                             if 1 server found, or default, if 0 found.
1.594     raeburn  1739: output: returns 2 items: 
1.586     raeburn  1740: (a) form element which contains either:
                   1741:    (i) <select name="$name">
                   1742:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   1743:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   1744:        </select>
                   1745:        form item if there are multiple library servers in $domain, or
                   1746:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   1747:        if there is only one library server in $domain.
                   1748: 
                   1749: (b) number of library servers found.
                   1750: 
                   1751: See loncreateuser.pm for example of use.
1.35      matthew  1752: 
                   1753: =cut
                   1754: 
                   1755: #-------------------------------------------
1.586     raeburn  1756: sub home_server_form_item {
                   1757:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 1758:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  1759:     my $result;
                   1760:     my $numlib = keys(%servers);
                   1761:     if ($numlib > 1) {
                   1762:         $result .= '<select name="'.$name.'" />'."\n";
                   1763:         if ($default) {
                   1764:             $result .= '<option value="default" selected>'.&mt('default').
                   1765:                        '</option>'."\n";
                   1766:         }
                   1767:         foreach my $hostid (sort(keys(%servers))) {
                   1768:             $result.= '<option value="'.$hostid.'">'.
                   1769: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   1770:         }
                   1771:         $result .= '</select>'."\n";
                   1772:     } elsif ($numlib == 1) {
                   1773:         my $hostid;
                   1774:         foreach my $item (keys(%servers)) {
                   1775:             $hostid = $item;
                   1776:         }
                   1777:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   1778:                    $hostid.'" />';
                   1779:                    if (!$hide) {
                   1780:                        $result .= $hostid.' '.$servers{$hostid};
                   1781:                    }
                   1782:                    $result .= "\n";
                   1783:     } elsif ($default) {
                   1784:         $result .= '<input type="hidden" name="'.$name.
                   1785:                    '" value="default" />';
                   1786:                    if (!$hide) {
                   1787:                        $result .= &mt('default');
                   1788:                    }
                   1789:                    $result .= "\n";
1.33      matthew  1790:     }
1.586     raeburn  1791:     return ($result,$numlib);
1.33      matthew  1792: }
1.112     bowersj2 1793: 
                   1794: =pod
                   1795: 
1.534     albertel 1796: =back 
                   1797: 
1.112     bowersj2 1798: =cut
1.87      matthew  1799: 
                   1800: ###############################################################
1.112     bowersj2 1801: ##                  Decoding User Agent                      ##
1.87      matthew  1802: ###############################################################
                   1803: 
                   1804: =pod
                   1805: 
1.112     bowersj2 1806: =head1 Decoding the User Agent
                   1807: 
                   1808: =over 4
                   1809: 
                   1810: =item * &decode_user_agent()
1.87      matthew  1811: 
                   1812: Inputs: $r
                   1813: 
                   1814: Outputs:
                   1815: 
                   1816: =over 4
                   1817: 
1.112     bowersj2 1818: =item * $httpbrowser
1.87      matthew  1819: 
1.112     bowersj2 1820: =item * $clientbrowser
1.87      matthew  1821: 
1.112     bowersj2 1822: =item * $clientversion
1.87      matthew  1823: 
1.112     bowersj2 1824: =item * $clientmathml
1.87      matthew  1825: 
1.112     bowersj2 1826: =item * $clientunicode
1.87      matthew  1827: 
1.112     bowersj2 1828: =item * $clientos
1.87      matthew  1829: 
                   1830: =back
                   1831: 
1.157     matthew  1832: =back 
                   1833: 
1.87      matthew  1834: =cut
                   1835: 
                   1836: ###############################################################
                   1837: ###############################################################
                   1838: sub decode_user_agent {
1.247     albertel 1839:     my ($r)=@_;
1.87      matthew  1840:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   1841:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   1842:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 1843:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  1844:     my $clientbrowser='unknown';
                   1845:     my $clientversion='0';
                   1846:     my $clientmathml='';
                   1847:     my $clientunicode='0';
                   1848:     for (my $i=0;$i<=$#browsertype;$i++) {
                   1849:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
                   1850: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   1851: 	    $clientbrowser=$bname;
                   1852:             $httpbrowser=~/$vreg/i;
                   1853: 	    $clientversion=$1;
                   1854:             $clientmathml=($clientversion>=$minv);
                   1855:             $clientunicode=($clientversion>=$univ);
                   1856: 	}
                   1857:     }
                   1858:     my $clientos='unknown';
                   1859:     if (($httpbrowser=~/linux/i) ||
                   1860:         ($httpbrowser=~/unix/i) ||
                   1861:         ($httpbrowser=~/ux/i) ||
                   1862:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   1863:     if (($httpbrowser=~/vax/i) ||
                   1864:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   1865:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   1866:     if (($httpbrowser=~/mac/i) ||
                   1867:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
                   1868:     if ($httpbrowser=~/win/i) { $clientos='win'; }
                   1869:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
                   1870:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
                   1871:             $clientunicode,$clientos,);
                   1872: }
                   1873: 
1.32      matthew  1874: ###############################################################
                   1875: ##    Authentication changing form generation subroutines    ##
                   1876: ###############################################################
                   1877: ##
                   1878: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   1879: ## hash, and have reasonable default values.
                   1880: ##
                   1881: ##    formname = the name given in the <form> tag.
1.35      matthew  1882: #-------------------------------------------
                   1883: 
1.45      matthew  1884: =pod
                   1885: 
1.112     bowersj2 1886: =head1 Authentication Routines
                   1887: 
                   1888: =over 4
                   1889: 
1.648     raeburn  1890: =item * &authform_xxxxxx()
1.35      matthew  1891: 
                   1892: The authform_xxxxxx subroutines provide javascript and html forms which 
                   1893: handle some of the conveniences required for authentication forms.  
                   1894: This is not an optimal method, but it works.  
                   1895: 
                   1896: =over 4
                   1897: 
1.112     bowersj2 1898: =item * authform_header
1.35      matthew  1899: 
1.112     bowersj2 1900: =item * authform_authorwarning
1.35      matthew  1901: 
1.112     bowersj2 1902: =item * authform_nochange
1.35      matthew  1903: 
1.112     bowersj2 1904: =item * authform_kerberos
1.35      matthew  1905: 
1.112     bowersj2 1906: =item * authform_internal
1.35      matthew  1907: 
1.112     bowersj2 1908: =item * authform_filesystem
1.35      matthew  1909: 
                   1910: =back
                   1911: 
1.648     raeburn  1912: See loncreateuser.pm for invocation and use examples.
1.157     matthew  1913: 
1.35      matthew  1914: =cut
                   1915: 
                   1916: #-------------------------------------------
1.32      matthew  1917: sub authform_header{  
                   1918:     my %in = (
                   1919:         formname => 'cu',
1.80      albertel 1920:         kerb_def_dom => '',
1.32      matthew  1921:         @_,
                   1922:     );
                   1923:     $in{'formname'} = 'document.' . $in{'formname'};
                   1924:     my $result='';
1.80      albertel 1925: 
                   1926: #---------------------------------------------- Code for upper case translation
                   1927:     my $Javascript_toUpperCase;
                   1928:     unless ($in{kerb_def_dom}) {
                   1929:         $Javascript_toUpperCase =<<"END";
                   1930:         switch (choice) {
                   1931:            case 'krb': currentform.elements[choicearg].value =
                   1932:                currentform.elements[choicearg].value.toUpperCase();
                   1933:                break;
                   1934:            default:
                   1935:         }
                   1936: END
                   1937:     } else {
                   1938:         $Javascript_toUpperCase = "";
                   1939:     }
                   1940: 
1.165     raeburn  1941:     my $radioval = "'nochange'";
1.591     raeburn  1942:     if (defined($in{'curr_authtype'})) {
                   1943:         if ($in{'curr_authtype'} ne '') {
                   1944:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   1945:         }
1.174     matthew  1946:     }
1.165     raeburn  1947:     my $argfield = 'null';
1.591     raeburn  1948:     if (defined($in{'mode'})) {
1.165     raeburn  1949:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  1950:             if (defined($in{'curr_autharg'})) {
                   1951:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  1952:                     $argfield = "'$in{'curr_autharg'}'";
                   1953:                 }
                   1954:             }
                   1955:         }
                   1956:     }
                   1957: 
1.32      matthew  1958:     $result.=<<"END";
                   1959: var current = new Object();
1.165     raeburn  1960: current.radiovalue = $radioval;
                   1961: current.argfield = $argfield;
1.32      matthew  1962: 
                   1963: function changed_radio(choice,currentform) {
                   1964:     var choicearg = choice + 'arg';
                   1965:     // If a radio button in changed, we need to change the argfield
                   1966:     if (current.radiovalue != choice) {
                   1967:         current.radiovalue = choice;
                   1968:         if (current.argfield != null) {
                   1969:             currentform.elements[current.argfield].value = '';
                   1970:         }
                   1971:         if (choice == 'nochange') {
                   1972:             current.argfield = null;
                   1973:         } else {
                   1974:             current.argfield = choicearg;
                   1975:             switch(choice) {
                   1976:                 case 'krb': 
                   1977:                     currentform.elements[current.argfield].value = 
                   1978:                         "$in{'kerb_def_dom'}";
                   1979:                 break;
                   1980:               default:
                   1981:                 break;
                   1982:             }
                   1983:         }
                   1984:     }
                   1985:     return;
                   1986: }
1.22      www      1987: 
1.32      matthew  1988: function changed_text(choice,currentform) {
                   1989:     var choicearg = choice + 'arg';
                   1990:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 1991:         $Javascript_toUpperCase
1.32      matthew  1992:         // clear old field
                   1993:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   1994:             currentform.elements[current.argfield].value = '';
                   1995:         }
                   1996:         current.argfield = choicearg;
                   1997:     }
                   1998:     set_auth_radio_buttons(choice,currentform);
                   1999:     return;
1.20      www      2000: }
1.32      matthew  2001: 
                   2002: function set_auth_radio_buttons(newvalue,currentform) {
                   2003:     var i=0;
                   2004:     while (i < currentform.login.length) {
                   2005:         if (currentform.login[i].value == newvalue) { break; }
                   2006:         i++;
                   2007:     }
                   2008:     if (i == currentform.login.length) {
                   2009:         return;
                   2010:     }
                   2011:     current.radiovalue = newvalue;
                   2012:     currentform.login[i].checked = true;
                   2013:     return;
                   2014: }
                   2015: END
                   2016:     return $result;
                   2017: }
                   2018: 
                   2019: sub authform_authorwarning{
                   2020:     my $result='';
1.144     matthew  2021:     $result='<i>'.
                   2022:         &mt('As a general rule, only authors or co-authors should be '.
                   2023:             'filesystem authenticated '.
                   2024:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2025:     return $result;
                   2026: }
                   2027: 
                   2028: sub authform_nochange{  
                   2029:     my %in = (
                   2030:               formname => 'document.cu',
                   2031:               kerb_def_dom => 'MSU.EDU',
                   2032:               @_,
                   2033:           );
1.586     raeburn  2034:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
                   2035:     my $result;
                   2036:     if (keys(%can_assign) == 0) {
                   2037:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
                   2038:     } else {
                   2039:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2040:                   '<input type="radio" name="login" value="nochange" '.
                   2041:                   'checked="checked" onclick="'.
1.281     albertel 2042:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2043: 	    '</label>';
1.586     raeburn  2044:     }
1.32      matthew  2045:     return $result;
                   2046: }
                   2047: 
1.591     raeburn  2048: sub authform_kerberos {
1.32      matthew  2049:     my %in = (
                   2050:               formname => 'document.cu',
                   2051:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2052:               kerb_def_auth => 'krb4',
1.32      matthew  2053:               @_,
                   2054:               );
1.586     raeburn  2055:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
                   2056:         $autharg,$jscall);
                   2057:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
1.80      albertel 2058:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.586     raeburn  2059:        $check5 = ' checked="on"';
1.80      albertel 2060:     } else {
1.586     raeburn  2061:        $check4 = ' checked="on"';
1.80      albertel 2062:     }
1.165     raeburn  2063:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2064:     if (defined($in{'curr_authtype'})) {
                   2065:         if ($in{'curr_authtype'} eq 'krb') {
1.586     raeburn  2066:             $krbcheck = ' checked="on"';
1.623     raeburn  2067:             if (defined($in{'mode'})) {
                   2068:                 if ($in{'mode'} eq 'modifyuser') {
                   2069:                     $krbcheck = '';
                   2070:                 }
                   2071:             }
1.591     raeburn  2072:             if (defined($in{'curr_kerb_ver'})) {
                   2073:                 if ($in{'curr_krb_ver'} eq '5') {
                   2074:                     $check5 = ' checked="on"';
                   2075:                     $check4 = '';
                   2076:                 } else {
                   2077:                     $check4 = ' checked="on"';
                   2078:                     $check5 = '';
                   2079:                 }
1.586     raeburn  2080:             }
1.591     raeburn  2081:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2082:                 $krbarg = $in{'curr_autharg'};
                   2083:             }
1.586     raeburn  2084:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2085:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2086:                     $result = 
                   2087:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2088:         $in{'curr_autharg'},$krbver);
                   2089:                 } else {
                   2090:                     $result =
                   2091:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2092:                 }
                   2093:                 return $result; 
                   2094:             }
                   2095:         }
                   2096:     } else {
                   2097:         if ($authnum == 1) {
                   2098:             $authtype = '<input type="hidden" name="login" value="krb">';
1.165     raeburn  2099:         }
                   2100:     }
1.586     raeburn  2101:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2102:         return;
1.587     raeburn  2103:     } elsif ($authtype eq '') {
1.591     raeburn  2104:         if (defined($in{'mode'})) {
1.587     raeburn  2105:             if ($in{'mode'} eq 'modifycourse') {
                   2106:                 if ($authnum == 1) {
                   2107:                     $authtype = '<input type="hidden" name="login" value="krb">';
                   2108:                 }
                   2109:             }
                   2110:         }
1.586     raeburn  2111:     }
                   2112:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2113:     if ($authtype eq '') {
                   2114:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2115:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
                   2116:                     $krbcheck.' />';
                   2117:     }
                   2118:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
                   2119:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
                   2120:          $in{'curr_authtype'} eq 'krb5') ||
                   2121:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
                   2122:          $in{'curr_authtype'} eq 'krb4')) {
                   2123:         $result .= &mt
1.144     matthew  2124:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2125:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2126:          '<label>'.$authtype,
1.281     albertel 2127:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2128:              'value="'.$krbarg.'" '.
1.144     matthew  2129:              'onchange="'.$jscall.'" />',
1.281     albertel 2130:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
                   2131:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
                   2132: 	 '</label>');
1.586     raeburn  2133:     } elsif ($can_assign{'krb4'}) {
                   2134:         $result .= &mt
                   2135:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2136:          '[_3] Version 4 [_4]',
                   2137:          '<label>'.$authtype,
                   2138:          '</label><input type="text" size="10" name="krbarg" '.
                   2139:              'value="'.$krbarg.'" '.
                   2140:              'onchange="'.$jscall.'" />',
                   2141:          '<label><input type="hidden" name="krbver" value="4" />',
                   2142:          '</label>');
                   2143:     } elsif ($can_assign{'krb5'}) {
                   2144:         $result .= &mt
                   2145:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2146:          '[_3] Version 5 [_4]',
                   2147:          '<label>'.$authtype,
                   2148:          '</label><input type="text" size="10" name="krbarg" '.
                   2149:              'value="'.$krbarg.'" '.
                   2150:              'onchange="'.$jscall.'" />',
                   2151:          '<label><input type="hidden" name="krbver" value="5" />',
                   2152:          '</label>');
                   2153:     }
1.32      matthew  2154:     return $result;
                   2155: }
                   2156: 
                   2157: sub authform_internal{  
1.586     raeburn  2158:     my %in = (
1.32      matthew  2159:                 formname => 'document.cu',
                   2160:                 kerb_def_dom => 'MSU.EDU',
                   2161:                 @_,
                   2162:                 );
1.586     raeburn  2163:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
                   2164:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
1.591     raeburn  2165:     if (defined($in{'curr_authtype'})) {
                   2166:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2167:             if ($can_assign{'int'}) {
                   2168:                 $intcheck = 'checked="on" ';
1.623     raeburn  2169:                 if (defined($in{'mode'})) {
                   2170:                     if ($in{'mode'} eq 'modifyuser') {
                   2171:                         $intcheck = '';
                   2172:                     }
                   2173:                 }
1.591     raeburn  2174:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2175:                     $intarg = $in{'curr_autharg'};
                   2176:                 }
                   2177:             } else {
                   2178:                 $result = &mt('Currently internally authenticated.');
                   2179:                 return $result;
1.165     raeburn  2180:             }
                   2181:         }
1.586     raeburn  2182:     } else {
                   2183:         if ($authnum == 1) {
                   2184:             $authtype = '<input type="hidden" name="login" value="int">';
                   2185:         }
                   2186:     }
                   2187:     if (!$can_assign{'int'}) {
                   2188:         return;
1.587     raeburn  2189:     } elsif ($authtype eq '') {
1.591     raeburn  2190:         if (defined($in{'mode'})) {
1.587     raeburn  2191:             if ($in{'mode'} eq 'modifycourse') {
                   2192:                 if ($authnum == 1) {
                   2193:                     $authtype = '<input type="hidden" name="login" value="int">';
                   2194:                 }
                   2195:             }
                   2196:         }
1.165     raeburn  2197:     }
1.586     raeburn  2198:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   2199:     if ($authtype eq '') {
                   2200:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
                   2201:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
                   2202:     }
1.605     bisitz   2203:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.586     raeburn  2204:                $intarg.'" onchange="'.$jscall.'" />';
                   2205:     $result = &mt
1.144     matthew  2206:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  2207:          '<label>'.$authtype,'</label>'.$autharg);
1.620     www      2208:     $result.="<label><input type=\"checkbox\" name=\"visible\" onClick='if (this.checked) { this.form.intarg.type=\"text\" } else { this.form.intarg.type=\"password\" }' />".&mt('Visible input').'</label>';
1.32      matthew  2209:     return $result;
                   2210: }
                   2211: 
                   2212: sub authform_local{  
                   2213:     my %in = (
                   2214:               formname => 'document.cu',
                   2215:               kerb_def_dom => 'MSU.EDU',
                   2216:               @_,
                   2217:               );
1.586     raeburn  2218:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
                   2219:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
1.591     raeburn  2220:     if (defined($in{'curr_authtype'})) {
                   2221:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  2222:             if ($can_assign{'loc'}) {
                   2223:                 $loccheck = 'checked="on" ';
1.623     raeburn  2224:                 if (defined($in{'mode'})) {
                   2225:                     if ($in{'mode'} eq 'modifyuser') {
                   2226:                         $loccheck = '';
                   2227:                     }
                   2228:                 }
1.591     raeburn  2229:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2230:                     $locarg = $in{'curr_autharg'};
                   2231:                 }
                   2232:             } else {
                   2233:                 $result = &mt('Currently using local (institutional) authentication.');
                   2234:                 return $result;
1.165     raeburn  2235:             }
                   2236:         }
1.586     raeburn  2237:     } else {
                   2238:         if ($authnum == 1) {
                   2239:             $authtype = '<input type="hidden" name="login" value="loc">';
                   2240:         }
                   2241:     }
                   2242:     if (!$can_assign{'loc'}) {
                   2243:         return;
1.587     raeburn  2244:     } elsif ($authtype eq '') {
1.591     raeburn  2245:         if (defined($in{'mode'})) {
1.587     raeburn  2246:             if ($in{'mode'} eq 'modifycourse') {
                   2247:                 if ($authnum == 1) {
                   2248:                     $authtype = '<input type="hidden" name="login" value="loc">';
                   2249:                 }
                   2250:             }
                   2251:         }
1.165     raeburn  2252:     }
1.586     raeburn  2253:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   2254:     if ($authtype eq '') {
                   2255:         $authtype = '<input type="radio" name="login" value="loc" '.
                   2256:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
                   2257:                     $jscall.'" />';
                   2258:     }
                   2259:     $autharg = '<input type="text" size="10" name="locarg" value="'.
                   2260:                $locarg.'" onchange="'.$jscall.'" />';
                   2261:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   2262:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  2263:     return $result;
                   2264: }
                   2265: 
                   2266: sub authform_filesystem{  
                   2267:     my %in = (
                   2268:               formname => 'document.cu',
                   2269:               kerb_def_dom => 'MSU.EDU',
                   2270:               @_,
                   2271:               );
1.586     raeburn  2272:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
                   2273:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
1.591     raeburn  2274:     if (defined($in{'curr_authtype'})) {
                   2275:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  2276:             if ($can_assign{'fsys'}) {
                   2277:                 $fsyscheck = 'checked="on" ';
1.623     raeburn  2278:                 if (defined($in{'mode'})) {
                   2279:                     if ($in{'mode'} eq 'modifyuser') {
                   2280:                         $fsyscheck = '';
                   2281:                     }
                   2282:                 }
1.586     raeburn  2283:             } else {
                   2284:                 $result = &mt('Currently Filesystem Authenticated.');
                   2285:                 return $result;
                   2286:             }           
                   2287:         }
                   2288:     } else {
                   2289:         if ($authnum == 1) {
                   2290:             $authtype = '<input type="hidden" name="login" value="fsys">';
                   2291:         }
                   2292:     }
                   2293:     if (!$can_assign{'fsys'}) {
                   2294:         return;
1.587     raeburn  2295:     } elsif ($authtype eq '') {
1.591     raeburn  2296:         if (defined($in{'mode'})) {
1.587     raeburn  2297:             if ($in{'mode'} eq 'modifycourse') {
                   2298:                 if ($authnum == 1) {
                   2299:                     $authtype = '<input type="hidden" name="login" value="fsys">';
                   2300:                 }
                   2301:             }
                   2302:         }
1.586     raeburn  2303:     }
                   2304:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   2305:     if ($authtype eq '') {
                   2306:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   2307:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
                   2308:                     $jscall.'" />';
                   2309:     }
                   2310:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
                   2311:                ' onchange="'.$jscall.'" />';
                   2312:     $result = &mt
1.144     matthew  2313:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 2314:          '<label><input type="radio" name="login" value="fsys" '.
1.586     raeburn  2315:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1.605     bisitz   2316:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.144     matthew  2317:                   'onchange="'.$jscall.'" />');
1.32      matthew  2318:     return $result;
                   2319: }
                   2320: 
1.586     raeburn  2321: sub get_assignable_auth {
                   2322:     my ($dom) = @_;
                   2323:     if ($dom eq '') {
                   2324:         $dom = $env{'request.role.domain'};
                   2325:     }
                   2326:     my %can_assign = (
                   2327:                           krb4 => 1,
                   2328:                           krb5 => 1,
                   2329:                           int  => 1,
                   2330:                           loc  => 1,
                   2331:                      );
                   2332:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   2333:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   2334:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   2335:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   2336:             my $context;
                   2337:             if ($env{'request.role'} =~ /^au/) {
                   2338:                 $context = 'author';
                   2339:             } elsif ($env{'request.role'} =~ /^dc/) {
                   2340:                 $context = 'domain';
                   2341:             } elsif ($env{'request.course.id'}) {
                   2342:                 $context = 'course';
                   2343:             }
                   2344:             if ($context) {
                   2345:                 if (ref($authhash->{$context}) eq 'HASH') {
                   2346:                    %can_assign = %{$authhash->{$context}}; 
                   2347:                 }
                   2348:             }
                   2349:         }
                   2350:     }
                   2351:     my $authnum = 0;
                   2352:     foreach my $key (keys(%can_assign)) {
                   2353:         if ($can_assign{$key}) {
                   2354:             $authnum ++;
                   2355:         }
                   2356:     }
                   2357:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   2358:         $authnum --;
                   2359:     }
                   2360:     return ($authnum,%can_assign);
                   2361: }
                   2362: 
1.80      albertel 2363: ###############################################################
                   2364: ##    Get Kerberos Defaults for Domain                 ##
                   2365: ###############################################################
                   2366: ##
                   2367: ## Returns default kerberos version and an associated argument
                   2368: ## as listed in file domain.tab. If not listed, provides
                   2369: ## appropriate default domain and kerberos version.
                   2370: ##
                   2371: #-------------------------------------------
                   2372: 
                   2373: =pod
                   2374: 
1.648     raeburn  2375: =item * &get_kerberos_defaults()
1.80      albertel 2376: 
                   2377: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  2378: version and domain. If not found, it defaults to version 4 and the 
                   2379: domain of the server.
1.80      albertel 2380: 
1.648     raeburn  2381: =over 4
                   2382: 
1.80      albertel 2383: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   2384: 
1.648     raeburn  2385: =back
                   2386: 
                   2387: =back
                   2388: 
1.80      albertel 2389: =cut
                   2390: 
                   2391: #-------------------------------------------
                   2392: sub get_kerberos_defaults {
                   2393:     my $domain=shift;
1.641     raeburn  2394:     my ($krbdef,$krbdefdom);
                   2395:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2396:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   2397:         $krbdef = $domdefaults{'auth_def'};
                   2398:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   2399:     } else {
1.80      albertel 2400:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   2401:         my $krbdefdom=$1;
                   2402:         $krbdefdom=~tr/a-z/A-Z/;
                   2403:         $krbdef = "krb4";
                   2404:     }
                   2405:     return ($krbdef,$krbdefdom);
                   2406: }
1.112     bowersj2 2407: 
1.32      matthew  2408: 
1.46      matthew  2409: ###############################################################
                   2410: ##                Thesaurus Functions                        ##
                   2411: ###############################################################
1.20      www      2412: 
1.46      matthew  2413: =pod
1.20      www      2414: 
1.112     bowersj2 2415: =head1 Thesaurus Functions
                   2416: 
                   2417: =over 4
                   2418: 
1.648     raeburn  2419: =item * &initialize_keywords()
1.46      matthew  2420: 
                   2421: Initializes the package variable %Keywords if it is empty.  Uses the
                   2422: package variable $thesaurus_db_file.
                   2423: 
                   2424: =cut
                   2425: 
                   2426: ###################################################
                   2427: 
                   2428: sub initialize_keywords {
                   2429:     return 1 if (scalar keys(%Keywords));
                   2430:     # If we are here, %Keywords is empty, so fill it up
                   2431:     #   Make sure the file we need exists...
                   2432:     if (! -e $thesaurus_db_file) {
                   2433:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   2434:                                  " failed because it does not exist");
                   2435:         return 0;
                   2436:     }
                   2437:     #   Set up the hash as a database
                   2438:     my %thesaurus_db;
                   2439:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 2440:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  2441:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   2442:                                  $thesaurus_db_file);
                   2443:         return 0;
                   2444:     } 
                   2445:     #  Get the average number of appearances of a word.
                   2446:     my $avecount = $thesaurus_db{'average.count'};
                   2447:     #  Put keywords (those that appear > average) into %Keywords
                   2448:     while (my ($word,$data)=each (%thesaurus_db)) {
                   2449:         my ($count,undef) = split /:/,$data;
                   2450:         $Keywords{$word}++ if ($count > $avecount);
                   2451:     }
                   2452:     untie %thesaurus_db;
                   2453:     # Remove special values from %Keywords.
1.356     albertel 2454:     foreach my $value ('total.count','average.count') {
                   2455:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  2456:   }
1.46      matthew  2457:     return 1;
                   2458: }
                   2459: 
                   2460: ###################################################
                   2461: 
                   2462: =pod
                   2463: 
1.648     raeburn  2464: =item * &keyword($word)
1.46      matthew  2465: 
                   2466: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   2467: than the average number of times in the thesaurus database.  Calls 
                   2468: &initialize_keywords
                   2469: 
                   2470: =cut
                   2471: 
                   2472: ###################################################
1.20      www      2473: 
                   2474: sub keyword {
1.46      matthew  2475:     return if (!&initialize_keywords());
                   2476:     my $word=lc(shift());
                   2477:     $word=~s/\W//g;
                   2478:     return exists($Keywords{$word});
1.20      www      2479: }
1.46      matthew  2480: 
                   2481: ###############################################################
                   2482: 
                   2483: =pod 
1.20      www      2484: 
1.648     raeburn  2485: =item * &get_related_words()
1.46      matthew  2486: 
1.160     matthew  2487: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  2488: an array of words.  If the keyword is not in the thesaurus, an empty array
                   2489: will be returned.  The order of the words returned is determined by the
                   2490: database which holds them.
                   2491: 
                   2492: Uses global $thesaurus_db_file.
                   2493: 
                   2494: =cut
                   2495: 
                   2496: ###############################################################
                   2497: sub get_related_words {
                   2498:     my $keyword = shift;
                   2499:     my %thesaurus_db;
                   2500:     if (! -e $thesaurus_db_file) {
                   2501:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   2502:                                  "failed because the file does not exist");
                   2503:         return ();
                   2504:     }
                   2505:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 2506:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  2507:         return ();
                   2508:     } 
                   2509:     my @Words=();
1.429     www      2510:     my $count=0;
1.46      matthew  2511:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 2512: 	# The first element is the number of times
                   2513: 	# the word appears.  We do not need it now.
1.429     www      2514: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   2515: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   2516: 	my $threshold=$mostfrequentcount/10;
                   2517:         foreach my $possibleword (@RelatedWords) {
                   2518:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   2519:             if ($wordcount>$threshold) {
                   2520: 		push(@Words,$word);
                   2521:                 $count++;
                   2522:                 if ($count>10) { last; }
                   2523: 	    }
1.20      www      2524:         }
                   2525:     }
1.46      matthew  2526:     untie %thesaurus_db;
                   2527:     return @Words;
1.14      harris41 2528: }
1.46      matthew  2529: 
1.112     bowersj2 2530: =pod
                   2531: 
                   2532: =back
                   2533: 
                   2534: =cut
1.61      www      2535: 
                   2536: # -------------------------------------------------------------- Plaintext name
1.81      albertel 2537: =pod
                   2538: 
1.112     bowersj2 2539: =head1 User Name Functions
                   2540: 
                   2541: =over 4
                   2542: 
1.648     raeburn  2543: =item * &plainname($uname,$udom,$first)
1.81      albertel 2544: 
1.112     bowersj2 2545: Takes a users logon name and returns it as a string in
1.226     albertel 2546: "first middle last generation" form 
                   2547: if $first is set to 'lastname' then it returns it as
                   2548: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 2549: 
                   2550: =cut
1.61      www      2551: 
1.295     www      2552: 
1.81      albertel 2553: ###############################################################
1.61      www      2554: sub plainname {
1.226     albertel 2555:     my ($uname,$udom,$first)=@_;
1.537     albertel 2556:     return if (!defined($uname) || !defined($udom));
1.295     www      2557:     my %names=&getnames($uname,$udom);
1.226     albertel 2558:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   2559: 					  $names{'middlename'},
                   2560: 					  $names{'lastname'},
                   2561: 					  $names{'generation'},$first);
                   2562:     $name=~s/^\s+//;
1.62      www      2563:     $name=~s/\s+$//;
                   2564:     $name=~s/\s+/ /g;
1.353     albertel 2565:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      2566:     return $name;
1.61      www      2567: }
1.66      www      2568: 
                   2569: # -------------------------------------------------------------------- Nickname
1.81      albertel 2570: =pod
                   2571: 
1.648     raeburn  2572: =item * &nickname($uname,$udom)
1.81      albertel 2573: 
                   2574: Gets a users name and returns it as a string as
                   2575: 
                   2576: "&quot;nickname&quot;"
1.66      www      2577: 
1.81      albertel 2578: if the user has a nickname or
                   2579: 
                   2580: "first middle last generation"
                   2581: 
                   2582: if the user does not
                   2583: 
                   2584: =cut
1.66      www      2585: 
                   2586: sub nickname {
                   2587:     my ($uname,$udom)=@_;
1.537     albertel 2588:     return if (!defined($uname) || !defined($udom));
1.295     www      2589:     my %names=&getnames($uname,$udom);
1.68      albertel 2590:     my $name=$names{'nickname'};
1.66      www      2591:     if ($name) {
                   2592:        $name='&quot;'.$name.'&quot;'; 
                   2593:     } else {
                   2594:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   2595: 	     $names{'lastname'}.' '.$names{'generation'};
                   2596:        $name=~s/\s+$//;
                   2597:        $name=~s/\s+/ /g;
                   2598:     }
                   2599:     return $name;
                   2600: }
                   2601: 
1.295     www      2602: sub getnames {
                   2603:     my ($uname,$udom)=@_;
1.537     albertel 2604:     return if (!defined($uname) || !defined($udom));
1.433     albertel 2605:     if ($udom eq 'public' && $uname eq 'public') {
                   2606: 	return ('lastname' => &mt('Public'));
                   2607:     }
1.295     www      2608:     my $id=$uname.':'.$udom;
                   2609:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   2610:     if ($cached) {
                   2611: 	return %{$names};
                   2612:     } else {
                   2613: 	my %loadnames=&Apache::lonnet::get('environment',
                   2614:                     ['firstname','middlename','lastname','generation','nickname'],
                   2615: 					 $udom,$uname);
                   2616: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   2617: 	return %loadnames;
                   2618:     }
                   2619: }
1.61      www      2620: 
1.542     raeburn  2621: # -------------------------------------------------------------------- getemails
1.648     raeburn  2622: 
1.542     raeburn  2623: =pod
                   2624: 
1.648     raeburn  2625: =item * &getemails($uname,$udom)
1.542     raeburn  2626: 
                   2627: Gets a user's email information and returns it as a hash with keys:
                   2628: notification, critnotification, permanentemail
                   2629: 
                   2630: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  2631: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  2632:  
1.648     raeburn  2633: 
1.542     raeburn  2634: =cut
                   2635: 
1.648     raeburn  2636: 
1.466     albertel 2637: sub getemails {
                   2638:     my ($uname,$udom)=@_;
                   2639:     if ($udom eq 'public' && $uname eq 'public') {
                   2640: 	return;
                   2641:     }
1.467     www      2642:     if (!$udom) { $udom=$env{'user.domain'}; }
                   2643:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 2644:     my $id=$uname.':'.$udom;
                   2645:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   2646:     if ($cached) {
                   2647: 	return %{$names};
                   2648:     } else {
                   2649: 	my %loadnames=&Apache::lonnet::get('environment',
                   2650:                     			   ['notification','critnotification',
                   2651: 					    'permanentemail'],
                   2652: 					   $udom,$uname);
                   2653: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   2654: 	return %loadnames;
                   2655:     }
                   2656: }
                   2657: 
1.551     albertel 2658: sub flush_email_cache {
                   2659:     my ($uname,$udom)=@_;
                   2660:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   2661:     if (!$uname) { $uname=$env{'user.name'};   }
                   2662:     return if ($udom eq 'public' && $uname eq 'public');
                   2663:     my $id=$uname.':'.$udom;
                   2664:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   2665: }
                   2666: 
1.61      www      2667: # ------------------------------------------------------------------ Screenname
1.81      albertel 2668: 
                   2669: =pod
                   2670: 
1.648     raeburn  2671: =item * &screenname($uname,$udom)
1.81      albertel 2672: 
                   2673: Gets a users screenname and returns it as a string
                   2674: 
                   2675: =cut
1.61      www      2676: 
                   2677: sub screenname {
                   2678:     my ($uname,$udom)=@_;
1.258     albertel 2679:     if ($uname eq $env{'user.name'} &&
                   2680: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 2681:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 2682:     return $names{'screenname'};
1.62      www      2683: }
                   2684: 
1.212     albertel 2685: 
1.62      www      2686: # ------------------------------------------------------------- Message Wrapper
                   2687: 
                   2688: sub messagewrapper {
1.369     www      2689:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      2690:     return 
1.441     albertel 2691:         '<a href="/adm/email?compose=individual&amp;'.
                   2692:         'recname='.$username.'&amp;recdom='.$domain.
                   2693: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  2694:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      2695: }
                   2696: # --------------------------------------------------------------- Notes Wrapper
                   2697: 
                   2698: sub noteswrapper {
                   2699:     my ($link,$un,$do)=@_;
                   2700:     return 
                   2701: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
1.62      www      2702: }
                   2703: # ------------------------------------------------------------- Aboutme Wrapper
                   2704: 
                   2705: sub aboutmewrapper {
1.166     www      2706:     my ($link,$username,$domain,$target)=@_;
1.447     raeburn  2707:     if (!defined($username)  && !defined($domain)) {
                   2708:         return;
                   2709:     }
1.205     www      2710:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.454     banghart 2711: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal page").'">'.$link.'</a>';
1.62      www      2712: }
                   2713: 
                   2714: # ------------------------------------------------------------ Syllabus Wrapper
                   2715: 
                   2716: 
                   2717: sub syllabuswrapper {
1.109     matthew  2718:     my ($linktext,$coursedir,$domain,$fontcolor)=@_;
                   2719:     if ($fontcolor) { 
                   2720:         $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>'; 
                   2721:     }
1.208     matthew  2722:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      2723: }
1.14      harris41 2724: 
1.208     matthew  2725: sub track_student_link {
1.268     albertel 2726:     my ($linktext,$sname,$sdom,$target,$start) = @_;
                   2727:     my $link ="/adm/trackstudent?";
1.208     matthew  2728:     my $title = 'View recent activity';
                   2729:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   2730:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 2731:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  2732:         $title .= ' of this student';
1.268     albertel 2733:     } 
1.208     matthew  2734:     if (defined($target) && $target !~ /^\s*$/) {
                   2735:         $target = qq{target="$target"};
                   2736:     } else {
                   2737:         $target = '';
                   2738:     }
1.268     albertel 2739:     if ($start) { $link.='&amp;start='.$start; }
1.554     albertel 2740:     $title = &mt($title);
                   2741:     $linktext = &mt($linktext);
1.448     albertel 2742:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   2743: 	&help_open_topic('View_recent_activity');
1.208     matthew  2744: }
                   2745: 
1.508     www      2746: # ===================================================== Display a student photo
                   2747: 
                   2748: 
1.509     albertel 2749: sub student_image_tag {
1.508     www      2750:     my ($domain,$user)=@_;
                   2751:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   2752:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   2753: 	return '<img src="'.$imgsrc.'" align="right" />';
                   2754:     } else {
                   2755: 	return '';
                   2756:     }
                   2757: }
                   2758: 
1.112     bowersj2 2759: =pod
                   2760: 
                   2761: =back
                   2762: 
                   2763: =head1 Access .tab File Data
                   2764: 
                   2765: =over 4
                   2766: 
1.648     raeburn  2767: =item * &languageids() 
1.112     bowersj2 2768: 
                   2769: returns list of all language ids
                   2770: 
                   2771: =cut
                   2772: 
1.14      harris41 2773: sub languageids {
1.16      harris41 2774:     return sort(keys(%language));
1.14      harris41 2775: }
                   2776: 
1.112     bowersj2 2777: =pod
                   2778: 
1.648     raeburn  2779: =item * &languagedescription() 
1.112     bowersj2 2780: 
                   2781: returns description of a specified language id
                   2782: 
                   2783: =cut
                   2784: 
1.14      harris41 2785: sub languagedescription {
1.125     www      2786:     my $code=shift;
                   2787:     return  ($supported_language{$code}?'* ':'').
                   2788:             $language{$code}.
1.126     www      2789: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      2790: }
                   2791: 
                   2792: sub plainlanguagedescription {
                   2793:     my $code=shift;
                   2794:     return $language{$code};
                   2795: }
                   2796: 
                   2797: sub supportedlanguagecode {
                   2798:     my $code=shift;
                   2799:     return $supported_language{$code};
1.97      www      2800: }
                   2801: 
1.112     bowersj2 2802: =pod
                   2803: 
1.648     raeburn  2804: =item * &copyrightids() 
1.112     bowersj2 2805: 
                   2806: returns list of all copyrights
                   2807: 
                   2808: =cut
                   2809: 
                   2810: sub copyrightids {
                   2811:     return sort(keys(%cprtag));
                   2812: }
                   2813: 
                   2814: =pod
                   2815: 
1.648     raeburn  2816: =item * &copyrightdescription() 
1.112     bowersj2 2817: 
                   2818: returns description of a specified copyright id
                   2819: 
                   2820: =cut
                   2821: 
                   2822: sub copyrightdescription {
1.166     www      2823:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 2824: }
1.197     matthew  2825: 
                   2826: =pod
                   2827: 
1.648     raeburn  2828: =item * &source_copyrightids() 
1.192     taceyjo1 2829: 
                   2830: returns list of all source copyrights
                   2831: 
                   2832: =cut
                   2833: 
                   2834: sub source_copyrightids {
                   2835:     return sort(keys(%scprtag));
                   2836: }
                   2837: 
                   2838: =pod
                   2839: 
1.648     raeburn  2840: =item * &source_copyrightdescription() 
1.192     taceyjo1 2841: 
                   2842: returns description of a specified source copyright id
                   2843: 
                   2844: =cut
                   2845: 
                   2846: sub source_copyrightdescription {
                   2847:     return &mt($scprtag{shift(@_)});
                   2848: }
1.112     bowersj2 2849: 
                   2850: =pod
                   2851: 
1.648     raeburn  2852: =item * &filecategories() 
1.112     bowersj2 2853: 
                   2854: returns list of all file categories
                   2855: 
                   2856: =cut
                   2857: 
                   2858: sub filecategories {
                   2859:     return sort(keys(%category_extensions));
                   2860: }
                   2861: 
                   2862: =pod
                   2863: 
1.648     raeburn  2864: =item * &filecategorytypes() 
1.112     bowersj2 2865: 
                   2866: returns list of file types belonging to a given file
                   2867: category
                   2868: 
                   2869: =cut
                   2870: 
                   2871: sub filecategorytypes {
1.356     albertel 2872:     my ($cat) = @_;
                   2873:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 2874: }
                   2875: 
                   2876: =pod
                   2877: 
1.648     raeburn  2878: =item * &fileembstyle() 
1.112     bowersj2 2879: 
                   2880: returns embedding style for a specified file type
                   2881: 
                   2882: =cut
                   2883: 
                   2884: sub fileembstyle {
                   2885:     return $fe{lc(shift(@_))};
1.169     www      2886: }
                   2887: 
1.351     www      2888: sub filemimetype {
                   2889:     return $fm{lc(shift(@_))};
                   2890: }
                   2891: 
1.169     www      2892: 
                   2893: sub filecategoryselect {
                   2894:     my ($name,$value)=@_;
1.189     matthew  2895:     return &select_form($value,$name,
1.169     www      2896: 			'' => &mt('Any category'),
                   2897: 			map { $_,$_ } sort(keys(%category_extensions)));
1.112     bowersj2 2898: }
                   2899: 
                   2900: =pod
                   2901: 
1.648     raeburn  2902: =item * &filedescription() 
1.112     bowersj2 2903: 
                   2904: returns description for a specified file type
                   2905: 
                   2906: =cut
                   2907: 
                   2908: sub filedescription {
1.188     matthew  2909:     my $file_description = $fd{lc(shift())};
                   2910:     $file_description =~ s:([\[\]]):~$1:g;
                   2911:     return &mt($file_description);
1.112     bowersj2 2912: }
                   2913: 
                   2914: =pod
                   2915: 
1.648     raeburn  2916: =item * &filedescriptionex() 
1.112     bowersj2 2917: 
                   2918: returns description for a specified file type with
                   2919: extra formatting
                   2920: 
                   2921: =cut
                   2922: 
                   2923: sub filedescriptionex {
                   2924:     my $ex=shift;
1.188     matthew  2925:     my $file_description = $fd{lc($ex)};
                   2926:     $file_description =~ s:([\[\]]):~$1:g;
                   2927:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 2928: }
                   2929: 
                   2930: # End of .tab access
                   2931: =pod
                   2932: 
                   2933: =back
                   2934: 
                   2935: =cut
                   2936: 
                   2937: # ------------------------------------------------------------------ File Types
                   2938: sub fileextensions {
                   2939:     return sort(keys(%fe));
                   2940: }
                   2941: 
1.97      www      2942: # ----------------------------------------------------------- Display Languages
                   2943: # returns a hash with all desired display languages
                   2944: #
                   2945: 
                   2946: sub display_languages {
                   2947:     my %languages=();
1.356     albertel 2948:     foreach my $lang (&preferred_languages()) {
                   2949: 	$languages{$lang}=1;
1.97      www      2950:     }
                   2951:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 2952:     if ($env{'form.displaylanguage'}) {
1.356     albertel 2953: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   2954: 	    $languages{$lang}=1;
1.97      www      2955:         }
                   2956:     }
                   2957:     return %languages;
1.14      harris41 2958: }
                   2959: 
1.117     www      2960: sub preferred_languages {
                   2961:     my @languages=();
1.654     www      2962:     if (($env{'request.role.adv'}) && ($env{'form.languages'})) {
                   2963:         @languages=(@languages,split(/\s*(\,|\;|\:)\s*/,$env{'form.languages'}));
                   2964:     }
1.258     albertel 2965:     if ($env{'course.'.$env{'request.course.id'}.'.languages'}) {
1.117     www      2966: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,
1.258     albertel 2967: 	         $env{'course.'.$env{'request.course.id'}.'.languages'}));
1.177     www      2968:     }
1.654     www      2969: 
1.258     albertel 2970:     if ($env{'environment.languages'}) {
1.459     albertel 2971: 	@languages=(@languages,
                   2972: 		    split(/\s*(\,|\;|\:)\s*/,$env{'environment.languages'}));
1.118     www      2973:     }
1.583     albertel 2974:     my $browser=$ENV{'HTTP_ACCEPT_LANGUAGE'};
1.162     www      2975:     if ($browser) {
1.583     albertel 2976: 	my @browser = 
                   2977: 	    map { (split(/\s*;\s*/,$_))[0] } (split(/\s*,\s*/,$browser));
                   2978: 	push(@languages,@browser);
1.162     www      2979:     }
1.641     raeburn  2980: 
                   2981:     foreach my $domtype ($env{'user.domain'},$env{'request.role.domain'},
                   2982:                          $Apache::lonnet::perlvar{'lonDefDomain'}) {
                   2983:         if ($domtype ne '') {
                   2984:             my %domdefs = &Apache::lonnet::get_domain_defaults($domtype);
                   2985:             if ($domdefs{'lang_def'} ne '') {
                   2986:                 push(@languages,$domdefs{'lang_def'});
                   2987:             }
                   2988:         }
1.118     www      2989:     }
1.679.2.4  raeburn  2990:     return &get_genlanguages(@languages);
                   2991: }
                   2992: 
                   2993: sub get_genlanguages {
                   2994:     my (@languages) = @_;
1.118     www      2995: # turn "en-ca" into "en-ca,en"
                   2996:     my @genlanguages;
1.356     albertel 2997:     foreach my $lang (@languages) {
1.679.2.4  raeburn  2998:         unless ($lang=~/\w/) { next; }
                   2999:         push(@genlanguages,$lang);
                   3000:         if ($lang=~/(\-|\_)/) {
                   3001:             push(@genlanguages,(split(/(\-|\_)/,$lang))[0]);
                   3002:         }
1.118     www      3003:     }
1.583     albertel 3004:     #uniqueify the languages list
                   3005:     my %count;
                   3006:     @genlanguages = map { $count{$_}++ == 0 ? $_ : () } @genlanguages;
1.118     www      3007:     return @genlanguages;
1.117     www      3008: }
                   3009: 
1.582     albertel 3010: sub languages {
                   3011:     my ($possible_langs) = @_;
                   3012:     my @preferred_langs = &preferred_languages();
                   3013:     if (!ref($possible_langs)) {
                   3014: 	if( wantarray ) {
                   3015: 	    return @preferred_langs;
                   3016: 	} else {
                   3017: 	    return $preferred_langs[0];
                   3018: 	}
                   3019:     }
                   3020:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3021:     my @preferred_possibilities;
                   3022:     foreach my $preferred_lang (@preferred_langs) {
                   3023: 	if (exists($possibilities{$preferred_lang})) {
                   3024: 	    push(@preferred_possibilities, $preferred_lang);
                   3025: 	}
                   3026:     }
                   3027:     if( wantarray ) {
                   3028: 	return @preferred_possibilities;
                   3029:     }
                   3030:     return $preferred_possibilities[0];
                   3031: }
                   3032: 
1.112     bowersj2 3033: ###############################################################
                   3034: ##               Student Answer Attempts                     ##
                   3035: ###############################################################
                   3036: 
                   3037: =pod
                   3038: 
                   3039: =head1 Alternate Problem Views
                   3040: 
                   3041: =over 4
                   3042: 
1.648     raeburn  3043: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.112     bowersj2 3044:     $getattempt, $regexp, $gradesub)
                   3045: 
                   3046: Return string with previous attempt on problem. Arguments:
                   3047: 
                   3048: =over 4
                   3049: 
                   3050: =item * $symb: Problem, including path
                   3051: 
                   3052: =item * $username: username of the desired student
                   3053: 
                   3054: =item * $domain: domain of the desired student
1.14      harris41 3055: 
1.112     bowersj2 3056: =item * $course: Course ID
1.14      harris41 3057: 
1.112     bowersj2 3058: =item * $getattempt: Leave blank for all attempts, otherwise put
                   3059:     something
1.14      harris41 3060: 
1.112     bowersj2 3061: =item * $regexp: if string matches this regexp, the string will be
                   3062:     sent to $gradesub
1.14      harris41 3063: 
1.112     bowersj2 3064: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 3065: 
1.112     bowersj2 3066: =back
1.14      harris41 3067: 
1.112     bowersj2 3068: The output string is a table containing all desired attempts, if any.
1.16      harris41 3069: 
1.112     bowersj2 3070: =cut
1.1       albertel 3071: 
                   3072: sub get_previous_attempt {
1.43      ng       3073:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
1.1       albertel 3074:   my $prevattempts='';
1.43      ng       3075:   no strict 'refs';
1.1       albertel 3076:   if ($symb) {
1.3       albertel 3077:     my (%returnhash)=
                   3078:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 3079:     if ($returnhash{'version'}) {
                   3080:       my %lasthash=();
                   3081:       my $version;
                   3082:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.356     albertel 3083:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   3084: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
1.19      harris41 3085:         }
1.1       albertel 3086:       }
1.596     albertel 3087:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   3088:       $prevattempts.='<th>'.&mt('History').'</th>';
1.356     albertel 3089:       foreach my $key (sort(keys(%lasthash))) {
                   3090: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       3091: 	if ($#parts > 0) {
1.31      albertel 3092: 	  my $data=$parts[-1];
                   3093: 	  pop(@parts);
1.596     albertel 3094: 	  $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.31      albertel 3095: 	} else {
1.41      ng       3096: 	  if ($#parts == 0) {
                   3097: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   3098: 	  } else {
                   3099: 	    $prevattempts.='<th>'.$ign.'</th>';
                   3100: 	  }
1.31      albertel 3101: 	}
1.16      harris41 3102:       }
1.596     albertel 3103:       $prevattempts.=&end_data_table_header_row();
1.40      ng       3104:       if ($getattempt eq '') {
                   3105: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.596     albertel 3106: 	  $prevattempts.=&start_data_table_row().
                   3107: 	      '<td>'.&mt('Transaction [_1]',$version).'</td>';
1.356     albertel 3108: 	    foreach my $key (sort(keys(%lasthash))) {
1.581     albertel 3109: 		my $value = &format_previous_attempt_value($key,
                   3110: 							   $returnhash{$version.':'.$key});
                   3111: 		$prevattempts.='<td>'.$value.'&nbsp;</td>';   
1.40      ng       3112: 	    }
1.596     albertel 3113: 	  $prevattempts.=&end_data_table_row();
1.40      ng       3114: 	 }
1.1       albertel 3115:       }
1.596     albertel 3116:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 3117:       foreach my $key (sort(keys(%lasthash))) {
1.581     albertel 3118: 	my $value = &format_previous_attempt_value($key,$lasthash{$key});
1.356     albertel 3119: 	if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
1.40      ng       3120: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
1.16      harris41 3121:       }
1.596     albertel 3122:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 3123:     } else {
1.596     albertel 3124:       $prevattempts=
                   3125: 	  &start_data_table().&start_data_table_row().
                   3126: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   3127: 	  &end_data_table_row().&end_data_table();
1.1       albertel 3128:     }
                   3129:   } else {
1.596     albertel 3130:     $prevattempts=
                   3131: 	  &start_data_table().&start_data_table_row().
                   3132: 	  '<td>'.&mt('No data.').'</td>'.
                   3133: 	  &end_data_table_row().&end_data_table();
1.1       albertel 3134:   }
1.10      albertel 3135: }
                   3136: 
1.581     albertel 3137: sub format_previous_attempt_value {
                   3138:     my ($key,$value) = @_;
                   3139:     if ($key =~ /timestamp/) {
                   3140: 	$value = &Apache::lonlocal::locallocaltime($value);
                   3141:     } elsif (ref($value) eq 'ARRAY') {
                   3142: 	$value = '('.join(', ', @{ $value }).')';
                   3143:     } else {
                   3144: 	$value = &unescape($value);
                   3145:     }
                   3146:     return $value;
                   3147: }
                   3148: 
                   3149: 
1.107     albertel 3150: sub relative_to_absolute {
                   3151:     my ($url,$output)=@_;
                   3152:     my $parser=HTML::TokeParser->new(\$output);
                   3153:     my $token;
                   3154:     my $thisdir=$url;
                   3155:     my @rlinks=();
                   3156:     while ($token=$parser->get_token) {
                   3157: 	if ($token->[0] eq 'S') {
                   3158: 	    if ($token->[1] eq 'a') {
                   3159: 		if ($token->[2]->{'href'}) {
                   3160: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   3161: 		}
                   3162: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   3163: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   3164: 	    } elsif ($token->[1] eq 'base') {
                   3165: 		$thisdir=$token->[2]->{'href'};
                   3166: 	    }
                   3167: 	}
                   3168:     }
                   3169:     $thisdir=~s-/[^/]*$--;
1.356     albertel 3170:     foreach my $link (@rlinks) {
                   3171: 	unless (($link=~/^http:\/\//i) ||
                   3172: 		($link=~/^\//) ||
                   3173: 		($link=~/^javascript:/i) ||
                   3174: 		($link=~/^mailto:/i) ||
                   3175: 		($link=~/^\#/)) {
                   3176: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   3177: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 3178: 	}
                   3179:     }
                   3180: # -------------------------------------------------- Deal with Applet codebases
                   3181:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   3182:     return $output;
                   3183: }
                   3184: 
1.112     bowersj2 3185: =pod
                   3186: 
1.648     raeburn  3187: =item * &get_student_view()
1.112     bowersj2 3188: 
                   3189: show a snapshot of what student was looking at
                   3190: 
                   3191: =cut
                   3192: 
1.10      albertel 3193: sub get_student_view {
1.186     albertel 3194:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      3195:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 3196:   my (%form);
1.10      albertel 3197:   my @elements=('symb','courseid','domain','username');
                   3198:   foreach my $element (@elements) {
1.186     albertel 3199:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 3200:   }
1.186     albertel 3201:   if (defined($moreenv)) {
                   3202:       %form=(%form,%{$moreenv});
                   3203:   }
1.236     albertel 3204:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 3205:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      3206:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 3207:   $userview=~s/\<body[^\>]*\>//gi;
                   3208:   $userview=~s/\<\/body\>//gi;
                   3209:   $userview=~s/\<html\>//gi;
                   3210:   $userview=~s/\<\/html\>//gi;
                   3211:   $userview=~s/\<head\>//gi;
                   3212:   $userview=~s/\<\/head\>//gi;
                   3213:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 3214:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      3215:   if (wantarray) {
                   3216:      return ($userview,$response);
                   3217:   } else {
                   3218:      return $userview;
                   3219:   }
                   3220: }
                   3221: 
                   3222: sub get_student_view_with_retries {
                   3223:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   3224: 
                   3225:     my $ok = 0;                 # True if we got a good response.
                   3226:     my $content;
                   3227:     my $response;
                   3228: 
                   3229:     # Try to get the student_view done. within the retries count:
                   3230:     
                   3231:     do {
                   3232:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   3233:          $ok      = $response->is_success;
                   3234:          if (!$ok) {
                   3235:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   3236:          }
                   3237:          $retries--;
                   3238:     } while (!$ok && ($retries > 0));
                   3239:     
                   3240:     if (!$ok) {
                   3241:        $content = '';          # On error return an empty content.
                   3242:     }
1.651     www      3243:     if (wantarray) {
                   3244:        return ($content, $response);
                   3245:     } else {
                   3246:        return $content;
                   3247:     }
1.11      albertel 3248: }
                   3249: 
1.112     bowersj2 3250: =pod
                   3251: 
1.648     raeburn  3252: =item * &get_student_answers() 
1.112     bowersj2 3253: 
                   3254: show a snapshot of how student was answering problem
                   3255: 
                   3256: =cut
                   3257: 
1.11      albertel 3258: sub get_student_answers {
1.100     sakharuk 3259:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      3260:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 3261:   my (%moreenv);
1.11      albertel 3262:   my @elements=('symb','courseid','domain','username');
                   3263:   foreach my $element (@elements) {
1.186     albertel 3264:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 3265:   }
1.186     albertel 3266:   $moreenv{'grade_target'}='answer';
                   3267:   %moreenv=(%form,%moreenv);
1.497     raeburn  3268:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   3269:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 3270:   return $userview;
1.1       albertel 3271: }
1.116     albertel 3272: 
                   3273: =pod
                   3274: 
                   3275: =item * &submlink()
                   3276: 
1.242     albertel 3277: Inputs: $text $uname $udom $symb $target
1.116     albertel 3278: 
                   3279: Returns: A link to grades.pm such as to see the SUBM view of a student
                   3280: 
                   3281: =cut
                   3282: 
                   3283: ###############################################
                   3284: sub submlink {
1.242     albertel 3285:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 3286:     if (!($uname && $udom)) {
                   3287: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 3288: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 3289: 	if (!$symb) { $symb=$cursymb; }
                   3290:     }
1.254     matthew  3291:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      3292:     $symb=&escape($symb);
1.242     albertel 3293:     if ($target) { $target="target=\"$target\""; }
                   3294:     return '<a href="/adm/grades?&command=submission&'.
                   3295: 	'symb='.$symb.'&student='.$uname.
                   3296: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
                   3297: }
                   3298: ##############################################
                   3299: 
                   3300: =pod
                   3301: 
                   3302: =item * &pgrdlink()
                   3303: 
                   3304: Inputs: $text $uname $udom $symb $target
                   3305: 
                   3306: Returns: A link to grades.pm such as to see the PGRD view of a student
                   3307: 
                   3308: =cut
                   3309: 
                   3310: ###############################################
                   3311: sub pgrdlink {
                   3312:     my $link=&submlink(@_);
                   3313:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   3314:     return $link;
                   3315: }
                   3316: ##############################################
                   3317: 
                   3318: =pod
                   3319: 
                   3320: =item * &pprmlink()
                   3321: 
                   3322: Inputs: $text $uname $udom $symb $target
                   3323: 
                   3324: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 3325: student and a specific resource
1.242     albertel 3326: 
                   3327: =cut
                   3328: 
                   3329: ###############################################
                   3330: sub pprmlink {
                   3331:     my ($text,$uname,$udom,$symb,$target)=@_;
                   3332:     if (!($uname && $udom)) {
                   3333: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 3334: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 3335: 	if (!$symb) { $symb=$cursymb; }
                   3336:     }
1.254     matthew  3337:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      3338:     $symb=&escape($symb);
1.242     albertel 3339:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 3340:     return '<a href="/adm/parmset?command=set&amp;'.
                   3341: 	'symb='.$symb.'&amp;uname='.$uname.
                   3342: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 3343: }
                   3344: ##############################################
1.37      matthew  3345: 
1.112     bowersj2 3346: =pod
                   3347: 
                   3348: =back
                   3349: 
                   3350: =cut
                   3351: 
1.37      matthew  3352: ###############################################
1.51      www      3353: 
                   3354: 
                   3355: sub timehash {
1.679.2.5  raeburn  3356:     my ($thistime) = @_;
                   3357:     my $timezone = &Apache::lonlocal::gettimezone();
                   3358:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   3359:                      ->set_time_zone($timezone);
                   3360:     my $wday = $dt->day_of_week();
                   3361:     if ($wday == 7) { $wday = 0; }
                   3362:     return ( 'second' => $dt->second(),
                   3363:              'minute' => $dt->minute(),
                   3364:              'hour'   => $dt->hour(),
                   3365:              'day'     => $dt->day_of_month(),
                   3366:              'month'   => $dt->month(),
                   3367:              'year'    => $dt->year(),
                   3368:              'weekday' => $wday,
                   3369:              'dayyear' => $dt->day_of_year(),
                   3370:              'dlsav'   => $dt->is_dst() );
1.51      www      3371: }
                   3372: 
1.370     www      3373: sub utc_string {
                   3374:     my ($date)=@_;
1.371     www      3375:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      3376: }
                   3377: 
1.51      www      3378: sub maketime {
                   3379:     my %th=@_;
1.679.2.5  raeburn  3380:     my ($epoch_time,$timezone,$dt);
                   3381:     $timezone = &Apache::lonlocal::gettimezone();
                   3382:     eval {
                   3383:         $dt = DateTime->new( year   => $th{'year'},
                   3384:                              month  => $th{'month'},
                   3385:                              day    => $th{'day'},
                   3386:                              hour   => $th{'hour'},
                   3387:                              minute => $th{'minute'},
                   3388:                              second => $th{'second'},
                   3389:                              time_zone => $timezone,
                   3390:                          );
                   3391:     };
                   3392:     if (!$@) {
                   3393:         $epoch_time = $dt->epoch;
                   3394:         if ($epoch_time) {
                   3395:             return $epoch_time;
                   3396:         }
                   3397:     }
1.51      www      3398:     return POSIX::mktime(
                   3399:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      3400:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      3401: }
                   3402: 
                   3403: #########################################
1.51      www      3404: 
                   3405: sub findallcourses {
1.482     raeburn  3406:     my ($roles,$uname,$udom) = @_;
1.355     albertel 3407:     my %roles;
                   3408:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 3409:     my %courses;
1.51      www      3410:     my $now=time;
1.482     raeburn  3411:     if (!defined($uname)) {
                   3412:         $uname = $env{'user.name'};
                   3413:     }
                   3414:     if (!defined($udom)) {
                   3415:         $udom = $env{'user.domain'};
                   3416:     }
                   3417:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   3418:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
                   3419:         if (!%roles) {
                   3420:             %roles = (
                   3421:                        cc => 1,
                   3422:                        in => 1,
                   3423:                        ep => 1,
                   3424:                        ta => 1,
                   3425:                        cr => 1,
                   3426:                        st => 1,
                   3427:              );
                   3428:         }
                   3429:         foreach my $entry (keys(%roleshash)) {
                   3430:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   3431:             if ($trole =~ /^cr/) { 
                   3432:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   3433:             } else {
                   3434:                 next if (!exists($roles{$trole}));
                   3435:             }
                   3436:             if ($tend) {
                   3437:                 next if ($tend < $now);
                   3438:             }
                   3439:             if ($tstart) {
                   3440:                 next if ($tstart > $now);
                   3441:             }
                   3442:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
                   3443:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
                   3444:             if ($secpart eq '') {
                   3445:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   3446:                 $sec = 'none';
                   3447:                 $realsec = '';
                   3448:             } else {
                   3449:                 $cnum = $cnumpart;
                   3450:                 ($sec,$role) = split(/_/,$secpart);
                   3451:                 $realsec = $sec;
1.490     raeburn  3452:             }
1.482     raeburn  3453:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
                   3454:         }
                   3455:     } else {
                   3456:         foreach my $key (keys(%env)) {
1.483     albertel 3457: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   3458:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  3459: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   3460: 	        next if ($role eq 'ca' || $role eq 'aa');
                   3461: 	        next if (%roles && !exists($roles{$role}));
                   3462: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   3463:                 my $active=1;
                   3464:                 if ($starttime) {
                   3465: 		    if ($now<$starttime) { $active=0; }
                   3466:                 }
                   3467:                 if ($endtime) {
                   3468:                     if ($now>$endtime) { $active=0; }
                   3469:                 }
                   3470:                 if ($active) {
                   3471:                     if ($sec eq '') {
                   3472:                         $sec = 'none';
                   3473:                     }
                   3474:                     $courses{$cdom.'_'.$cnum}{$sec} = 
                   3475:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
1.474     raeburn  3476:                 }
                   3477:             }
1.51      www      3478:         }
                   3479:     }
1.474     raeburn  3480:     return %courses;
1.51      www      3481: }
1.37      matthew  3482: 
1.54      www      3483: ###############################################
1.474     raeburn  3484: 
                   3485: sub blockcheck {
1.482     raeburn  3486:     my ($setters,$activity,$uname,$udom) = @_;
1.490     raeburn  3487: 
                   3488:     if (!defined($udom)) {
                   3489:         $udom = $env{'user.domain'};
                   3490:     }
                   3491:     if (!defined($uname)) {
                   3492:         $uname = $env{'user.name'};
                   3493:     }
                   3494: 
                   3495:     # If uname and udom are for a course, check for blocks in the course.
                   3496: 
                   3497:     if (&Apache::lonnet::is_course($udom,$uname)) {
                   3498:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
1.502     raeburn  3499:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
1.490     raeburn  3500:         return ($startblock,$endblock);
                   3501:     }
1.474     raeburn  3502: 
1.502     raeburn  3503:     my $startblock = 0;
                   3504:     my $endblock = 0;
1.482     raeburn  3505:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  3506: 
1.490     raeburn  3507:     # If uname is for a user, and activity is course-specific, i.e.,
                   3508:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  3509: 
1.490     raeburn  3510:     if (($activity eq 'boards' || $activity eq 'chat' ||
                   3511:          $activity eq 'groups') && ($env{'request.course.id'})) {
                   3512:         foreach my $key (keys(%live_courses)) {
                   3513:             if ($key ne $env{'request.course.id'}) {
                   3514:                 delete($live_courses{$key});
                   3515:             }
                   3516:         }
                   3517:     }
                   3518: 
                   3519:     my $otheruser = 0;
                   3520:     my %own_courses;
                   3521:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   3522:         # Resource belongs to user other than current user.
                   3523:         $otheruser = 1;
                   3524:         # Gather courses for current user
                   3525:         %own_courses = 
                   3526:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   3527:     }
                   3528: 
                   3529:     # Gather active course roles - course coordinator, instructor, 
                   3530:     # exam proctor, ta, student, or custom role.
1.474     raeburn  3531: 
                   3532:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  3533:         my ($cdom,$cnum);
                   3534:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   3535:             $cdom = $env{'course.'.$course.'.domain'};
                   3536:             $cnum = $env{'course.'.$course.'.num'};
                   3537:         } else {
1.490     raeburn  3538:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  3539:         }
                   3540:         my $no_ownblock = 0;
                   3541:         my $no_userblock = 0;
1.533     raeburn  3542:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  3543:             # Check if current user has 'evb' priv for this
                   3544:             if (defined($own_courses{$course})) {
                   3545:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   3546:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   3547:                     if ($sec ne 'none') {
                   3548:                         $checkrole .= '/'.$sec;
                   3549:                     }
                   3550:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   3551:                         $no_ownblock = 1;
                   3552:                         last;
                   3553:                     }
                   3554:                 }
                   3555:             }
                   3556:             # if they have 'evb' priv and are currently not playing student
                   3557:             next if (($no_ownblock) &&
                   3558:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   3559:         }
1.474     raeburn  3560:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  3561:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  3562:             if ($sec ne 'none') {
1.482     raeburn  3563:                 $checkrole .= '/'.$sec;
1.474     raeburn  3564:             }
1.490     raeburn  3565:             if ($otheruser) {
                   3566:                 # Resource belongs to user other than current user.
                   3567:                 # Assemble privs for that user, and check for 'evb' priv.
1.482     raeburn  3568:                 my ($trole,$tdom,$tnum,$tsec);
                   3569:                 my $entry = $live_courses{$course}{$sec};
                   3570:                 if ($entry =~ /^cr/) {
                   3571:                     ($trole,$tdom,$tnum,$tsec) = 
                   3572:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   3573:                 } else {
                   3574:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   3575:                 }
                   3576:                 my ($spec,$area,$trest,%allroles,%userroles);
                   3577:                 $area = '/'.$tdom.'/'.$tnum;
                   3578:                 $trest = $tnum;
                   3579:                 if ($tsec ne '') {
                   3580:                     $area .= '/'.$tsec;
                   3581:                     $trest .= '/'.$tsec;
                   3582:                 }
                   3583:                 $spec = $trole.'.'.$area;
                   3584:                 if ($trole =~ /^cr/) {
                   3585:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   3586:                                                       $tdom,$spec,$trest,$area);
                   3587:                 } else {
                   3588:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   3589:                                                        $tdom,$spec,$trest,$area);
                   3590:                 }
                   3591:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.486     raeburn  3592:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   3593:                     if ($1) {
                   3594:                         $no_userblock = 1;
                   3595:                         last;
                   3596:                     }
                   3597:                 }
1.490     raeburn  3598:             } else {
                   3599:                 # Resource belongs to current user
                   3600:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  3601:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   3602:                     $no_ownblock = 1;
                   3603:                     last;
                   3604:                 }
1.474     raeburn  3605:             }
                   3606:         }
                   3607:         # if they have the evb priv and are currently not playing student
1.482     raeburn  3608:         next if (($no_ownblock) &&
1.491     albertel 3609:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  3610:         next if ($no_userblock);
1.474     raeburn  3611: 
1.490     raeburn  3612:         # Retrieve blocking times and identity of blocker for course
                   3613:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  3614:         
                   3615:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
                   3616:         if (($start != 0) && 
                   3617:             (($startblock == 0) || ($startblock > $start))) {
                   3618:             $startblock = $start;
                   3619:         }
                   3620:         if (($end != 0)  &&
                   3621:             (($endblock == 0) || ($endblock < $end))) {
                   3622:             $endblock = $end;
                   3623:         }
1.490     raeburn  3624:     }
                   3625:     return ($startblock,$endblock);
                   3626: }
                   3627: 
                   3628: sub get_blocks {
                   3629:     my ($setters,$activity,$cdom,$cnum) = @_;
                   3630:     my $startblock = 0;
                   3631:     my $endblock = 0;
                   3632:     my $course = $cdom.'_'.$cnum;
                   3633:     $setters->{$course} = {};
                   3634:     $setters->{$course}{'staff'} = [];
                   3635:     $setters->{$course}{'times'} = [];
                   3636:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   3637:     foreach my $record (keys(%records)) {
                   3638:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
                   3639:         if ($start <= time && $end >= time) {
                   3640:             my ($staff_name,$staff_dom,$title,$blocks) =
                   3641:                 &parse_block_record($records{$record});
                   3642:             if ($blocks->{$activity} eq 'on') {
                   3643:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   3644:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
1.491     albertel 3645:                 if ( ($startblock == 0) || ($startblock > $start) ) {
                   3646:                     $startblock = $start;
1.490     raeburn  3647:                 }
1.491     albertel 3648:                 if ( ($endblock == 0) || ($endblock < $end) ) {
                   3649:                     $endblock = $end;
1.474     raeburn  3650:                 }
                   3651:             }
                   3652:         }
                   3653:     }
                   3654:     return ($startblock,$endblock);
                   3655: }
                   3656: 
                   3657: sub parse_block_record {
                   3658:     my ($record) = @_;
                   3659:     my ($setuname,$setudom,$title,$blocks);
                   3660:     if (ref($record) eq 'HASH') {
                   3661:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   3662:         $title = &unescape($record->{'event'});
                   3663:         $blocks = $record->{'blocks'};
                   3664:     } else {
                   3665:         my @data = split(/:/,$record,3);
                   3666:         if (scalar(@data) eq 2) {
                   3667:             $title = $data[1];
                   3668:             ($setuname,$setudom) = split(/@/,$data[0]);
                   3669:         } else {
                   3670:             ($setuname,$setudom,$title) = @data;
                   3671:         }
                   3672:         $blocks = { 'com' => 'on' };
                   3673:     }
                   3674:     return ($setuname,$setudom,$title,$blocks);
                   3675: }
                   3676: 
                   3677: sub build_block_table {
                   3678:     my ($startblock,$endblock,$setters) = @_;
                   3679:     my %lt = &Apache::lonlocal::texthash(
                   3680:         'cacb' => 'Currently active communication blocks',
                   3681:         'cour' => 'Course',
                   3682:         'dura' => 'Duration',
                   3683:         'blse' => 'Block set by'
                   3684:     );
                   3685:     my $output;
1.476     raeburn  3686:     $output = '<br />'.$lt{'cacb'}.':<br />';
1.474     raeburn  3687:     $output .= &start_data_table();
                   3688:     $output .= '
                   3689: <tr>
                   3690:  <th>'.$lt{'cour'}.'</th>
                   3691:  <th>'.$lt{'dura'}.'</th>
                   3692:  <th>'.$lt{'blse'}.'</th>
                   3693: </tr>
                   3694: ';
                   3695:     foreach my $course (keys(%{$setters})) {
                   3696:         my %courseinfo=&Apache::lonnet::coursedescription($course);
                   3697:         for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
                   3698:             my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
1.490     raeburn  3699:             my $fullname = &plainname($uname,$udom);
                   3700:             if (defined($env{'user.name'}) && defined($env{'user.domain'})
                   3701:                 && $env{'user.name'} ne 'public' 
                   3702:                 && $env{'user.domain'} ne 'public') {
                   3703:                 $fullname = &aboutmewrapper($fullname,$uname,$udom);
                   3704:             }
1.474     raeburn  3705:             my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
                   3706:             $openblock = &Apache::lonlocal::locallocaltime($openblock);
                   3707:             $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
                   3708:             $output .= &Apache::loncommon::start_data_table_row().
                   3709:                        '<td>'.$courseinfo{'description'}.'</td>'.
                   3710:                        '<td>'.$openblock.' to '.$closeblock.'</td>'.
1.490     raeburn  3711:                        '<td>'.$fullname.'</td>'.
1.474     raeburn  3712:                         &Apache::loncommon::end_data_table_row();
                   3713:         }
                   3714:     }
                   3715:     $output .= &end_data_table();
                   3716: }
                   3717: 
1.490     raeburn  3718: sub blocking_status {
                   3719:     my ($activity,$uname,$udom) = @_;
                   3720:     my %setters;
                   3721:     my ($blocked,$output,$ownitem,$is_course);
                   3722:     my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
                   3723:     if ($startblock && $endblock) {
                   3724:         $blocked = 1;
                   3725:         if (wantarray) {
                   3726:             my $category;
                   3727:             if ($activity eq 'boards') {
                   3728:                 $category = 'Discussion posts in this course';
                   3729:             } elsif ($activity eq 'blogs') {
                   3730:                 $category = 'Blogs';
                   3731:             } elsif ($activity eq 'port') {
                   3732:                 if (defined($uname) && defined($udom)) {
                   3733:                     if ($uname eq $env{'user.name'} &&
                   3734:                         $udom eq $env{'user.domain'}) {
                   3735:                         $ownitem = 1;
                   3736:                     }
                   3737:                 }
                   3738:                 $is_course = &Apache::lonnet::is_course($udom,$uname);
                   3739:                 if ($ownitem) { 
                   3740:                     $category = 'Your portfolio files';  
                   3741:                 } elsif ($is_course) {
                   3742:                     my $coursedesc;
                   3743:                     foreach my $course (keys(%setters)) {
                   3744:                         my %courseinfo =
                   3745:                              &Apache::lonnet::coursedescription($course);
                   3746:                         $coursedesc = $courseinfo{'description'};
                   3747:                     }
                   3748:                     $category = "Group files in the course '$coursedesc'";
                   3749:                 } else {
                   3750:                     $category = 'Portfolio files belonging to ';
                   3751:                     if ($env{'user.name'} eq 'public' && 
                   3752:                         $env{'user.domain'} eq 'public') {
                   3753:                         $category .= &plainname($uname,$udom);
                   3754:                     } else {
                   3755:                         $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);  
                   3756:                     }
                   3757:                 }
                   3758:             } elsif ($activity eq 'groups') {
                   3759:                 $category = 'Groups in this course';
                   3760:             }
                   3761:             my $showstart = &Apache::lonlocal::locallocaltime($startblock);
                   3762:             my $showend = &Apache::lonlocal::locallocaltime($endblock);
                   3763:             $output = '<br />'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'<br />';
                   3764:             if (!($activity eq 'port' && !($ownitem) && !($is_course))) { 
                   3765:                 $output .= &build_block_table($startblock,$endblock,\%setters);
                   3766:             }
                   3767:         }
                   3768:     }
                   3769:     if (wantarray) {
                   3770:         return ($blocked,$output);
                   3771:     } else {
                   3772:         return $blocked;
                   3773:     }
                   3774: }
                   3775: 
1.60      matthew  3776: ###############################################
                   3777: 
1.679.2.1  raeburn  3778: sub check_ip_acc {
                   3779:     my ($acc)=@_;
                   3780:     &Apache::lonxml::debug("acc is $acc");
                   3781:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   3782:         return 1;
                   3783:     }
                   3784:     my $allowed=0;
                   3785:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
                   3786: 
                   3787:     my $name;
                   3788:     foreach my $pattern (split(',',$acc)) {
                   3789:         $pattern =~ s/^\s*//;
                   3790:         $pattern =~ s/\s*$//;
                   3791:         if ($pattern =~ /\*$/) {
                   3792:             #35.8.*
                   3793:             $pattern=~s/\*//;
                   3794:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   3795:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   3796:             #35.8.3.[34-56]
                   3797:             my $low=$2;
                   3798:             my $high=$3;
                   3799:             $pattern=$1;
                   3800:             if ($ip =~ /^\Q$pattern\E/) {
                   3801:                 my $last=(split(/\./,$ip))[3];
                   3802:                 if ($last <=$high && $last >=$low) { $allowed=1; }
                   3803:             }
                   3804:         } elsif ($pattern =~ /^\*/) {
                   3805:             #*.msu.edu
                   3806:             $pattern=~s/\*//;
                   3807:             if (!defined($name)) {
                   3808:                 use Socket;
                   3809:                 my $netaddr=inet_aton($ip);
                   3810:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   3811:             }
                   3812:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   3813:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   3814:             #127.0.0.1
                   3815:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   3816:         } else {
                   3817:             #some.name.com
                   3818:             if (!defined($name)) {
                   3819:                 use Socket;
                   3820:                 my $netaddr=inet_aton($ip);
                   3821:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   3822:             }
                   3823:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   3824:         }
                   3825:         if ($allowed) { last; }
                   3826:     }
                   3827:     return $allowed;
                   3828: }
                   3829: 
                   3830: ###############################################
                   3831: 
1.60      matthew  3832: =pod
                   3833: 
1.112     bowersj2 3834: =head1 Domain Template Functions
                   3835: 
                   3836: =over 4
                   3837: 
                   3838: =item * &determinedomain()
1.60      matthew  3839: 
                   3840: Inputs: $domain (usually will be undef)
                   3841: 
1.63      www      3842: Returns: Determines which domain should be used for designs
1.60      matthew  3843: 
                   3844: =cut
1.54      www      3845: 
1.60      matthew  3846: ###############################################
1.63      www      3847: sub determinedomain {
                   3848:     my $domain=shift;
1.531     albertel 3849:     if (! $domain) {
1.60      matthew  3850:         # Determine domain if we have not been given one
                   3851:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
1.258     albertel 3852:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   3853:         if ($env{'request.role.domain'}) { 
                   3854:             $domain=$env{'request.role.domain'}; 
1.60      matthew  3855:         }
                   3856:     }
1.63      www      3857:     return $domain;
                   3858: }
                   3859: ###############################################
1.517     raeburn  3860: 
1.518     albertel 3861: sub devalidate_domconfig_cache {
                   3862:     my ($udom)=@_;
                   3863:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   3864: }
                   3865: 
                   3866: # ---------------------- Get domain configuration for a domain
                   3867: sub get_domainconf {
                   3868:     my ($udom) = @_;
                   3869:     my $cachetime=1800;
                   3870:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   3871:     if (defined($cached)) { return %{$result}; }
                   3872: 
                   3873:     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   3874: 					     ['login','rolecolors'],$udom);
1.632     raeburn  3875:     my (%designhash,%legacy);
1.518     albertel 3876:     if (keys(%domconfig) > 0) {
                   3877:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  3878:             if (keys(%{$domconfig{'login'}})) {
                   3879:                 foreach my $key (keys(%{$domconfig{'login'}})) {
                   3880:                     $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   3881:                 }
                   3882:             } else {
                   3883:                 $legacy{'login'} = 1;
1.518     albertel 3884:             }
1.632     raeburn  3885:         } else {
                   3886:             $legacy{'login'} = 1;
1.518     albertel 3887:         }
                   3888:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  3889:             if (keys(%{$domconfig{'rolecolors'}})) {
                   3890:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   3891:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   3892:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   3893:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   3894:                         }
1.518     albertel 3895:                     }
                   3896:                 }
1.632     raeburn  3897:             } else {
                   3898:                 $legacy{'rolecolors'} = 1;
1.518     albertel 3899:             }
1.632     raeburn  3900:         } else {
                   3901:             $legacy{'rolecolors'} = 1;
1.518     albertel 3902:         }
1.632     raeburn  3903:         if (keys(%legacy) > 0) {
                   3904:             my %legacyhash = &get_legacy_domconf($udom);
                   3905:             foreach my $item (keys(%legacyhash)) {
                   3906:                 if ($item =~ /^\Q$udom\E\.login/) {
                   3907:                     if ($legacy{'login'}) { 
                   3908:                         $designhash{$item} = $legacyhash{$item};
                   3909:                     }
                   3910:                 } else {
                   3911:                     if ($legacy{'rolecolors'}) {
                   3912:                         $designhash{$item} = $legacyhash{$item};
                   3913:                     }
1.518     albertel 3914:                 }
                   3915:             }
                   3916:         }
1.632     raeburn  3917:     } else {
                   3918:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 3919:     }
                   3920:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   3921: 				  $cachetime);
                   3922:     return %designhash;
                   3923: }
                   3924: 
1.632     raeburn  3925: sub get_legacy_domconf {
                   3926:     my ($udom) = @_;
                   3927:     my %legacyhash;
                   3928:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   3929:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   3930:     if (-e $designfile) {
                   3931:         if ( open (my $fh,"<$designfile") ) {
                   3932:             while (my $line = <$fh>) {
                   3933:                 next if ($line =~ /^\#/);
                   3934:                 chomp($line);
                   3935:                 my ($key,$val)=(split(/\=/,$line));
                   3936:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   3937:             }
                   3938:             close($fh);
                   3939:         }
                   3940:     }
                   3941:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
                   3942:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   3943:     }
                   3944:     return %legacyhash;
                   3945: }
                   3946: 
1.63      www      3947: =pod
                   3948: 
1.112     bowersj2 3949: =item * &domainlogo()
1.63      www      3950: 
                   3951: Inputs: $domain (usually will be undef)
                   3952: 
                   3953: Returns: A link to a domain logo, if the domain logo exists.
                   3954: If the domain logo does not exist, a description of the domain.
                   3955: 
                   3956: =cut
1.112     bowersj2 3957: 
1.63      www      3958: ###############################################
                   3959: sub domainlogo {
1.517     raeburn  3960:     my $domain = &determinedomain(shift);
1.518     albertel 3961:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  3962:     # See if there is a logo
                   3963:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  3964:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 3965:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   3966: 	    if ($imgsrc =~ m{^/res/}) {
                   3967: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   3968: 		&Apache::lonnet::repcopy($local_name);
                   3969: 	    }
                   3970: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  3971:         } 
                   3972:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 3973:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   3974:         return &Apache::lonnet::domain($domain,'description');
1.59      www      3975:     } else {
1.60      matthew  3976:         return '';
1.59      www      3977:     }
                   3978: }
1.63      www      3979: ##############################################
                   3980: 
                   3981: =pod
                   3982: 
1.112     bowersj2 3983: =item * &designparm()
1.63      www      3984: 
                   3985: Inputs: $which parameter; $domain (usually will be undef)
                   3986: 
                   3987: Returns: value of designparamter $which
                   3988: 
                   3989: =cut
1.112     bowersj2 3990: 
1.397     albertel 3991: 
1.400     albertel 3992: ##############################################
1.397     albertel 3993: sub designparm {
                   3994:     my ($which,$domain)=@_;
1.258     albertel 3995:     if ($env{'browser.blackwhite'} eq 'on') {
1.635     raeburn  3996: 	if ($which=~/\.(font|alink|vlink|link|textcol)$/) {
1.110     www      3997: 	    return '#000000';
                   3998: 	}
1.635     raeburn  3999: 	if ($which=~/\.(pgbg|sidebg|bgcol)$/) {
1.110     www      4000: 	    return '#FFFFFF';
                   4001: 	}
                   4002: 	if ($which=~/\.tabbg$/) {
                   4003: 	    return '#CCCCCC';
                   4004: 	}
                   4005:     }
1.397     albertel 4006:     if (exists($env{'environment.color.'.$which})) {
1.258     albertel 4007: 	return $env{'environment.color.'.$which};
1.96      www      4008:     }
1.63      www      4009:     $domain=&determinedomain($domain);
1.518     albertel 4010:     my %domdesign = &get_domainconf($domain);
1.520     raeburn  4011:     my $output;
1.517     raeburn  4012:     if ($domdesign{$domain.'.'.$which} ne '') {
1.520     raeburn  4013: 	$output = $domdesign{$domain.'.'.$which};
1.63      www      4014:     } else {
1.520     raeburn  4015:         $output = $defaultdesign{$which};
                   4016:     }
                   4017:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  4018:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 4019:         if ($output =~ m{^/(adm|res)/}) {
                   4020: 	    if ($output =~ m{^/res/}) {
                   4021: 		my $local_name = &Apache::lonnet::filelocation('',$output);
                   4022: 		&Apache::lonnet::repcopy($local_name);
                   4023: 	    }
1.520     raeburn  4024:             $output = &lonhttpdurl($output);
                   4025:         }
1.63      www      4026:     }
1.520     raeburn  4027:     return $output;
1.63      www      4028: }
1.59      www      4029: 
1.60      matthew  4030: ###############################################
                   4031: ###############################################
                   4032: 
                   4033: =pod
                   4034: 
1.112     bowersj2 4035: =back
                   4036: 
1.549     albertel 4037: =head1 HTML Helpers
1.112     bowersj2 4038: 
                   4039: =over 4
                   4040: 
                   4041: =item * &bodytag()
1.60      matthew  4042: 
                   4043: Returns a uniform header for LON-CAPA web pages.
                   4044: 
                   4045: Inputs: 
                   4046: 
1.112     bowersj2 4047: =over 4
                   4048: 
                   4049: =item * $title, A title to be displayed on the page.
                   4050: 
                   4051: =item * $function, the current role (can be undef).
                   4052: 
                   4053: =item * $addentries, extra parameters for the <body> tag.
                   4054: 
                   4055: =item * $bodyonly, if defined, only return the <body> tag.
                   4056: 
                   4057: =item * $domain, if defined, force a given domain.
                   4058: 
                   4059: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      4060:             text interface only)
1.60      matthew  4061: 
1.326     albertel 4062: =item * $customtitle, alternate text to use instead of $title
                   4063:                       in the title box that appears, this text
                   4064:                       is not auto translated like the $title is
1.309     albertel 4065: 
                   4066: =item * $notopbar, if true, keep the 'what is this' info but remove the
                   4067:                    navigational links
1.317     albertel 4068: 
1.338     albertel 4069: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   4070: 
                   4071: =item * $notitle, if true keep the nav controls, but remove the title bar
                   4072: 
1.361     albertel 4073: =item * $no_inline_link, if true and in remote mode, don't show the 
                   4074:          'Switch To Inline Menu' link
                   4075: 
1.460     albertel 4076: =item * $args, optional argument valid values are
                   4077:             no_auto_mt_title -> prevents &mt()ing the title arg
1.562     albertel 4078:             inherit_jsmath -> when creating popup window in a page,
                   4079:                               should it have jsmath forced on by the
                   4080:                               current page
1.460     albertel 4081: 
1.112     bowersj2 4082: =back
                   4083: 
1.60      matthew  4084: Returns: A uniform header for LON-CAPA web pages.  
                   4085: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   4086: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   4087: other decorations will be returned.
                   4088: 
                   4089: =cut
                   4090: 
1.54      www      4091: sub bodytag {
1.309     albertel 4092:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
1.460     albertel 4093: 	$notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
1.339     albertel 4094: 
1.460     albertel 4095:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.339     albertel 4096: 
1.183     matthew  4097:     $function = &get_users_function() if (!$function);
1.339     albertel 4098:     my $img =    &designparm($function.'.img',$domain);
                   4099:     my $font =   &designparm($function.'.font',$domain);
                   4100:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   4101: 
                   4102:     my %design = ( 'style'   => 'margin-top: 0px',
1.535     albertel 4103: 		   'bgcolor' => $pgbg,
1.339     albertel 4104: 		   'text'    => $font,
                   4105:                    'alink'   => &designparm($function.'.alink',$domain),
                   4106: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   4107: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 4108:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 4109: 
1.63      www      4110:  # role and realm
1.378     raeburn  4111:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
                   4112:     if ($role  eq 'ca') {
1.479     albertel 4113:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 4114:         $realm = &plainname($rname,$rdom);
1.378     raeburn  4115:     } 
1.55      www      4116: # realm
1.258     albertel 4117:     if ($env{'request.course.id'}) {
1.378     raeburn  4118:         if ($env{'request.role'} !~ /^cr/) {
                   4119:             $role = &Apache::lonnet::plaintext($role,&course_type());
                   4120:         }
1.359     albertel 4121: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  4122:     } else {
                   4123:         $role = &Apache::lonnet::plaintext($role);
1.54      www      4124:     }
1.433     albertel 4125: 
1.359     albertel 4126:     if (!$realm) { $realm='&nbsp;'; }
1.55      www      4127: # Set messages
1.60      matthew  4128:     my $messages=&domainlogo($domain);
1.330     albertel 4129: 
1.438     albertel 4130:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 4131: 
1.101     www      4132: # construct main body tag
1.359     albertel 4133:     my $bodytag = "<body $extra_body_attr>".
1.562     albertel 4134: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
1.252     albertel 4135: 
1.530     albertel 4136:     if ($bodyonly) {
1.60      matthew  4137:         return $bodytag;
1.258     albertel 4138:     } elsif ($env{'browser.interface'} eq 'textual') {
1.95      www      4139: # Accessibility
1.224     raeburn  4140:           
1.337     albertel 4141: 	$bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
1.338     albertel 4142: 	if (!$notitle) {
1.337     albertel 4143: 	    $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
                   4144: 	}
                   4145: 	return $bodytag;
1.359     albertel 4146:     }
                   4147: 
1.410     albertel 4148:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
1.433     albertel 4149:     if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4150: 	undef($role);
1.434     albertel 4151:     } else {
                   4152: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
1.433     albertel 4153:     }
1.359     albertel 4154:     
                   4155:     my $roleinfo=(<<ENDROLE);
                   4156: <td class="LC_title_bar_who">
                   4157: <div class="LC_title_bar_name">
1.410     albertel 4158:     $name
1.361     albertel 4159:     &nbsp;
1.359     albertel 4160: </div>
                   4161: <div class="LC_title_bar_role">
1.361     albertel 4162: $role&nbsp;
1.359     albertel 4163: </div>
                   4164: <div class="LC_title_bar_realm">
1.361     albertel 4165: $realm&nbsp;
1.359     albertel 4166: </div>
1.206     albertel 4167: </td>
                   4168: ENDROLE
1.235     raeburn  4169: 
1.359     albertel 4170:     my $titleinfo = '<span class="LC_title_bar_title">'.$title.'</span>';
                   4171:     if ($customtitle) {
                   4172:         $titleinfo = $customtitle;
                   4173:     }
                   4174:     #
                   4175:     # Extra info if you are the DC
                   4176:     my $dc_info = '';
                   4177:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   4178:                         $env{'course.'.$env{'request.course.id'}.
                   4179:                                  '.domain'}.'/'})) {
                   4180:         my $cid = $env{'request.course.id'};
                   4181:         $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      4182:         $dc_info =~ s/\s+$//;
1.359     albertel 4183:         $dc_info = '('.$dc_info.')';
                   4184:     }
                   4185: 
1.644     www      4186:     if (($env{'environment.remote'} eq 'off') || ($args->{'suppress_header_logos'})) {
1.359     albertel 4187:         # No Remote
1.258     albertel 4188: 	if ($env{'request.state'} eq 'construct') {
1.359     albertel 4189: 	    $forcereg=1;
                   4190: 	}
                   4191: 
                   4192: 	if (!$customtitle && $env{'request.state'} eq 'construct') {
                   4193: 	    # this is for resources; directories have customtitle, and crumbs
                   4194:             # and select recent are created in lonpubdir.pm  
1.229     albertel 4195: 	    my ($uname,$thisdisfn)=
1.258     albertel 4196: 		($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
1.229     albertel 4197: 	    my $formaction='/priv/'.$uname.'/'.$thisdisfn;
                   4198: 	    $formaction=~s/\/+/\//g;
                   4199: 
1.359     albertel 4200: 	    my $parentpath = '';
                   4201: 	    my $lastitem = '';
                   4202: 	    if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   4203: 		$parentpath = $1;
                   4204: 		$lastitem = $2;
                   4205: 	    } else {
                   4206: 		$lastitem = $thisdisfn;
                   4207: 	    }
                   4208: 	    $titleinfo = 
1.640     bisitz   4209: 		&Apache::loncommon::help_open_menu('','',3,'Authoring')
                   4210: 		.'<b>'.&mt('Construction Space').'</b>:&nbsp;'
                   4211: 		.'<form name="dirs" method="post" action="'.$formaction
1.359     albertel 4212: 		.'" target="_top"><tt><b>'
                   4213: 		.&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<font size=\"+1\">$lastitem</font></b></tt><br />"
                   4214: 		.&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   4215: 		.'</form>'
                   4216: 		.&Apache::lonmenu::constspaceform();
1.235     raeburn  4217:         }
1.359     albertel 4218: 
1.337     albertel 4219:         my $titletable;
1.338     albertel 4220: 	if (!$notitle) {
1.337     albertel 4221: 	    $titletable =
1.359     albertel 4222: 		'<table id="LC_title_bar">'.
                   4223:                          "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
                   4224: 			 '</tr></table>';
1.337     albertel 4225: 	}
1.359     albertel 4226: 	if ($notopbar) {
                   4227: 	    $bodytag .= $titletable;
                   4228: 	} else {
                   4229: 	    if ($env{'request.state'} eq 'construct') {
1.337     albertel 4230:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
                   4231: 							  $titletable);
1.272     raeburn  4232:             } else {
1.336     albertel 4233:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
1.359     albertel 4234: 		    $titletable;
1.272     raeburn  4235:             }
1.235     raeburn  4236:         }
                   4237:         return $bodytag;
1.94      www      4238:     }
1.95      www      4239: 
1.93      www      4240: #
1.95      www      4241: # Top frame rendering, Remote is up
1.93      www      4242: #
1.359     albertel 4243: 
1.517     raeburn  4244:     my $imgsrc = $img;
                   4245:     if ($img =~ /^\/adm/) {
1.575     albertel 4246:         $imgsrc = &lonhttpdurl($img);
1.517     raeburn  4247:     }
                   4248:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
1.359     albertel 4249: 
1.305     www      4250:     # Explicit link to get inline menu
1.361     albertel 4251:     my $menu= ($no_inline_link?''
                   4252: 	       :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
1.245     matthew  4253:     #
1.338     albertel 4254:     if ($notitle) {
1.337     albertel 4255: 	return $bodytag;
                   4256:     }
1.94      www      4257:     return(<<ENDBODY);
1.60      matthew  4258: $bodytag
1.359     albertel 4259: <table id="LC_title_bar" class="LC_with_remote">
1.368     albertel 4260: <tr><td class="LC_title_bar_role_logo">$upperleft</td>
1.359     albertel 4261:     <td class="LC_title_bar_domain_logo">$messages&nbsp;</td>
1.54      www      4262: </tr>
1.359     albertel 4263: <tr><td>$titleinfo $dc_info $menu</td>
                   4264: $roleinfo
1.368     albertel 4265: </tr>
1.356     albertel 4266: </table>
1.54      www      4267: ENDBODY
1.182     matthew  4268: }
                   4269: 
1.330     albertel 4270: sub make_attr_string {
                   4271:     my ($register,$attr_ref) = @_;
                   4272: 
                   4273:     if ($attr_ref && !ref($attr_ref)) {
                   4274: 	die("addentries Must be a hash ref ".
                   4275: 	    join(':',caller(1))." ".
                   4276: 	    join(':',caller(0))." ");
                   4277:     }
                   4278: 
                   4279:     if ($register) {
1.339     albertel 4280: 	my ($on_load,$on_unload);
                   4281: 	foreach my $key (keys(%{$attr_ref})) {
                   4282: 	    if      (lc($key) eq 'onload') {
                   4283: 		$on_load.=$attr_ref->{$key}.';';
                   4284: 		delete($attr_ref->{$key});
                   4285: 
                   4286: 	    } elsif (lc($key) eq 'onunload') {
                   4287: 		$on_unload.=$attr_ref->{$key}.';';
                   4288: 		delete($attr_ref->{$key});
                   4289: 	    }
                   4290: 	}
                   4291: 	$attr_ref->{'onload'}  =
                   4292: 	    &Apache::lonmenu::loadevents().  $on_load;
                   4293: 	$attr_ref->{'onunload'}=
                   4294: 	    &Apache::lonmenu::unloadevents().$on_unload;
                   4295:     }
                   4296: 
                   4297: # Accessibility font enhance
                   4298:     if ($env{'browser.fontenhance'} eq 'on') {
                   4299: 	my $style;
                   4300: 	foreach my $key (keys(%{$attr_ref})) {
                   4301: 	    if (lc($key) eq 'style') {
                   4302: 		$style.=$attr_ref->{$key}.';';
                   4303: 		delete($attr_ref->{$key});
                   4304: 	    }
                   4305: 	}
                   4306: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
1.330     albertel 4307:     }
1.339     albertel 4308: 
                   4309:     if ($env{'browser.blackwhite'} eq 'on') {
                   4310: 	delete($attr_ref->{'font'});
                   4311: 	delete($attr_ref->{'link'});
                   4312: 	delete($attr_ref->{'alink'});
                   4313: 	delete($attr_ref->{'vlink'});
                   4314: 	delete($attr_ref->{'bgcolor'});
                   4315: 	delete($attr_ref->{'background'});
                   4316:     }
                   4317: 
1.330     albertel 4318:     my $attr_string;
                   4319:     foreach my $attr (keys(%$attr_ref)) {
                   4320: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   4321:     }
                   4322:     return $attr_string;
                   4323: }
                   4324: 
                   4325: 
1.182     matthew  4326: ###############################################
1.251     albertel 4327: ###############################################
                   4328: 
                   4329: =pod
                   4330: 
                   4331: =item * &endbodytag()
                   4332: 
                   4333: Returns a uniform footer for LON-CAPA web pages.
                   4334: 
1.635     raeburn  4335: Inputs: 1 - optional reference to an args hash
                   4336: If in the hash, key for noredirectlink has a value which evaluates to true,
                   4337: a 'Continue' link is not displayed if the page contains an
                   4338: internal redirect in the <head></head> section,
                   4339: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 4340: 
                   4341: =cut
                   4342: 
                   4343: sub endbodytag {
1.635     raeburn  4344:     my ($args) = @_;
1.251     albertel 4345:     my $endbodytag='</body>';
1.269     albertel 4346:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
1.315     albertel 4347:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  4348:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   4349: 	    $endbodytag=
                   4350: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   4351: 	        &mt('Continue').'</a>'.
                   4352: 	        $endbodytag;
                   4353:         }
1.315     albertel 4354:     }
1.251     albertel 4355:     return $endbodytag;
                   4356: }
                   4357: 
1.352     albertel 4358: =pod
                   4359: 
                   4360: =item * &standard_css()
                   4361: 
                   4362: Returns a style sheet
                   4363: 
                   4364: Inputs: (all optional)
                   4365:             domain         -> force to color decorate a page for a specific
                   4366:                                domain
                   4367:             function       -> force usage of a specific rolish color scheme
                   4368:             bgcolor        -> override the default page bgcolor
                   4369: 
                   4370: =cut
                   4371: 
1.343     albertel 4372: sub standard_css {
1.345     albertel 4373:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 4374:     $function  = &get_users_function() if (!$function);
                   4375:     my $img    = &designparm($function.'.img',   $domain);
                   4376:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   4377:     my $font   = &designparm($function.'.font',  $domain);
1.345     albertel 4378:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 4379:     my $pgbg_or_bgcolor =
                   4380: 	         $bgcolor ||
1.352     albertel 4381: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 4382:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 4383:     my $alink  = &designparm($function.'.alink', $domain);
                   4384:     my $vlink  = &designparm($function.'.vlink', $domain);
                   4385:     my $link   = &designparm($function.'.link',  $domain);
                   4386: 
1.602     albertel 4387:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 4388:     my $mono                 = 'monospace';
1.352     albertel 4389:     my $data_table_head      = $tabbg;
                   4390:     my $data_table_light     = '#EEEEEE';
1.470     banghart 4391:     my $data_table_dark      = '#DDDDDD';
                   4392:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 4393:     my $data_table_highlight = '#FFFF00';
1.352     albertel 4394:     my $mail_new             = '#FFBB77';
                   4395:     my $mail_new_hover       = '#DD9955';
                   4396:     my $mail_read            = '#BBBB77';
                   4397:     my $mail_read_hover      = '#999944';
                   4398:     my $mail_replied         = '#AAAA88';
                   4399:     my $mail_replied_hover   = '#888855';
                   4400:     my $mail_other           = '#99BBBB';
                   4401:     my $mail_other_hover     = '#669999';
1.391     albertel 4402:     my $table_header         = '#DDDDDD';
1.489     raeburn  4403:     my $feedback_link_bg     = '#BBBBBB';
1.392     albertel 4404: 
1.608     albertel 4405:     my $border = ($env{'browser.type'} eq 'explorer' ||
                   4406: 		  $env{'browser.type'} eq 'safari'     ) ? '0px 2px 0px 2px'
                   4407: 	                                                 : '0px 3px 0px 4px';
1.448     albertel 4408: 
1.523     albertel 4409: 
1.343     albertel 4410:     return <<END;
1.345     albertel 4411: h1, h2, h3, th { font-family: $sans }
1.343     albertel 4412: a:focus { color: red; background: yellow } 
1.510     albertel 4413: table.thinborder,
1.523     albertel 4414: 
1.510     albertel 4415: table.thinborder tr th {
                   4416:   border-style: solid;
                   4417:   border-width: 1px;
                   4418:   background: $tabbg;
                   4419: }
1.523     albertel 4420: table.thinborder tr td {
1.510     albertel 4421:   border-style: solid;
                   4422:   border-width: 1px
                   4423: }
1.426     albertel 4424: 
1.343     albertel 4425: form, .inline { display: inline; }
                   4426: .center { text-align: center; }
1.593     albertel 4427: .LC_filename {font-family: $mono; white-space:pre;}
1.350     albertel 4428: .LC_error {
                   4429:   color: red;
                   4430:   font-size: larger;
                   4431: }
1.457     albertel 4432: .LC_warning,
                   4433: .LC_diff_removed {
1.394     albertel 4434:   color: red;
                   4435: }
1.532     albertel 4436: 
                   4437: .LC_info,
1.457     albertel 4438: .LC_success,
                   4439: .LC_diff_added {
1.350     albertel 4440:   color: green;
                   4441: }
1.543     albertel 4442: .LC_unknown {
                   4443:   color: yellow;
                   4444: }
                   4445: 
1.440     albertel 4446: .LC_icon {
                   4447:   border: 0px;
                   4448: }
1.539     albertel 4449: .LC_indexer_icon {
                   4450:   border: 0px;
                   4451:   height: 22px;
                   4452: }
1.543     albertel 4453: .LC_docs_spacer {
                   4454:   width: 25px;
                   4455:   height: 1px;
                   4456:   border: 0px;
                   4457: }
1.346     albertel 4458: 
1.532     albertel 4459: .LC_internal_info {
                   4460:   color: #999;
                   4461: }
                   4462: 
1.458     albertel 4463: table.LC_pastsubmission {
                   4464:   border: 1px solid black;
                   4465:   margin: 2px;
                   4466: }
                   4467: 
1.606     albertel 4468: table#LC_top_nav, table#LC_menubuttons,table#LC_nav_location {
1.345     albertel 4469:   width: 100%;
                   4470:   background: $pgbg;
1.392     albertel 4471:   border: 2px;
1.402     albertel 4472:   border-collapse: separate;
1.403     albertel 4473:   padding: 0px;
1.345     albertel 4474: }
1.392     albertel 4475: 
1.606     albertel 4476: table#LC_title_bar, table.LC_breadcrumbs, 
1.393     albertel 4477: table#LC_title_bar.LC_with_remote {
1.359     albertel 4478:   width: 100%;
1.392     albertel 4479:   border-color: $pgbg;
                   4480:   border-style: solid;
                   4481:   border-width: $border;
                   4482: 
1.379     albertel 4483:   background: $pgbg;
                   4484:   font-family: $sans;
1.392     albertel 4485:   border-collapse: collapse;
1.403     albertel 4486:   padding: 0px;
1.359     albertel 4487: }
1.392     albertel 4488: 
1.409     albertel 4489: table.LC_docs_path {
                   4490:   width: 100%;
                   4491:   border: 0;
                   4492:   background: $pgbg;
                   4493:   font-family: $sans;
                   4494:   border-collapse: collapse;
                   4495:   padding: 0px;
                   4496: }
                   4497: 
1.359     albertel 4498: table#LC_title_bar td {
                   4499:   background: $tabbg;
                   4500: }
                   4501: table#LC_title_bar td.LC_title_bar_who {
                   4502:   background: $tabbg;
                   4503:   color: $font;
1.427     albertel 4504:   font: small $sans;
1.359     albertel 4505:   text-align: right;
                   4506: }
1.469     banghart 4507: span.LC_metadata {
                   4508:     font-family: $sans;
                   4509: }
1.359     albertel 4510: span.LC_title_bar_title {
1.416     albertel 4511:   font: bold x-large $sans;
1.359     albertel 4512: }
                   4513: table#LC_title_bar td.LC_title_bar_domain_logo {
                   4514:   background: $sidebg;
                   4515:   text-align: right;
1.368     albertel 4516:   padding: 0px;
                   4517: }
                   4518: table#LC_title_bar td.LC_title_bar_role_logo {
                   4519:   background: $sidebg;
                   4520:   padding: 0px;
1.359     albertel 4521: }
                   4522: 
1.346     albertel 4523: table#LC_menubuttons_mainmenu {
1.526     www      4524:   width: 100%;
1.346     albertel 4525:   border: 0px;
                   4526:   border-spacing: 1px;
1.372     albertel 4527:   padding: 0px 1px;
1.346     albertel 4528:   margin: 0px;
                   4529:   border-collapse: separate;
                   4530: }
                   4531: table#LC_menubuttons img, table#LC_menubuttons_mainmenu img {
                   4532:   border: 0px;
                   4533: }
1.345     albertel 4534: table#LC_top_nav td {
                   4535:   background: $tabbg;
1.392     albertel 4536:   border: 0px;
1.407     albertel 4537:   font-size: small;
1.345     albertel 4538: }
                   4539: table#LC_top_nav td a, div#LC_top_nav a {
                   4540:   color: $font;
                   4541:   font-family: $sans;
                   4542: }
1.364     albertel 4543: table#LC_top_nav td.LC_top_nav_logo {
                   4544:   background: $tabbg;
1.432     albertel 4545:   text-align: left;
1.408     albertel 4546:   white-space: nowrap;
1.432     albertel 4547:   width: 31px;
1.408     albertel 4548: }
                   4549: table#LC_top_nav td.LC_top_nav_logo img {
1.432     albertel 4550:   border: 0px;
1.408     albertel 4551:   vertical-align: bottom;
1.364     albertel 4552: }
1.432     albertel 4553: table#LC_top_nav td.LC_top_nav_exit,
                   4554: table#LC_top_nav td.LC_top_nav_help {
                   4555:   width: 2.0em;
                   4556: }
1.442     albertel 4557: table#LC_top_nav td.LC_top_nav_login {
                   4558:   width: 4.0em;
                   4559:   text-align: center;
                   4560: }
1.409     albertel 4561: table.LC_breadcrumbs td, table.LC_docs_path td  {
1.357     albertel 4562:   background: $tabbg;
                   4563:   color: $font;
                   4564:   font-family: $sans;
1.358     albertel 4565:   font-size: smaller;
1.357     albertel 4566: }
1.411     albertel 4567: table.LC_breadcrumbs td.LC_breadcrumbs_component,
1.409     albertel 4568: table.LC_docs_path td.LC_docs_path_component {
1.357     albertel 4569:   background: $tabbg;
                   4570:   color: $font;
                   4571:   font-family: $sans;
                   4572:   font-size: larger;
                   4573:   text-align: right;
                   4574: }
1.383     albertel 4575: td.LC_table_cell_checkbox {
                   4576:   text-align: center;
                   4577: }
                   4578: 
1.522     albertel 4579: table#LC_mainmenu td.LC_mainmenu_column {
                   4580:     vertical-align: top;
                   4581: }
                   4582: 
1.346     albertel 4583: .LC_menubuttons_inline_text {
                   4584:   color: $font;
                   4585:   font-family: $sans;
                   4586:   font-size: smaller;
                   4587: }
                   4588: 
1.526     www      4589: .LC_menubuttons_link {
                   4590:   text-decoration: none;
                   4591: }
                   4592: 
1.522     albertel 4593: .LC_menubuttons_category {
1.521     www      4594:   color: $font;
1.526     www      4595:   background: $pgbg;
1.521     www      4596:   font-family: $sans;
                   4597:   font-size: larger;
                   4598:   font-weight: bold;
                   4599: }
                   4600: 
1.346     albertel 4601: td.LC_menubuttons_text {
1.526     www      4602:   width: 90%;
1.346     albertel 4603:   color: $font;
                   4604:   font-family: $sans;
                   4605: }
1.526     www      4606: 
1.346     albertel 4607: td.LC_menubuttons_img {
                   4608: }
1.526     www      4609: 
1.346     albertel 4610: .LC_current_location {
                   4611:   font-family: $sans;
                   4612:   background: $tabbg;
                   4613: }
                   4614: .LC_new_mail {
                   4615:   font-family: $sans;
1.634     www      4616:   background: $tabbg;
1.346     albertel 4617:   font-weight: bold;
                   4618: }
1.347     albertel 4619: 
1.526     www      4620: .LC_rolesmenu_is {
                   4621:   font-family: $sans;
                   4622: }
                   4623: 
                   4624: .LC_rolesmenu_selected {
                   4625:   font-family: $sans;
                   4626: }
                   4627: 
                   4628: .LC_rolesmenu_future {
                   4629:   font-family: $sans;
                   4630: }
                   4631: 
                   4632: 
                   4633: .LC_rolesmenu_will {
                   4634:   font-family: $sans;
                   4635: }
                   4636: 
                   4637: .LC_rolesmenu_will_not {
                   4638:   font-family: $sans;
                   4639: }
                   4640: 
                   4641: .LC_rolesmenu_expired {
                   4642:   font-family: $sans;
                   4643: }
                   4644: 
                   4645: .LC_rolesinfo {
                   4646:   font-family: $sans;
                   4647: }
                   4648: 
1.527     www      4649: .LC_dropadd_labeltext {
                   4650:   font-family: $sans;
                   4651:   text-align: right;
                   4652: }
                   4653: 
                   4654: .LC_preferences_labeltext {
                   4655:   font-family: $sans;
                   4656:   text-align: right;
                   4657: }
                   4658: 
1.666     raeburn  4659: .LC_roleslog_note {
                   4660:   font-size: smaller;
                   4661: }
                   4662: 
1.440     albertel 4663: table.LC_aboutme_port {
                   4664:   border: 0px;
                   4665:   border-collapse: collapse;
                   4666:   border-spacing: 0px;
                   4667: }
1.349     albertel 4668: table.LC_data_table, table.LC_mail_list {
1.347     albertel 4669:   border: 1px solid #000000;
1.402     albertel 4670:   border-collapse: separate;
1.426     albertel 4671:   border-spacing: 1px;
1.610     albertel 4672:   background: $pgbg;
1.347     albertel 4673: }
1.422     albertel 4674: .LC_data_table_dense {
                   4675:   font-size: small;
                   4676: }
1.507     raeburn  4677: table.LC_nested_outer {
                   4678:   border: 1px solid #000000;
1.589     raeburn  4679:   border-collapse: collapse;
1.507     raeburn  4680:   border-spacing: 0px;
                   4681:   width: 100%;
                   4682: }
                   4683: table.LC_nested {
                   4684:   border: 0px;
1.589     raeburn  4685:   border-collapse: collapse;
1.507     raeburn  4686:   border-spacing: 0px;
                   4687:   width: 100%;
                   4688: }
1.523     albertel 4689: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th,
                   4690: table.LC_prior_tries tr th {
1.349     albertel 4691:   font-weight: bold;
                   4692:   background-color: $data_table_head;
1.421     albertel 4693:   font-size: smaller;
1.347     albertel 4694: }
1.610     albertel 4695: table.LC_data_table tr.LC_odd_row > td, 
1.440     albertel 4696: table.LC_aboutme_port tr td {
1.349     albertel 4697:   background-color: $data_table_light;
1.425     albertel 4698:   padding: 2px;
1.347     albertel 4699: }
1.610     albertel 4700: table.LC_data_table tr.LC_even_row > td,
1.440     albertel 4701: table.LC_aboutme_port tr.LC_even_row td {
1.349     albertel 4702:   background-color: $data_table_dark;
1.347     albertel 4703: }
1.425     albertel 4704: table.LC_data_table tr.LC_data_table_highlight td {
                   4705:   background-color: $data_table_darker;
                   4706: }
1.639     raeburn  4707: table.LC_data_table tr td.LC_leftcol_header {
                   4708:   background-color: $data_table_head;
                   4709:   font-weight: bold;
                   4710: }
1.451     albertel 4711: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  4712: table.LC_nested tr.LC_empty_row td {
1.347     albertel 4713:   background-color: #FFFFFF;
1.421     albertel 4714:   font-weight: bold;
                   4715:   font-style: italic;
                   4716:   text-align: center;
                   4717:   padding: 8px;
1.347     albertel 4718: }
1.507     raeburn  4719: table.LC_nested tr.LC_empty_row td {
1.465     albertel 4720:   padding: 4ex
                   4721: }
1.507     raeburn  4722: table.LC_nested_outer tr th {
                   4723:   font-weight: bold;
                   4724:   background-color: $data_table_head;
                   4725:   font-size: smaller;
                   4726:   border-bottom: 1px solid #000000;
                   4727: }
                   4728: table.LC_nested_outer tr td.LC_subheader {
                   4729:   background-color: $data_table_head;
                   4730:   font-weight: bold;
                   4731:   font-size: small;
                   4732:   border-bottom: 1px solid #000000;
                   4733:   text-align: right;
1.451     albertel 4734: }
1.507     raeburn  4735: table.LC_nested tr.LC_info_row td {
1.451     albertel 4736:   background-color: #CCC;
                   4737:   font-weight: bold;
                   4738:   font-size: small;
1.507     raeburn  4739:   text-align: center;
                   4740: }
1.589     raeburn  4741: table.LC_nested tr.LC_info_row td.LC_left_item,
                   4742: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  4743:   text-align: left;
1.451     albertel 4744: }
1.507     raeburn  4745: table.LC_nested td {
1.451     albertel 4746:   background-color: #FFF;
                   4747:   font-size: small;
1.507     raeburn  4748: }
                   4749: table.LC_nested_outer tr th.LC_right_item,
                   4750: table.LC_nested tr.LC_info_row td.LC_right_item,
                   4751: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   4752: table.LC_nested tr td.LC_right_item {
1.451     albertel 4753:   text-align: right;
                   4754: }
                   4755: 
1.507     raeburn  4756: table.LC_nested tr.LC_odd_row td {
1.451     albertel 4757:   background-color: #EEE;
                   4758: }
                   4759: 
1.473     raeburn  4760: table.LC_createuser {
                   4761: }
                   4762: 
                   4763: table.LC_createuser tr.LC_section_row td {
                   4764:   font-size: smaller;
                   4765: }
                   4766: 
                   4767: table.LC_createuser tr.LC_info_row td  {
                   4768:   background-color: #CCC;
                   4769:   font-weight: bold;
                   4770:   text-align: center;
                   4771: }
                   4772: 
1.349     albertel 4773: table.LC_calendar {
                   4774:   border: 1px solid #000000;
                   4775:   border-collapse: collapse;
                   4776: }
                   4777: table.LC_calendar_pickdate {
                   4778:   font-size: xx-small;
                   4779: }
                   4780: table.LC_calendar tr td {
                   4781:   border: 1px solid #000000;
                   4782:   vertical-align: top;
                   4783: }
                   4784: table.LC_calendar tr td.LC_calendar_day_empty {
                   4785:   background-color: $data_table_dark;
                   4786: }
                   4787: table.LC_calendar tr td.LC_calendar_day_current {
                   4788:   background-color: $data_table_highlight;
                   4789: }
                   4790: 
                   4791: table.LC_mail_list tr.LC_mail_new {
                   4792:   background-color: $mail_new;
                   4793: }
                   4794: table.LC_mail_list tr.LC_mail_new:hover {
                   4795:   background-color: $mail_new_hover;
                   4796: }
                   4797: table.LC_mail_list tr.LC_mail_read {
                   4798:   background-color: $mail_read;
                   4799: }
                   4800: table.LC_mail_list tr.LC_mail_read:hover {
                   4801:   background-color: $mail_read_hover;
                   4802: }
                   4803: table.LC_mail_list tr.LC_mail_replied {
                   4804:   background-color: $mail_replied;
                   4805: }
                   4806: table.LC_mail_list tr.LC_mail_replied:hover {
                   4807:   background-color: $mail_replied_hover;
                   4808: }
                   4809: table.LC_mail_list tr.LC_mail_other {
                   4810:   background-color: $mail_other;
                   4811: }
                   4812: table.LC_mail_list tr.LC_mail_other:hover {
                   4813:   background-color: $mail_other_hover;
                   4814: }
1.494     raeburn  4815: table.LC_mail_list tr.LC_mail_even {
                   4816: }
                   4817: table.LC_mail_list tr.LC_mail_odd {
                   4818: }
                   4819: 
1.385     albertel 4820: 
1.386     albertel 4821: table#LC_portfolio_actions {
                   4822:   width: auto;
                   4823:   background: $pgbg;
                   4824:   border: 0px;
                   4825:   border-spacing: 2px 2px;
                   4826:   padding: 0px;
                   4827:   margin: 0px;
                   4828:   border-collapse: separate;
                   4829: }
                   4830: table#LC_portfolio_actions td.LC_label {
                   4831:   background: $tabbg;
                   4832:   text-align: right;
                   4833: }
                   4834: table#LC_portfolio_actions td.LC_value {
                   4835:   background: $tabbg;
                   4836: }
1.385     albertel 4837: 
1.391     albertel 4838: table#LC_cstr_controls {
                   4839:   width: 100%;
                   4840:   border-collapse: collapse;
                   4841: }
                   4842: table#LC_cstr_controls tr td {
                   4843:   border: 4px solid $pgbg;
                   4844:   padding: 4px;
                   4845:   text-align: center;
                   4846:   background: $tabbg;
                   4847: }
                   4848: table#LC_cstr_controls tr th {
                   4849:   border: 4px solid $pgbg;
                   4850:   background: $table_header;
                   4851:   text-align: center;
                   4852:   font-family: $sans;
                   4853:   font-size: smaller;
                   4854: }
                   4855: 
1.389     albertel 4856: table#LC_browser {
                   4857:  
                   4858: }
                   4859: table#LC_browser tr th {
1.391     albertel 4860:   background: $table_header;
1.389     albertel 4861: }
1.390     albertel 4862: table#LC_browser tr td {
                   4863:   padding: 2px;
                   4864: }
1.389     albertel 4865: table#LC_browser tr.LC_browser_file,
                   4866: table#LC_browser tr.LC_browser_file_published {
                   4867:   background: #CCFF88;
                   4868: }
                   4869: table#LC_browser tr.LC_browser_file_locked,
                   4870: table#LC_browser tr.LC_browser_file_unpublished {
                   4871:   background: #FFAA99;
1.387     albertel 4872: }
1.389     albertel 4873: table#LC_browser tr.LC_browser_file_obsolete {
                   4874:   background: #AAAAAA;
1.387     albertel 4875: }
1.455     albertel 4876: table#LC_browser tr.LC_browser_file_modified,
                   4877: table#LC_browser tr.LC_browser_file_metamodified {
1.389     albertel 4878:   background: #FFFF77;
1.387     albertel 4879: }
1.389     albertel 4880: table#LC_browser tr.LC_browser_folder {
                   4881:   background: #CCCCFF;
1.387     albertel 4882: }
1.388     albertel 4883: span.LC_current_location {
                   4884:   font-size: x-large;
                   4885:   background: $pgbg;
                   4886: }
1.387     albertel 4887: 
1.395     albertel 4888: span.LC_parm_menu_item {
                   4889:   font-size: larger;
                   4890:   font-family: $sans;
                   4891: }
                   4892: span.LC_parm_scope_all {
                   4893:   color: red;
                   4894: }
                   4895: span.LC_parm_scope_folder {
                   4896:   color: green;
                   4897: }
                   4898: span.LC_parm_scope_resource {
                   4899:   color: orange;
                   4900: }
                   4901: span.LC_parm_part {
                   4902:   color: blue;
                   4903: }
                   4904: span.LC_parm_folder, span.LC_parm_symb {
                   4905:   font-size: x-small;
                   4906:   font-family: $mono;
                   4907:   color: #AAAAAA;
                   4908: }
                   4909: 
1.396     albertel 4910: td.LC_parm_overview_level_menu, td.LC_parm_overview_map_menu,
                   4911: td.LC_parm_overview_parm_selectors, td.LC_parm_overview_parm_restrictions {
                   4912:   border: 1px solid black;
                   4913:   border-collapse: collapse;
                   4914: }
                   4915: table.LC_parm_overview_restrictions td {
                   4916:   border-width: 1px 4px 1px 4px;
                   4917:   border-style: solid;
                   4918:   border-color: $pgbg;
                   4919:   text-align: center;
                   4920: }
                   4921: table.LC_parm_overview_restrictions th {
                   4922:   background: $tabbg;
                   4923:   border-width: 1px 4px 1px 4px;
                   4924:   border-style: solid;
                   4925:   border-color: $pgbg;
                   4926: }
1.398     albertel 4927: table#LC_helpmenu {
                   4928:   border: 0px;
                   4929:   height: 55px;
                   4930:   border-spacing: 0px;
                   4931: }
                   4932: 
                   4933: table#LC_helpmenu fieldset legend {
                   4934:   font-size: larger;
                   4935:   font-weight: bold;
                   4936: }
1.397     albertel 4937: table#LC_helpmenu_links {
                   4938:   width: 100%;
                   4939:   border: 1px solid black;
                   4940:   background: $pgbg;
                   4941:   padding: 0px;
                   4942:   border-spacing: 1px;
                   4943: }
                   4944: table#LC_helpmenu_links tr td {
                   4945:   padding: 1px;
                   4946:   background: $tabbg;
1.399     albertel 4947:   text-align: center;
                   4948:   font-weight: bold;
1.397     albertel 4949: }
1.396     albertel 4950: 
1.397     albertel 4951: table#LC_helpmenu_links a:link, table#LC_helpmenu_links a:visited,
                   4952: table#LC_helpmenu_links a:active {
                   4953:   text-decoration: none;
                   4954:   color: $font;
                   4955: }
                   4956: table#LC_helpmenu_links a:hover {
                   4957:   text-decoration: underline;
                   4958:   color: $vlink;
                   4959: }
1.396     albertel 4960: 
1.417     albertel 4961: .LC_chrt_popup_exists {
                   4962:   border: 1px solid #339933;
                   4963:   margin: -1px;
                   4964: }
                   4965: .LC_chrt_popup_up {
                   4966:   border: 1px solid yellow;
                   4967:   margin: -1px;
                   4968: }
                   4969: .LC_chrt_popup {
                   4970:   border: 1px solid #8888FF;
                   4971:   background: #CCCCFF;
                   4972: }
1.421     albertel 4973: table.LC_pick_box {
                   4974:   border-collapse: separate;
                   4975:   background: white;
                   4976:   border: 1px solid black;
                   4977:   border-spacing: 1px;
                   4978: }
                   4979: table.LC_pick_box td.LC_pick_box_title {
                   4980:   background: $tabbg;
                   4981:   font-weight: bold;
                   4982:   text-align: right;
                   4983:   width: 184px;
                   4984:   padding: 8px;
                   4985: }
1.645     raeburn  4986: table.LC_pick_box td.LC_selfenroll_pick_box_title {
                   4987:   background: $tabbg;
                   4988:   font-weight: bold;
                   4989:   text-align: right;
                   4990:   width: 350px;
                   4991:   padding: 8px;
                   4992: }
                   4993: 
1.579     raeburn  4994: table.LC_pick_box td.LC_pick_box_value {
                   4995:   text-align: left;
                   4996:   padding: 8px;
                   4997: }
                   4998: table.LC_pick_box td.LC_pick_box_select {
                   4999:   text-align: left;
                   5000:   padding: 8px;
                   5001: }
1.424     albertel 5002: table.LC_pick_box td.LC_pick_box_separator {
1.421     albertel 5003:   padding: 0px;
                   5004:   height: 1px;
                   5005:   background: black;
                   5006: }
                   5007: table.LC_pick_box td.LC_pick_box_submit {
                   5008:   text-align: right;
                   5009: }
1.579     raeburn  5010: table.LC_pick_box td.LC_evenrow_value {
                   5011:   text-align: left;
                   5012:   padding: 8px;
                   5013:   background-color: $data_table_light;
                   5014: }
                   5015: table.LC_pick_box td.LC_oddrow_value {
                   5016:   text-align: left;
                   5017:   padding: 8px;
                   5018:   background-color: $data_table_light;
                   5019: }
                   5020: table.LC_helpform_receipt {
                   5021:   width: 620px;
                   5022:   border-collapse: separate;
                   5023:   background: white;
                   5024:   border: 1px solid black;
                   5025:   border-spacing: 1px;
                   5026: }
                   5027: table.LC_helpform_receipt td.LC_pick_box_title {
                   5028:   background: $tabbg;
                   5029:   font-weight: bold;
                   5030:   text-align: right;
                   5031:   width: 184px;
                   5032:   padding: 8px;
                   5033: }
                   5034: table.LC_helpform_receipt td.LC_evenrow_value {
                   5035:   text-align: left;
                   5036:   padding: 8px;
                   5037:   background-color: $data_table_light;
                   5038: }
                   5039: table.LC_helpform_receipt td.LC_oddrow_value {
                   5040:   text-align: left;
                   5041:   padding: 8px;
                   5042:   background-color: $data_table_light;
                   5043: }
                   5044: table.LC_helpform_receipt td.LC_pick_box_separator {
                   5045:   padding: 0px;
                   5046:   height: 1px;
                   5047:   background: black;
                   5048: }
                   5049: span.LC_helpform_receipt_cat {
                   5050:   font-weight: bold;
                   5051: }
1.424     albertel 5052: table.LC_group_priv_box {
                   5053:   background: white;
                   5054:   border: 1px solid black;
                   5055:   border-spacing: 1px;
                   5056: }
                   5057: table.LC_group_priv_box td.LC_pick_box_title {
                   5058:   background: $tabbg;
                   5059:   font-weight: bold;
                   5060:   text-align: right;
                   5061:   width: 184px;
                   5062: }
                   5063: table.LC_group_priv_box td.LC_groups_fixed {
                   5064:   background: $data_table_light;
                   5065:   text-align: center;
                   5066: }
                   5067: table.LC_group_priv_box td.LC_groups_optional {
                   5068:   background: $data_table_dark;
                   5069:   text-align: center;
                   5070: }
                   5071: table.LC_group_priv_box td.LC_groups_functionality {
                   5072:   background: $data_table_darker;
                   5073:   text-align: center;
                   5074:   font-weight: bold;
                   5075: }
                   5076: table.LC_group_priv td {
                   5077:   text-align: left;
                   5078:   padding: 0px;
                   5079: }
                   5080: 
1.421     albertel 5081: table.LC_notify_front_page {
                   5082:   background: white;
                   5083:   border: 1px solid black;
                   5084:   padding: 8px;
                   5085: }
                   5086: table.LC_notify_front_page td {
                   5087:   padding: 8px;
                   5088: }
1.424     albertel 5089: .LC_navbuttons {
                   5090:   margin: 2ex 0ex 2ex 0ex;
                   5091: }
1.423     albertel 5092: .LC_topic_bar {
                   5093:   font-family: $sans;
                   5094:   font-weight: bold;
                   5095:   width: 100%;
                   5096:   background: $tabbg;
                   5097:   vertical-align: middle;
                   5098:   margin: 2ex 0ex 2ex 0ex;
                   5099: }
                   5100: .LC_topic_bar span {
                   5101:   vertical-align: middle;
                   5102: }
                   5103: .LC_topic_bar img {
                   5104:   vertical-align: bottom;
                   5105: }
                   5106: table.LC_course_group_status {
                   5107:   margin: 20px;
                   5108: }
                   5109: table.LC_status_selector td {
                   5110:   vertical-align: top;
                   5111:   text-align: center;
1.424     albertel 5112:   padding: 4px;
                   5113: }
                   5114: table.LC_descriptive_input td.LC_description {
                   5115:   vertical-align: top;
                   5116:   text-align: right;
                   5117:   font-weight: bold;
1.423     albertel 5118: }
1.599     albertel 5119: div.LC_feedback_link {
1.616     albertel 5120:   clear: both;
1.599     albertel 5121:   background: white;
                   5122:   width: 100%;  
1.489     raeburn  5123: }
                   5124: span.LC_feedback_link {
1.599     albertel 5125:   background: $feedback_link_bg;
                   5126:   font-size: larger;
                   5127: }
                   5128: span.LC_message_link {
                   5129:   background: $feedback_link_bg;
                   5130:   font-size: larger;
                   5131:   position: absolute;
                   5132:   right: 1em;
1.489     raeburn  5133: }
1.421     albertel 5134: 
1.515     albertel 5135: table.LC_prior_tries {
1.524     albertel 5136:   border: 1px solid #000000;
                   5137:   border-collapse: separate;
                   5138:   border-spacing: 1px;
1.515     albertel 5139: }
1.523     albertel 5140: 
1.515     albertel 5141: table.LC_prior_tries td {
1.524     albertel 5142:   padding: 2px;
1.515     albertel 5143: }
1.523     albertel 5144: 
                   5145: .LC_answer_correct {
                   5146:   background: #AAFFAA;
                   5147:   color: black;
                   5148: }
                   5149: .LC_answer_charged_try {
                   5150:   background: #FFAAAA ! important;
                   5151:   color: black;
                   5152: }
                   5153: .LC_answer_not_charged_try, 
                   5154: .LC_answer_no_grade,
                   5155: .LC_answer_late {
                   5156:   background: #FFFFAA;
                   5157:   color: black;
                   5158: }
                   5159: .LC_answer_previous {
                   5160:   background: #AAAAFF;
                   5161:   color: black;
                   5162: }
                   5163: .LC_answer_no_message {
                   5164:   background: #FFFFFF;
                   5165:   color: black;
                   5166: }
                   5167: .LC_answer_unknown {
                   5168:   background: orange;
                   5169:   color: black;
                   5170: }
                   5171: 
                   5172: 
1.529     albertel 5173: span.LC_prior_numerical,
                   5174: span.LC_prior_string,
                   5175: span.LC_prior_custom,
                   5176: span.LC_prior_reaction,
                   5177: span.LC_prior_math {
1.523     albertel 5178:   font-family: monospace;
                   5179:   white-space: pre;
                   5180: }
                   5181: 
1.525     albertel 5182: span.LC_prior_string {
                   5183:   font-family: monospace;
                   5184:   white-space: pre;
                   5185: }
                   5186: 
1.523     albertel 5187: table.LC_prior_option {
                   5188:   width: 100%;
                   5189:   border-collapse: collapse;
                   5190: }
1.528     albertel 5191: table.LC_prior_rank, table.LC_prior_match {
                   5192:   border-collapse: collapse;
                   5193: }
                   5194: table.LC_prior_option tr td,
                   5195: table.LC_prior_rank tr td,
                   5196: table.LC_prior_match tr td {
1.524     albertel 5197:   border: 1px solid #000000;
1.515     albertel 5198: }
                   5199: 
1.519     raeburn  5200: span.LC_nobreak {
1.544     albertel 5201:   white-space: nowrap;
1.519     raeburn  5202: }
                   5203: 
1.576     raeburn  5204: span.LC_cusr_emph {
                   5205:   font-style: italic;
                   5206: }
                   5207: 
1.633     raeburn  5208: span.LC_cusr_subheading {
                   5209:   font-weight: normal;
                   5210:   font-size: 85%;
                   5211: }
                   5212: 
1.545     albertel 5213: table.LC_docs_documents {
                   5214:   background: #BBBBBB;
1.547     albertel 5215:   border-width: 0px;
1.545     albertel 5216:   border-collapse: collapse;
                   5217: }
                   5218: 
                   5219: table.LC_docs_documents td.LC_docs_document {
                   5220:   border: 2px solid black;
                   5221:   padding: 4px;
                   5222: }
                   5223: 
                   5224: .LC_docs_course_commands div {
                   5225:   float: left;
                   5226:   border: 4px solid #AAAAAA;
                   5227:   padding: 4px;
                   5228:   background: #DDDDCC;
                   5229: }
                   5230: 
                   5231: .LC_docs_entry_move {
                   5232:   border: 0px;
                   5233:   border-collapse: collapse;
1.544     albertel 5234: }
                   5235: 
1.545     albertel 5236: .LC_docs_entry_move td {
                   5237:   border: 2px solid #BBBBBB;
                   5238:   background: #DDDDDD;
                   5239: }
                   5240: 
                   5241: .LC_docs_editor td.LC_docs_entry_commands {
                   5242:   background: #DDDDDD;
                   5243:   font-size: x-small;
                   5244: }
1.544     albertel 5245: .LC_docs_copy {
1.545     albertel 5246:   color: #000099;
1.544     albertel 5247: }
                   5248: .LC_docs_cut {
1.545     albertel 5249:   color: #550044;
1.544     albertel 5250: }
                   5251: .LC_docs_rename {
1.545     albertel 5252:   color: #009900;
1.544     albertel 5253: }
                   5254: .LC_docs_remove {
1.545     albertel 5255:   color: #990000;
                   5256: }
                   5257: 
1.547     albertel 5258: .LC_docs_reinit_warn,
                   5259: .LC_docs_ext_edit {
                   5260:   font-size: x-small;
                   5261: }
                   5262: 
1.545     albertel 5263: .LC_docs_editor td.LC_docs_entry_title,
                   5264: .LC_docs_editor td.LC_docs_entry_icon {
                   5265:   background: #FFFFBB;
                   5266: }
                   5267: .LC_docs_editor td.LC_docs_entry_parameter {
                   5268:   background: #BBBBFF;
                   5269:   font-size: x-small;
                   5270:   white-space: nowrap;
                   5271: }
                   5272: 
                   5273: table.LC_docs_adddocs td,
                   5274: table.LC_docs_adddocs th {
                   5275:   border: 1px solid #BBBBBB;
                   5276:   padding: 4px;
                   5277:   background: #DDDDDD;
1.543     albertel 5278: }
                   5279: 
1.584     albertel 5280: table.LC_sty_begin {
                   5281:   background: #BBFFBB;
                   5282: }
                   5283: table.LC_sty_end {
                   5284:   background: #FFBBBB;
                   5285: }
                   5286: 
1.589     raeburn  5287: table.LC_double_column {
                   5288:   border-width: 0px;
                   5289:   border-collapse: collapse;
                   5290:   width: 100%;
                   5291:   padding: 2px;
                   5292: }
                   5293: 
                   5294: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  5295:   top: 2px;
1.589     raeburn  5296:   left: 2px;
                   5297:   width: 47%;
                   5298:   vertical-align: top;
                   5299: }
                   5300: 
                   5301: table.LC_double_column tr td.LC_right_col {
                   5302:   top: 2px;
                   5303:   right: 2px; 
                   5304:   width: 47%;
                   5305:   vertical-align: top;
                   5306: }
                   5307: 
1.594     raeburn  5308: span.LC_role_level {
                   5309:   font-weight: bold;
                   5310: }
                   5311: 
1.591     raeburn  5312: div.LC_left_float {
                   5313:   float: left;
                   5314:   padding-right: 5%;
1.597     albertel 5315:   padding-bottom: 4px;
1.591     raeburn  5316: }
                   5317: 
                   5318: div.LC_clear_float_header {
1.597     albertel 5319:   padding-bottom: 2px;
1.591     raeburn  5320: }
                   5321: 
                   5322: div.LC_clear_float_footer {
1.597     albertel 5323:   padding-top: 10px;
1.591     raeburn  5324:   clear: both;
                   5325: }
                   5326: 
1.597     albertel 5327: 
1.601     albertel 5328: div.LC_grade_select_mode {
1.604     albertel 5329:   font-family: $sans;
1.601     albertel 5330: }
                   5331: div.LC_grade_select_mode div div {
                   5332:   margin: 5px;
                   5333: }
                   5334: div.LC_grade_select_mode_selector {
                   5335:   margin: 5px;
                   5336:   float: left;
                   5337: }
                   5338: div.LC_grade_select_mode_selector_header {
                   5339:   font: bold medium $sans;
                   5340: }
                   5341: div.LC_grade_select_mode_type {
                   5342:   clear: left;
                   5343: }
                   5344: 
1.597     albertel 5345: div.LC_grade_show_user {
                   5346:   margin-top: 20px;
                   5347:   border: 1px solid black;
                   5348: }
                   5349: div.LC_grade_user_name {
                   5350:   background: #DDDDEE;
                   5351:   border-bottom: 1px solid black;
                   5352:   font: bold large $sans;
                   5353: }
                   5354: div.LC_grade_show_user_odd_row div.LC_grade_user_name {
                   5355:   background: #DDEEDD;
                   5356: }
                   5357: 
                   5358: div.LC_grade_show_problem,
                   5359: div.LC_grade_submissions,
                   5360: div.LC_grade_message_center,
                   5361: div.LC_grade_info_links,
                   5362: div.LC_grade_assign {
                   5363:   margin: 5px;
                   5364:   width: 99%;
                   5365:   background: #FFFFFF;
                   5366: }
                   5367: div.LC_grade_show_problem_header,
                   5368: div.LC_grade_submissions_header,
                   5369: div.LC_grade_message_center_header,
                   5370: div.LC_grade_assign_header {
                   5371:   font: bold large $sans;
                   5372: }
                   5373: div.LC_grade_show_problem_problem,
                   5374: div.LC_grade_submissions_body,
                   5375: div.LC_grade_message_center_body,
                   5376: div.LC_grade_assign_body {
                   5377:   border: 1px solid black;
                   5378:   width: 99%;
                   5379:   background: #FFFFFF;
                   5380: }
1.598     albertel 5381: span.LC_grade_check_note {
                   5382:   font: normal medium $sans;
                   5383:   display: inline;
                   5384:   position: absolute;
                   5385:   right: 1em;
                   5386: }
1.597     albertel 5387: 
1.613     albertel 5388: table.LC_scantron_action {
                   5389:   width: 100%;
                   5390: }
                   5391: table.LC_scantron_action tr th {
                   5392:   font: normal bold $sans;
                   5393: }
1.600     albertel 5394: 
1.614     albertel 5395: div.LC_edit_problem_header, 
                   5396: div.LC_edit_problem_footer {
1.600     albertel 5397:   font: normal medium $sans;
1.602     albertel 5398:   margin: 2px;
1.600     albertel 5399: }
                   5400: div.LC_edit_problem_header,
1.602     albertel 5401: div.LC_edit_problem_header div,
1.614     albertel 5402: div.LC_edit_problem_footer,
                   5403: div.LC_edit_problem_footer div,
1.602     albertel 5404: div.LC_edit_problem_editxml_header,
                   5405: div.LC_edit_problem_editxml_header div {
1.600     albertel 5406:   margin-top: 5px;
                   5407: }
1.602     albertel 5408: div.LC_edit_problem_header_edit_row {
                   5409:   background: $tabbg;
                   5410:   padding: 3px;
                   5411:   margin-bottom: 5px;
                   5412: }
1.600     albertel 5413: div.LC_edit_problem_header_title {
1.602     albertel 5414:   font: larger bold $sans;
                   5415:   background: $tabbg;
                   5416:   padding: 3px;
                   5417: }
                   5418: table.LC_edit_problem_header_title {
                   5419:   font: larger bold $sans;
                   5420:   width: 100%;
                   5421:   border-color: $pgbg;
                   5422:   border-style: solid;
                   5423:   border-width: $border;
                   5424: 
1.600     albertel 5425:   background: $tabbg;
1.602     albertel 5426:   border-collapse: collapse;
                   5427:   padding: 0px
                   5428: }
                   5429: 
                   5430: div.LC_edit_problem_discards {
                   5431:   float: left;
                   5432:   padding-bottom: 5px;
                   5433: }
                   5434: div.LC_edit_problem_saves {
                   5435:   float: right;
                   5436:   padding-bottom: 5px;
1.600     albertel 5437: }
                   5438: hr.LC_edit_problem_divide {
1.602     albertel 5439:   clear: both;
1.600     albertel 5440:   color: $tabbg;
                   5441:   background-color: $tabbg;
                   5442:   height: 3px;
                   5443:   border: 0px;
                   5444: }
1.679     riegler  5445: img.stift{
1.678     riegler  5446:   border-width:0;
1.679     riegler  5447:   vertical-align:middle;
1.677     riegler  5448: }
1.343     albertel 5449: END
                   5450: }
                   5451: 
1.306     albertel 5452: =pod
                   5453: 
                   5454: =item * &headtag()
                   5455: 
                   5456: Returns a uniform footer for LON-CAPA web pages.
                   5457: 
1.307     albertel 5458: Inputs: $title - optional title for the head
                   5459:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 5460:         $args - optional arguments
1.319     albertel 5461:             force_register - if is true call registerurl so the remote is 
                   5462:                              informed
1.415     albertel 5463:             redirect       -> array ref of
                   5464:                                    1- seconds before redirect occurs
                   5465:                                    2- url to redirect to
                   5466:                                    3- whether the side effect should occur
1.315     albertel 5467:                            (side effect of setting 
                   5468:                                $env{'internal.head.redirect'} to the url 
                   5469:                                redirected too)
1.352     albertel 5470:             domain         -> force to color decorate a page for a specific
                   5471:                                domain
                   5472:             function       -> force usage of a specific rolish color scheme
                   5473:             bgcolor        -> override the default page bgcolor
1.460     albertel 5474:             no_auto_mt_title
                   5475:                            -> prevent &mt()ing the title arg
1.464     albertel 5476: 
1.306     albertel 5477: =cut
                   5478: 
                   5479: sub headtag {
1.313     albertel 5480:     my ($title,$head_extra,$args) = @_;
1.306     albertel 5481:     
1.363     albertel 5482:     my $function = $args->{'function'} || &get_users_function();
                   5483:     my $domain   = $args->{'domain'}   || &determinedomain();
                   5484:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.418     albertel 5485:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 5486: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 5487: 		   #time(),
1.418     albertel 5488: 		   $env{'environment.color.timestamp'},
1.363     albertel 5489: 		   $function,$domain,$bgcolor);
                   5490: 
1.369     www      5491:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 5492: 
1.308     albertel 5493:     my $result =
                   5494: 	'<head>'.
1.461     albertel 5495: 	&font_settings();
1.319     albertel 5496: 
1.461     albertel 5497:     if (!$args->{'frameset'}) {
                   5498: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   5499:     }
1.319     albertel 5500:     if ($args->{'force_register'}) {
                   5501: 	$result .= &Apache::lonmenu::registerurl(1);
                   5502:     }
1.436     albertel 5503:     if (!$args->{'no_nav_bar'} 
                   5504: 	&& !$args->{'only_body'}
                   5505: 	&& !$args->{'frameset'}) {
                   5506: 	$result .= &help_menu_js();
                   5507:     }
1.319     albertel 5508: 
1.314     albertel 5509:     if (ref($args->{'redirect'})) {
1.414     albertel 5510: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 5511: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 5512: 	if (!$inhibit_continue) {
                   5513: 	    $env{'internal.head.redirect'} = $url;
                   5514: 	}
1.313     albertel 5515: 	$result.=<<ADDMETA
                   5516: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 5517: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 5518: ADDMETA
                   5519:     }
1.306     albertel 5520:     if (!defined($title)) {
                   5521: 	$title = 'The LearningOnline Network with CAPA';
                   5522:     }
1.460     albertel 5523:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   5524:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.414     albertel 5525: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
                   5526: 	.$head_extra;
1.306     albertel 5527:     return $result;
                   5528: }
                   5529: 
                   5530: =pod
                   5531: 
1.340     albertel 5532: =item * &font_settings()
                   5533: 
                   5534: Returns neccessary <meta> to set the proper encoding
                   5535: 
                   5536: Inputs: none
                   5537: 
                   5538: =cut
                   5539: 
                   5540: sub font_settings {
                   5541:     my $headerstring='';
1.647     www      5542:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
1.340     albertel 5543: 	$headerstring.=
                   5544: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
                   5545:     }
                   5546:     return $headerstring;
                   5547: }
                   5548: 
1.341     albertel 5549: =pod
                   5550: 
                   5551: =item * &xml_begin()
                   5552: 
                   5553: Returns the needed doctype and <html>
                   5554: 
                   5555: Inputs: none
                   5556: 
                   5557: =cut
                   5558: 
                   5559: sub xml_begin {
                   5560:     my $output='';
                   5561: 
1.592     albertel 5562:     if ($env{'internal.start_page'}==1) {
                   5563: 	&Apache::lonhtmlcommon::init_htmlareafields();
                   5564:     }
1.342     albertel 5565: 
1.341     albertel 5566:     if ($env{'browser.mathml'}) {
                   5567: 	$output='<?xml version="1.0"?>'
                   5568:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   5569: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   5570:             
                   5571: #	    .'<!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">] >'
                   5572: 	    .'<!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">'
                   5573:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   5574: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
                   5575:     } else {
                   5576: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
                   5577:     }
                   5578:     return $output;
                   5579: }
1.340     albertel 5580: 
                   5581: =pod
                   5582: 
1.306     albertel 5583: =item * &endheadtag()
                   5584: 
                   5585: Returns a uniform </head> for LON-CAPA web pages.
                   5586: 
                   5587: Inputs: none
                   5588: 
                   5589: =cut
                   5590: 
                   5591: sub endheadtag {
                   5592:     return '</head>';
                   5593: }
                   5594: 
                   5595: =pod
                   5596: 
                   5597: =item * &head()
                   5598: 
                   5599: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
                   5600: 
1.648     raeburn  5601: Inputs:
                   5602: 
                   5603: =over 4
                   5604: 
                   5605: $title - optional title for the page
                   5606: 
                   5607: $head_extra - optional extra HTML to put inside the <head>
                   5608: 
                   5609: =back
1.405     albertel 5610: 
1.306     albertel 5611: =cut
                   5612: 
                   5613: sub head {
1.325     albertel 5614:     my ($title,$head_extra,$args) = @_;
                   5615:     return &headtag($title,$head_extra,$args).&endheadtag();
1.306     albertel 5616: }
                   5617: 
                   5618: =pod
                   5619: 
                   5620: =item * &start_page()
                   5621: 
                   5622: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   5623: 
1.648     raeburn  5624: Inputs:
                   5625: 
                   5626: =over 4
                   5627: 
                   5628: $title - optional title for the page
                   5629: 
                   5630: $head_extra - optional extra HTML to incude inside the <head>
                   5631: 
                   5632: $args - additional optional args supported are:
                   5633: 
                   5634: =over 8
                   5635: 
                   5636:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 5637:                                     arg on
1.648     raeburn  5638:              no_nav_bar     -> is true will set &bodytag() notopbar arg on
                   5639:              add_entries    -> additional attributes to add to the  <body>
                   5640:              domain         -> force to color decorate a page for a 
1.317     albertel 5641:                                     specific domain
1.648     raeburn  5642:              function       -> force usage of a specific rolish color
1.317     albertel 5643:                                     scheme
1.648     raeburn  5644:              redirect       -> see &headtag()
                   5645:              bgcolor        -> override the default page bg color
                   5646:              js_ready       -> return a string ready for being used in 
1.317     albertel 5647:                                     a javascript writeln
1.648     raeburn  5648:              html_encode    -> return a string ready for being used in 
1.320     albertel 5649:                                     a html attribute
1.648     raeburn  5650:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 5651:                                     $forcereg arg
1.648     raeburn  5652:              body_title     -> alternate text to use instead of $title
1.326     albertel 5653:                                     in the title box that appears, this text
                   5654:                                     is not auto translated like the $title is
1.648     raeburn  5655:              frameset       -> if true will start with a <frameset>
1.330     albertel 5656:                                     rather than <body>
1.648     raeburn  5657:              no_title       -> if true the title bar won't be shown
                   5658:              skip_phases    -> hash ref of 
1.338     albertel 5659:                                     head -> skip the <html><head> generation
                   5660:                                     body -> skip all <body> generation
1.648     raeburn  5661:              no_inline_link -> if true and in remote mode, don't show the 
1.361     albertel 5662:                                     'Switch To Inline Menu' link
1.648     raeburn  5663:              no_auto_mt_title -> prevent &mt()ing the title arg
                   5664:              inherit_jsmath -> when creating popup window in a page,
                   5665:                                     should it have jsmath forced on by the
                   5666:                                     current page
1.361     albertel 5667: 
1.648     raeburn  5668: =back
1.460     albertel 5669: 
1.648     raeburn  5670: =back
1.562     albertel 5671: 
1.306     albertel 5672: =cut
                   5673: 
                   5674: sub start_page {
1.309     albertel 5675:     my ($title,$head_extra,$args) = @_;
1.318     albertel 5676:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.313     albertel 5677:     my %head_args;
1.352     albertel 5678:     foreach my $arg ('redirect','force_register','domain','function',
1.460     albertel 5679: 		     'bgcolor','frameset','no_nav_bar','only_body',
                   5680: 		     'no_auto_mt_title') {
1.319     albertel 5681: 	if (defined($args->{$arg})) {
1.324     raeburn  5682: 	    $head_args{$arg} = $args->{$arg};
1.319     albertel 5683: 	}
1.313     albertel 5684:     }
1.319     albertel 5685: 
1.315     albertel 5686:     $env{'internal.start_page'}++;
1.338     albertel 5687:     my $result;
                   5688:     if (! exists($args->{'skip_phases'}{'head'}) ) {
                   5689: 	$result.=
1.341     albertel 5690: 	    &xml_begin().
1.338     albertel 5691: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
                   5692:     }
                   5693:     
                   5694:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   5695: 	if ($args->{'frameset'}) {
                   5696: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   5697: 						$args->{'add_entries'});
                   5698: 	    $result .= "\n<frameset $attr_string>\n";
                   5699: 	} else {
                   5700: 	    $result .=
                   5701: 		&bodytag($title, 
                   5702: 			 $args->{'function'},       $args->{'add_entries'},
                   5703: 			 $args->{'only_body'},      $args->{'domain'},
                   5704: 			 $args->{'force_register'}, $args->{'body_title'},
                   5705: 			 $args->{'no_nav_bar'},     $args->{'bgcolor'},
1.460     albertel 5706: 			 $args->{'no_title'},       $args->{'no_inline_link'},
                   5707: 			 $args);
1.338     albertel 5708: 	}
1.330     albertel 5709:     }
1.338     albertel 5710: 
1.315     albertel 5711:     if ($args->{'js_ready'}) {
1.317     albertel 5712: 	$result = &js_ready($result);
1.315     albertel 5713:     }
1.320     albertel 5714:     if ($args->{'html_encode'}) {
                   5715: 	$result = &html_encode($result);
                   5716:     }
1.315     albertel 5717:     return $result;
1.306     albertel 5718: }
                   5719: 
1.330     albertel 5720: 
1.306     albertel 5721: =pod
                   5722: 
                   5723: =item * &head()
                   5724: 
                   5725: Returns a complete </body></html> section for LON-CAPA web pages.
                   5726: 
1.315     albertel 5727: Inputs:         $args - additional optional args supported are:
                   5728:                  js_ready     -> return a string ready for being used in 
                   5729:                                  a javascript writeln
1.320     albertel 5730:                  html_encode  -> return a string ready for being used in 
                   5731:                                  a html attribute
1.330     albertel 5732:                  frameset     -> if true will start with a <frameset>
                   5733:                                  rather than <body>
1.493     albertel 5734:                  dicsussion   -> if true will get discussion from
                   5735:                                   lonxml::xmlend
                   5736:                                  (you can pass the target and parser arguments
                   5737:                                   through optional 'target' and 'parser' args
                   5738:                                   to this routine)
1.306     albertel 5739: 
                   5740: =cut
                   5741: 
                   5742: sub end_page {
1.315     albertel 5743:     my ($args) = @_;
                   5744:     $env{'internal.end_page'}++;
1.330     albertel 5745:     my $result;
1.335     albertel 5746:     if ($args->{'discussion'}) {
                   5747: 	my ($target,$parser);
                   5748: 	if (ref($args->{'discussion'})) {
                   5749: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   5750: 				$args->{'discussion'}{'parser'});
                   5751: 	}
                   5752: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   5753:     }
                   5754: 
1.330     albertel 5755:     if ($args->{'frameset'}) {
                   5756: 	$result .= '</frameset>';
                   5757:     } else {
1.635     raeburn  5758: 	$result .= &endbodytag($args);
1.330     albertel 5759:     }
                   5760:     $result .= "\n</html>";
                   5761: 
1.315     albertel 5762:     if ($args->{'js_ready'}) {
1.317     albertel 5763: 	$result = &js_ready($result);
1.315     albertel 5764:     }
1.335     albertel 5765: 
1.320     albertel 5766:     if ($args->{'html_encode'}) {
                   5767: 	$result = &html_encode($result);
                   5768:     }
1.335     albertel 5769: 
1.315     albertel 5770:     return $result;
                   5771: }
                   5772: 
1.320     albertel 5773: sub html_encode {
                   5774:     my ($result) = @_;
                   5775: 
1.322     albertel 5776:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 5777:     
                   5778:     return $result;
                   5779: }
1.317     albertel 5780: sub js_ready {
                   5781:     my ($result) = @_;
                   5782: 
1.323     albertel 5783:     $result =~ s/[\n\r]/ /xmsg;
                   5784:     $result =~ s/\\/\\\\/xmsg;
                   5785:     $result =~ s/'/\\'/xmsg;
1.372     albertel 5786:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 5787:     
                   5788:     return $result;
                   5789: }
                   5790: 
1.315     albertel 5791: sub validate_page {
                   5792:     if (  exists($env{'internal.start_page'})
1.316     albertel 5793: 	  &&     $env{'internal.start_page'} > 1) {
                   5794: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 5795: 				 $env{'internal.start_page'}.' '.
1.316     albertel 5796: 				 $ENV{'request.filename'});
1.315     albertel 5797:     }
                   5798:     if (  exists($env{'internal.end_page'})
1.316     albertel 5799: 	  &&     $env{'internal.end_page'} > 1) {
                   5800: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 5801: 				 $env{'internal.end_page'}.' '.
1.316     albertel 5802: 				 $env{'request.filename'});
1.315     albertel 5803:     }
                   5804:     if (     exists($env{'internal.start_page'})
                   5805: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 5806: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   5807: 				 $env{'request.filename'});
1.315     albertel 5808:     }
                   5809:     if (   ! exists($env{'internal.start_page'})
                   5810: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 5811: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   5812: 				 $env{'request.filename'});
1.315     albertel 5813:     }
1.306     albertel 5814: }
1.315     albertel 5815: 
1.318     albertel 5816: sub simple_error_page {
                   5817:     my ($r,$title,$msg) = @_;
                   5818:     my $page =
                   5819: 	&Apache::loncommon::start_page($title).
                   5820: 	&mt($msg).
                   5821: 	&Apache::loncommon::end_page();
                   5822:     if (ref($r)) {
                   5823: 	$r->print($page);
1.327     albertel 5824: 	return;
1.318     albertel 5825:     }
                   5826:     return $page;
                   5827: }
1.347     albertel 5828: 
                   5829: {
1.610     albertel 5830:     my @row_count;
1.347     albertel 5831:     sub start_data_table {
1.422     albertel 5832: 	my ($add_class) = @_;
                   5833: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.610     albertel 5834: 	unshift(@row_count,0);
1.422     albertel 5835: 	return '<table class="'.$css_class.'">'."\n";
1.347     albertel 5836:     }
                   5837: 
                   5838:     sub end_data_table {
1.610     albertel 5839: 	shift(@row_count);
1.389     albertel 5840: 	return '</table>'."\n";;
1.347     albertel 5841:     }
                   5842: 
                   5843:     sub start_data_table_row {
1.422     albertel 5844: 	my ($add_class) = @_;
1.610     albertel 5845: 	$row_count[0]++;
                   5846: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.428     albertel 5847: 	$css_class = (join(' ',$css_class,$add_class));
1.422     albertel 5848: 	return  '<tr class="'.$css_class.'">'."\n";;
1.347     albertel 5849:     }
1.471     banghart 5850:     
                   5851:     sub continue_data_table_row {
                   5852: 	my ($add_class) = @_;
1.610     albertel 5853: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.471     banghart 5854: 	$css_class = (join(' ',$css_class,$add_class));
                   5855: 	return  '<tr class="'.$css_class.'">'."\n";;
                   5856:     }
1.347     albertel 5857: 
                   5858:     sub end_data_table_row {
1.389     albertel 5859: 	return '</tr>'."\n";;
1.347     albertel 5860:     }
1.367     www      5861: 
1.421     albertel 5862:     sub start_data_table_empty_row {
1.610     albertel 5863: 	$row_count[0]++;
1.421     albertel 5864: 	return  '<tr class="LC_empty_row" >'."\n";;
                   5865:     }
                   5866: 
                   5867:     sub end_data_table_empty_row {
                   5868: 	return '</tr>'."\n";;
                   5869:     }
                   5870: 
1.367     www      5871:     sub start_data_table_header_row {
1.389     albertel 5872: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      5873:     }
                   5874: 
                   5875:     sub end_data_table_header_row {
1.389     albertel 5876: 	return '</tr>'."\n";;
1.367     www      5877:     }
1.347     albertel 5878: }
                   5879: 
1.548     albertel 5880: =pod
                   5881: 
                   5882: =item * &inhibit_menu_check($arg)
                   5883: 
                   5884: Checks for a inhibitmenu state and generates output to preserve it
                   5885: 
                   5886: Inputs:         $arg - can be any of
                   5887:                      - undef - in which case the return value is a string 
                   5888:                                to add  into arguments list of a uri
                   5889:                      - 'input' - in which case the return value is a HTML
                   5890:                                  <form> <input> field of type hidden to
                   5891:                                  preserve the value
                   5892:                      - a url - in which case the return value is the url with
                   5893:                                the neccesary cgi args added to preserve the
                   5894:                                inhibitmenu state
                   5895:                      - a ref to a url - no return value, but the string is
                   5896:                                         updated to include the neccessary cgi
                   5897:                                         args to preserve the inhibitmenu state
                   5898: 
                   5899: =cut
                   5900: 
                   5901: sub inhibit_menu_check {
                   5902:     my ($arg) = @_;
                   5903:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5904:     if ($arg eq 'input') {
                   5905: 	if ($env{'form.inhibitmenu'}) {
                   5906: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   5907: 	} else {
                   5908: 	    return
                   5909: 	}
                   5910:     }
                   5911:     if ($env{'form.inhibitmenu'}) {
                   5912: 	if (ref($arg)) {
                   5913: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   5914: 	} elsif ($arg eq '') {
                   5915: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   5916: 	} else {
                   5917: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   5918: 	}
                   5919:     }
                   5920:     if (!ref($arg)) {
                   5921: 	return $arg;
                   5922:     }
                   5923: }
                   5924: 
1.251     albertel 5925: ###############################################
1.182     matthew  5926: 
                   5927: =pod
                   5928: 
1.549     albertel 5929: =back
                   5930: 
                   5931: =head1 User Information Routines
                   5932: 
                   5933: =over 4
                   5934: 
1.405     albertel 5935: =item * &get_users_function()
1.182     matthew  5936: 
                   5937: Used by &bodytag to determine the current users primary role.
                   5938: Returns either 'student','coordinator','admin', or 'author'.
                   5939: 
                   5940: =cut
                   5941: 
                   5942: ###############################################
                   5943: sub get_users_function {
                   5944:     my $function = 'student';
1.258     albertel 5945:     if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
1.182     matthew  5946:         $function='coordinator';
                   5947:     }
1.258     albertel 5948:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  5949:         $function='admin';
                   5950:     }
1.258     albertel 5951:     if (($env{'request.role'}=~/^(au|ca)/) ||
1.182     matthew  5952:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
                   5953:         $function='author';
                   5954:     }
                   5955:     return $function;
1.54      www      5956: }
1.99      www      5957: 
                   5958: ###############################################
                   5959: 
1.233     raeburn  5960: =pod
                   5961: 
1.542     raeburn  5962: =item * &check_user_status()
1.274     raeburn  5963: 
                   5964: Determines current status of supplied role for a
                   5965: specific user. Roles can be active, previous or future.
                   5966: 
                   5967: Inputs: 
                   5968: user's domain, user's username, course's domain,
1.375     raeburn  5969: course's number, optional section ID.
1.274     raeburn  5970: 
                   5971: Outputs:
                   5972: role status: active, previous or future. 
                   5973: 
                   5974: =cut
                   5975: 
                   5976: sub check_user_status {
1.412     raeburn  5977:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.274     raeburn  5978:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
                   5979:     my @uroles = keys %userinfo;
                   5980:     my $srchstr;
                   5981:     my $active_chk = 'none';
1.412     raeburn  5982:     my $now = time;
1.274     raeburn  5983:     if (@uroles > 0) {
1.412     raeburn  5984:         if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  5985:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   5986:         } else {
1.412     raeburn  5987:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   5988:         }
                   5989:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  5990:             my $role_end = 0;
                   5991:             my $role_start = 0;
                   5992:             $active_chk = 'active';
1.412     raeburn  5993:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   5994:                 $role_end = $1;
                   5995:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   5996:                     $role_start = $1;
1.274     raeburn  5997:                 }
                   5998:             }
                   5999:             if ($role_start > 0) {
1.412     raeburn  6000:                 if ($now < $role_start) {
1.274     raeburn  6001:                     $active_chk = 'future';
                   6002:                 }
                   6003:             }
                   6004:             if ($role_end > 0) {
1.412     raeburn  6005:                 if ($now > $role_end) {
1.274     raeburn  6006:                     $active_chk = 'previous';
                   6007:                 }
                   6008:             }
                   6009:         }
                   6010:     }
                   6011:     return $active_chk;
                   6012: }
                   6013: 
                   6014: ###############################################
                   6015: 
                   6016: =pod
                   6017: 
1.405     albertel 6018: =item * &get_sections()
1.233     raeburn  6019: 
                   6020: Determines all the sections for a course including
                   6021: sections with students and sections containing other roles.
1.419     raeburn  6022: Incoming parameters: 
                   6023: 
                   6024: 1. domain
                   6025: 2. course number 
                   6026: 3. reference to array containing roles for which sections should 
                   6027: be gathered (optional).
                   6028: 4. reference to array containing status types for which sections 
                   6029: should be gathered (optional).
                   6030: 
                   6031: If the third argument is undefined, sections are gathered for any role. 
                   6032: If the fourth argument is undefined, sections are gathered for any status.
                   6033: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  6034:  
1.374     raeburn  6035: Returns section hash (keys are section IDs, values are
                   6036: number of users in each section), subject to the
1.419     raeburn  6037: optional roles filter, optional status filter 
1.233     raeburn  6038: 
                   6039: =cut
                   6040: 
                   6041: ###############################################
                   6042: sub get_sections {
1.419     raeburn  6043:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 6044:     if (!defined($cdom) || !defined($cnum)) {
                   6045:         my $cid =  $env{'request.course.id'};
                   6046: 
                   6047: 	return if (!defined($cid));
                   6048: 
                   6049:         $cdom = $env{'course.'.$cid.'.domain'};
                   6050:         $cnum = $env{'course.'.$cid.'.num'};
                   6051:     }
                   6052: 
                   6053:     my %sectioncount;
1.419     raeburn  6054:     my $now = time;
1.240     albertel 6055: 
1.366     albertel 6056:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
1.276     albertel 6057: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 6058: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   6059: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  6060:         my $start_index = &Apache::loncoursedata::CL_START();
                   6061:         my $end_index = &Apache::loncoursedata::CL_END();
                   6062:         my $status;
1.366     albertel 6063: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  6064: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   6065: 				                     $data->[$status_index],
                   6066:                                                      $data->[$start_index],
                   6067:                                                      $data->[$end_index]);
                   6068:             if ($stu_status eq 'Active') {
                   6069:                 $status = 'active';
                   6070:             } elsif ($end < $now) {
                   6071:                 $status = 'previous';
                   6072:             } elsif ($start > $now) {
                   6073:                 $status = 'future';
                   6074:             } 
                   6075: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   6076:                 if ((!defined($possible_status)) || (($status ne '') && 
                   6077:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   6078: 		    $sectioncount{$section}++;
                   6079:                 }
1.240     albertel 6080: 	    }
                   6081: 	}
                   6082:     }
                   6083:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   6084:     foreach my $user (sort(keys(%courseroles))) {
                   6085: 	if ($user !~ /^(\w{2})/) { next; }
                   6086: 	my ($role) = ($user =~ /^(\w{2})/);
                   6087: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  6088: 	my ($section,$status);
1.240     albertel 6089: 	if ($role eq 'cr' &&
                   6090: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   6091: 	    $section=$1;
                   6092: 	}
                   6093: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   6094: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  6095:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   6096:         if ($end == -1 && $start == -1) {
                   6097:             next; #deleted role
                   6098:         }
                   6099:         if (!defined($possible_status)) { 
                   6100:             $sectioncount{$section}++;
                   6101:         } else {
                   6102:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   6103:                 $status = 'active';
                   6104:             } elsif ($end < $now) {
                   6105:                 $status = 'future';
                   6106:             } elsif ($start > $now) {
                   6107:                 $status = 'previous';
                   6108:             }
                   6109:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   6110:                 $sectioncount{$section}++;
                   6111:             }
                   6112:         }
1.233     raeburn  6113:     }
1.366     albertel 6114:     return %sectioncount;
1.233     raeburn  6115: }
                   6116: 
1.274     raeburn  6117: ###############################################
1.294     raeburn  6118: 
                   6119: =pod
1.405     albertel 6120: 
                   6121: =item * &get_course_users()
                   6122: 
1.275     raeburn  6123: Retrieves usernames:domains for users in the specified course
                   6124: with specific role(s), and access status. 
                   6125: 
                   6126: Incoming parameters:
1.277     albertel 6127: 1. course domain
                   6128: 2. course number
                   6129: 3. access status: users must have - either active, 
1.275     raeburn  6130: previous, future, or all.
1.277     albertel 6131: 4. reference to array of permissible roles
1.288     raeburn  6132: 5. reference to array of section restrictions (optional)
                   6133: 6. reference to results object (hash of hashes).
                   6134: 7. reference to optional userdata hash
1.609     raeburn  6135: 8. reference to optional statushash
1.630     raeburn  6136: 9. flag if privileged users (except those set to unhide in
                   6137:    course settings) should be excluded    
1.609     raeburn  6138: Keys of top level results hash are roles.
1.275     raeburn  6139: Keys of inner hashes are username:domain, with 
                   6140: values set to access type.
1.288     raeburn  6141: Optional userdata hash returns an array with arguments in the 
                   6142: same order as loncoursedata::get_classlist() for student data.
                   6143: 
1.609     raeburn  6144: Optional statushash returns
                   6145: 
1.288     raeburn  6146: Entries for end, start, section and status are blank because
                   6147: of the possibility of multiple values for non-student roles.
                   6148: 
1.275     raeburn  6149: =cut
1.405     albertel 6150: 
1.275     raeburn  6151: ###############################################
1.405     albertel 6152: 
1.275     raeburn  6153: sub get_course_users {
1.630     raeburn  6154:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  6155:     my %idx = ();
1.419     raeburn  6156:     my %seclists;
1.288     raeburn  6157: 
                   6158:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   6159:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   6160:     $idx{end} = &Apache::loncoursedata::CL_END();
                   6161:     $idx{start} = &Apache::loncoursedata::CL_START();
                   6162:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   6163:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   6164:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   6165:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   6166: 
1.290     albertel 6167:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 6168:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  6169:         my $now = time;
1.277     albertel 6170:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  6171:             my $match = 0;
1.412     raeburn  6172:             my $secmatch = 0;
1.419     raeburn  6173:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  6174:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  6175:             if ($section eq '') {
                   6176:                 $section = 'none';
                   6177:             }
1.291     albertel 6178:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 6179:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  6180:                     $secmatch = 1;
                   6181:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 6182:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  6183:                         $secmatch = 1;
                   6184:                     }
                   6185:                 } else {  
1.419     raeburn  6186: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  6187: 		        $secmatch = 1;
                   6188:                     }
1.290     albertel 6189: 		}
1.412     raeburn  6190:                 if (!$secmatch) {
                   6191:                     next;
                   6192:                 }
1.419     raeburn  6193:             }
1.275     raeburn  6194:             if (defined($$types{'active'})) {
1.288     raeburn  6195:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  6196:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  6197:                     $match = 1;
1.275     raeburn  6198:                 }
                   6199:             }
                   6200:             if (defined($$types{'previous'})) {
1.609     raeburn  6201:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  6202:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  6203:                     $match = 1;
1.275     raeburn  6204:                 }
                   6205:             }
                   6206:             if (defined($$types{'future'})) {
1.609     raeburn  6207:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  6208:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  6209:                     $match = 1;
1.275     raeburn  6210:                 }
                   6211:             }
1.609     raeburn  6212:             if ($match) {
                   6213:                 push(@{$seclists{$student}},$section);
                   6214:                 if (ref($userdata) eq 'HASH') {
                   6215:                     $$userdata{$student} = $$classlist{$student};
                   6216:                 }
                   6217:                 if (ref($statushash) eq 'HASH') {
                   6218:                     $statushash->{$student}{'st'}{$section} = $status;
                   6219:                 }
1.288     raeburn  6220:             }
1.275     raeburn  6221:         }
                   6222:     }
1.412     raeburn  6223:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  6224:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   6225:         my $now = time;
1.609     raeburn  6226:         my %displaystatus = ( previous => 'Expired',
                   6227:                               active   => 'Active',
                   6228:                               future   => 'Future',
                   6229:                             );
1.630     raeburn  6230:         my %nothide;
                   6231:         if ($hidepriv) {
                   6232:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   6233:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   6234:                 if ($user !~ /:/) {
                   6235:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   6236:                 } else {
                   6237:                     $nothide{$user} = 1;
                   6238:                 }
                   6239:             }
                   6240:         }
1.439     raeburn  6241:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  6242:             my $match = 0;
1.412     raeburn  6243:             my $secmatch = 0;
1.439     raeburn  6244:             my $status;
1.412     raeburn  6245:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  6246:             $user =~ s/:$//;
1.439     raeburn  6247:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   6248:             if ($end == -1 || $start == -1) {
                   6249:                 next;
                   6250:             }
                   6251:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   6252:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  6253:                 my ($uname,$udom) = split(/:/,$user);
                   6254:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 6255:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  6256:                         $secmatch = 1;
                   6257:                     } elsif ($usec eq '') {
1.420     albertel 6258:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  6259:                             $secmatch = 1;
                   6260:                         }
                   6261:                     } else {
                   6262:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   6263:                             $secmatch = 1;
                   6264:                         }
                   6265:                     }
                   6266:                     if (!$secmatch) {
                   6267:                         next;
                   6268:                     }
1.288     raeburn  6269:                 }
1.419     raeburn  6270:                 if ($usec eq '') {
                   6271:                     $usec = 'none';
                   6272:                 }
1.275     raeburn  6273:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  6274:                     if ($hidepriv) {
                   6275:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
                   6276:                             (!$nothide{$uname.':'.$udom})) {
                   6277:                             next;
                   6278:                         }
                   6279:                     }
1.503     raeburn  6280:                     if ($end > 0 && $end < $now) {
1.439     raeburn  6281:                         $status = 'previous';
                   6282:                     } elsif ($start > $now) {
                   6283:                         $status = 'future';
                   6284:                     } else {
                   6285:                         $status = 'active';
                   6286:                     }
1.277     albertel 6287:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  6288:                         if ($status eq $type) {
1.420     albertel 6289:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  6290:                                 push(@{$$users{$role}{$user}},$type);
                   6291:                             }
1.288     raeburn  6292:                             $match = 1;
                   6293:                         }
                   6294:                     }
1.419     raeburn  6295:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   6296:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   6297: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   6298:                         }
1.420     albertel 6299:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  6300:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   6301:                         }
1.609     raeburn  6302:                         if (ref($statushash) eq 'HASH') {
                   6303:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   6304:                         }
1.275     raeburn  6305:                     }
                   6306:                 }
                   6307:             }
                   6308:         }
1.290     albertel 6309:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  6310:             if ((defined($cdom)) && (defined($cnum))) {
                   6311:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   6312:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   6313:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  6314:                     next if ($owner eq '');
                   6315:                     my ($ownername,$ownerdom);
                   6316:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   6317:                         $ownername = $1;
                   6318:                         $ownerdom = $2;
                   6319:                     } else {
                   6320:                         $ownername = $owner;
                   6321:                         $ownerdom = $cdom;
                   6322:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  6323:                     }
                   6324:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 6325:                     if (defined($userdata) && 
1.609     raeburn  6326: 			!exists($$userdata{$owner})) {
                   6327: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   6328:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   6329:                             push(@{$seclists{$owner}},'none');
                   6330:                         }
                   6331:                         if (ref($statushash) eq 'HASH') {
                   6332:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  6333:                         }
1.290     albertel 6334: 		    }
1.279     raeburn  6335:                 }
                   6336:             }
                   6337:         }
1.419     raeburn  6338:         foreach my $user (keys(%seclists)) {
                   6339:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   6340:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   6341:         }
1.275     raeburn  6342:     }
                   6343:     return;
                   6344: }
                   6345: 
1.288     raeburn  6346: sub get_user_info {
                   6347:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 6348:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   6349: 	&plainname($uname,$udom,'lastname');
1.291     albertel 6350:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  6351:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  6352:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   6353:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  6354:     return;
                   6355: }
1.275     raeburn  6356: 
1.472     raeburn  6357: ###############################################
                   6358: 
                   6359: =pod
                   6360: 
                   6361: =item * &get_user_quota()
                   6362: 
                   6363: Retrieves quota assigned for storage of portfolio files for a user  
                   6364: 
                   6365: Incoming parameters:
                   6366: 1. user's username
                   6367: 2. user's domain
                   6368: 
                   6369: Returns:
1.536     raeburn  6370: 1. Disk quota (in Mb) assigned to student.
                   6371: 2. (Optional) Type of setting: custom or default
                   6372:    (individually assigned or default for user's 
                   6373:    institutional status).
                   6374: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   6375:    or student - types as defined in localenroll::inst_usertypes 
                   6376:    for user's domain, which determines default quota for user.
                   6377: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  6378: 
                   6379: If a value has been stored in the user's environment, 
1.536     raeburn  6380: it will return that, otherwise it returns the maximal default
                   6381: defined for the user's instituional status(es) in the domain.
1.472     raeburn  6382: 
                   6383: =cut
                   6384: 
                   6385: ###############################################
                   6386: 
                   6387: 
                   6388: sub get_user_quota {
                   6389:     my ($uname,$udom) = @_;
1.536     raeburn  6390:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  6391:     if (!defined($udom)) {
                   6392:         $udom = $env{'user.domain'};
                   6393:     }
                   6394:     if (!defined($uname)) {
                   6395:         $uname = $env{'user.name'};
                   6396:     }
                   6397:     if (($udom eq '' || $uname eq '') ||
                   6398:         ($udom eq 'public') && ($uname eq 'public')) {
                   6399:         $quota = 0;
1.536     raeburn  6400:         $quotatype = 'default';
                   6401:         $defquota = 0; 
1.472     raeburn  6402:     } else {
1.536     raeburn  6403:         my $inststatus;
1.472     raeburn  6404:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   6405:             $quota = $env{'environment.portfolioquota'};
1.536     raeburn  6406:             $inststatus = $env{'environment.inststatus'};
1.472     raeburn  6407:         } else {
1.536     raeburn  6408:             my %userenv = 
                   6409:                 &Apache::lonnet::get('environment',['portfolioquota',
                   6410:                                      'inststatus'],$udom,$uname);
1.472     raeburn  6411:             my ($tmp) = keys(%userenv);
                   6412:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   6413:                 $quota = $userenv{'portfolioquota'};
1.536     raeburn  6414:                 $inststatus = $userenv{'inststatus'};
1.472     raeburn  6415:             } else {
                   6416:                 undef(%userenv);
                   6417:             }
                   6418:         }
1.536     raeburn  6419:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
1.472     raeburn  6420:         if ($quota eq '') {
1.536     raeburn  6421:             $quota = $defquota;
                   6422:             $quotatype = 'default';
                   6423:         } else {
                   6424:             $quotatype = 'custom';
1.472     raeburn  6425:         }
                   6426:     }
1.536     raeburn  6427:     if (wantarray) {
                   6428:         return ($quota,$quotatype,$settingstatus,$defquota);
                   6429:     } else {
                   6430:         return $quota;
                   6431:     }
1.472     raeburn  6432: }
                   6433: 
                   6434: ###############################################
                   6435: 
                   6436: =pod
                   6437: 
                   6438: =item * &default_quota()
                   6439: 
1.536     raeburn  6440: Retrieves default quota assigned for storage of user portfolio files,
                   6441: given an (optional) user's institutional status.
1.472     raeburn  6442: 
                   6443: Incoming parameters:
                   6444: 1. domain
1.536     raeburn  6445: 2. (Optional) institutional status(es).  This is a : separated list of 
                   6446:    status types (e.g., faculty, staff, student etc.)
                   6447:    which apply to the user for whom the default is being retrieved.
                   6448:    If the institutional status string in undefined, the domain
                   6449:    default quota will be returned. 
1.472     raeburn  6450: 
                   6451: Returns:
                   6452: 1. Default disk quota (in Mb) for user portfolios in the domain.
1.536     raeburn  6453: 2. (Optional) institutional type which determined the value of the
                   6454:    default quota.
1.472     raeburn  6455: 
                   6456: If a value has been stored in the domain's configuration db,
                   6457: it will return that, otherwise it returns 20 (for backwards 
                   6458: compatibility with domains which have not set up a configuration
                   6459: db file; the original statically defined portfolio quota was 20 Mb). 
                   6460: 
1.536     raeburn  6461: If the user's status includes multiple types (e.g., staff and student),
                   6462: the largest default quota which applies to the user determines the
                   6463: default quota returned.
                   6464: 
1.472     raeburn  6465: =cut
                   6466: 
                   6467: ###############################################
                   6468: 
                   6469: 
                   6470: sub default_quota {
1.536     raeburn  6471:     my ($udom,$inststatus) = @_;
                   6472:     my ($defquota,$settingstatus);
                   6473:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  6474:                                             ['quotas'],$udom);
                   6475:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  6476:         if ($inststatus ne '') {
                   6477:             my @statuses = split(/:/,$inststatus);
                   6478:             foreach my $item (@statuses) {
1.622     raeburn  6479:                 if ($quotahash{'quotas'}{$item} ne '') {
1.536     raeburn  6480:                     if ($defquota eq '') {
1.622     raeburn  6481:                         $defquota = $quotahash{'quotas'}{$item};
1.536     raeburn  6482:                         $settingstatus = $item;
1.622     raeburn  6483:                     } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   6484:                         $defquota = $quotahash{'quotas'}{$item};
1.536     raeburn  6485:                         $settingstatus = $item;
                   6486:                     }
                   6487:                 }
                   6488:             }
                   6489:         }
                   6490:         if ($defquota eq '') {
1.622     raeburn  6491:             $defquota = $quotahash{'quotas'}{'default'};
1.536     raeburn  6492:             $settingstatus = 'default';
                   6493:         }
                   6494:     } else {
                   6495:         $settingstatus = 'default';
                   6496:         $defquota = 20;
                   6497:     }
                   6498:     if (wantarray) {
                   6499:         return ($defquota,$settingstatus);
1.472     raeburn  6500:     } else {
1.536     raeburn  6501:         return $defquota;
1.472     raeburn  6502:     }
                   6503: }
                   6504: 
1.384     raeburn  6505: sub get_secgrprole_info {
                   6506:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   6507:     my %sections_count = &get_sections($cdom,$cnum);
                   6508:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   6509:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   6510:     my @groups = sort(keys(%curr_groups));
                   6511:     my $allroles = [];
                   6512:     my $rolehash;
                   6513:     my $accesshash = {
                   6514:                      active => 'Currently has access',
                   6515:                      future => 'Will have future access',
                   6516:                      previous => 'Previously had access',
                   6517:                   };
                   6518:     if ($needroles) {
                   6519:         $rolehash = {'all' => 'all'};
1.385     albertel 6520:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   6521: 	if (&Apache::lonnet::error(%user_roles)) {
                   6522: 	    undef(%user_roles);
                   6523: 	}
                   6524:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  6525:             my ($role)=split(/\:/,$item,2);
                   6526:             if ($role eq 'cr') { next; }
                   6527:             if ($role =~ /^cr/) {
                   6528:                 $$rolehash{$role} = (split('/',$role))[3];
                   6529:             } else {
                   6530:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   6531:             }
                   6532:         }
                   6533:         foreach my $key (sort(keys(%{$rolehash}))) {
                   6534:             push(@{$allroles},$key);
                   6535:         }
                   6536:         push (@{$allroles},'st');
                   6537:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   6538:     }
                   6539:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   6540: }
                   6541: 
1.555     raeburn  6542: sub user_picker {
1.627     raeburn  6543:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
1.555     raeburn  6544:     my $currdom = $dom;
                   6545:     my %curr_selected = (
                   6546:                         srchin => 'dom',
1.580     raeburn  6547:                         srchby => 'lastname',
1.555     raeburn  6548:                       );
                   6549:     my $srchterm;
1.625     raeburn  6550:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  6551:         if ($srch->{'srchby'} ne '') {
                   6552:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   6553:         }
                   6554:         if ($srch->{'srchin'} ne '') {
                   6555:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   6556:         }
                   6557:         if ($srch->{'srchtype'} ne '') {
                   6558:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   6559:         }
                   6560:         if ($srch->{'srchdomain'} ne '') {
                   6561:             $currdom = $srch->{'srchdomain'};
                   6562:         }
                   6563:         $srchterm = $srch->{'srchterm'};
                   6564:     }
                   6565:     my %lt=&Apache::lonlocal::texthash(
1.573     raeburn  6566:                     'usr'       => 'Search criteria',
1.563     raeburn  6567:                     'doma'      => 'Domain/institution to search',
1.558     albertel 6568:                     'uname'     => 'username',
                   6569:                     'lastname'  => 'last name',
1.555     raeburn  6570:                     'lastfirst' => 'last name, first name',
1.558     albertel 6571:                     'crs'       => 'in this course',
1.576     raeburn  6572:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 6573:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  6574:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 6575:                     'exact'     => 'is',
                   6576:                     'contains'  => 'contains',
1.569     raeburn  6577:                     'begins'    => 'begins with',
1.571     raeburn  6578:                     'youm'      => "You must include some text to search for.",
                   6579:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   6580:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   6581:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   6582:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   6583:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   6584:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   6585:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  6586:                                        );
1.563     raeburn  6587:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   6588:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  6589: 
                   6590:     my @srchins = ('crs','dom','alc','instd');
                   6591: 
                   6592:     foreach my $option (@srchins) {
                   6593:         # FIXME 'alc' option unavailable until 
                   6594:         #       loncreateuser::print_user_query_page()
                   6595:         #       has been completed.
                   6596:         next if ($option eq 'alc');
                   6597:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  6598:         if ($curr_selected{'srchin'} eq $option) {
                   6599:             $srchinsel .= ' 
                   6600:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   6601:         } else {
                   6602:             $srchinsel .= '
                   6603:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   6604:         }
1.555     raeburn  6605:     }
1.563     raeburn  6606:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  6607: 
                   6608:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  6609:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  6610:         if ($curr_selected{'srchby'} eq $option) {
                   6611:             $srchbysel .= '
                   6612:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   6613:         } else {
                   6614:             $srchbysel .= '
                   6615:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   6616:          }
                   6617:     }
                   6618:     $srchbysel .= "\n  </select>\n";
                   6619: 
                   6620:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  6621:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  6622:         if ($curr_selected{'srchtype'} eq $option) {
                   6623:             $srchtypesel .= '
                   6624:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   6625:         } else {
                   6626:             $srchtypesel .= '
                   6627:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   6628:         }
                   6629:     }
                   6630:     $srchtypesel .= "\n  </select>\n";
                   6631: 
1.558     albertel 6632:     my ($newuserscript,$new_user_create);
1.556     raeburn  6633: 
                   6634:     if ($forcenewuser) {
1.576     raeburn  6635:         if (ref($srch) eq 'HASH') {
                   6636:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
1.627     raeburn  6637:                 if ($cancreate) {
                   6638:                     $new_user_create = '<p> <input type="submit" name="forcenew" value="'.&HTML::Entities::encode(&mt('Make new user "[_1]"',$srchterm),'<>&"').'" onclick="javascript:setSearch(\'1\','.$caller.');" /> </p>';
                   6639:                 } else {
                   6640:                     my $helplink = ' href="javascript:helpMenu('."'display'".')"';
                   6641:                     my %usertypetext = (
                   6642:                         official   => 'institutional',
                   6643:                         unofficial => 'non-institutional',
                   6644:                     );
                   6645:                     $new_user_create = '<br /><span class="LC_warning">'.&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.").' '.&mt('Contact the <a[_1]>helpdesk</a> for assistance.',$helplink).'</span><br /><br />';
                   6646:                 }
1.576     raeburn  6647:             }
                   6648:         }
                   6649: 
1.556     raeburn  6650:         $newuserscript = <<"ENDSCRIPT";
                   6651: 
1.570     raeburn  6652: function setSearch(createnew,callingForm) {
1.556     raeburn  6653:     if (createnew == 1) {
1.570     raeburn  6654:         for (var i=0; i<callingForm.srchby.length; i++) {
                   6655:             if (callingForm.srchby.options[i].value == 'uname') {
                   6656:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  6657:             }
                   6658:         }
1.570     raeburn  6659:         for (var i=0; i<callingForm.srchin.length; i++) {
                   6660:             if ( callingForm.srchin.options[i].value == 'dom') {
                   6661: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  6662:             }
                   6663:         }
1.570     raeburn  6664:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   6665:             if (callingForm.srchtype.options[i].value == 'exact') {
                   6666:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  6667:             }
                   6668:         }
1.570     raeburn  6669:         for (var i=0; i<callingForm.srchdomain.length; i++) {
                   6670:             if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
                   6671:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  6672:             }
                   6673:         }
                   6674:     }
                   6675: }
                   6676: ENDSCRIPT
1.558     albertel 6677: 
1.556     raeburn  6678:     }
                   6679: 
1.555     raeburn  6680:     my $output = <<"END_BLOCK";
1.556     raeburn  6681: <script type="text/javascript">
1.570     raeburn  6682: function validateEntry(callingForm) {
1.558     albertel 6683: 
1.556     raeburn  6684:     var checkok = 1;
1.558     albertel 6685:     var srchin;
1.570     raeburn  6686:     for (var i=0; i<callingForm.srchin.length; i++) {
                   6687: 	if ( callingForm.srchin[i].checked ) {
                   6688: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 6689: 	}
                   6690:     }
                   6691: 
1.570     raeburn  6692:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   6693:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   6694:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   6695:     var srchterm =  callingForm.srchterm.value;
                   6696:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  6697:     var msg = "";
                   6698: 
                   6699:     if (srchterm == "") {
                   6700:         checkok = 0;
1.571     raeburn  6701:         msg += "$lt{'youm'}\\n";
1.556     raeburn  6702:     }
                   6703: 
1.569     raeburn  6704:     if (srchtype== 'begins') {
                   6705:         if (srchterm.length < 2) {
                   6706:             checkok = 0;
1.571     raeburn  6707:             msg += "$lt{'thte'}\\n";
1.569     raeburn  6708:         }
                   6709:     }
                   6710: 
1.556     raeburn  6711:     if (srchtype== 'contains') {
                   6712:         if (srchterm.length < 3) {
                   6713:             checkok = 0;
1.571     raeburn  6714:             msg += "$lt{'thet'}\\n";
1.556     raeburn  6715:         }
                   6716:     }
                   6717:     if (srchin == 'instd') {
                   6718:         if (srchdomain == '') {
                   6719:             checkok = 0;
1.571     raeburn  6720:             msg += "$lt{'yomc'}\\n";
1.556     raeburn  6721:         }
                   6722:     }
                   6723:     if (srchin == 'dom') {
                   6724:         if (srchdomain == '') {
                   6725:             checkok = 0;
1.571     raeburn  6726:             msg += "$lt{'ymcd'}\\n";
1.556     raeburn  6727:         }
                   6728:     }
                   6729:     if (srchby == 'lastfirst') {
                   6730:         if (srchterm.indexOf(",") == -1) {
                   6731:             checkok = 0;
1.571     raeburn  6732:             msg += "$lt{'whus'}\\n";
1.556     raeburn  6733:         }
                   6734:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   6735:             checkok = 0;
1.571     raeburn  6736:             msg += "$lt{'whse'}\\n";
1.556     raeburn  6737:         }
                   6738:     }
                   6739:     if (checkok == 0) {
1.571     raeburn  6740:         alert("$lt{'thfo'}\\n"+msg);
1.556     raeburn  6741:         return;
                   6742:     }
                   6743:     if (checkok == 1) {
1.570     raeburn  6744:         callingForm.submit();
1.556     raeburn  6745:     }
                   6746: }
                   6747: 
                   6748: $newuserscript
                   6749: 
                   6750: </script>
1.558     albertel 6751: 
                   6752: $new_user_create
                   6753: 
1.555     raeburn  6754: <table>
1.558     albertel 6755:  <tr>
1.573     raeburn  6756:   <td>$lt{'doma'}:</td>
                   6757:   <td>$domform</td>
                   6758:   </td>
                   6759:  </tr>
                   6760:  <tr>
                   6761:   <td>$lt{'usr'}:</td>
1.563     raeburn  6762:   <td>$srchbysel
                   6763:       $srchtypesel 
                   6764:       <input type="text" size="15" name="srchterm" value="$srchterm" />
1.564     albertel 6765:       $srchinsel 
1.563     raeburn  6766:   </td>
                   6767:  </tr>
1.555     raeburn  6768: </table>
                   6769: <br />
                   6770: END_BLOCK
1.558     albertel 6771: 
1.555     raeburn  6772:     return $output;
                   6773: }
                   6774: 
1.612     raeburn  6775: sub user_rule_check {
1.615     raeburn  6776:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.612     raeburn  6777:     my $response;
                   6778:     if (ref($usershash) eq 'HASH') {
                   6779:         foreach my $user (keys(%{$usershash})) {
                   6780:             my ($uname,$udom) = split(/:/,$user);
                   6781:             next if ($udom eq '' || $uname eq '');
1.615     raeburn  6782:             my ($id,$newuser);
1.612     raeburn  6783:             if (ref($usershash->{$user}) eq 'HASH') {
1.615     raeburn  6784:                 $newuser = $usershash->{$user}->{'newuser'};
1.612     raeburn  6785:                 $id = $usershash->{$user}->{'id'};
                   6786:             }
                   6787:             my $inst_response;
                   6788:             if (ref($checks) eq 'HASH') {
                   6789:                 if (defined($checks->{'username'})) {
1.615     raeburn  6790:                     ($inst_response,%{$inst_results->{$user}}) = 
1.612     raeburn  6791:                         &Apache::lonnet::get_instuser($udom,$uname);
                   6792:                 } elsif (defined($checks->{'id'})) {
1.615     raeburn  6793:                     ($inst_response,%{$inst_results->{$user}}) =
1.612     raeburn  6794:                         &Apache::lonnet::get_instuser($udom,undef,$id);
                   6795:                 }
1.615     raeburn  6796:             } else {
                   6797:                 ($inst_response,%{$inst_results->{$user}}) =
                   6798:                     &Apache::lonnet::get_instuser($udom,$uname);
                   6799:                 return;
1.612     raeburn  6800:             }
1.615     raeburn  6801:             if (!$got_rules->{$udom}) {
1.612     raeburn  6802:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
                   6803:                                                   ['usercreation'],$udom);
                   6804:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
1.615     raeburn  6805:                     foreach my $item ('username','id') {
1.612     raeburn  6806:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   6807:                             $$curr_rules{$udom}{$item} = 
                   6808:                                 $domconfig{'usercreation'}{$item.'_rule'};
1.585     raeburn  6809:                         }
                   6810:                     }
                   6811:                 }
1.615     raeburn  6812:                 $got_rules->{$udom} = 1;  
1.585     raeburn  6813:             }
1.612     raeburn  6814:             foreach my $item (keys(%{$checks})) {
                   6815:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   6816:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   6817:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
                   6818:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
                   6819:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   6820:                                 if ($rule_check{$rule}) {
                   6821:                                     $$rulematch{$user}{$item} = $rule;
                   6822:                                     if ($inst_response eq 'ok') {
1.615     raeburn  6823:                                         if (ref($inst_results) eq 'HASH') {
                   6824:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   6825:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   6826:                                                     $$alerts{$item}{$udom}{$uname} = 1;
                   6827:                                                 }
1.612     raeburn  6828:                                             }
                   6829:                                         }
1.615     raeburn  6830:                                     }
                   6831:                                     last;
1.585     raeburn  6832:                                 }
                   6833:                             }
                   6834:                         }
                   6835:                     }
                   6836:                 }
                   6837:             }
                   6838:         }
                   6839:     }
1.612     raeburn  6840:     return;
                   6841: }
                   6842: 
                   6843: sub user_rule_formats {
                   6844:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   6845:     my %text = ( 
                   6846:                  'username' => 'Usernames',
                   6847:                  'id'       => 'IDs',
                   6848:                );
                   6849:     my $output;
                   6850:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   6851:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   6852:         if (@{$ruleorder} > 0) {
                   6853:             $output = '<br />'.&mt("$text{$check} with the following format(s) may <span class=\"LC_cusr_emph\">only</span> be used for verified users at [_1]:",$domdesc).' <ul>';
                   6854:             foreach my $rule (@{$ruleorder}) {
                   6855:                 if (ref($curr_rules) eq 'ARRAY') {
                   6856:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   6857:                         if (ref($rules->{$rule}) eq 'HASH') {
                   6858:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   6859:                                         $rules->{$rule}{'desc'}.'</li>';
                   6860:                         }
                   6861:                     }
                   6862:                 }
                   6863:             }
                   6864:             $output .= '</ul>';
                   6865:         }
                   6866:     }
                   6867:     return $output;
                   6868: }
                   6869: 
                   6870: sub instrule_disallow_msg {
1.615     raeburn  6871:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  6872:     my $response;
                   6873:     my %text = (
                   6874:                   item   => 'username',
                   6875:                   items  => 'usernames',
                   6876:                   match  => 'matches',
                   6877:                   do     => 'does',
                   6878:                   action => 'a username',
                   6879:                   one    => 'one',
                   6880:                );
                   6881:     if ($count > 1) {
                   6882:         $text{'item'} = 'usernames';
                   6883:         $text{'match'} ='match';
                   6884:         $text{'do'} = 'do';
                   6885:         $text{'action'} = 'usernames',
                   6886:         $text{'one'} = 'ones';
                   6887:     }
                   6888:     if ($checkitem eq 'id') {
                   6889:         $text{'items'} = 'IDs';
                   6890:         $text{'item'} = 'ID';
                   6891:         $text{'action'} = 'an ID';
1.615     raeburn  6892:         if ($count > 1) {
                   6893:             $text{'item'} = 'IDs';
                   6894:             $text{'action'} = 'IDs';
                   6895:         }
1.612     raeburn  6896:     }
1.674     bisitz   6897:     $response = &mt("The $text{'item'} you chose $text{'match'} the format of $text{'items'} defined for [_1], but the $text{'item'} $text{'do'} not exist in the institutional directory.",'<span class="LC_cusr_emph">'.$domdesc.'</span>').'<br />';
1.615     raeburn  6898:     if ($mode eq 'upload') {
                   6899:         if ($checkitem eq 'username') {
                   6900:             $response .= &mt("You will need to modify your upload file so it will include $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   6901:         } elsif ($checkitem eq 'id') {
1.674     bisitz   6902:             $response .= &mt("Either upload a file which includes $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or when associating fields with data columns, omit an association for the Student/Employee ID field.");
1.615     raeburn  6903:         }
1.669     raeburn  6904:     } elsif ($mode eq 'selfcreate') {
                   6905:         if ($checkitem eq 'id') {
                   6906:             $response .= &mt("You must either choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or leave the ID field blank.");
                   6907:         }
1.615     raeburn  6908:     } else {
                   6909:         if ($checkitem eq 'username') {
                   6910:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   6911:         } elsif ($checkitem eq 'id') {
                   6912:             $response .= &mt("You must either choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or leave the ID field blank.");
                   6913:         }
1.612     raeburn  6914:     }
                   6915:     return $response;
1.585     raeburn  6916: }
                   6917: 
1.624     raeburn  6918: sub personal_data_fieldtitles {
                   6919:     my %fieldtitles = &Apache::lonlocal::texthash (
                   6920:                         id => 'Student/Employee ID',
                   6921:                         permanentemail => 'E-mail address',
                   6922:                         lastname => 'Last Name',
                   6923:                         firstname => 'First Name',
                   6924:                         middlename => 'Middle Name',
                   6925:                         generation => 'Generation',
                   6926:                         gen => 'Generation',
                   6927:                    );
                   6928:     return %fieldtitles;
                   6929: }
                   6930: 
1.642     raeburn  6931: sub sorted_inst_types {
                   6932:     my ($dom) = @_;
                   6933:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   6934:     my $othertitle = &mt('All users');
                   6935:     if ($env{'request.course.id'}) {
1.668     raeburn  6936:         $othertitle  = &mt('Any users');
1.642     raeburn  6937:     }
                   6938:     my @types;
                   6939:     if (ref($order) eq 'ARRAY') {
                   6940:         @types = @{$order};
                   6941:     }
                   6942:     if (@types == 0) {
                   6943:         if (ref($usertypes) eq 'HASH') {
                   6944:             @types = sort(keys(%{$usertypes}));
                   6945:         }
                   6946:     }
                   6947:     if (keys(%{$usertypes}) > 0) {
                   6948:         $othertitle = &mt('Other users');
                   6949:     }
                   6950:     return ($othertitle,$usertypes,\@types);
                   6951: }
                   6952: 
1.645     raeburn  6953: sub get_institutional_codes {
                   6954:     my ($settings,$allcourses,$LC_code) = @_;
                   6955: # Get complete list of course sections to update
                   6956:     my @currsections = ();
                   6957:     my @currxlists = ();
                   6958:     my $coursecode = $$settings{'internal.coursecode'};
                   6959: 
                   6960:     if ($$settings{'internal.sectionnums'} ne '') {
                   6961:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   6962:     }
                   6963: 
                   6964:     if ($$settings{'internal.crosslistings'} ne '') {
                   6965:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   6966:     }
                   6967: 
                   6968:     if (@currxlists > 0) {
                   6969:         foreach (@currxlists) {
                   6970:             if (m/^([^:]+):(\w*)$/) {
                   6971:                 unless (grep/^$1$/,@{$allcourses}) {
                   6972:                     push @{$allcourses},$1;
                   6973:                     $$LC_code{$1} = $2;
                   6974:                 }
                   6975:             }
                   6976:         }
                   6977:     }
                   6978:  
                   6979:     if (@currsections > 0) {
                   6980:         foreach (@currsections) {
                   6981:             if (m/^(\w+):(\w*)$/) {
                   6982:                 my $sec = $coursecode.$1;
                   6983:                 my $lc_sec = $2;
                   6984:                 unless (grep/^$sec$/,@{$allcourses}) {
                   6985:                     push @{$allcourses},$sec;
                   6986:                     $$LC_code{$sec} = $lc_sec;
                   6987:                 }
                   6988:             }
                   6989:         }
                   6990:     }
                   6991:     return;
                   6992: }
                   6993: 
1.112     bowersj2 6994: =pod
                   6995: 
1.549     albertel 6996: =back
                   6997: 
                   6998: =head1 HTTP Helpers
                   6999: 
                   7000: =over 4
                   7001: 
1.648     raeburn  7002: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 7003: 
1.258     albertel 7004: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 7005: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 7006: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 7007: 
                   7008: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   7009: $possible_names is an ref to an array of form element names.  As an example:
                   7010: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 7011: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 7012: 
                   7013: =cut
1.1       albertel 7014: 
1.6       albertel 7015: sub get_unprocessed_cgi {
1.25      albertel 7016:   my ($query,$possible_names)= @_;
1.26      matthew  7017:   # $Apache::lonxml::debug=1;
1.356     albertel 7018:   foreach my $pair (split(/&/,$query)) {
                   7019:     my ($name, $value) = split(/=/,$pair);
1.369     www      7020:     $name = &unescape($name);
1.25      albertel 7021:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   7022:       $value =~ tr/+/ /;
                   7023:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 7024:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 7025:     }
1.16      harris41 7026:   }
1.6       albertel 7027: }
                   7028: 
1.112     bowersj2 7029: =pod
                   7030: 
1.648     raeburn  7031: =item * &cacheheader() 
1.112     bowersj2 7032: 
                   7033: returns cache-controlling header code
                   7034: 
                   7035: =cut
                   7036: 
1.7       albertel 7037: sub cacheheader {
1.258     albertel 7038:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 7039:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   7040:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 7041:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   7042:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 7043:     return $output;
1.7       albertel 7044: }
                   7045: 
1.112     bowersj2 7046: =pod
                   7047: 
1.648     raeburn  7048: =item * &no_cache($r) 
1.112     bowersj2 7049: 
                   7050: specifies header code to not have cache
                   7051: 
                   7052: =cut
                   7053: 
1.9       albertel 7054: sub no_cache {
1.216     albertel 7055:     my ($r) = @_;
                   7056:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 7057: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 7058:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   7059:     $r->no_cache(1);
                   7060:     $r->header_out("Expires" => $date);
                   7061:     $r->header_out("Pragma" => "no-cache");
1.123     www      7062: }
                   7063: 
                   7064: sub content_type {
1.181     albertel 7065:     my ($r,$type,$charset) = @_;
1.299     foxr     7066:     if ($r) {
                   7067: 	#  Note that printout.pl calls this with undef for $r.
                   7068: 	&no_cache($r);
                   7069:     }
1.258     albertel 7070:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 7071:     unless ($charset) {
                   7072: 	$charset=&Apache::lonlocal::current_encoding;
                   7073:     }
                   7074:     if ($charset) { $type.='; charset='.$charset; }
                   7075:     if ($r) {
                   7076: 	$r->content_type($type);
                   7077:     } else {
                   7078: 	print("Content-type: $type\n\n");
                   7079:     }
1.9       albertel 7080: }
1.25      albertel 7081: 
1.112     bowersj2 7082: =pod
                   7083: 
1.648     raeburn  7084: =item * &add_to_env($name,$value) 
1.112     bowersj2 7085: 
1.258     albertel 7086: adds $name to the %env hash with value
1.112     bowersj2 7087: $value, if $name already exists, the entry is converted to an array
                   7088: reference and $value is added to the array.
                   7089: 
                   7090: =cut
                   7091: 
1.25      albertel 7092: sub add_to_env {
                   7093:   my ($name,$value)=@_;
1.258     albertel 7094:   if (defined($env{$name})) {
                   7095:     if (ref($env{$name})) {
1.25      albertel 7096:       #already have multiple values
1.258     albertel 7097:       push(@{ $env{$name} },$value);
1.25      albertel 7098:     } else {
                   7099:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 7100:       my $first=$env{$name};
                   7101:       undef($env{$name});
                   7102:       push(@{ $env{$name} },$first,$value);
1.25      albertel 7103:     }
                   7104:   } else {
1.258     albertel 7105:     $env{$name}=$value;
1.25      albertel 7106:   }
1.31      albertel 7107: }
1.149     albertel 7108: 
                   7109: =pod
                   7110: 
1.648     raeburn  7111: =item * &get_env_multiple($name) 
1.149     albertel 7112: 
1.258     albertel 7113: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 7114: values may be defined and end up as an array ref.
                   7115: 
                   7116: returns an array of values
                   7117: 
                   7118: =cut
                   7119: 
                   7120: sub get_env_multiple {
                   7121:     my ($name) = @_;
                   7122:     my @values;
1.258     albertel 7123:     if (defined($env{$name})) {
1.149     albertel 7124:         # exists is it an array
1.258     albertel 7125:         if (ref($env{$name})) {
                   7126:             @values=@{ $env{$name} };
1.149     albertel 7127:         } else {
1.258     albertel 7128:             $values[0]=$env{$name};
1.149     albertel 7129:         }
                   7130:     }
                   7131:     return(@values);
                   7132: }
                   7133: 
1.660     raeburn  7134: sub ask_for_embedded_content {
                   7135:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
                   7136:     my $upload_output = '
                   7137:    <form name="upload_embedded" action="'.$actionurl.'"
                   7138:                   method="post" enctype="multipart/form-data">';
                   7139:     $upload_output .= $state;
1.661     raeburn  7140:     $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
1.660     raeburn  7141: 
                   7142:     my $num = 0;
                   7143:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
                   7144:         $upload_output .= &start_data_table_row().
                   7145:             '<td>'.$embed_file.'</td><td>';
                   7146:         if ($args->{'ignore_remote_references'}
                   7147:             && $embed_file =~ m{^\w+://}) {
                   7148:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
                   7149:         } elsif ($args->{'error_on_invalid_names'}
                   7150:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
                   7151: 
                   7152:             $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
                   7153: 
                   7154:         } else {
                   7155:             $upload_output .='
1.661     raeburn  7156:            <input name="embedded_item_'.$num.'" type="file" value="" />
1.660     raeburn  7157:            <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
                   7158:             my $attrib = join(':',@{$$allfiles{$embed_file}});
                   7159:             $upload_output .=
                   7160:                 "\n\t\t".
                   7161:                 '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   7162:                 $attrib.'" />';
                   7163:             if (exists($$codebase{$embed_file})) {
                   7164:                 $upload_output .=
                   7165:                     "\n\t\t".
                   7166:                     '<input name="codebase_'.$num.'" type="hidden" value="'.
                   7167:                     &escape($$codebase{$embed_file}).'" />';
                   7168:             }
                   7169:         }
                   7170:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
                   7171:         $num++;
                   7172:     }
                   7173:     $upload_output .= &Apache::loncommon::end_data_table().'<br />
                   7174:    <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
                   7175:    <input type ="submit" value="'.&mt('Upload Listed Files').'" />
                   7176:    '.&mt('(only files for which a location has been provided will be uploaded)').'
                   7177:    </form>';
                   7178:     return $upload_output;
                   7179: }
                   7180: 
1.661     raeburn  7181: sub upload_embedded {
                   7182:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
                   7183:         $current_disk_usage) = @_;
                   7184:     my $output;
                   7185:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   7186:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   7187:         my $orig_uploaded_filename =
                   7188:             $env{'form.embedded_item_'.$i.'.filename'};
                   7189: 
                   7190:         $env{'form.embedded_orig_'.$i} =
                   7191:             &unescape($env{'form.embedded_orig_'.$i});
                   7192:         my ($path,$fname) =
                   7193:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   7194:         # no path, whole string is fname
                   7195:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   7196: 
                   7197:         $path = $env{'form.currentpath'}.$path;
                   7198:         $fname = &Apache::lonnet::clean_filename($fname);
                   7199:         # See if there is anything left
                   7200:         next if ($fname eq '');
                   7201: 
                   7202:         # Check if file already exists as a file or directory.
                   7203:         my ($state,$msg);
                   7204:         if ($context eq 'portfolio') {
                   7205:             my $port_path = $dirpath;
                   7206:             if ($group ne '') {
                   7207:                 $port_path = "groups/$group/$port_path";
                   7208:             }
                   7209:             ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
                   7210:                                               $dir_root,$port_path,$disk_quota,
                   7211:                                               $current_disk_usage,$uname,$udom);
                   7212:             if ($state eq 'will_exceed_quota'
                   7213:                 || $state eq 'file_locked'
                   7214:                 || $state eq 'file_exists' ) {
                   7215:                 $output .= $msg;
                   7216:                 next;
                   7217:             }
                   7218:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   7219:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   7220:             if ($state eq 'exists') {
                   7221:                 $output .= $msg;
                   7222:                 next;
                   7223:             }
                   7224:         }
                   7225:         # Check if extension is valid
                   7226:         if (($fname =~ /\.(\w+)$/) &&
                   7227:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
                   7228:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
                   7229:             next;
                   7230:         } elsif (($fname =~ /\.(\w+)$/) &&
                   7231:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
                   7232:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
                   7233:             next;
                   7234:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
                   7235:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
                   7236:             next;
                   7237:         }
                   7238: 
                   7239:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
                   7240:         if ($context eq 'portfolio') {
                   7241:             my $result=
                   7242:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
                   7243:                                                 $dirpath.$path);
                   7244:             if ($result !~ m|^/uploaded/|) {
                   7245:                 $output .= '<span class="LC_error">'
                   7246:                       .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   7247:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   7248:                       .'</span><br />';
                   7249:                 next;
                   7250:             } else {
                   7251:                 $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
                   7252:                            $path.$fname.'</span>').'</p>';     
                   7253:             }
                   7254:         } else {
                   7255: # Save the file
                   7256:             my $target = $env{'form.embedded_item_'.$i};
                   7257:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   7258:             my $dest = $fullpath.$fname;
                   7259:             my $url = $url_root.$dirpath.'/'.$path.$fname;
                   7260:             my @parts=split(/\//,$fullpath);
                   7261:             my $count;
                   7262:             my $filepath = $dir_root;
                   7263:             for ($count=4;$count<=$#parts;$count++) {
                   7264:                 $filepath .= "/$parts[$count]";
                   7265:                 if ((-e $filepath)!=1) {
                   7266:                     mkdir($filepath,0770);
                   7267:                 }
                   7268:             }
                   7269:             my $fh;
                   7270:             if (!open($fh,'>'.$dest)) {
                   7271:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   7272:                 $output .= '<span class="LC_error">'.
                   7273:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
                   7274:                            '</span><br />';
                   7275:             } else {
                   7276:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   7277:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   7278:                     $output .= '<span class="LC_error">'.
                   7279:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
                   7280:                               '</span><br />';
                   7281:                 } else {
                   7282:                     if ($context eq 'testbank') {
                   7283:                         $output .= &mt('Embedded file uploaded successfully:').
                   7284:                                    '&nbsp;<a href="'.$url.'">'.
                   7285:                                    $orig_uploaded_filename.'</a><br />';
                   7286:                     } else {
                   7287:                         $output .= '<font size="+2">'.
                   7288:                                    &mt('View embedded file: [_1]','<a href="'.$url.'">'.
                   7289:                                    $orig_uploaded_filename.'</a>').'</font><br />';
                   7290:                     }
                   7291:                 }
                   7292:                 close($fh);
                   7293:             }
                   7294:         }
                   7295:     }
                   7296:     return $output;
                   7297: }
                   7298: 
                   7299: sub check_for_existing {
                   7300:     my ($path,$fname,$element) = @_;
                   7301:     my ($state,$msg);
                   7302:     if (-d $path.'/'.$fname) {
                   7303:         $state = 'exists';
                   7304:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   7305:     } elsif (-e $path.'/'.$fname) {
                   7306:         $state = 'exists';
                   7307:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   7308:     }
                   7309:     if ($state eq 'exists') {
                   7310:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   7311:     }
                   7312:     return ($state,$msg);
                   7313: }
                   7314: 
                   7315: sub check_for_upload {
                   7316:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   7317:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
                   7318:     my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
                   7319:     my $getpropath = 1;
                   7320:     my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
                   7321:                                             $getpropath);
                   7322:     my $found_file = 0;
                   7323:     my $locked_file = 0;
                   7324:     foreach my $line (@dir_list) {
                   7325:         my ($file_name)=split(/\&/,$line,2);
                   7326:         if ($file_name eq $fname){
                   7327:             $file_name = $path.$file_name;
                   7328:             if ($group ne '') {
                   7329:                 $file_name = $group.$file_name;
                   7330:             }
                   7331:             $found_file = 1;
                   7332:             if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
                   7333:                 $locked_file = 1;
                   7334:             }
                   7335:         }
                   7336:     }
                   7337:     if (($current_disk_usage + $filesize) > $disk_quota){
                   7338:         my $msg = '<span class="LC_error">'.
                   7339:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
                   7340:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
                   7341:         return ('will_exceed_quota',$msg);
                   7342:     } elsif ($found_file) {
                   7343:         if ($locked_file) {
                   7344:             my $msg = '<span class="LC_error">';
                   7345:             $msg .= &mt('Unable to upload [_1]. A locked file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>','<span class="LC_filename">'.$port_path.$env{'form.currentpath'}.'</span>');
                   7346:             $msg .= '</span><br />';
                   7347:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   7348:             return ('file_locked',$msg);
                   7349:         } else {
                   7350:             my $msg = '<span class="LC_error">';
                   7351:             $msg .= &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
                   7352:             $msg .= '</span>';
                   7353:             $msg .= '<br />';
                   7354:             $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
                   7355:             return ('file_exists',$msg);
                   7356:         }
                   7357:     }
                   7358: }
                   7359: 
1.31      albertel 7360: 
1.41      ng       7361: =pod
1.45      matthew  7362: 
1.464     albertel 7363: =back
1.41      ng       7364: 
1.112     bowersj2 7365: =head1 CSV Upload/Handling functions
1.38      albertel 7366: 
1.41      ng       7367: =over 4
                   7368: 
1.648     raeburn  7369: =item * &upfile_store($r)
1.41      ng       7370: 
                   7371: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 7372: needs $env{'form.upfile'}
1.41      ng       7373: returns $datatoken to be put into hidden field
                   7374: 
                   7375: =cut
1.31      albertel 7376: 
                   7377: sub upfile_store {
                   7378:     my $r=shift;
1.258     albertel 7379:     $env{'form.upfile'}=~s/\r/\n/gs;
                   7380:     $env{'form.upfile'}=~s/\f/\n/gs;
                   7381:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   7382:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 7383: 
1.258     albertel 7384:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   7385: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 7386:     {
1.158     raeburn  7387:         my $datafile = $r->dir_config('lonDaemons').
                   7388:                            '/tmp/'.$datatoken.'.tmp';
                   7389:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 7390:             print $fh $env{'form.upfile'};
1.158     raeburn  7391:             close($fh);
                   7392:         }
1.31      albertel 7393:     }
                   7394:     return $datatoken;
                   7395: }
                   7396: 
1.56      matthew  7397: =pod
                   7398: 
1.648     raeburn  7399: =item * &load_tmp_file($r)
1.41      ng       7400: 
                   7401: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 7402: needs $env{'form.datatoken'},
                   7403: sets $env{'form.upfile'} to the contents of the file
1.41      ng       7404: 
                   7405: =cut
1.31      albertel 7406: 
                   7407: sub load_tmp_file {
                   7408:     my $r=shift;
                   7409:     my @studentdata=();
                   7410:     {
1.158     raeburn  7411:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 7412:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  7413:         if ( open(my $fh,"<$studentfile") ) {
                   7414:             @studentdata=<$fh>;
                   7415:             close($fh);
                   7416:         }
1.31      albertel 7417:     }
1.258     albertel 7418:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 7419: }
                   7420: 
1.56      matthew  7421: =pod
                   7422: 
1.648     raeburn  7423: =item * &upfile_record_sep()
1.41      ng       7424: 
                   7425: Separate uploaded file into records
                   7426: returns array of records,
1.258     albertel 7427: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       7428: 
                   7429: =cut
1.31      albertel 7430: 
                   7431: sub upfile_record_sep {
1.258     albertel 7432:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 7433:     } else {
1.248     albertel 7434: 	my @records;
1.258     albertel 7435: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 7436: 	    if ($line=~/^\s*$/) { next; }
                   7437: 	    push(@records,$line);
                   7438: 	}
                   7439: 	return @records;
1.31      albertel 7440:     }
                   7441: }
                   7442: 
1.56      matthew  7443: =pod
                   7444: 
1.648     raeburn  7445: =item * &record_sep($record)
1.41      ng       7446: 
1.258     albertel 7447: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       7448: 
                   7449: =cut
                   7450: 
1.263     www      7451: sub takeleft {
                   7452:     my $index=shift;
                   7453:     return substr('0000'.$index,-4,4);
                   7454: }
                   7455: 
1.31      albertel 7456: sub record_sep {
                   7457:     my $record=shift;
                   7458:     my %components=();
1.258     albertel 7459:     if ($env{'form.upfiletype'} eq 'xml') {
                   7460:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 7461:         my $i=0;
1.356     albertel 7462:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 7463:             $field=~s/^(\"|\')//;
                   7464:             $field=~s/(\"|\')$//;
1.263     www      7465:             $components{&takeleft($i)}=$field;
1.31      albertel 7466:             $i++;
                   7467:         }
1.258     albertel 7468:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 7469:         my $i=0;
1.356     albertel 7470:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 7471:             $field=~s/^(\"|\')//;
                   7472:             $field=~s/(\"|\')$//;
1.263     www      7473:             $components{&takeleft($i)}=$field;
1.31      albertel 7474:             $i++;
                   7475:         }
                   7476:     } else {
1.561     www      7477:         my $separator=',';
1.480     banghart 7478:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      7479:             $separator=';';
1.480     banghart 7480:         }
1.31      albertel 7481:         my $i=0;
1.561     www      7482: # the character we are looking for to indicate the end of a quote or a record 
                   7483:         my $looking_for=$separator;
                   7484: # do not add the characters to the fields
                   7485:         my $ignore=0;
                   7486: # we just encountered a separator (or the beginning of the record)
                   7487:         my $just_found_separator=1;
                   7488: # store the field we are working on here
                   7489:         my $field='';
                   7490: # work our way through all characters in record
                   7491:         foreach my $character ($record=~/(.)/g) {
                   7492:             if ($character eq $looking_for) {
                   7493:                if ($character ne $separator) {
                   7494: # Found the end of a quote, again looking for separator
                   7495:                   $looking_for=$separator;
                   7496:                   $ignore=1;
                   7497:                } else {
                   7498: # Found a separator, store away what we got
                   7499:                   $components{&takeleft($i)}=$field;
                   7500: 	          $i++;
                   7501:                   $just_found_separator=1;
                   7502:                   $ignore=0;
                   7503:                   $field='';
                   7504:                }
                   7505:                next;
                   7506:             }
                   7507: # single or double quotation marks after a separator indicate beginning of a quote
                   7508: # we are now looking for the end of the quote and need to ignore separators
                   7509:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   7510:                $looking_for=$character;
                   7511:                next;
                   7512:             }
                   7513: # ignore would be true after we reached the end of a quote
                   7514:             if ($ignore) { next; }
                   7515:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   7516:             $field.=$character;
                   7517:             $just_found_separator=0; 
1.31      albertel 7518:         }
1.561     www      7519: # catch the very last entry, since we never encountered the separator
                   7520:         $components{&takeleft($i)}=$field;
1.31      albertel 7521:     }
                   7522:     return %components;
                   7523: }
                   7524: 
1.144     matthew  7525: ######################################################
                   7526: ######################################################
                   7527: 
1.56      matthew  7528: =pod
                   7529: 
1.648     raeburn  7530: =item * &upfile_select_html()
1.41      ng       7531: 
1.144     matthew  7532: Return HTML code to select a file from the users machine and specify 
                   7533: the file type.
1.41      ng       7534: 
                   7535: =cut
                   7536: 
1.144     matthew  7537: ######################################################
                   7538: ######################################################
1.31      albertel 7539: sub upfile_select_html {
1.144     matthew  7540:     my %Types = (
                   7541:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 7542:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  7543:                  space => &mt('Space separated'),
                   7544:                  tab   => &mt('Tabulator separated'),
                   7545: #                 xml   => &mt('HTML/XML'),
                   7546:                  );
                   7547:     my $Str = '<input type="file" name="upfile" size="50" />'.
                   7548:         '<br />Type: <select name="upfiletype">';
                   7549:     foreach my $type (sort(keys(%Types))) {
                   7550:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   7551:     }
                   7552:     $Str .= "</select>\n";
                   7553:     return $Str;
1.31      albertel 7554: }
                   7555: 
1.301     albertel 7556: sub get_samples {
                   7557:     my ($records,$toget) = @_;
                   7558:     my @samples=({});
                   7559:     my $got=0;
                   7560:     foreach my $rec (@$records) {
                   7561: 	my %temp = &record_sep($rec);
                   7562: 	if (! grep(/\S/, values(%temp))) { next; }
                   7563: 	if (%temp) {
                   7564: 	    $samples[$got]=\%temp;
                   7565: 	    $got++;
                   7566: 	    if ($got == $toget) { last; }
                   7567: 	}
                   7568:     }
                   7569:     return \@samples;
                   7570: }
                   7571: 
1.144     matthew  7572: ######################################################
                   7573: ######################################################
                   7574: 
1.56      matthew  7575: =pod
                   7576: 
1.648     raeburn  7577: =item * &csv_print_samples($r,$records)
1.41      ng       7578: 
                   7579: Prints a table of sample values from each column uploaded $r is an
                   7580: Apache Request ref, $records is an arrayref from
                   7581: &Apache::loncommon::upfile_record_sep
                   7582: 
                   7583: =cut
                   7584: 
1.144     matthew  7585: ######################################################
                   7586: ######################################################
1.31      albertel 7587: sub csv_print_samples {
                   7588:     my ($r,$records) = @_;
1.662     bisitz   7589:     my $samples = &get_samples($records,5);
1.301     albertel 7590: 
1.594     raeburn  7591:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   7592:               &start_data_table_header_row());
1.356     albertel 7593:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
                   7594:         $r->print('<th>'.&mt('Column&nbsp;[_1]',($sample+1)).'</th>'); }
1.594     raeburn  7595:     $r->print(&end_data_table_header_row());
1.301     albertel 7596:     foreach my $hash (@$samples) {
1.594     raeburn  7597: 	$r->print(&start_data_table_row());
1.356     albertel 7598: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 7599: 	    $r->print('<td>');
1.356     albertel 7600: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 7601: 	    $r->print('</td>');
                   7602: 	}
1.594     raeburn  7603: 	$r->print(&end_data_table_row());
1.31      albertel 7604:     }
1.594     raeburn  7605:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 7606: }
                   7607: 
1.144     matthew  7608: ######################################################
                   7609: ######################################################
                   7610: 
1.56      matthew  7611: =pod
                   7612: 
1.648     raeburn  7613: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       7614: 
                   7615: Prints a table to create associations between values and table columns.
1.144     matthew  7616: 
1.41      ng       7617: $r is an Apache Request ref,
                   7618: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  7619: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       7620: 
                   7621: =cut
                   7622: 
1.144     matthew  7623: ######################################################
                   7624: ######################################################
1.31      albertel 7625: sub csv_print_select_table {
                   7626:     my ($r,$records,$d) = @_;
1.301     albertel 7627:     my $i=0;
                   7628:     my $samples = &get_samples($records,1);
1.144     matthew  7629:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  7630: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  7631:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  7632:               '<th>'.&mt('Column').'</th>'.
                   7633:               &end_data_table_header_row()."\n");
1.356     albertel 7634:     foreach my $array_ref (@$d) {
                   7635: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.594     raeburn  7636: 	$r->print(&start_data_table_row().'<tr><td>'.$display.'</td>');
1.31      albertel 7637: 
                   7638: 	$r->print('<td><select name=f'.$i.
1.32      matthew  7639: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 7640: 	$r->print('<option value="none"></option>');
1.356     albertel 7641: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   7642: 	    $r->print('<option value="'.$sample.'"'.
                   7643:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   7644:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 7645: 	}
1.594     raeburn  7646: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 7647: 	$i++;
                   7648:     }
1.594     raeburn  7649:     $r->print(&end_data_table());
1.31      albertel 7650:     $i--;
                   7651:     return $i;
                   7652: }
1.56      matthew  7653: 
1.144     matthew  7654: ######################################################
                   7655: ######################################################
                   7656: 
1.56      matthew  7657: =pod
1.31      albertel 7658: 
1.648     raeburn  7659: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       7660: 
                   7661: Prints a table of sample values from the upload and can make associate samples to internal names.
                   7662: 
                   7663: $r is an Apache Request ref,
                   7664: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   7665: $d is an array of 2 element arrays (internal name, displayed name)
                   7666: 
                   7667: =cut
                   7668: 
1.144     matthew  7669: ######################################################
                   7670: ######################################################
1.31      albertel 7671: sub csv_samples_select_table {
                   7672:     my ($r,$records,$d) = @_;
                   7673:     my $i=0;
1.144     matthew  7674:     #
1.662     bisitz   7675:     my $max_samples = 5;
                   7676:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  7677:     $r->print(&start_data_table().
                   7678:               &start_data_table_header_row().'<th>'.
                   7679:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   7680:               &end_data_table_header_row());
1.301     albertel 7681: 
                   7682:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  7683: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  7684: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 7685: 	foreach my $option (@$d) {
                   7686: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  7687: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 7688:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  7689:                       $display.'</option>');
1.31      albertel 7690: 	}
                   7691: 	$r->print('</select></td><td>');
1.662     bisitz   7692: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 7693: 	    if (defined($samples->[$line]{$key})) { 
                   7694: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   7695: 	    }
                   7696: 	}
1.594     raeburn  7697: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 7698: 	$i++;
                   7699:     }
1.594     raeburn  7700:     $r->print(&end_data_table());
1.31      albertel 7701:     $i--;
                   7702:     return($i);
1.115     matthew  7703: }
                   7704: 
1.144     matthew  7705: ######################################################
                   7706: ######################################################
                   7707: 
1.115     matthew  7708: =pod
                   7709: 
1.648     raeburn  7710: =item * &clean_excel_name($name)
1.115     matthew  7711: 
                   7712: Returns a replacement for $name which does not contain any illegal characters.
                   7713: 
                   7714: =cut
                   7715: 
1.144     matthew  7716: ######################################################
                   7717: ######################################################
1.115     matthew  7718: sub clean_excel_name {
                   7719:     my ($name) = @_;
                   7720:     $name =~ s/[:\*\?\/\\]//g;
                   7721:     if (length($name) > 31) {
                   7722:         $name = substr($name,0,31);
                   7723:     }
                   7724:     return $name;
1.25      albertel 7725: }
1.84      albertel 7726: 
1.85      albertel 7727: =pod
                   7728: 
1.648     raeburn  7729: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 7730: 
                   7731: Returns either 1 or undef
                   7732: 
                   7733: 1 if the part is to be hidden, undef if it is to be shown
                   7734: 
                   7735: Arguments are:
                   7736: 
                   7737: $id the id of the part to be checked
                   7738: $symb, optional the symb of the resource to check
                   7739: $udom, optional the domain of the user to check for
                   7740: $uname, optional the username of the user to check for
                   7741: 
                   7742: =cut
1.84      albertel 7743: 
                   7744: sub check_if_partid_hidden {
                   7745:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 7746:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 7747: 					 $symb,$udom,$uname);
1.141     albertel 7748:     my $truth=1;
                   7749:     #if the string starts with !, then the list is the list to show not hide
                   7750:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 7751:     my @hiddenlist=split(/,/,$hiddenparts);
                   7752:     foreach my $checkid (@hiddenlist) {
1.141     albertel 7753: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 7754:     }
1.141     albertel 7755:     return !$truth;
1.84      albertel 7756: }
1.127     matthew  7757: 
1.138     matthew  7758: 
                   7759: ############################################################
                   7760: ############################################################
                   7761: 
                   7762: =pod
                   7763: 
1.157     matthew  7764: =back 
                   7765: 
1.138     matthew  7766: =head1 cgi-bin script and graphing routines
                   7767: 
1.157     matthew  7768: =over 4
                   7769: 
1.648     raeburn  7770: =item * &get_cgi_id()
1.138     matthew  7771: 
                   7772: Inputs: none
                   7773: 
                   7774: Returns an id which can be used to pass environment variables
                   7775: to various cgi-bin scripts.  These environment variables will
                   7776: be removed from the users environment after a given time by
                   7777: the routine &Apache::lonnet::transfer_profile_to_env.
                   7778: 
                   7779: =cut
                   7780: 
                   7781: ############################################################
                   7782: ############################################################
1.152     albertel 7783: my $uniq=0;
1.136     matthew  7784: sub get_cgi_id {
1.154     albertel 7785:     $uniq=($uniq+1)%100000;
1.280     albertel 7786:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  7787: }
                   7788: 
1.127     matthew  7789: ############################################################
                   7790: ############################################################
                   7791: 
                   7792: =pod
                   7793: 
1.648     raeburn  7794: =item * &DrawBarGraph()
1.127     matthew  7795: 
1.138     matthew  7796: Facilitates the plotting of data in a (stacked) bar graph.
                   7797: Puts plot definition data into the users environment in order for 
                   7798: graph.png to plot it.  Returns an <img> tag for the plot.
                   7799: The bars on the plot are labeled '1','2',...,'n'.
                   7800: 
                   7801: Inputs:
                   7802: 
                   7803: =over 4
                   7804: 
                   7805: =item $Title: string, the title of the plot
                   7806: 
                   7807: =item $xlabel: string, text describing the X-axis of the plot
                   7808: 
                   7809: =item $ylabel: string, text describing the Y-axis of the plot
                   7810: 
                   7811: =item $Max: scalar, the maximum Y value to use in the plot
                   7812: If $Max is < any data point, the graph will not be rendered.
                   7813: 
1.140     matthew  7814: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  7815: they are plotted.  If undefined, default values will be used.
                   7816: 
1.178     matthew  7817: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   7818: 
1.138     matthew  7819: =item @Values: An array of array references.  Each array reference holds data
                   7820: to be plotted in a stacked bar chart.
                   7821: 
1.239     matthew  7822: =item If the final element of @Values is a hash reference the key/value
                   7823: pairs will be added to the graph definition.
                   7824: 
1.138     matthew  7825: =back
                   7826: 
                   7827: Returns:
                   7828: 
                   7829: An <img> tag which references graph.png and the appropriate identifying
                   7830: information for the plot.
                   7831: 
1.127     matthew  7832: =cut
                   7833: 
                   7834: ############################################################
                   7835: ############################################################
1.134     matthew  7836: sub DrawBarGraph {
1.178     matthew  7837:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  7838:     #
                   7839:     if (! defined($colors)) {
                   7840:         $colors = ['#33ff00', 
                   7841:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   7842:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   7843:                   ]; 
                   7844:     }
1.228     matthew  7845:     my $extra_settings = {};
                   7846:     if (ref($Values[-1]) eq 'HASH') {
                   7847:         $extra_settings = pop(@Values);
                   7848:     }
1.127     matthew  7849:     #
1.136     matthew  7850:     my $identifier = &get_cgi_id();
                   7851:     my $id = 'cgi.'.$identifier;        
1.129     matthew  7852:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  7853:         return '';
                   7854:     }
1.225     matthew  7855:     #
                   7856:     my @Labels;
                   7857:     if (defined($labels)) {
                   7858:         @Labels = @$labels;
                   7859:     } else {
                   7860:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   7861:             push (@Labels,$i+1);
                   7862:         }
                   7863:     }
                   7864:     #
1.129     matthew  7865:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  7866:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  7867:     my %ValuesHash;
                   7868:     my $NumSets=1;
                   7869:     foreach my $array (@Values) {
                   7870:         next if (! ref($array));
1.136     matthew  7871:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  7872:             join(',',@$array);
1.129     matthew  7873:     }
1.127     matthew  7874:     #
1.136     matthew  7875:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  7876:     if ($NumBars < 3) {
                   7877:         $width = 120+$NumBars*32;
1.220     matthew  7878:         $xskip = 1;
1.225     matthew  7879:         $bar_width = 30;
                   7880:     } elsif ($NumBars < 5) {
                   7881:         $width = 120+$NumBars*20;
                   7882:         $xskip = 1;
                   7883:         $bar_width = 20;
1.220     matthew  7884:     } elsif ($NumBars < 10) {
1.136     matthew  7885:         $width = 120+$NumBars*15;
                   7886:         $xskip = 1;
                   7887:         $bar_width = 15;
                   7888:     } elsif ($NumBars <= 25) {
                   7889:         $width = 120+$NumBars*11;
                   7890:         $xskip = 5;
                   7891:         $bar_width = 8;
                   7892:     } elsif ($NumBars <= 50) {
                   7893:         $width = 120+$NumBars*8;
                   7894:         $xskip = 5;
                   7895:         $bar_width = 4;
                   7896:     } else {
                   7897:         $width = 120+$NumBars*8;
                   7898:         $xskip = 5;
                   7899:         $bar_width = 4;
                   7900:     }
                   7901:     #
1.137     matthew  7902:     $Max = 1 if ($Max < 1);
                   7903:     if ( int($Max) < $Max ) {
                   7904:         $Max++;
                   7905:         $Max = int($Max);
                   7906:     }
1.127     matthew  7907:     $Title  = '' if (! defined($Title));
                   7908:     $xlabel = '' if (! defined($xlabel));
                   7909:     $ylabel = '' if (! defined($ylabel));
1.369     www      7910:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   7911:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   7912:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  7913:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  7914:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   7915:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   7916:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   7917:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   7918:     $ValuesHash{$id.'.height'}   = $height;
                   7919:     $ValuesHash{$id.'.width'}    = $width;
                   7920:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   7921:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   7922:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  7923:     #
1.228     matthew  7924:     # Deal with other parameters
                   7925:     while (my ($key,$value) = each(%$extra_settings)) {
                   7926:         $ValuesHash{$id.'.'.$key} = $value;
                   7927:     }
                   7928:     #
1.646     raeburn  7929:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  7930:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   7931: }
                   7932: 
                   7933: ############################################################
                   7934: ############################################################
                   7935: 
                   7936: =pod
                   7937: 
1.648     raeburn  7938: =item * &DrawXYGraph()
1.137     matthew  7939: 
1.138     matthew  7940: Facilitates the plotting of data in an XY graph.
                   7941: Puts plot definition data into the users environment in order for 
                   7942: graph.png to plot it.  Returns an <img> tag for the plot.
                   7943: 
                   7944: Inputs:
                   7945: 
                   7946: =over 4
                   7947: 
                   7948: =item $Title: string, the title of the plot
                   7949: 
                   7950: =item $xlabel: string, text describing the X-axis of the plot
                   7951: 
                   7952: =item $ylabel: string, text describing the Y-axis of the plot
                   7953: 
                   7954: =item $Max: scalar, the maximum Y value to use in the plot
                   7955: If $Max is < any data point, the graph will not be rendered.
                   7956: 
                   7957: =item $colors: Array ref containing the hex color codes for the data to be 
                   7958: plotted in.  If undefined, default values will be used.
                   7959: 
                   7960: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   7961: 
                   7962: =item $Ydata: Array ref containing Array refs.  
1.185     www      7963: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  7964: 
                   7965: =item %Values: hash indicating or overriding any default values which are 
                   7966: passed to graph.png.  
                   7967: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   7968: 
                   7969: =back
                   7970: 
                   7971: Returns:
                   7972: 
                   7973: An <img> tag which references graph.png and the appropriate identifying
                   7974: information for the plot.
                   7975: 
1.137     matthew  7976: =cut
                   7977: 
                   7978: ############################################################
                   7979: ############################################################
                   7980: sub DrawXYGraph {
                   7981:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   7982:     #
                   7983:     # Create the identifier for the graph
                   7984:     my $identifier = &get_cgi_id();
                   7985:     my $id = 'cgi.'.$identifier;
                   7986:     #
                   7987:     $Title  = '' if (! defined($Title));
                   7988:     $xlabel = '' if (! defined($xlabel));
                   7989:     $ylabel = '' if (! defined($ylabel));
                   7990:     my %ValuesHash = 
                   7991:         (
1.369     www      7992:          $id.'.title'  => &escape($Title),
                   7993:          $id.'.xlabel' => &escape($xlabel),
                   7994:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  7995:          $id.'.y_max_value'=> $Max,
                   7996:          $id.'.labels'     => join(',',@$Xlabels),
                   7997:          $id.'.PlotType'   => 'XY',
                   7998:          );
                   7999:     #
                   8000:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   8001:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   8002:     }
                   8003:     #
                   8004:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   8005:         return '';
                   8006:     }
                   8007:     my $NumSets=1;
1.138     matthew  8008:     foreach my $array (@{$Ydata}){
1.137     matthew  8009:         next if (! ref($array));
                   8010:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   8011:     }
1.138     matthew  8012:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  8013:     #
                   8014:     # Deal with other parameters
                   8015:     while (my ($key,$value) = each(%Values)) {
                   8016:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  8017:     }
                   8018:     #
1.646     raeburn  8019:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  8020:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   8021: }
                   8022: 
                   8023: ############################################################
                   8024: ############################################################
                   8025: 
                   8026: =pod
                   8027: 
1.648     raeburn  8028: =item * &DrawXYYGraph()
1.138     matthew  8029: 
                   8030: Facilitates the plotting of data in an XY graph with two Y axes.
                   8031: Puts plot definition data into the users environment in order for 
                   8032: graph.png to plot it.  Returns an <img> tag for the plot.
                   8033: 
                   8034: Inputs:
                   8035: 
                   8036: =over 4
                   8037: 
                   8038: =item $Title: string, the title of the plot
                   8039: 
                   8040: =item $xlabel: string, text describing the X-axis of the plot
                   8041: 
                   8042: =item $ylabel: string, text describing the Y-axis of the plot
                   8043: 
                   8044: =item $colors: Array ref containing the hex color codes for the data to be 
                   8045: plotted in.  If undefined, default values will be used.
                   8046: 
                   8047: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   8048: 
                   8049: =item $Ydata1: The first data set
                   8050: 
                   8051: =item $Min1: The minimum value of the left Y-axis
                   8052: 
                   8053: =item $Max1: The maximum value of the left Y-axis
                   8054: 
                   8055: =item $Ydata2: The second data set
                   8056: 
                   8057: =item $Min2: The minimum value of the right Y-axis
                   8058: 
                   8059: =item $Max2: The maximum value of the left Y-axis
                   8060: 
                   8061: =item %Values: hash indicating or overriding any default values which are 
                   8062: passed to graph.png.  
                   8063: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   8064: 
                   8065: =back
                   8066: 
                   8067: Returns:
                   8068: 
                   8069: An <img> tag which references graph.png and the appropriate identifying
                   8070: information for the plot.
1.136     matthew  8071: 
                   8072: =cut
                   8073: 
                   8074: ############################################################
                   8075: ############################################################
1.137     matthew  8076: sub DrawXYYGraph {
                   8077:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   8078:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  8079:     #
                   8080:     # Create the identifier for the graph
                   8081:     my $identifier = &get_cgi_id();
                   8082:     my $id = 'cgi.'.$identifier;
                   8083:     #
                   8084:     $Title  = '' if (! defined($Title));
                   8085:     $xlabel = '' if (! defined($xlabel));
                   8086:     $ylabel = '' if (! defined($ylabel));
                   8087:     my %ValuesHash = 
                   8088:         (
1.369     www      8089:          $id.'.title'  => &escape($Title),
                   8090:          $id.'.xlabel' => &escape($xlabel),
                   8091:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  8092:          $id.'.labels' => join(',',@$Xlabels),
                   8093:          $id.'.PlotType' => 'XY',
                   8094:          $id.'.NumSets' => 2,
1.137     matthew  8095:          $id.'.two_axes' => 1,
                   8096:          $id.'.y1_max_value' => $Max1,
                   8097:          $id.'.y1_min_value' => $Min1,
                   8098:          $id.'.y2_max_value' => $Max2,
                   8099:          $id.'.y2_min_value' => $Min2,
1.136     matthew  8100:          );
                   8101:     #
1.137     matthew  8102:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   8103:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   8104:     }
                   8105:     #
                   8106:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   8107:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  8108:         return '';
                   8109:     }
                   8110:     my $NumSets=1;
1.137     matthew  8111:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  8112:         next if (! ref($array));
                   8113:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  8114:     }
                   8115:     #
                   8116:     # Deal with other parameters
                   8117:     while (my ($key,$value) = each(%Values)) {
                   8118:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  8119:     }
                   8120:     #
1.646     raeburn  8121:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 8122:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  8123: }
                   8124: 
                   8125: ############################################################
                   8126: ############################################################
                   8127: 
                   8128: =pod
                   8129: 
1.157     matthew  8130: =back 
                   8131: 
1.139     matthew  8132: =head1 Statistics helper routines?  
                   8133: 
                   8134: Bad place for them but what the hell.
                   8135: 
1.157     matthew  8136: =over 4
                   8137: 
1.648     raeburn  8138: =item * &chartlink()
1.139     matthew  8139: 
                   8140: Returns a link to the chart for a specific student.  
                   8141: 
                   8142: Inputs:
                   8143: 
                   8144: =over 4
                   8145: 
                   8146: =item $linktext: The text of the link
                   8147: 
                   8148: =item $sname: The students username
                   8149: 
                   8150: =item $sdomain: The students domain
                   8151: 
                   8152: =back
                   8153: 
1.157     matthew  8154: =back
                   8155: 
1.139     matthew  8156: =cut
                   8157: 
                   8158: ############################################################
                   8159: ############################################################
                   8160: sub chartlink {
                   8161:     my ($linktext, $sname, $sdomain) = @_;
                   8162:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      8163:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 8164:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  8165:        '">'.$linktext.'</a>';
1.153     matthew  8166: }
                   8167: 
                   8168: #######################################################
                   8169: #######################################################
                   8170: 
                   8171: =pod
                   8172: 
                   8173: =head1 Course Environment Routines
1.157     matthew  8174: 
                   8175: =over 4
1.153     matthew  8176: 
1.648     raeburn  8177: =item * &restore_course_settings()
1.153     matthew  8178: 
1.648     raeburn  8179: =item * &store_course_settings()
1.153     matthew  8180: 
                   8181: Restores/Store indicated form parameters from the course environment.
                   8182: Will not overwrite existing values of the form parameters.
                   8183: 
                   8184: Inputs: 
                   8185: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   8186: 
                   8187: a hash ref describing the data to be stored.  For example:
                   8188:    
                   8189: %Save_Parameters = ('Status' => 'scalar',
                   8190:     'chartoutputmode' => 'scalar',
                   8191:     'chartoutputdata' => 'scalar',
                   8192:     'Section' => 'array',
1.373     raeburn  8193:     'Group' => 'array',
1.153     matthew  8194:     'StudentData' => 'array',
                   8195:     'Maps' => 'array');
                   8196: 
                   8197: Returns: both routines return nothing
                   8198: 
1.631     raeburn  8199: =back
                   8200: 
1.153     matthew  8201: =cut
                   8202: 
                   8203: #######################################################
                   8204: #######################################################
                   8205: sub store_course_settings {
1.496     albertel 8206:     return &store_settings($env{'request.course.id'},@_);
                   8207: }
                   8208: 
                   8209: sub store_settings {
1.153     matthew  8210:     # save to the environment
                   8211:     # appenv the same items, just to be safe
1.300     albertel 8212:     my $udom  = $env{'user.domain'};
                   8213:     my $uname = $env{'user.name'};
1.496     albertel 8214:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  8215:     my %SaveHash;
                   8216:     my %AppHash;
                   8217:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 8218:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 8219:         my $envname = 'environment.'.$basename;
1.258     albertel 8220:         if (exists($env{'form.'.$setting})) {
1.153     matthew  8221:             # Save this value away
                   8222:             if ($type eq 'scalar' &&
1.258     albertel 8223:                 (! exists($env{$envname}) || 
                   8224:                  $env{$envname} ne $env{'form.'.$setting})) {
                   8225:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   8226:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  8227:             } elsif ($type eq 'array') {
                   8228:                 my $stored_form;
1.258     albertel 8229:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  8230:                     $stored_form = join(',',
                   8231:                                         map {
1.369     www      8232:                                             &escape($_);
1.258     albertel 8233:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  8234:                 } else {
                   8235:                     $stored_form = 
1.369     www      8236:                         &escape($env{'form.'.$setting});
1.153     matthew  8237:                 }
                   8238:                 # Determine if the array contents are the same.
1.258     albertel 8239:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  8240:                     $SaveHash{$basename} = $stored_form;
                   8241:                     $AppHash{$envname}   = $stored_form;
                   8242:                 }
                   8243:             }
                   8244:         }
                   8245:     }
                   8246:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 8247:                                           $udom,$uname);
1.153     matthew  8248:     if ($put_result !~ /^(ok|delayed)/) {
                   8249:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   8250:                                  'got error:'.$put_result);
                   8251:     }
                   8252:     # Make sure these settings stick around in this session, too
1.646     raeburn  8253:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  8254:     return;
                   8255: }
                   8256: 
                   8257: sub restore_course_settings {
1.499     albertel 8258:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 8259: }
                   8260: 
                   8261: sub restore_settings {
                   8262:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  8263:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 8264:         next if (exists($env{'form.'.$setting}));
1.496     albertel 8265:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  8266:             '.'.$setting;
1.258     albertel 8267:         if (exists($env{$envname})) {
1.153     matthew  8268:             if ($type eq 'scalar') {
1.258     albertel 8269:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  8270:             } elsif ($type eq 'array') {
1.258     albertel 8271:                 $env{'form.'.$setting} = [ 
1.153     matthew  8272:                                            map { 
1.369     www      8273:                                                &unescape($_); 
1.258     albertel 8274:                                            } split(',',$env{$envname})
1.153     matthew  8275:                                            ];
                   8276:             }
                   8277:         }
                   8278:     }
1.127     matthew  8279: }
                   8280: 
1.618     raeburn  8281: #######################################################
                   8282: #######################################################
                   8283: 
                   8284: =pod
                   8285: 
                   8286: =head1 Domain E-mail Routines  
                   8287: 
                   8288: =over 4
                   8289: 
1.648     raeburn  8290: =item * &build_recipient_list()
1.618     raeburn  8291: 
                   8292: Build recipient lists for three types of e-mail:
                   8293: (a) Error Reports, (b) Package Updates, (c) Help requests, generated by
1.619     raeburn  8294: lonerrorhandler.pm, CHECKRPMS and lonsupportreq.pm respectively.
1.618     raeburn  8295: 
                   8296: Inputs:
1.619     raeburn  8297: defmail (scalar - email address of default recipient), 
1.618     raeburn  8298: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
1.619     raeburn  8299: defdom (domain for which to retrieve configuration settings),
                   8300: origmail (scalar - email address of recipient from loncapa.conf, 
                   8301: i.e., predates configuration by DC via domainprefs.pm 
1.618     raeburn  8302: 
1.655     raeburn  8303: Returns: comma separated list of addresses to which to send e-mail.
                   8304: 
                   8305: =back
1.618     raeburn  8306: 
                   8307: =cut
                   8308: 
                   8309: ############################################################
                   8310: ############################################################
                   8311: sub build_recipient_list {
1.619     raeburn  8312:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  8313:     my @recipients;
                   8314:     my $otheremails;
                   8315:     my %domconfig =
                   8316:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
                   8317:     if (ref($domconfig{'contacts'}) eq 'HASH') {
                   8318:         if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   8319:             my @contacts = ('adminemail','supportemail');
                   8320:             foreach my $item (@contacts) {
                   8321:                 if ($domconfig{'contacts'}{$mailing}{$item}) {
1.619     raeburn  8322:                     my $addr = $domconfig{'contacts'}{$item}; 
                   8323:                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   8324:                         push(@recipients,$addr);
                   8325:                     }
1.618     raeburn  8326:                 }
                   8327:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   8328:             }
                   8329:         }
1.619     raeburn  8330:     } elsif ($origmail ne '') {
                   8331:         push(@recipients,$origmail);
1.618     raeburn  8332:     }
1.679.2.6! raeburn  8333:     if (defined($defmail)) {
        !          8334:         if ($defmail ne '') {
        !          8335:             push(@recipients,$defmail);
        !          8336:         }
1.618     raeburn  8337:     }
                   8338:     if ($otheremails) {
1.619     raeburn  8339:         my @others;
                   8340:         if ($otheremails =~ /,/) {
                   8341:             @others = split(/,/,$otheremails);
1.618     raeburn  8342:         } else {
1.619     raeburn  8343:             push(@others,$otheremails);
                   8344:         }
                   8345:         foreach my $addr (@others) {
                   8346:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   8347:                 push(@recipients,$addr);
                   8348:             }
1.618     raeburn  8349:         }
                   8350:     }
1.619     raeburn  8351:     my $recipientlist = join(',',@recipients); 
1.618     raeburn  8352:     return $recipientlist;
                   8353: }
                   8354: 
1.127     matthew  8355: ############################################################
                   8356: ############################################################
1.154     albertel 8357: 
1.655     raeburn  8358: =pod
                   8359: 
                   8360: =head1 Course Catalog Routines
                   8361: 
                   8362: =over 4
                   8363: 
                   8364: =item * &gather_categories()
                   8365: 
                   8366: Converts category definitions - keys of categories hash stored in  
                   8367: coursecategories in configuration.db on the primary library server in a 
                   8368: domain - to an array.  Also generates javascript and idx hash used to 
                   8369: generate Domain Coordinator interface for editing Course Categories.
                   8370: 
                   8371: Inputs:
1.663     raeburn  8372: 
1.655     raeburn  8373: categories (reference to hash of category definitions).
1.663     raeburn  8374: 
1.655     raeburn  8375: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   8376:       categories and subcategories).
1.663     raeburn  8377: 
1.655     raeburn  8378: idx (reference to hash of counters used in Domain Coordinator interface for 
                   8379:       editing Course Categories).
1.663     raeburn  8380: 
1.655     raeburn  8381: jsarray (reference to array of categories used to create Javascript arrays for
                   8382:          Domain Coordinator interface for editing Course Categories).
                   8383: 
                   8384: Returns: nothing
                   8385: 
                   8386: Side effects: populates cats, idx and jsarray. 
                   8387: 
                   8388: =cut
                   8389: 
                   8390: sub gather_categories {
                   8391:     my ($categories,$cats,$idx,$jsarray) = @_;
                   8392:     my %counters;
                   8393:     my $num = 0;
                   8394:     foreach my $item (keys(%{$categories})) {
                   8395:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   8396:         if ($container eq '' && $depth == 0) {
                   8397:             $cats->[$depth][$categories->{$item}] = $cat;
                   8398:         } else {
                   8399:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   8400:         }
                   8401:         my ($escitem,$tail) = split(/:/,$item,2);
                   8402:         if ($counters{$tail} eq '') {
                   8403:             $counters{$tail} = $num;
                   8404:             $num ++;
                   8405:         }
                   8406:         if (ref($idx) eq 'HASH') {
                   8407:             $idx->{$item} = $counters{$tail};
                   8408:         }
                   8409:         if (ref($jsarray) eq 'ARRAY') {
                   8410:             push(@{$jsarray->[$counters{$tail}]},$item);
                   8411:         }
                   8412:     }
                   8413:     return;
                   8414: }
                   8415: 
                   8416: =pod
                   8417: 
                   8418: =item * &extract_categories()
                   8419: 
                   8420: Used to generate breadcrumb trails for course categories.
                   8421: 
                   8422: Inputs:
1.663     raeburn  8423: 
1.655     raeburn  8424: categories (reference to hash of category definitions).
1.663     raeburn  8425: 
1.655     raeburn  8426: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   8427:       categories and subcategories).
1.663     raeburn  8428: 
1.655     raeburn  8429: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  8430: 
1.655     raeburn  8431: allitems (reference to hash - key is category key 
                   8432:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  8433: 
1.655     raeburn  8434: idx (reference to hash of counters used in Domain Coordinator interface for
                   8435:       editing Course Categories).
1.663     raeburn  8436: 
1.655     raeburn  8437: jsarray (reference to array of categories used to create Javascript arrays for
                   8438:          Domain Coordinator interface for editing Course Categories).
                   8439: 
1.665     raeburn  8440: subcats (reference to hash of arrays containing all subcategories within each 
                   8441:          category, -recursive)
                   8442: 
1.655     raeburn  8443: Returns: nothing
                   8444: 
                   8445: Side effects: populates trails and allitems hash references.
                   8446: 
                   8447: =cut
                   8448: 
                   8449: sub extract_categories {
1.665     raeburn  8450:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  8451:     if (ref($categories) eq 'HASH') {
                   8452:         &gather_categories($categories,$cats,$idx,$jsarray);
                   8453:         if (ref($cats->[0]) eq 'ARRAY') {
                   8454:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   8455:                 my $name = $cats->[0][$i];
                   8456:                 my $item = &escape($name).'::0';
                   8457:                 my $trailstr;
                   8458:                 if ($name eq 'instcode') {
                   8459:                     $trailstr = &mt('Official courses (with institutional codes)');
                   8460:                 } else {
                   8461:                     $trailstr = $name;
                   8462:                 }
                   8463:                 if ($allitems->{$item} eq '') {
                   8464:                     push(@{$trails},$trailstr);
                   8465:                     $allitems->{$item} = scalar(@{$trails})-1;
                   8466:                 }
                   8467:                 my @parents = ($name);
                   8468:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   8469:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   8470:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  8471:                         if (ref($subcats) eq 'HASH') {
                   8472:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   8473:                         }
                   8474:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   8475:                     }
                   8476:                 } else {
                   8477:                     if (ref($subcats) eq 'HASH') {
                   8478:                         $subcats->{$item} = [];
1.655     raeburn  8479:                     }
                   8480:                 }
                   8481:             }
                   8482:         }
                   8483:     }
                   8484:     return;
                   8485: }
                   8486: 
                   8487: =pod
                   8488: 
                   8489: =item *&recurse_categories()
                   8490: 
                   8491: Recursively used to generate breadcrumb trails for course categories.
                   8492: 
                   8493: Inputs:
1.663     raeburn  8494: 
1.655     raeburn  8495: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   8496:       categories and subcategories).
1.663     raeburn  8497: 
1.655     raeburn  8498: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  8499: 
                   8500: category (current course category, for which breadcrumb trail is being generated).
                   8501: 
                   8502: trails (reference to array of breadcrumb trails for each category).
                   8503: 
1.655     raeburn  8504: allitems (reference to hash - key is category key
                   8505:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  8506: 
1.655     raeburn  8507: parents (array containing containers directories for current category, 
                   8508:          back to top level). 
                   8509: 
                   8510: Returns: nothing
                   8511: 
                   8512: Side effects: populates trails and allitems hash references
                   8513: 
                   8514: =cut
                   8515: 
                   8516: sub recurse_categories {
1.665     raeburn  8517:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  8518:     my $shallower = $depth - 1;
                   8519:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   8520:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   8521:             my $name = $cats->[$depth]{$category}[$k];
                   8522:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   8523:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   8524:             if ($allitems->{$item} eq '') {
                   8525:                 push(@{$trails},$trailstr);
                   8526:                 $allitems->{$item} = scalar(@{$trails})-1;
                   8527:             }
                   8528:             my $deeper = $depth+1;
                   8529:             push(@{$parents},$category);
1.665     raeburn  8530:             if (ref($subcats) eq 'HASH') {
                   8531:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   8532:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   8533:                     my $higher;
                   8534:                     if ($j > 0) {
                   8535:                         $higher = &escape($parents->[$j]).':'.
                   8536:                                   &escape($parents->[$j-1]).':'.$j;
                   8537:                     } else {
                   8538:                         $higher = &escape($parents->[$j]).'::'.$j;
                   8539:                     }
                   8540:                     push(@{$subcats->{$higher}},$subcat);
                   8541:                 }
                   8542:             }
                   8543:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   8544:                                 $subcats);
1.655     raeburn  8545:             pop(@{$parents});
                   8546:         }
                   8547:     } else {
                   8548:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   8549:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   8550:         if ($allitems->{$item} eq '') {
                   8551:             push(@{$trails},$trailstr);
                   8552:             $allitems->{$item} = scalar(@{$trails})-1;
                   8553:         }
                   8554:     }
                   8555:     return;
                   8556: }
                   8557: 
1.663     raeburn  8558: =pod
                   8559: 
                   8560: =item *&assign_categories_table()
                   8561: 
                   8562: Create a datatable for display of hierarchical categories in a domain,
                   8563: with checkboxes to allow a course to be categorized. 
                   8564: 
                   8565: Inputs:
                   8566: 
                   8567: cathash - reference to hash of categories defined for the domain (from
                   8568:           configuration.db)
                   8569: 
                   8570: currcat - scalar with an & separated list of categories assigned to a course. 
                   8571: 
                   8572: Returns: $output (markup to be displayed) 
                   8573: 
                   8574: =cut
                   8575: 
                   8576: sub assign_categories_table {
                   8577:     my ($cathash,$currcat) = @_;
                   8578:     my $output;
                   8579:     if (ref($cathash) eq 'HASH') {
                   8580:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   8581:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   8582:         $maxdepth = scalar(@cats);
                   8583:         if (@cats > 0) {
                   8584:             my $itemcount = 0;
                   8585:             if (ref($cats[0]) eq 'ARRAY') {
                   8586:                 $output = &Apache::loncommon::start_data_table();
                   8587:                 my @currcategories;
                   8588:                 if ($currcat ne '') {
                   8589:                     @currcategories = split('&',$currcat);
                   8590:                 }
                   8591:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   8592:                     my $parent = $cats[0][$i];
                   8593:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   8594:                     next if ($parent eq 'instcode');
                   8595:                     my $item = &escape($parent).'::0';
                   8596:                     my $checked = '';
                   8597:                     if (@currcategories > 0) {
                   8598:                         if (grep(/^\Q$item\E$/,@currcategories)) {
                   8599:                             $checked = ' checked="checked" ';
                   8600:                         }
                   8601:                     }
1.675     raeburn  8602:                     $output .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   8603:                                '<input type="checkbox" name="usecategory" value="'.
                   8604:                                $item.'"'.$checked.' />'.$parent.'</span>'.
                   8605:                                '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  8606:                     my $depth = 1;
                   8607:                     push(@path,$parent);
                   8608:                     $output .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
                   8609:                     pop(@path);
                   8610:                     $output .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
                   8611:                     $itemcount ++;
                   8612:                 }
                   8613:                 $output .= &Apache::loncommon::end_data_table();
                   8614:             }
                   8615:         }
                   8616:     }
                   8617:     return $output;
                   8618: }
                   8619: 
                   8620: =pod
                   8621: 
                   8622: =item *&assign_category_rows()
                   8623: 
                   8624: Create a datatable row for display of nested categories in a domain,
                   8625: with checkboxes to allow a course to be categorized,called recursively.
                   8626: 
                   8627: Inputs:
                   8628: 
                   8629: itemcount - track row number for alternating colors
                   8630: 
                   8631: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   8632:       categories and subcategories.
                   8633: 
                   8634: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   8635: 
                   8636: parent - parent of current category item
                   8637: 
                   8638: path - Array containing all categories back up through the hierarchy from the
                   8639:        current category to the top level.
                   8640: 
                   8641: currcategories - reference to array of current categories assigned to the course
                   8642: 
                   8643: Returns: $output (markup to be displayed).
                   8644: 
                   8645: =cut
                   8646: 
                   8647: sub assign_category_rows {
                   8648:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
                   8649:     my ($text,$name,$item,$chgstr);
                   8650:     if (ref($cats) eq 'ARRAY') {
                   8651:         my $maxdepth = scalar(@{$cats});
                   8652:         if (ref($cats->[$depth]) eq 'HASH') {
                   8653:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   8654:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   8655:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   8656:                 $text .= '<td><table class="LC_datatable">';
                   8657:                 for (my $j=0; $j<$numchildren; $j++) {
                   8658:                     $name = $cats->[$depth]{$parent}[$j];
                   8659:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   8660:                     my $deeper = $depth+1;
                   8661:                     my $checked = '';
                   8662:                     if (ref($currcategories) eq 'ARRAY') {
                   8663:                         if (@{$currcategories} > 0) {
                   8664:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
                   8665:                                 $checked = ' checked="checked" ';
                   8666:                             }
                   8667:                         }
                   8668:                     }
1.664     raeburn  8669:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   8670:                              '<input type="checkbox" name="usecategory" value="'.
1.675     raeburn  8671:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
                   8672:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   8673:                              '</td><td>';
1.663     raeburn  8674:                     if (ref($path) eq 'ARRAY') {
                   8675:                         push(@{$path},$name);
                   8676:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
                   8677:                         pop(@{$path});
                   8678:                     }
                   8679:                     $text .= '</td></tr>';
                   8680:                 }
                   8681:                 $text .= '</table></td>';
                   8682:             }
                   8683:         }
                   8684:     }
                   8685:     return $text;
                   8686: }
                   8687: 
1.655     raeburn  8688: ############################################################
                   8689: ############################################################
                   8690: 
                   8691: 
1.443     albertel 8692: sub commit_customrole {
1.664     raeburn  8693:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  8694:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 8695:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   8696:                          ($end?', ending '.localtime($end):'').': <b>'.
                   8697:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  8698:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 8699:                  '</b><br />';
                   8700:     return $output;
                   8701: }
                   8702: 
                   8703: sub commit_standardrole {
1.541     raeburn  8704:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
                   8705:     my ($output,$logmsg,$linefeed);
                   8706:     if ($context eq 'auto') {
                   8707:         $linefeed = "\n";
                   8708:     } else {
                   8709:         $linefeed = "<br />\n";
                   8710:     }  
1.443     albertel 8711:     if ($three eq 'st') {
1.541     raeburn  8712:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
                   8713:                                          $one,$two,$sec,$context);
                   8714:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  8715:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   8716:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 8717:         } else {
1.541     raeburn  8718:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 8719:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  8720:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   8721:             if ($context eq 'auto') {
                   8722:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   8723:             } else {
                   8724:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   8725:                &mt('Add to classlist').': <b>ok</b>';
                   8726:             }
                   8727:             $output .= $linefeed;
1.443     albertel 8728:         }
                   8729:     } else {
                   8730:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   8731:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  8732:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  8733:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  8734:         if ($context eq 'auto') {
                   8735:             $output .= $result.$linefeed;
                   8736:         } else {
                   8737:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   8738:         }
1.443     albertel 8739:     }
                   8740:     return $output;
                   8741: }
                   8742: 
                   8743: sub commit_studentrole {
1.541     raeburn  8744:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
1.626     raeburn  8745:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  8746:     if ($context eq 'auto') {
                   8747:         $linefeed = "\n";
                   8748:     } else {
                   8749:         $linefeed = '<br />'."\n";
                   8750:     }
1.443     albertel 8751:     if (defined($one) && defined($two)) {
                   8752:         my $cid=$one.'_'.$two;
                   8753:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   8754:         my $secchange = 0;
                   8755:         my $expire_role_result;
                   8756:         my $modify_section_result;
1.628     raeburn  8757:         if ($oldsec ne '-1') { 
                   8758:             if ($oldsec ne $sec) {
1.443     albertel 8759:                 $secchange = 1;
1.628     raeburn  8760:                 my $now = time;
1.443     albertel 8761:                 my $uurl='/'.$cid;
                   8762:                 $uurl=~s/\_/\//g;
                   8763:                 if ($oldsec) {
                   8764:                     $uurl.='/'.$oldsec;
                   8765:                 }
1.626     raeburn  8766:                 $oldsecurl = $uurl;
1.628     raeburn  8767:                 $expire_role_result = 
1.652     raeburn  8768:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  8769:                 if ($env{'request.course.sec'} ne '') { 
                   8770:                     if ($expire_role_result eq 'refused') {
                   8771:                         my @roles = ('st');
                   8772:                         my @statuses = ('previous');
                   8773:                         my @roledoms = ($one);
                   8774:                         my $withsec = 1;
                   8775:                         my %roleshash = 
                   8776:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   8777:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   8778:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   8779:                             my ($oldstart,$oldend) = 
                   8780:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   8781:                             if ($oldend > 0 && $oldend <= $now) {
                   8782:                                 $expire_role_result = 'ok';
                   8783:                             }
                   8784:                         }
                   8785:                     }
                   8786:                 }
1.443     albertel 8787:                 $result = $expire_role_result;
                   8788:             }
                   8789:         }
                   8790:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.652     raeburn  8791:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
1.443     albertel 8792:             if ($modify_section_result =~ /^ok/) {
                   8793:                 if ($secchange == 1) {
1.628     raeburn  8794:                     if ($sec eq '') {
                   8795:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   8796:                     } else {
                   8797:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   8798:                     }
1.443     albertel 8799:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  8800:                     if ($sec eq '') {
                   8801:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   8802:                     } else {
                   8803:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   8804:                     }
1.443     albertel 8805:                 } else {
1.628     raeburn  8806:                     if ($sec eq '') {
                   8807:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   8808:                     } else {
                   8809:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   8810:                     }
1.443     albertel 8811:                 }
                   8812:             } else {
1.628     raeburn  8813:                 if ($secchange) {       
                   8814:                     $$logmsg .= &mt('Error when attempting section change for [_1] from old section "[_2]" to new section: "[_3]" in course [_4] -error:',$uname,$oldsec,$sec,$cid).' '.$modify_section_result.$linefeed;
                   8815:                 } else {
                   8816:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   8817:                 }
1.443     albertel 8818:             }
                   8819:             $result = $modify_section_result;
                   8820:         } elsif ($secchange == 1) {
1.628     raeburn  8821:             if ($oldsec eq '') {
                   8822:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
                   8823:             } else {
                   8824:                 $$logmsg .= &mt('Error when attempting to expire existing role for [_1] in section [_2] in course [_3] -error: ',$uname,$oldsec,$cid).' '.$expire_role_result.$linefeed;
                   8825:             }
1.626     raeburn  8826:             if ($expire_role_result eq 'refused') {
                   8827:                 my $newsecurl = '/'.$cid;
                   8828:                 $newsecurl =~ s/\_/\//g;
                   8829:                 if ($sec ne '') {
                   8830:                     $newsecurl.='/'.$sec;
                   8831:                 }
                   8832:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   8833:                     if ($sec eq '') {
                   8834:                         $$logmsg .= &mt('Although your current role has privileges to add students to section "[_1]", you do not have privileges to modify existing enrollments unaffiliated with any section.',$sec).$linefeed;
                   8835:                     } else {
                   8836:                         $$logmsg .= &mt('Although your current role has privileges to add students to section "[_1]", you do not have privileges to modify existing enrollments in other sections.',$sec).$linefeed;
                   8837:                     }
                   8838:                 }
                   8839:             }
1.443     albertel 8840:         }
                   8841:     } else {
1.626     raeburn  8842:         $$logmsg .= &mt('Incomplete course id defined.').$linefeed.&mt('Addition of user [_1] from domain [_2] to course [_3], section [_4] not completed.',$uname,$udom,$one.'_'.$two,$sec).$linefeed;
1.443     albertel 8843:         $result = "error: incomplete course id\n";
                   8844:     }
                   8845:     return $result;
                   8846: }
                   8847: 
                   8848: ############################################################
                   8849: ############################################################
                   8850: 
1.566     albertel 8851: sub check_clone {
1.578     raeburn  8852:     my ($args,$linefeed) = @_;
1.566     albertel 8853:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   8854:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   8855:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   8856:     my $clonemsg;
                   8857:     my $can_clone = 0;
                   8858: 
                   8859:     if ($clonehome eq 'no_host') {
1.578     raeburn  8860:         $clonemsg = &mt('No new course created.').$linefeed.&mt('A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});     
1.566     albertel 8861:     } else {
                   8862: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.568     albertel 8863: 	if ($env{'request.role.domain'} eq $args->{'clonedomain'}) {
1.566     albertel 8864: 	    $can_clone = 1;
                   8865: 	} else {
                   8866: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
                   8867: 						 $args->{'clonedomain'},$args->{'clonecourse'});
                   8868: 	    my @cloners = split(/,/,$clonehash{'cloners'});
1.578     raeburn  8869:             if (grep(/^\*$/,@cloners)) {
                   8870:                 $can_clone = 1;
                   8871:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   8872:                 $can_clone = 1;
                   8873:             } else {
                   8874: 	        my %roleshash =
                   8875: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   8876: 					 $args->{'ccdomain'},
                   8877:                                          'userroles',['active'],['cc'],
                   8878: 					 [$args->{'clonedomain'}]);
                   8879: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
                   8880: 		    $can_clone = 1;
                   8881: 	        } else {
                   8882:                     $clonemsg = &mt('No new course created.').$linefeed.&mt('The new course could not be cloned from the existing course because the new course owner ([_1]) does not have cloning rights in the existing course ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
                   8883: 	        }
1.566     albertel 8884: 	    }
1.578     raeburn  8885:         }
1.566     albertel 8886:     }
                   8887:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   8888: }
                   8889: 
1.444     albertel 8890: sub construct_course {
1.541     raeburn  8891:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context) = @_;
1.444     albertel 8892:     my $outcome;
1.541     raeburn  8893:     my $linefeed =  '<br />'."\n";
                   8894:     if ($context eq 'auto') {
                   8895:         $linefeed = "\n";
                   8896:     }
1.566     albertel 8897: 
                   8898: #
                   8899: # Are we cloning?
                   8900: #
                   8901:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   8902:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  8903: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 8904: 	if ($context ne 'auto') {
1.578     raeburn  8905:             if ($clonemsg ne '') {
                   8906: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   8907:             }
1.566     albertel 8908: 	}
                   8909: 	$outcome .= $clonemsg.$linefeed;
                   8910: 
                   8911:         if (!$can_clone) {
                   8912: 	    return (0,$outcome);
                   8913: 	}
                   8914:     }
                   8915: 
1.444     albertel 8916: #
                   8917: # Open course
                   8918: #
                   8919:     my $crstype = lc($args->{'crstype'});
                   8920:     my %cenv=();
                   8921:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   8922:                                              $args->{'cdescr'},
                   8923:                                              $args->{'curl'},
                   8924:                                              $args->{'course_home'},
                   8925:                                              $args->{'nonstandard'},
                   8926:                                              $args->{'crscode'},
                   8927:                                              $args->{'ccuname'}.':'.
                   8928:                                              $args->{'ccdomain'},
                   8929:                                              $args->{'crstype'});
                   8930: 
                   8931:     # Note: The testing routines depend on this being output; see 
                   8932:     # Utils::Course. This needs to at least be output as a comment
                   8933:     # if anyone ever decides to not show this, and Utils::Course::new
                   8934:     # will need to be suitably modified.
1.541     raeburn  8935:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.444     albertel 8936: #
                   8937: # Check if created correctly
                   8938: #
1.479     albertel 8939:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 8940:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.541     raeburn  8941:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 8942: 
1.444     albertel 8943: #
1.566     albertel 8944: # Do the cloning
                   8945: #   
                   8946:     if ($can_clone && $cloneid) {
                   8947: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   8948: 	if ($context ne 'auto') {
                   8949: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   8950: 	}
                   8951: 	$outcome .= $clonemsg.$linefeed;
                   8952: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 8953: # Copy all files
1.637     www      8954: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 8955: # Restore URL
1.566     albertel 8956: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 8957: # Restore title
1.566     albertel 8958: 	$cenv{'description'}=$oldcenv{'description'};
1.444     albertel 8959: # Mark as cloned
1.566     albertel 8960: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      8961: # Need to clone grading mode
                   8962:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   8963:         $cenv{'grading'}=$newenv{'grading'};
                   8964: # Do not clone these environment entries
                   8965:         &Apache::lonnet::del('environment',
                   8966:                   ['default_enrollment_start_date',
                   8967:                    'default_enrollment_end_date',
                   8968:                    'question.email',
                   8969:                    'policy.email',
                   8970:                    'comment.email',
                   8971:                    'pch.users.denied',
                   8972:                    'plc.users.denied'],
                   8973:                    $$crsudom,$$crsunum);
1.444     albertel 8974:     }
1.566     albertel 8975: 
1.444     albertel 8976: #
                   8977: # Set environment (will override cloned, if existing)
                   8978: #
                   8979:     my @sections = ();
                   8980:     my @xlists = ();
                   8981:     if ($args->{'crstype'}) {
                   8982:         $cenv{'type'}=$args->{'crstype'};
                   8983:     }
                   8984:     if ($args->{'crsid'}) {
                   8985:         $cenv{'courseid'}=$args->{'crsid'};
                   8986:     }
                   8987:     if ($args->{'crscode'}) {
                   8988:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   8989:     }
                   8990:     if ($args->{'crsquota'} ne '') {
                   8991:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   8992:     } else {
                   8993:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   8994:     }
                   8995:     if ($args->{'ccuname'}) {
                   8996:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   8997:                                         ':'.$args->{'ccdomain'};
                   8998:     } else {
                   8999:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   9000:     }
                   9001:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   9002:     if ($args->{'crssections'}) {
                   9003:         $cenv{'internal.sectionnums'} = '';
                   9004:         if ($args->{'crssections'} =~ m/,/) {
                   9005:             @sections = split/,/,$args->{'crssections'};
                   9006:         } else {
                   9007:             $sections[0] = $args->{'crssections'};
                   9008:         }
                   9009:         if (@sections > 0) {
                   9010:             foreach my $item (@sections) {
                   9011:                 my ($sec,$gp) = split/:/,$item;
                   9012:                 my $class = $args->{'crscode'}.$sec;
                   9013:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   9014:                 $cenv{'internal.sectionnums'} .= $item.',';
                   9015:                 unless ($addcheck eq 'ok') {
                   9016:                     push @badclasses, $class;
                   9017:                 }
                   9018:             }
                   9019:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   9020:         }
                   9021:     }
                   9022: # do not hide course coordinator from staff listing, 
                   9023: # even if privileged
                   9024:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   9025: # add crosslistings
                   9026:     if ($args->{'crsxlist'}) {
                   9027:         $cenv{'internal.crosslistings'}='';
                   9028:         if ($args->{'crsxlist'} =~ m/,/) {
                   9029:             @xlists = split/,/,$args->{'crsxlist'};
                   9030:         } else {
                   9031:             $xlists[0] = $args->{'crsxlist'};
                   9032:         }
                   9033:         if (@xlists > 0) {
                   9034:             foreach my $item (@xlists) {
                   9035:                 my ($xl,$gp) = split/:/,$item;
                   9036:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   9037:                 $cenv{'internal.crosslistings'} .= $item.',';
                   9038:                 unless ($addcheck eq 'ok') {
                   9039:                     push @badclasses, $xl;
                   9040:                 }
                   9041:             }
                   9042:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   9043:         }
                   9044:     }
                   9045:     if ($args->{'autoadds'}) {
                   9046:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   9047:     }
                   9048:     if ($args->{'autodrops'}) {
                   9049:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   9050:     }
                   9051: # check for notification of enrollment changes
                   9052:     my @notified = ();
                   9053:     if ($args->{'notify_owner'}) {
                   9054:         if ($args->{'ccuname'} ne '') {
                   9055:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   9056:         }
                   9057:     }
                   9058:     if ($args->{'notify_dc'}) {
                   9059:         if ($uname ne '') { 
1.630     raeburn  9060:             push(@notified,$uname.':'.$udom);
1.444     albertel 9061:         }
                   9062:     }
                   9063:     if (@notified > 0) {
                   9064:         my $notifylist;
                   9065:         if (@notified > 1) {
                   9066:             $notifylist = join(',',@notified);
                   9067:         } else {
                   9068:             $notifylist = $notified[0];
                   9069:         }
                   9070:         $cenv{'internal.notifylist'} = $notifylist;
                   9071:     }
                   9072:     if (@badclasses > 0) {
                   9073:         my %lt=&Apache::lonlocal::texthash(
                   9074:                 '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',
                   9075:                 'dnhr' => 'does not have rights to access enrollment in these classes',
                   9076:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
                   9077:         );
1.541     raeburn  9078:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
                   9079:                            ' ('.$lt{'adby'}.')';
                   9080:         if ($context eq 'auto') {
                   9081:             $outcome .= $badclass_msg.$linefeed;
1.566     albertel 9082:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.541     raeburn  9083:             foreach my $item (@badclasses) {
                   9084:                 if ($context eq 'auto') {
                   9085:                     $outcome .= " - $item\n";
                   9086:                 } else {
                   9087:                     $outcome .= "<li>$item</li>\n";
                   9088:                 }
                   9089:             }
                   9090:             if ($context eq 'auto') {
                   9091:                 $outcome .= $linefeed;
                   9092:             } else {
1.566     albertel 9093:                 $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  9094:             }
                   9095:         } 
1.444     albertel 9096:     }
                   9097:     if ($args->{'no_end_date'}) {
                   9098:         $args->{'endaccess'} = 0;
                   9099:     }
                   9100:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   9101:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   9102:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   9103:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   9104:     if ($args->{'showphotos'}) {
                   9105:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   9106:     }
                   9107:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   9108:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   9109:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   9110:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  9111:             my $krb_msg = &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'); 
                   9112:             if ($context eq 'auto') {
                   9113:                 $outcome .= $krb_msg;
                   9114:             } else {
1.566     albertel 9115:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  9116:             }
                   9117:             $outcome .= $linefeed;
1.444     albertel 9118:         }
                   9119:     }
                   9120:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   9121:        if ($args->{'setpolicy'}) {
                   9122:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   9123:        }
                   9124:        if ($args->{'setcontent'}) {
                   9125:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   9126:        }
                   9127:     }
                   9128:     if ($args->{'reshome'}) {
                   9129: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   9130: 	$cenv{'reshome'}=~s/\/+$/\//;
                   9131:     }
                   9132: #
                   9133: # course has keyed access
                   9134: #
                   9135:     if ($args->{'setkeys'}) {
                   9136:        $cenv{'keyaccess'}='yes';
                   9137:     }
                   9138: # if specified, key authority is not course, but user
                   9139: # only active if keyaccess is yes
                   9140:     if ($args->{'keyauth'}) {
1.487     albertel 9141: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   9142: 	$user = &LONCAPA::clean_username($user);
                   9143: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     9144: 	if ($user ne '' && $domain ne '') {
1.487     albertel 9145: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 9146: 	}
                   9147:     }
                   9148: 
                   9149:     if ($args->{'disresdis'}) {
                   9150:         $cenv{'pch.roles.denied'}='st';
                   9151:     }
                   9152:     if ($args->{'disablechat'}) {
                   9153:         $cenv{'plc.roles.denied'}='st';
                   9154:     }
                   9155: 
                   9156:     # Record we've not yet viewed the Course Initialization Helper for this 
                   9157:     # course
                   9158:     $cenv{'course.helper.not.run'} = 1;
                   9159:     #
                   9160:     # Use new Randomseed
                   9161:     #
                   9162:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   9163:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   9164:     #
                   9165:     # The encryption code and receipt prefix for this course
                   9166:     #
                   9167:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   9168:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   9169:     #
                   9170:     # By default, use standard grading
                   9171:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   9172: 
1.541     raeburn  9173:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   9174:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 9175: #
                   9176: # Open all assignments
                   9177: #
                   9178:     if ($args->{'openall'}) {
                   9179:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   9180:        my %storecontent = ($storeunder         => time,
                   9181:                            $storeunder.'.type' => 'date_start');
                   9182:        
                   9183:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  9184:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 9185:    }
                   9186: #
                   9187: # Set first page
                   9188: #
                   9189:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   9190: 	    || ($cloneid)) {
1.445     albertel 9191: 	use LONCAPA::map;
1.444     albertel 9192: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 9193: 
                   9194: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   9195:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   9196: 
1.444     albertel 9197:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   9198:         my $title; my $url;
                   9199:         if ($args->{'firstres'} eq 'syl') {
                   9200: 	    $title='Syllabus';
                   9201:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   9202:         } else {
                   9203:             $title='Navigate Contents';
                   9204:             $url='/adm/navmaps';
                   9205:         }
1.445     albertel 9206: 
                   9207:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   9208: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   9209: 
                   9210: 	if ($errtext) { $fatal=2; }
1.541     raeburn  9211:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 9212:     }
1.566     albertel 9213: 
                   9214:     return (1,$outcome);
1.444     albertel 9215: }
                   9216: 
                   9217: ############################################################
                   9218: ############################################################
                   9219: 
1.378     raeburn  9220: sub course_type {
                   9221:     my ($cid) = @_;
                   9222:     if (!defined($cid)) {
                   9223:         $cid = $env{'request.course.id'};
                   9224:     }
1.404     albertel 9225:     if (defined($env{'course.'.$cid.'.type'})) {
                   9226:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  9227:     } else {
                   9228:         return 'Course';
1.377     raeburn  9229:     }
                   9230: }
1.156     albertel 9231: 
1.406     raeburn  9232: sub group_term {
                   9233:     my $crstype = &course_type();
                   9234:     my %names = (
                   9235:                   'Course' => 'group',
                   9236:                   'Group' => 'team',
                   9237:                 );
                   9238:     return $names{$crstype};
                   9239: }
                   9240: 
1.156     albertel 9241: sub icon {
                   9242:     my ($file)=@_;
1.505     albertel 9243:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 9244:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 9245:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 9246:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   9247: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   9248: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   9249: 	            $curfext.".gif") {
                   9250: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   9251: 		$curfext.".gif";
                   9252: 	}
                   9253:     }
1.249     albertel 9254:     return &lonhttpdurl($iconname);
1.154     albertel 9255: } 
1.84      albertel 9256: 
1.575     albertel 9257: sub lonhttpd_port {
1.215     albertel 9258:     my $lonhttpd_port=$Apache::lonnet::perlvar{'lonhttpdPort'};
                   9259:     if (!defined($lonhttpd_port)) { $lonhttpd_port='8080'; }
1.574     albertel 9260:     # IE doesn't like a secure page getting images from a non-secure
                   9261:     # port (when logging we haven't parsed the browser type so default
                   9262:     # back to secure
                   9263:     if ((!exists($env{'browser.type'}) || $env{'browser.type'} eq 'explorer')
                   9264: 	&& $ENV{'SERVER_PORT'} == 443) {
1.575     albertel 9265: 	return 443;
                   9266:     }
                   9267:     return $lonhttpd_port;
                   9268: 
                   9269: }
                   9270: 
                   9271: sub lonhttpdurl {
                   9272:     my ($url)=@_;
                   9273: 
                   9274:     my $lonhttpd_port = &lonhttpd_port();
                   9275:     if ($lonhttpd_port == 443) {
1.574     albertel 9276: 	return 'https://'.$ENV{'SERVER_NAME'}.$url;
                   9277:     }
1.215     albertel 9278:     return 'http://'.$ENV{'SERVER_NAME'}.':'.$lonhttpd_port.$url;
                   9279: }
                   9280: 
1.213     albertel 9281: sub connection_aborted {
                   9282:     my ($r)=@_;
                   9283:     $r->print(" ");$r->rflush();
                   9284:     my $c = $r->connection;
                   9285:     return $c->aborted();
                   9286: }
                   9287: 
1.221     foxr     9288: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     9289: #    strings as 'strings'.
                   9290: sub escape_single {
1.221     foxr     9291:     my ($input) = @_;
1.223     albertel 9292:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     9293:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   9294:     return $input;
                   9295: }
1.223     albertel 9296: 
1.222     foxr     9297: #  Same as escape_single, but escape's "'s  This 
                   9298: #  can be used for  "strings"
                   9299: sub escape_double {
                   9300:     my ($input) = @_;
                   9301:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   9302:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   9303:     return $input;
                   9304: }
1.223     albertel 9305:  
1.222     foxr     9306: #   Escapes the last element of a full URL.
                   9307: sub escape_url {
                   9308:     my ($url)   = @_;
1.238     raeburn  9309:     my @urlslices = split(/\//, $url,-1);
1.369     www      9310:     my $lastitem = &escape(pop(@urlslices));
1.223     albertel 9311:     return join('/',@urlslices).'/'.$lastitem;
1.222     foxr     9312: }
1.462     albertel 9313: 
                   9314: # -------------------------------------------------------- Initliaze user login
                   9315: sub init_user_environment {
1.463     albertel 9316:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 9317:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   9318: 
                   9319:     my $public=($username eq 'public' && $domain eq 'public');
                   9320: 
                   9321: # See if old ID present, if so, remove
                   9322: 
                   9323:     my ($filename,$cookie,$userroles);
                   9324:     my $now=time;
                   9325: 
                   9326:     if ($public) {
                   9327: 	my $max_public=100;
                   9328: 	my $oldest;
                   9329: 	my $oldest_time=0;
                   9330: 	for(my $next=1;$next<=$max_public;$next++) {
                   9331: 	    if (-e $lonids."/publicuser_$next.id") {
                   9332: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   9333: 		if ($mtime<$oldest_time || !$oldest_time) {
                   9334: 		    $oldest_time=$mtime;
                   9335: 		    $oldest=$next;
                   9336: 		}
                   9337: 	    } else {
                   9338: 		$cookie="publicuser_$next";
                   9339: 		last;
                   9340: 	    }
                   9341: 	}
                   9342: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   9343:     } else {
1.463     albertel 9344: 	# if this isn't a robot, kill any existing non-robot sessions
                   9345: 	if (!$args->{'robot'}) {
                   9346: 	    opendir(DIR,$lonids);
                   9347: 	    while ($filename=readdir(DIR)) {
                   9348: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   9349: 		    unlink($lonids.'/'.$filename);
                   9350: 		}
1.462     albertel 9351: 	    }
1.463     albertel 9352: 	    closedir(DIR);
1.462     albertel 9353: 	}
                   9354: # Give them a new cookie
1.463     albertel 9355: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.679.2.3  raeburn  9356: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 9357: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 9358:     
                   9359: # Initialize roles
                   9360: 
                   9361: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
                   9362:     }
                   9363: # ------------------------------------ Check browser type and MathML capability
                   9364: 
                   9365:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
                   9366:         $clientunicode,$clientos) = &decode_user_agent($r);
                   9367: 
                   9368: # -------------------------------------- Any accessibility options to remember?
                   9369:     if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
                   9370: 	foreach my $option ('imagesuppress','appletsuppress',
                   9371: 			    'embedsuppress','fontenhance','blackwhite') {
                   9372: 	    if ($form->{$option} eq 'true') {
                   9373: 		&Apache::lonnet::put('environment',{$option => 'on'},
                   9374: 				     $domain,$username);
                   9375: 	    } else {
                   9376: 		&Apache::lonnet::del('environment',[$option],
                   9377: 				     $domain,$username);
                   9378: 	    }
                   9379: 	}
                   9380:     }
                   9381: # ------------------------------------------------------------- Get environment
                   9382: 
                   9383:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   9384:     my ($tmp) = keys(%userenv);
                   9385:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9386: 	# default remote control to off
                   9387: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
                   9388:     } else {
                   9389: 	undef(%userenv);
                   9390:     }
                   9391:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   9392: 	$form->{'interface'}=$userenv{'interface'};
                   9393:     }
                   9394:     $env{'environment.remote'}=$userenv{'remote'};
                   9395:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   9396: 
                   9397: # --------------- Do not trust query string to be put directly into environment
                   9398:     foreach my $option ('imagesuppress','appletsuppress',
                   9399: 			'embedsuppress','fontenhance','blackwhite',
                   9400: 			'interface','localpath','localres') {
                   9401: 	$form->{$option}=~s/[\n\r\=]//gs;
                   9402:     }
                   9403: # --------------------------------------------------------- Write first profile
                   9404: 
                   9405:     {
                   9406: 	my %initial_env = 
                   9407: 	    ("user.name"          => $username,
                   9408: 	     "user.domain"        => $domain,
                   9409: 	     "user.home"          => $authhost,
                   9410: 	     "browser.type"       => $clientbrowser,
                   9411: 	     "browser.version"    => $clientversion,
                   9412: 	     "browser.mathml"     => $clientmathml,
                   9413: 	     "browser.unicode"    => $clientunicode,
                   9414: 	     "browser.os"         => $clientos,
                   9415: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   9416: 	     "request.course.fn"  => '',
                   9417: 	     "request.course.uri" => '',
                   9418: 	     "request.course.sec" => '',
                   9419: 	     "request.role"       => 'cm',
                   9420: 	     "request.role.adv"   => $env{'user.adv'},
                   9421: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   9422: 
                   9423:         if ($form->{'localpath'}) {
                   9424: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   9425: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   9426:         }
                   9427: 	
                   9428: 	if ($public) {
                   9429: 	    $initial_env{"environment.remote"} = "off";
                   9430: 	}
                   9431: 	if ($form->{'interface'}) {
                   9432: 	    $form->{'interface'}=~s/\W//gs;
                   9433: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   9434: 	    $env{'browser.interface'}=$form->{'interface'};
                   9435: 	    foreach my $option ('imagesuppress','appletsuppress',
                   9436: 				'embedsuppress','fontenhance','blackwhite') {
                   9437: 		if (($form->{$option} eq 'true') ||
                   9438: 		    ($userenv{$option} eq 'on')) {
                   9439: 		    $initial_env{"browser.$option"} = "on";
                   9440: 		}
                   9441: 	    }
                   9442: 	}
                   9443: 
                   9444: 	$env{'user.environment'} = "$lonids/$cookie.id";
                   9445: 	
                   9446: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   9447: 		 &GDBM_WRCREAT(),0640)) {
                   9448: 	    &_add_to_env(\%disk_env,\%initial_env);
                   9449: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   9450: 	    &_add_to_env(\%disk_env,$userroles);
1.463     albertel 9451: 	    if (ref($args->{'extra_env'})) {
                   9452: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   9453: 	    }
1.462     albertel 9454: 	    untie(%disk_env);
                   9455: 	} else {
                   9456: 	    &Apache::lonnet::logthis("<font color=\"blue\">WARNING: ".
                   9457: 			   'Could not create environment storage in lonauth: '.$!.'</font>');
                   9458: 	    return 'error: '.$!;
                   9459: 	}
                   9460:     }
                   9461:     $env{'request.role'}='cm';
                   9462:     $env{'request.role.adv'}=$env{'user.adv'};
                   9463:     $env{'browser.type'}=$clientbrowser;
                   9464: 
                   9465:     return $cookie;
                   9466: 
                   9467: }
                   9468: 
                   9469: sub _add_to_env {
                   9470:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  9471:     if (ref($env_data) eq 'HASH') {
                   9472:         while (my ($key,$value) = each(%$env_data)) {
                   9473: 	    $idf->{$prefix.$key} = $value;
                   9474: 	    $env{$prefix.$key}   = $value;
                   9475:         }
1.462     albertel 9476:     }
                   9477: }
                   9478: 
                   9479: 
1.41      ng       9480: =pod
                   9481: 
                   9482: =back
                   9483: 
1.112     bowersj2 9484: =cut
1.41      ng       9485: 
1.112     bowersj2 9486: 1;
                   9487: __END__;
1.41      ng       9488: 

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