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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.672   ! raeburn     4: # $Id: loncommon.pm,v 1.671 2008/07/14 10:16:11 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)
                    907: 	.'</td></tr></table>';
1.172     www       908: }
                    909: 
1.430     albertel  910: sub general_help {
                    911:     my $helptopic='Student_Intro';
                    912:     if ($env{'request.role'}=~/^(ca|au)/) {
                    913: 	$helptopic='Authoring_Intro';
                    914:     } elsif ($env{'request.role'}=~/^cc/) {
                    915: 	$helptopic='Course_Coordination_Intro';
1.672   ! raeburn   916:     } elsif ($env{'request.role'}=~/^dc/) {
        !           917:         $helptopic='Domain_Coordination_Intro';
1.430     albertel  918:     }
                    919:     return $helptopic;
                    920: }
                    921: 
                    922: sub update_help_link {
                    923:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                    924:     my $origurl = $ENV{'REQUEST_URI'};
                    925:     $origurl=~s|^/~|/priv/|;
                    926:     my $timestamp = time;
                    927:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                    928:         $$datum = &escape($$datum);
                    929:     }
                    930: 
                    931:     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";
                    932:     my $output .= <<"ENDOUTPUT";
                    933: <script type="text/javascript">
                    934: banner_link = '$banner_link';
                    935: </script>
                    936: ENDOUTPUT
                    937:     return $output;
                    938: }
                    939: 
                    940: # now just updates the help link and generates a blue icon
1.193     raeburn   941: sub help_open_menu {
1.430     albertel  942:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart  943: 	= @_;    
1.430     albertel  944:     $stayOnPage = 0 if (not defined $stayOnPage);
1.572     banghart  945:     # only use pop-up help (stayOnPage == 0)
1.552     banghart  946:     # if environment.remote is on (using remote control UI)
1.572     banghart  947:     if ($env{'browser.interface'} eq 'textual' ||
                    948:     	$env{'environment.remote'} eq 'off' ) {
1.552     banghart  949:         $stayOnPage=1;
1.430     albertel  950:     }
                    951:     my $output;
                    952:     if ($component_help) {
                    953: 	if (!$text) {
                    954: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                    955: 				       $width,$height);
                    956: 	} else {
                    957: 	    my $help_text;
                    958: 	    $help_text=&unescape($topic);
                    959: 	    $output='<table><tr><td>'.
                    960: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                    961: 				 $width,$height).'</td></tr></table>';
                    962: 	}
                    963:     }
                    964:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                    965:     return $output.$banner_link;
                    966: }
                    967: 
                    968: sub top_nav_help {
                    969:     my ($text) = @_;
1.436     albertel  970:     $text = &mt($text);
1.572     banghart  971:     my $stay_on_page = 
1.436     albertel  972: 	($env{'browser.interface'}  eq 'textual' ||
                    973: 	 $env{'environment.remote'} eq 'off' );
1.572     banghart  974:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1.436     albertel  975: 	                     : "javascript:helpMenu('open')";
1.572     banghart  976:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1.436     albertel  977: 
1.201     raeburn   978:     my $title = &mt('Get help');
1.436     albertel  979: 
                    980:     return <<"END";
                    981: $banner_link
                    982:  <a href="$link" title="$title">$text</a>
                    983: END
                    984: }
                    985: 
                    986: sub help_menu_js {
                    987:     my ($text) = @_;
                    988: 
                    989:     my $stayOnPage = 
                    990: 	($env{'browser.interface'}  eq 'textual' ||
                    991: 	 $env{'environment.remote'} eq 'off' );
                    992: 
                    993:     my $width = 620;
                    994:     my $height = 600;
1.430     albertel  995:     my $helptopic=&general_help();
                    996:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
1.261     albertel  997:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel  998:     my $start_page =
                    999:         &Apache::loncommon::start_page('Help Menu', undef,
                   1000: 				       {'frameset'    => 1,
                   1001: 					'js_ready'    => 1,
                   1002: 					'add_entries' => {
                   1003: 					    'border' => '0',
1.579     raeburn  1004: 					    'rows'   => "110,*",},});
1.331     albertel 1005:     my $end_page =
                   1006:         &Apache::loncommon::end_page({'frameset' => 1,
                   1007: 				      'js_ready' => 1,});
                   1008: 
1.436     albertel 1009:     my $template .= <<"ENDTEMPLATE";
                   1010: <script type="text/javascript">
1.253     albertel 1011: // <!-- BEGIN LON-CAPA Internal
                   1012: // <![CDATA[
1.430     albertel 1013: var banner_link = '';
1.243     raeburn  1014: function helpMenu(target) {
                   1015:     var caller = this;
                   1016:     if (target == 'open') {
                   1017:         var newWindow = null;
                   1018:         try {
1.262     albertel 1019:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1020:         }
                   1021:         catch(error) {
                   1022:             writeHelp(caller);
                   1023:             return;
                   1024:         }
                   1025:         if (newWindow) {
                   1026:             caller = newWindow;
                   1027:         }
1.193     raeburn  1028:     }
1.243     raeburn  1029:     writeHelp(caller);
                   1030:     return;
                   1031: }
                   1032: function writeHelp(caller) {
1.430     albertel 1033:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
1.243     raeburn  1034:     caller.document.close()
                   1035:     caller.focus()
1.193     raeburn  1036: }
1.253     albertel 1037: // ]]>
1.219     albertel 1038: // END LON-CAPA Internal -->
1.436     albertel 1039: </script>
1.193     raeburn  1040: ENDTEMPLATE
                   1041:     return $template;
                   1042: }
                   1043: 
1.172     www      1044: sub help_open_bug {
                   1045:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1046:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1047:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1048:     $text = "" if (not defined $text);
                   1049:     $stayOnPage = 0 if (not defined $stayOnPage);
1.258     albertel 1050:     if ($env{'browser.interface'} eq 'textual' ||
                   1051: 	$env{'environment.remote'} eq 'off' ) {
1.172     www      1052: 	$stayOnPage=1;
                   1053:     }
1.184     albertel 1054:     $width = 600 if (not defined $width);
                   1055:     $height = 600 if (not defined $height);
1.172     www      1056: 
                   1057:     $topic=~s/\W+/\+/g;
                   1058:     my $link='';
                   1059:     my $template='';
1.379     albertel 1060:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1061: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1062:     if (!$stayOnPage)
                   1063:     {
                   1064: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1065:     }
                   1066:     else
                   1067:     {
                   1068: 	$link = $url;
                   1069:     }
                   1070:     # Add the text
                   1071:     if ($text ne "")
                   1072:     {
                   1073: 	$template .= 
                   1074:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.436     albertel 1075:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
1.172     www      1076:     }
                   1077: 
                   1078:     # Add the graphic
1.179     matthew  1079:     my $title = &mt('Report a Bug');
1.215     albertel 1080:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1081:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1082:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1083: ENDTEMPLATE
                   1084:     if ($text ne '') { $template.='</td></tr></table>' };
                   1085:     return $template;
                   1086: 
                   1087: }
                   1088: 
                   1089: sub help_open_faq {
                   1090:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1091:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1092:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1093:     $text = "" if (not defined $text);
                   1094:     $stayOnPage = 0 if (not defined $stayOnPage);
1.258     albertel 1095:     if ($env{'browser.interface'} eq 'textual' ||
                   1096: 	$env{'environment.remote'} eq 'off' ) {
1.172     www      1097: 	$stayOnPage=1;
                   1098:     }
                   1099:     $width = 350 if (not defined $width);
                   1100:     $height = 400 if (not defined $height);
                   1101: 
                   1102:     $topic=~s/\W+/\+/g;
                   1103:     my $link='';
                   1104:     my $template='';
                   1105:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1106:     if (!$stayOnPage)
                   1107:     {
                   1108: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1109:     }
                   1110:     else
                   1111:     {
                   1112: 	$link = $url;
                   1113:     }
                   1114: 
                   1115:     # Add the text
                   1116:     if ($text ne "")
                   1117:     {
                   1118: 	$template .= 
1.173     www      1119:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.436     albertel 1120:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
1.172     www      1121:     }
                   1122: 
                   1123:     # Add the graphic
1.179     matthew  1124:     my $title = &mt('View the FAQ');
1.215     albertel 1125:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1126:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1127:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1128: ENDTEMPLATE
                   1129:     if ($text ne '') { $template.='</td></tr></table>' };
                   1130:     return $template;
                   1131: 
1.44      bowersj2 1132: }
1.37      matthew  1133: 
1.180     matthew  1134: ###############################################################
                   1135: ###############################################################
                   1136: 
1.45      matthew  1137: =pod
                   1138: 
1.648     raeburn  1139: =item * &change_content_javascript():
1.256     matthew  1140: 
                   1141: This and the next function allow you to create small sections of an
                   1142: otherwise static HTML page that you can update on the fly with
                   1143: Javascript, even in Netscape 4.
                   1144: 
                   1145: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1146: must be written to the HTML page once. It will prove the Javascript
                   1147: function "change(name, content)". Calling the change function with the
                   1148: name of the section 
                   1149: you want to update, matching the name passed to C<changable_area>, and
                   1150: the new content you want to put in there, will put the content into
                   1151: that area.
                   1152: 
                   1153: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1154: to contain room for the original contents. You need to "make space"
                   1155: for whatever changes you wish to make, and be B<sure> to check your
                   1156: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1157: it's adequate for updating a one-line status display, but little more.
                   1158: This script will set the space to 100% width, so you only need to
                   1159: worry about height in Netscape 4.
                   1160: 
                   1161: Modern browsers are much less limiting, and if you can commit to the
                   1162: user not using Netscape 4, this feature may be used freely with
                   1163: pretty much any HTML.
                   1164: 
                   1165: =cut
                   1166: 
                   1167: sub change_content_javascript {
                   1168:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1169:     if ($env{'browser.type'} eq 'netscape' &&
                   1170: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1171: 	return (<<NETSCAPE4);
                   1172: 	function change(name, content) {
                   1173: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1174: 	    doc.open();
                   1175: 	    doc.write(content);
                   1176: 	    doc.close();
                   1177: 	}
                   1178: NETSCAPE4
                   1179:     } else {
                   1180: 	# Otherwise, we need to use semi-standards-compliant code
                   1181: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1182: 	# is really scary, and every useful browser supports it
                   1183: 	return (<<DOMBASED);
                   1184: 	function change(name, content) {
                   1185: 	    element = document.getElementById(name);
                   1186: 	    element.innerHTML = content;
                   1187: 	}
                   1188: DOMBASED
                   1189:     }
                   1190: }
                   1191: 
                   1192: =pod
                   1193: 
1.648     raeburn  1194: =item * &changable_area($name,$origContent):
1.256     matthew  1195: 
                   1196: This provides a "changable area" that can be modified on the fly via
                   1197: the Javascript code provided in C<change_content_javascript>. $name is
                   1198: the name you will use to reference the area later; do not repeat the
                   1199: same name on a given HTML page more then once. $origContent is what
                   1200: the area will originally contain, which can be left blank.
                   1201: 
                   1202: =cut
                   1203: 
                   1204: sub changable_area {
                   1205:     my ($name, $origContent) = @_;
                   1206: 
1.258     albertel 1207:     if ($env{'browser.type'} eq 'netscape' &&
                   1208: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1209: 	# If this is netscape 4, we need to use the Layer tag
                   1210: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1211:     } else {
                   1212: 	return "<span id='$name'>$origContent</span>";
                   1213:     }
                   1214: }
                   1215: 
                   1216: =pod
                   1217: 
1.648     raeburn  1218: =item * &viewport_geometry_js 
1.590     raeburn  1219: 
                   1220: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1221: 
                   1222: =cut
                   1223: 
                   1224: 
                   1225: sub viewport_geometry_js { 
                   1226:     return <<"GEOMETRY";
                   1227: var Geometry = {};
                   1228: function init_geometry() {
                   1229:     if (Geometry.init) { return };
                   1230:     Geometry.init=1;
                   1231:     if (window.innerHeight) {
                   1232:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1233:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1234:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1235:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1236:     }
                   1237:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1238:         Geometry.getViewportHeight =
                   1239:             function() { return document.documentElement.clientHeight; };
                   1240:         Geometry.getViewportWidth =
                   1241:             function() { return document.documentElement.clientWidth; };
                   1242: 
                   1243:         Geometry.getHorizontalScroll =
                   1244:             function() { return document.documentElement.scrollLeft; };
                   1245:         Geometry.getVerticalScroll =
                   1246:             function() { return document.documentElement.scrollTop; };
                   1247:     }
                   1248:     else if (document.body.clientHeight) {
                   1249:         Geometry.getViewportHeight =
                   1250:             function() { return document.body.clientHeight; };
                   1251:         Geometry.getViewportWidth =
                   1252:             function() { return document.body.clientWidth; };
                   1253:         Geometry.getHorizontalScroll =
                   1254:             function() { return document.body.scrollLeft; };
                   1255:         Geometry.getVerticalScroll =
                   1256:             function() { return document.body.scrollTop; };
                   1257:     }
                   1258: }
                   1259: 
                   1260: GEOMETRY
                   1261: }
                   1262: 
                   1263: =pod
                   1264: 
1.648     raeburn  1265: =item * &viewport_size_js()
1.590     raeburn  1266: 
                   1267: 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. 
                   1268: 
                   1269: =cut
                   1270: 
                   1271: sub viewport_size_js {
                   1272:     my $geometry = &viewport_geometry_js();
                   1273:     return <<"DIMS";
                   1274: 
                   1275: $geometry
                   1276: 
                   1277: function getViewportDims(width,height) {
                   1278:     init_geometry();
                   1279:     width.value = Geometry.getViewportWidth();
                   1280:     height.value = Geometry.getViewportHeight();
                   1281:     return;
                   1282: }
                   1283: 
                   1284: DIMS
                   1285: }
                   1286: 
                   1287: =pod
                   1288: 
1.648     raeburn  1289: =item * &resize_textarea_js()
1.565     albertel 1290: 
                   1291: emits the needed javascript to resize a textarea to be as big as possible
                   1292: 
                   1293: creates a function resize_textrea that takes two IDs first should be
                   1294: the id of the element to resize, second should be the id of a div that
                   1295: surrounds everything that comes after the textarea, this routine needs
                   1296: to be attached to the <body> for the onload and onresize events.
                   1297: 
1.648     raeburn  1298: =back
1.565     albertel 1299: 
                   1300: =cut
                   1301: 
                   1302: sub resize_textarea_js {
1.590     raeburn  1303:     my $geometry = &viewport_geometry_js();
1.565     albertel 1304:     return <<"RESIZE";
                   1305:     <script type="text/javascript">
1.590     raeburn  1306: $geometry
1.565     albertel 1307: 
1.588     albertel 1308: function getX(element) {
                   1309:     var x = 0;
                   1310:     while (element) {
                   1311: 	x += element.offsetLeft;
                   1312: 	element = element.offsetParent;
                   1313:     }
                   1314:     return x;
                   1315: }
                   1316: function getY(element) {
                   1317:     var y = 0;
                   1318:     while (element) {
                   1319: 	y += element.offsetTop;
                   1320: 	element = element.offsetParent;
                   1321:     }
                   1322:     return y;
                   1323: }
                   1324: 
                   1325: 
1.565     albertel 1326: function resize_textarea(textarea_id,bottom_id) {
                   1327:     init_geometry();
                   1328:     var textarea        = document.getElementById(textarea_id);
                   1329:     //alert(textarea);
                   1330: 
1.588     albertel 1331:     var textarea_top    = getY(textarea);
1.565     albertel 1332:     var textarea_height = textarea.offsetHeight;
                   1333:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1334:     var bottom_top      = getY(bottom);
1.565     albertel 1335:     var bottom_height   = bottom.offsetHeight;
                   1336:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1337:     var fudge           = 23;
1.565     albertel 1338:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1339:     if (new_height < 300) {
                   1340: 	new_height = 300;
                   1341:     }
                   1342:     textarea.style.height=new_height+'px';
                   1343: }
                   1344: </script>
                   1345: RESIZE
                   1346: 
                   1347: }
                   1348: 
                   1349: =pod
                   1350: 
1.256     matthew  1351: =head1 Excel and CSV file utility routines
                   1352: 
                   1353: =over 4
                   1354: 
                   1355: =cut
                   1356: 
                   1357: ###############################################################
                   1358: ###############################################################
                   1359: 
                   1360: =pod
                   1361: 
1.648     raeburn  1362: =item * &csv_translate($text) 
1.37      matthew  1363: 
1.185     www      1364: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  1365: format.
                   1366: 
                   1367: =cut
                   1368: 
1.180     matthew  1369: ###############################################################
                   1370: ###############################################################
1.37      matthew  1371: sub csv_translate {
                   1372:     my $text = shift;
                   1373:     $text =~ s/\"/\"\"/g;
1.209     albertel 1374:     $text =~ s/\n/ /g;
1.37      matthew  1375:     return $text;
                   1376: }
1.180     matthew  1377: 
                   1378: ###############################################################
                   1379: ###############################################################
                   1380: 
                   1381: =pod
                   1382: 
1.648     raeburn  1383: =item * &define_excel_formats()
1.180     matthew  1384: 
                   1385: Define some commonly used Excel cell formats.
                   1386: 
                   1387: Currently supported formats:
                   1388: 
                   1389: =over 4
                   1390: 
                   1391: =item header
                   1392: 
                   1393: =item bold
                   1394: 
                   1395: =item h1
                   1396: 
                   1397: =item h2
                   1398: 
                   1399: =item h3
                   1400: 
1.256     matthew  1401: =item h4
                   1402: 
                   1403: =item i
                   1404: 
1.180     matthew  1405: =item date
                   1406: 
                   1407: =back
                   1408: 
                   1409: Inputs: $workbook
                   1410: 
                   1411: Returns: $format, a hash reference.
                   1412: 
                   1413: =cut
                   1414: 
                   1415: ###############################################################
                   1416: ###############################################################
                   1417: sub define_excel_formats {
                   1418:     my ($workbook) = @_;
                   1419:     my $format;
                   1420:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   1421:                                                 bottom    => 1,
                   1422:                                                 align     => 'center');
                   1423:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   1424:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   1425:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   1426:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  1427:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  1428:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  1429:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  1430:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  1431:     return $format;
                   1432: }
                   1433: 
                   1434: ###############################################################
                   1435: ###############################################################
1.113     bowersj2 1436: 
                   1437: =pod
                   1438: 
1.648     raeburn  1439: =item * &create_workbook()
1.255     matthew  1440: 
                   1441: Create an Excel worksheet.  If it fails, output message on the
                   1442: request object and return undefs.
                   1443: 
                   1444: Inputs: Apache request object
                   1445: 
                   1446: Returns (undef) on failure, 
                   1447:     Excel worksheet object, scalar with filename, and formats 
                   1448:     from &Apache::loncommon::define_excel_formats on success
                   1449: 
                   1450: =cut
                   1451: 
                   1452: ###############################################################
                   1453: ###############################################################
                   1454: sub create_workbook {
                   1455:     my ($r) = @_;
                   1456:         #
                   1457:     # Create the excel spreadsheet
                   1458:     my $filename = '/prtspool/'.
1.258     albertel 1459:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  1460:         time.'_'.rand(1000000000).'.xls';
                   1461:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   1462:     if (! defined($workbook)) {
                   1463:         $r->log_error("Error creating excel spreadsheet $filename: $!");
                   1464:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
                   1465:                             "This error has been logged.  ".
                   1466:                             "Please alert your LON-CAPA administrator").
                   1467:                   '</p>');
                   1468:         return (undef);
                   1469:     }
                   1470:     #
                   1471:     $workbook->set_tempdir('/home/httpd/perl/tmp');
                   1472:     #
                   1473:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   1474:     return ($workbook,$filename,$format);
                   1475: }
                   1476: 
                   1477: ###############################################################
                   1478: ###############################################################
                   1479: 
                   1480: =pod
                   1481: 
1.648     raeburn  1482: =item * &create_text_file()
1.113     bowersj2 1483: 
1.542     raeburn  1484: Create a file to write to and eventually make available to the user.
1.256     matthew  1485: If file creation fails, outputs an error message on the request object and 
                   1486: return undefs.
1.113     bowersj2 1487: 
1.256     matthew  1488: Inputs: Apache request object, and file suffix
1.113     bowersj2 1489: 
1.256     matthew  1490: Returns (undef) on failure, 
                   1491:     Filehandle and filename on success.
1.113     bowersj2 1492: 
                   1493: =cut
                   1494: 
1.256     matthew  1495: ###############################################################
                   1496: ###############################################################
                   1497: sub create_text_file {
                   1498:     my ($r,$suffix) = @_;
                   1499:     if (! defined($suffix)) { $suffix = 'txt'; };
                   1500:     my $fh;
                   1501:     my $filename = '/prtspool/'.
1.258     albertel 1502:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  1503:         time.'_'.rand(1000000000).'.'.$suffix;
                   1504:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   1505:     if (! defined($fh)) {
                   1506:         $r->log_error("Couldn't open $filename for output $!");
                   1507:         $r->print("Problems occured in creating the output file.  ".
                   1508:                   "This error has been logged.  ".
                   1509:                   "Please alert your LON-CAPA administrator.");
1.113     bowersj2 1510:     }
1.256     matthew  1511:     return ($fh,$filename)
1.113     bowersj2 1512: }
                   1513: 
                   1514: 
1.256     matthew  1515: =pod 
1.113     bowersj2 1516: 
                   1517: =back
                   1518: 
                   1519: =cut
1.37      matthew  1520: 
                   1521: ###############################################################
1.33      matthew  1522: ##        Home server <option> list generating code          ##
                   1523: ###############################################################
1.35      matthew  1524: 
1.169     www      1525: # ------------------------------------------
                   1526: 
                   1527: sub domain_select {
                   1528:     my ($name,$value,$multiple)=@_;
                   1529:     my %domains=map { 
1.514     albertel 1530: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 1531:     } &Apache::lonnet::all_domains();
1.169     www      1532:     if ($multiple) {
                   1533: 	$domains{''}=&mt('Any domain');
1.550     albertel 1534: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 1535: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      1536:     } else {
1.550     albertel 1537: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.169     www      1538: 	return &select_form($name,$value,%domains);
                   1539:     }
                   1540: }
                   1541: 
1.282     albertel 1542: #-------------------------------------------
                   1543: 
                   1544: =pod
                   1545: 
1.519     raeburn  1546: =head1 Routines for form select boxes
                   1547: 
                   1548: =over 4
                   1549: 
1.648     raeburn  1550: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 1551: 
                   1552: Returns a string containing a <select> element int multiple mode
                   1553: 
                   1554: 
                   1555: Args:
                   1556:   $name - name of the <select> element
1.506     raeburn  1557:   $value - scalar or array ref of values that should already be selected
1.282     albertel 1558:   $size - number of rows long the select element is
1.283     albertel 1559:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 1560:           (shown text should already have been &mt())
1.506     raeburn  1561:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 1562: 
1.282     albertel 1563: =cut
                   1564: 
                   1565: #-------------------------------------------
1.169     www      1566: sub multiple_select_form {
1.284     albertel 1567:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      1568:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   1569:     my $output='';
1.191     matthew  1570:     if (! defined($size)) {
                   1571:         $size = 4;
1.283     albertel 1572:         if (scalar(keys(%$hash))<4) {
                   1573:             $size = scalar(keys(%$hash));
1.191     matthew  1574:         }
                   1575:     }
1.169     www      1576:     $output.="\n<select name='$name' size='$size' multiple='1'>";
1.501     banghart 1577:     my @order;
1.506     raeburn  1578:     if (ref($order) eq 'ARRAY')  {
                   1579:         @order = @{$order};
                   1580:     } else {
                   1581:         @order = sort(keys(%$hash));
1.501     banghart 1582:     }
                   1583:     if (exists($$hash{'select_form_order'})) {
                   1584:         @order = @{$$hash{'select_form_order'}};
                   1585:     }
                   1586:         
1.284     albertel 1587:     foreach my $key (@order) {
1.356     albertel 1588:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 1589:         $output.='selected="selected" ' if ($selected{$key});
                   1590:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      1591:     }
                   1592:     $output.="</select>\n";
                   1593:     return $output;
                   1594: }
                   1595: 
1.88      www      1596: #-------------------------------------------
                   1597: 
                   1598: =pod
                   1599: 
1.648     raeburn  1600: =item * &select_form($defdom,$name,%hash)
1.88      www      1601: 
                   1602: Returns a string containing a <select name='$name' size='1'> form to 
                   1603: allow a user to select options from a hash option_name => displayed text.  
                   1604: See lonrights.pm for an example invocation and use.
                   1605: 
                   1606: =cut
                   1607: 
                   1608: #-------------------------------------------
                   1609: sub select_form {
                   1610:     my ($def,$name,%hash) = @_;
                   1611:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
1.128     albertel 1612:     my @keys;
                   1613:     if (exists($hash{'select_form_order'})) {
                   1614: 	@keys=@{$hash{'select_form_order'}};
                   1615:     } else {
                   1616: 	@keys=sort(keys(%hash));
                   1617:     }
1.356     albertel 1618:     foreach my $key (@keys) {
                   1619:         $selectform.=
                   1620: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   1621:             ($key eq $def ? 'selected="selected" ' : '').
                   1622:                 ">".&mt($hash{$key})."</option>\n";
1.88      www      1623:     }
                   1624:     $selectform.="</select>";
                   1625:     return $selectform;
                   1626: }
                   1627: 
1.475     www      1628: # For display filters
                   1629: 
                   1630: sub display_filter {
                   1631:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      1632:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.475     www      1633:     return '<nobr><label>'.&mt('Records [_1]',
                   1634: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   1635: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.478     www      1636: 	   '</label></nobr> <nobr>'.
1.475     www      1637:            &mt('Filter [_1]',
1.477     www      1638: 	   &select_form($env{'form.displayfilter'},
                   1639: 			'displayfilter',
                   1640: 			('currentfolder' => 'Current folder/page',
                   1641: 			 'containing' => 'Containing phrase',
                   1642: 			 'none' => 'None'))).
1.478     www      1643: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></nobr>';
1.475     www      1644: }
                   1645: 
1.167     www      1646: sub gradeleveldescription {
                   1647:     my $gradelevel=shift;
                   1648:     my %gradelevels=(0 => 'Not specified',
                   1649: 		     1 => 'Grade 1',
                   1650: 		     2 => 'Grade 2',
                   1651: 		     3 => 'Grade 3',
                   1652: 		     4 => 'Grade 4',
                   1653: 		     5 => 'Grade 5',
                   1654: 		     6 => 'Grade 6',
                   1655: 		     7 => 'Grade 7',
                   1656: 		     8 => 'Grade 8',
                   1657: 		     9 => 'Grade 9',
                   1658: 		     10 => 'Grade 10',
                   1659: 		     11 => 'Grade 11',
                   1660: 		     12 => 'Grade 12',
                   1661: 		     13 => 'Grade 13',
                   1662: 		     14 => '100 Level',
                   1663: 		     15 => '200 Level',
                   1664: 		     16 => '300 Level',
                   1665: 		     17 => '400 Level',
                   1666: 		     18 => 'Graduate Level');
                   1667:     return &mt($gradelevels{$gradelevel});
                   1668: }
                   1669: 
1.163     www      1670: sub select_level_form {
                   1671:     my ($deflevel,$name)=@_;
                   1672:     unless ($deflevel) { $deflevel=0; }
1.167     www      1673:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   1674:     for (my $i=0; $i<=18; $i++) {
                   1675:         $selectform.="<option value=\"$i\" ".
1.253     albertel 1676:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      1677:                 ">".&gradeleveldescription($i)."</option>\n";
                   1678:     }
                   1679:     $selectform.="</select>";
                   1680:     return $selectform;
1.163     www      1681: }
1.167     www      1682: 
1.35      matthew  1683: #-------------------------------------------
                   1684: 
1.45      matthew  1685: =pod
                   1686: 
1.648     raeburn  1687: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc)
1.35      matthew  1688: 
                   1689: Returns a string containing a <select name='$name' size='1'> form to 
                   1690: allow a user to select the domain to preform an operation in.  
                   1691: See loncreateuser.pm for an example invocation and use.
                   1692: 
1.90      www      1693: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   1694: selected");
                   1695: 
1.563     raeburn  1696: If the $showdomdesc flag is set, the domain name is followed by the domain description. 
                   1697: 
1.35      matthew  1698: =cut
                   1699: 
                   1700: #-------------------------------------------
1.34      matthew  1701: sub select_dom_form {
1.563     raeburn  1702:     my ($defdom,$name,$includeempty,$showdomdesc) = @_;
1.550     albertel 1703:     my @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
1.90      www      1704:     if ($includeempty) { @domains=('',@domains); }
1.34      matthew  1705:     my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
1.356     albertel 1706:     foreach my $dom (@domains) {
                   1707:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  1708:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   1709:         if ($showdomdesc) {
                   1710:             if ($dom ne '') {
                   1711:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   1712:                 if ($domdesc ne '') {
                   1713:                     $selectdomain .= ' ('.$domdesc.')';
                   1714:                 }
                   1715:             } 
                   1716:         }
                   1717:         $selectdomain .= "</option>\n";
1.34      matthew  1718:     }
                   1719:     $selectdomain.="</select>";
                   1720:     return $selectdomain;
                   1721: }
                   1722: 
1.35      matthew  1723: #-------------------------------------------
                   1724: 
1.45      matthew  1725: =pod
                   1726: 
1.648     raeburn  1727: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  1728: 
1.586     raeburn  1729: input: 4 arguments (two required, two optional) - 
                   1730:     $domain - domain of new user
                   1731:     $name - name of form element
                   1732:     $default - Value of 'default' causes a default item to be first 
                   1733:                             option, and selected by default. 
                   1734:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   1735:                             if 1 server found, or default, if 0 found.
1.594     raeburn  1736: output: returns 2 items: 
1.586     raeburn  1737: (a) form element which contains either:
                   1738:    (i) <select name="$name">
                   1739:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   1740:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   1741:        </select>
                   1742:        form item if there are multiple library servers in $domain, or
                   1743:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   1744:        if there is only one library server in $domain.
                   1745: 
                   1746: (b) number of library servers found.
                   1747: 
                   1748: See loncreateuser.pm for example of use.
1.35      matthew  1749: 
                   1750: =cut
                   1751: 
                   1752: #-------------------------------------------
1.586     raeburn  1753: sub home_server_form_item {
                   1754:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 1755:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  1756:     my $result;
                   1757:     my $numlib = keys(%servers);
                   1758:     if ($numlib > 1) {
                   1759:         $result .= '<select name="'.$name.'" />'."\n";
                   1760:         if ($default) {
                   1761:             $result .= '<option value="default" selected>'.&mt('default').
                   1762:                        '</option>'."\n";
                   1763:         }
                   1764:         foreach my $hostid (sort(keys(%servers))) {
                   1765:             $result.= '<option value="'.$hostid.'">'.
                   1766: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   1767:         }
                   1768:         $result .= '</select>'."\n";
                   1769:     } elsif ($numlib == 1) {
                   1770:         my $hostid;
                   1771:         foreach my $item (keys(%servers)) {
                   1772:             $hostid = $item;
                   1773:         }
                   1774:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   1775:                    $hostid.'" />';
                   1776:                    if (!$hide) {
                   1777:                        $result .= $hostid.' '.$servers{$hostid};
                   1778:                    }
                   1779:                    $result .= "\n";
                   1780:     } elsif ($default) {
                   1781:         $result .= '<input type="hidden" name="'.$name.
                   1782:                    '" value="default" />';
                   1783:                    if (!$hide) {
                   1784:                        $result .= &mt('default');
                   1785:                    }
                   1786:                    $result .= "\n";
1.33      matthew  1787:     }
1.586     raeburn  1788:     return ($result,$numlib);
1.33      matthew  1789: }
1.112     bowersj2 1790: 
                   1791: =pod
                   1792: 
1.534     albertel 1793: =back 
                   1794: 
1.112     bowersj2 1795: =cut
1.87      matthew  1796: 
                   1797: ###############################################################
1.112     bowersj2 1798: ##                  Decoding User Agent                      ##
1.87      matthew  1799: ###############################################################
                   1800: 
                   1801: =pod
                   1802: 
1.112     bowersj2 1803: =head1 Decoding the User Agent
                   1804: 
                   1805: =over 4
                   1806: 
                   1807: =item * &decode_user_agent()
1.87      matthew  1808: 
                   1809: Inputs: $r
                   1810: 
                   1811: Outputs:
                   1812: 
                   1813: =over 4
                   1814: 
1.112     bowersj2 1815: =item * $httpbrowser
1.87      matthew  1816: 
1.112     bowersj2 1817: =item * $clientbrowser
1.87      matthew  1818: 
1.112     bowersj2 1819: =item * $clientversion
1.87      matthew  1820: 
1.112     bowersj2 1821: =item * $clientmathml
1.87      matthew  1822: 
1.112     bowersj2 1823: =item * $clientunicode
1.87      matthew  1824: 
1.112     bowersj2 1825: =item * $clientos
1.87      matthew  1826: 
                   1827: =back
                   1828: 
1.157     matthew  1829: =back 
                   1830: 
1.87      matthew  1831: =cut
                   1832: 
                   1833: ###############################################################
                   1834: ###############################################################
                   1835: sub decode_user_agent {
1.247     albertel 1836:     my ($r)=@_;
1.87      matthew  1837:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   1838:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   1839:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 1840:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  1841:     my $clientbrowser='unknown';
                   1842:     my $clientversion='0';
                   1843:     my $clientmathml='';
                   1844:     my $clientunicode='0';
                   1845:     for (my $i=0;$i<=$#browsertype;$i++) {
                   1846:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
                   1847: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   1848: 	    $clientbrowser=$bname;
                   1849:             $httpbrowser=~/$vreg/i;
                   1850: 	    $clientversion=$1;
                   1851:             $clientmathml=($clientversion>=$minv);
                   1852:             $clientunicode=($clientversion>=$univ);
                   1853: 	}
                   1854:     }
                   1855:     my $clientos='unknown';
                   1856:     if (($httpbrowser=~/linux/i) ||
                   1857:         ($httpbrowser=~/unix/i) ||
                   1858:         ($httpbrowser=~/ux/i) ||
                   1859:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   1860:     if (($httpbrowser=~/vax/i) ||
                   1861:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   1862:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   1863:     if (($httpbrowser=~/mac/i) ||
                   1864:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
                   1865:     if ($httpbrowser=~/win/i) { $clientos='win'; }
                   1866:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
                   1867:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
                   1868:             $clientunicode,$clientos,);
                   1869: }
                   1870: 
1.32      matthew  1871: ###############################################################
                   1872: ##    Authentication changing form generation subroutines    ##
                   1873: ###############################################################
                   1874: ##
                   1875: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   1876: ## hash, and have reasonable default values.
                   1877: ##
                   1878: ##    formname = the name given in the <form> tag.
1.35      matthew  1879: #-------------------------------------------
                   1880: 
1.45      matthew  1881: =pod
                   1882: 
1.112     bowersj2 1883: =head1 Authentication Routines
                   1884: 
                   1885: =over 4
                   1886: 
1.648     raeburn  1887: =item * &authform_xxxxxx()
1.35      matthew  1888: 
                   1889: The authform_xxxxxx subroutines provide javascript and html forms which 
                   1890: handle some of the conveniences required for authentication forms.  
                   1891: This is not an optimal method, but it works.  
                   1892: 
                   1893: =over 4
                   1894: 
1.112     bowersj2 1895: =item * authform_header
1.35      matthew  1896: 
1.112     bowersj2 1897: =item * authform_authorwarning
1.35      matthew  1898: 
1.112     bowersj2 1899: =item * authform_nochange
1.35      matthew  1900: 
1.112     bowersj2 1901: =item * authform_kerberos
1.35      matthew  1902: 
1.112     bowersj2 1903: =item * authform_internal
1.35      matthew  1904: 
1.112     bowersj2 1905: =item * authform_filesystem
1.35      matthew  1906: 
                   1907: =back
                   1908: 
1.648     raeburn  1909: See loncreateuser.pm for invocation and use examples.
1.157     matthew  1910: 
1.35      matthew  1911: =cut
                   1912: 
                   1913: #-------------------------------------------
1.32      matthew  1914: sub authform_header{  
                   1915:     my %in = (
                   1916:         formname => 'cu',
1.80      albertel 1917:         kerb_def_dom => '',
1.32      matthew  1918:         @_,
                   1919:     );
                   1920:     $in{'formname'} = 'document.' . $in{'formname'};
                   1921:     my $result='';
1.80      albertel 1922: 
                   1923: #---------------------------------------------- Code for upper case translation
                   1924:     my $Javascript_toUpperCase;
                   1925:     unless ($in{kerb_def_dom}) {
                   1926:         $Javascript_toUpperCase =<<"END";
                   1927:         switch (choice) {
                   1928:            case 'krb': currentform.elements[choicearg].value =
                   1929:                currentform.elements[choicearg].value.toUpperCase();
                   1930:                break;
                   1931:            default:
                   1932:         }
                   1933: END
                   1934:     } else {
                   1935:         $Javascript_toUpperCase = "";
                   1936:     }
                   1937: 
1.165     raeburn  1938:     my $radioval = "'nochange'";
1.591     raeburn  1939:     if (defined($in{'curr_authtype'})) {
                   1940:         if ($in{'curr_authtype'} ne '') {
                   1941:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   1942:         }
1.174     matthew  1943:     }
1.165     raeburn  1944:     my $argfield = 'null';
1.591     raeburn  1945:     if (defined($in{'mode'})) {
1.165     raeburn  1946:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  1947:             if (defined($in{'curr_autharg'})) {
                   1948:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  1949:                     $argfield = "'$in{'curr_autharg'}'";
                   1950:                 }
                   1951:             }
                   1952:         }
                   1953:     }
                   1954: 
1.32      matthew  1955:     $result.=<<"END";
                   1956: var current = new Object();
1.165     raeburn  1957: current.radiovalue = $radioval;
                   1958: current.argfield = $argfield;
1.32      matthew  1959: 
                   1960: function changed_radio(choice,currentform) {
                   1961:     var choicearg = choice + 'arg';
                   1962:     // If a radio button in changed, we need to change the argfield
                   1963:     if (current.radiovalue != choice) {
                   1964:         current.radiovalue = choice;
                   1965:         if (current.argfield != null) {
                   1966:             currentform.elements[current.argfield].value = '';
                   1967:         }
                   1968:         if (choice == 'nochange') {
                   1969:             current.argfield = null;
                   1970:         } else {
                   1971:             current.argfield = choicearg;
                   1972:             switch(choice) {
                   1973:                 case 'krb': 
                   1974:                     currentform.elements[current.argfield].value = 
                   1975:                         "$in{'kerb_def_dom'}";
                   1976:                 break;
                   1977:               default:
                   1978:                 break;
                   1979:             }
                   1980:         }
                   1981:     }
                   1982:     return;
                   1983: }
1.22      www      1984: 
1.32      matthew  1985: function changed_text(choice,currentform) {
                   1986:     var choicearg = choice + 'arg';
                   1987:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 1988:         $Javascript_toUpperCase
1.32      matthew  1989:         // clear old field
                   1990:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   1991:             currentform.elements[current.argfield].value = '';
                   1992:         }
                   1993:         current.argfield = choicearg;
                   1994:     }
                   1995:     set_auth_radio_buttons(choice,currentform);
                   1996:     return;
1.20      www      1997: }
1.32      matthew  1998: 
                   1999: function set_auth_radio_buttons(newvalue,currentform) {
                   2000:     var i=0;
                   2001:     while (i < currentform.login.length) {
                   2002:         if (currentform.login[i].value == newvalue) { break; }
                   2003:         i++;
                   2004:     }
                   2005:     if (i == currentform.login.length) {
                   2006:         return;
                   2007:     }
                   2008:     current.radiovalue = newvalue;
                   2009:     currentform.login[i].checked = true;
                   2010:     return;
                   2011: }
                   2012: END
                   2013:     return $result;
                   2014: }
                   2015: 
                   2016: sub authform_authorwarning{
                   2017:     my $result='';
1.144     matthew  2018:     $result='<i>'.
                   2019:         &mt('As a general rule, only authors or co-authors should be '.
                   2020:             'filesystem authenticated '.
                   2021:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2022:     return $result;
                   2023: }
                   2024: 
                   2025: sub authform_nochange{  
                   2026:     my %in = (
                   2027:               formname => 'document.cu',
                   2028:               kerb_def_dom => 'MSU.EDU',
                   2029:               @_,
                   2030:           );
1.586     raeburn  2031:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
                   2032:     my $result;
                   2033:     if (keys(%can_assign) == 0) {
                   2034:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
                   2035:     } else {
                   2036:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2037:                   '<input type="radio" name="login" value="nochange" '.
                   2038:                   'checked="checked" onclick="'.
1.281     albertel 2039:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2040: 	    '</label>';
1.586     raeburn  2041:     }
1.32      matthew  2042:     return $result;
                   2043: }
                   2044: 
1.591     raeburn  2045: sub authform_kerberos {
1.32      matthew  2046:     my %in = (
                   2047:               formname => 'document.cu',
                   2048:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2049:               kerb_def_auth => 'krb4',
1.32      matthew  2050:               @_,
                   2051:               );
1.586     raeburn  2052:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
                   2053:         $autharg,$jscall);
                   2054:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
1.80      albertel 2055:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.586     raeburn  2056:        $check5 = ' checked="on"';
1.80      albertel 2057:     } else {
1.586     raeburn  2058:        $check4 = ' checked="on"';
1.80      albertel 2059:     }
1.165     raeburn  2060:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2061:     if (defined($in{'curr_authtype'})) {
                   2062:         if ($in{'curr_authtype'} eq 'krb') {
1.586     raeburn  2063:             $krbcheck = ' checked="on"';
1.623     raeburn  2064:             if (defined($in{'mode'})) {
                   2065:                 if ($in{'mode'} eq 'modifyuser') {
                   2066:                     $krbcheck = '';
                   2067:                 }
                   2068:             }
1.591     raeburn  2069:             if (defined($in{'curr_kerb_ver'})) {
                   2070:                 if ($in{'curr_krb_ver'} eq '5') {
                   2071:                     $check5 = ' checked="on"';
                   2072:                     $check4 = '';
                   2073:                 } else {
                   2074:                     $check4 = ' checked="on"';
                   2075:                     $check5 = '';
                   2076:                 }
1.586     raeburn  2077:             }
1.591     raeburn  2078:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2079:                 $krbarg = $in{'curr_autharg'};
                   2080:             }
1.586     raeburn  2081:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2082:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2083:                     $result = 
                   2084:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2085:         $in{'curr_autharg'},$krbver);
                   2086:                 } else {
                   2087:                     $result =
                   2088:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2089:                 }
                   2090:                 return $result; 
                   2091:             }
                   2092:         }
                   2093:     } else {
                   2094:         if ($authnum == 1) {
                   2095:             $authtype = '<input type="hidden" name="login" value="krb">';
1.165     raeburn  2096:         }
                   2097:     }
1.586     raeburn  2098:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2099:         return;
1.587     raeburn  2100:     } elsif ($authtype eq '') {
1.591     raeburn  2101:         if (defined($in{'mode'})) {
1.587     raeburn  2102:             if ($in{'mode'} eq 'modifycourse') {
                   2103:                 if ($authnum == 1) {
                   2104:                     $authtype = '<input type="hidden" name="login" value="krb">';
                   2105:                 }
                   2106:             }
                   2107:         }
1.586     raeburn  2108:     }
                   2109:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2110:     if ($authtype eq '') {
                   2111:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2112:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
                   2113:                     $krbcheck.' />';
                   2114:     }
                   2115:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
                   2116:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
                   2117:          $in{'curr_authtype'} eq 'krb5') ||
                   2118:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
                   2119:          $in{'curr_authtype'} eq 'krb4')) {
                   2120:         $result .= &mt
1.144     matthew  2121:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2122:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2123:          '<label>'.$authtype,
1.281     albertel 2124:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2125:              'value="'.$krbarg.'" '.
1.144     matthew  2126:              'onchange="'.$jscall.'" />',
1.281     albertel 2127:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
                   2128:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
                   2129: 	 '</label>');
1.586     raeburn  2130:     } elsif ($can_assign{'krb4'}) {
                   2131:         $result .= &mt
                   2132:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2133:          '[_3] Version 4 [_4]',
                   2134:          '<label>'.$authtype,
                   2135:          '</label><input type="text" size="10" name="krbarg" '.
                   2136:              'value="'.$krbarg.'" '.
                   2137:              'onchange="'.$jscall.'" />',
                   2138:          '<label><input type="hidden" name="krbver" value="4" />',
                   2139:          '</label>');
                   2140:     } elsif ($can_assign{'krb5'}) {
                   2141:         $result .= &mt
                   2142:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2143:          '[_3] Version 5 [_4]',
                   2144:          '<label>'.$authtype,
                   2145:          '</label><input type="text" size="10" name="krbarg" '.
                   2146:              'value="'.$krbarg.'" '.
                   2147:              'onchange="'.$jscall.'" />',
                   2148:          '<label><input type="hidden" name="krbver" value="5" />',
                   2149:          '</label>');
                   2150:     }
1.32      matthew  2151:     return $result;
                   2152: }
                   2153: 
                   2154: sub authform_internal{  
1.586     raeburn  2155:     my %in = (
1.32      matthew  2156:                 formname => 'document.cu',
                   2157:                 kerb_def_dom => 'MSU.EDU',
                   2158:                 @_,
                   2159:                 );
1.586     raeburn  2160:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
                   2161:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
1.591     raeburn  2162:     if (defined($in{'curr_authtype'})) {
                   2163:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2164:             if ($can_assign{'int'}) {
                   2165:                 $intcheck = 'checked="on" ';
1.623     raeburn  2166:                 if (defined($in{'mode'})) {
                   2167:                     if ($in{'mode'} eq 'modifyuser') {
                   2168:                         $intcheck = '';
                   2169:                     }
                   2170:                 }
1.591     raeburn  2171:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2172:                     $intarg = $in{'curr_autharg'};
                   2173:                 }
                   2174:             } else {
                   2175:                 $result = &mt('Currently internally authenticated.');
                   2176:                 return $result;
1.165     raeburn  2177:             }
                   2178:         }
1.586     raeburn  2179:     } else {
                   2180:         if ($authnum == 1) {
                   2181:             $authtype = '<input type="hidden" name="login" value="int">';
                   2182:         }
                   2183:     }
                   2184:     if (!$can_assign{'int'}) {
                   2185:         return;
1.587     raeburn  2186:     } elsif ($authtype eq '') {
1.591     raeburn  2187:         if (defined($in{'mode'})) {
1.587     raeburn  2188:             if ($in{'mode'} eq 'modifycourse') {
                   2189:                 if ($authnum == 1) {
                   2190:                     $authtype = '<input type="hidden" name="login" value="int">';
                   2191:                 }
                   2192:             }
                   2193:         }
1.165     raeburn  2194:     }
1.586     raeburn  2195:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   2196:     if ($authtype eq '') {
                   2197:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
                   2198:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
                   2199:     }
1.605     bisitz   2200:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.586     raeburn  2201:                $intarg.'" onchange="'.$jscall.'" />';
                   2202:     $result = &mt
1.144     matthew  2203:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  2204:          '<label>'.$authtype,'</label>'.$autharg);
1.620     www      2205:     $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  2206:     return $result;
                   2207: }
                   2208: 
                   2209: sub authform_local{  
                   2210:     my %in = (
                   2211:               formname => 'document.cu',
                   2212:               kerb_def_dom => 'MSU.EDU',
                   2213:               @_,
                   2214:               );
1.586     raeburn  2215:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
                   2216:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
1.591     raeburn  2217:     if (defined($in{'curr_authtype'})) {
                   2218:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  2219:             if ($can_assign{'loc'}) {
                   2220:                 $loccheck = 'checked="on" ';
1.623     raeburn  2221:                 if (defined($in{'mode'})) {
                   2222:                     if ($in{'mode'} eq 'modifyuser') {
                   2223:                         $loccheck = '';
                   2224:                     }
                   2225:                 }
1.591     raeburn  2226:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2227:                     $locarg = $in{'curr_autharg'};
                   2228:                 }
                   2229:             } else {
                   2230:                 $result = &mt('Currently using local (institutional) authentication.');
                   2231:                 return $result;
1.165     raeburn  2232:             }
                   2233:         }
1.586     raeburn  2234:     } else {
                   2235:         if ($authnum == 1) {
                   2236:             $authtype = '<input type="hidden" name="login" value="loc">';
                   2237:         }
                   2238:     }
                   2239:     if (!$can_assign{'loc'}) {
                   2240:         return;
1.587     raeburn  2241:     } elsif ($authtype eq '') {
1.591     raeburn  2242:         if (defined($in{'mode'})) {
1.587     raeburn  2243:             if ($in{'mode'} eq 'modifycourse') {
                   2244:                 if ($authnum == 1) {
                   2245:                     $authtype = '<input type="hidden" name="login" value="loc">';
                   2246:                 }
                   2247:             }
                   2248:         }
1.165     raeburn  2249:     }
1.586     raeburn  2250:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   2251:     if ($authtype eq '') {
                   2252:         $authtype = '<input type="radio" name="login" value="loc" '.
                   2253:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
                   2254:                     $jscall.'" />';
                   2255:     }
                   2256:     $autharg = '<input type="text" size="10" name="locarg" value="'.
                   2257:                $locarg.'" onchange="'.$jscall.'" />';
                   2258:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   2259:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  2260:     return $result;
                   2261: }
                   2262: 
                   2263: sub authform_filesystem{  
                   2264:     my %in = (
                   2265:               formname => 'document.cu',
                   2266:               kerb_def_dom => 'MSU.EDU',
                   2267:               @_,
                   2268:               );
1.586     raeburn  2269:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
                   2270:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
1.591     raeburn  2271:     if (defined($in{'curr_authtype'})) {
                   2272:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  2273:             if ($can_assign{'fsys'}) {
                   2274:                 $fsyscheck = 'checked="on" ';
1.623     raeburn  2275:                 if (defined($in{'mode'})) {
                   2276:                     if ($in{'mode'} eq 'modifyuser') {
                   2277:                         $fsyscheck = '';
                   2278:                     }
                   2279:                 }
1.586     raeburn  2280:             } else {
                   2281:                 $result = &mt('Currently Filesystem Authenticated.');
                   2282:                 return $result;
                   2283:             }           
                   2284:         }
                   2285:     } else {
                   2286:         if ($authnum == 1) {
                   2287:             $authtype = '<input type="hidden" name="login" value="fsys">';
                   2288:         }
                   2289:     }
                   2290:     if (!$can_assign{'fsys'}) {
                   2291:         return;
1.587     raeburn  2292:     } elsif ($authtype eq '') {
1.591     raeburn  2293:         if (defined($in{'mode'})) {
1.587     raeburn  2294:             if ($in{'mode'} eq 'modifycourse') {
                   2295:                 if ($authnum == 1) {
                   2296:                     $authtype = '<input type="hidden" name="login" value="fsys">';
                   2297:                 }
                   2298:             }
                   2299:         }
1.586     raeburn  2300:     }
                   2301:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   2302:     if ($authtype eq '') {
                   2303:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   2304:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
                   2305:                     $jscall.'" />';
                   2306:     }
                   2307:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
                   2308:                ' onchange="'.$jscall.'" />';
                   2309:     $result = &mt
1.144     matthew  2310:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 2311:          '<label><input type="radio" name="login" value="fsys" '.
1.586     raeburn  2312:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1.605     bisitz   2313:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.144     matthew  2314:                   'onchange="'.$jscall.'" />');
1.32      matthew  2315:     return $result;
                   2316: }
                   2317: 
1.586     raeburn  2318: sub get_assignable_auth {
                   2319:     my ($dom) = @_;
                   2320:     if ($dom eq '') {
                   2321:         $dom = $env{'request.role.domain'};
                   2322:     }
                   2323:     my %can_assign = (
                   2324:                           krb4 => 1,
                   2325:                           krb5 => 1,
                   2326:                           int  => 1,
                   2327:                           loc  => 1,
                   2328:                      );
                   2329:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   2330:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   2331:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   2332:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   2333:             my $context;
                   2334:             if ($env{'request.role'} =~ /^au/) {
                   2335:                 $context = 'author';
                   2336:             } elsif ($env{'request.role'} =~ /^dc/) {
                   2337:                 $context = 'domain';
                   2338:             } elsif ($env{'request.course.id'}) {
                   2339:                 $context = 'course';
                   2340:             }
                   2341:             if ($context) {
                   2342:                 if (ref($authhash->{$context}) eq 'HASH') {
                   2343:                    %can_assign = %{$authhash->{$context}}; 
                   2344:                 }
                   2345:             }
                   2346:         }
                   2347:     }
                   2348:     my $authnum = 0;
                   2349:     foreach my $key (keys(%can_assign)) {
                   2350:         if ($can_assign{$key}) {
                   2351:             $authnum ++;
                   2352:         }
                   2353:     }
                   2354:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   2355:         $authnum --;
                   2356:     }
                   2357:     return ($authnum,%can_assign);
                   2358: }
                   2359: 
1.80      albertel 2360: ###############################################################
                   2361: ##    Get Kerberos Defaults for Domain                 ##
                   2362: ###############################################################
                   2363: ##
                   2364: ## Returns default kerberos version and an associated argument
                   2365: ## as listed in file domain.tab. If not listed, provides
                   2366: ## appropriate default domain and kerberos version.
                   2367: ##
                   2368: #-------------------------------------------
                   2369: 
                   2370: =pod
                   2371: 
1.648     raeburn  2372: =item * &get_kerberos_defaults()
1.80      albertel 2373: 
                   2374: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  2375: version and domain. If not found, it defaults to version 4 and the 
                   2376: domain of the server.
1.80      albertel 2377: 
1.648     raeburn  2378: =over 4
                   2379: 
1.80      albertel 2380: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   2381: 
1.648     raeburn  2382: =back
                   2383: 
                   2384: =back
                   2385: 
1.80      albertel 2386: =cut
                   2387: 
                   2388: #-------------------------------------------
                   2389: sub get_kerberos_defaults {
                   2390:     my $domain=shift;
1.641     raeburn  2391:     my ($krbdef,$krbdefdom);
                   2392:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2393:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   2394:         $krbdef = $domdefaults{'auth_def'};
                   2395:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   2396:     } else {
1.80      albertel 2397:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   2398:         my $krbdefdom=$1;
                   2399:         $krbdefdom=~tr/a-z/A-Z/;
                   2400:         $krbdef = "krb4";
                   2401:     }
                   2402:     return ($krbdef,$krbdefdom);
                   2403: }
1.112     bowersj2 2404: 
1.32      matthew  2405: 
1.46      matthew  2406: ###############################################################
                   2407: ##                Thesaurus Functions                        ##
                   2408: ###############################################################
1.20      www      2409: 
1.46      matthew  2410: =pod
1.20      www      2411: 
1.112     bowersj2 2412: =head1 Thesaurus Functions
                   2413: 
                   2414: =over 4
                   2415: 
1.648     raeburn  2416: =item * &initialize_keywords()
1.46      matthew  2417: 
                   2418: Initializes the package variable %Keywords if it is empty.  Uses the
                   2419: package variable $thesaurus_db_file.
                   2420: 
                   2421: =cut
                   2422: 
                   2423: ###################################################
                   2424: 
                   2425: sub initialize_keywords {
                   2426:     return 1 if (scalar keys(%Keywords));
                   2427:     # If we are here, %Keywords is empty, so fill it up
                   2428:     #   Make sure the file we need exists...
                   2429:     if (! -e $thesaurus_db_file) {
                   2430:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   2431:                                  " failed because it does not exist");
                   2432:         return 0;
                   2433:     }
                   2434:     #   Set up the hash as a database
                   2435:     my %thesaurus_db;
                   2436:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 2437:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  2438:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   2439:                                  $thesaurus_db_file);
                   2440:         return 0;
                   2441:     } 
                   2442:     #  Get the average number of appearances of a word.
                   2443:     my $avecount = $thesaurus_db{'average.count'};
                   2444:     #  Put keywords (those that appear > average) into %Keywords
                   2445:     while (my ($word,$data)=each (%thesaurus_db)) {
                   2446:         my ($count,undef) = split /:/,$data;
                   2447:         $Keywords{$word}++ if ($count > $avecount);
                   2448:     }
                   2449:     untie %thesaurus_db;
                   2450:     # Remove special values from %Keywords.
1.356     albertel 2451:     foreach my $value ('total.count','average.count') {
                   2452:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  2453:   }
1.46      matthew  2454:     return 1;
                   2455: }
                   2456: 
                   2457: ###################################################
                   2458: 
                   2459: =pod
                   2460: 
1.648     raeburn  2461: =item * &keyword($word)
1.46      matthew  2462: 
                   2463: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   2464: than the average number of times in the thesaurus database.  Calls 
                   2465: &initialize_keywords
                   2466: 
                   2467: =cut
                   2468: 
                   2469: ###################################################
1.20      www      2470: 
                   2471: sub keyword {
1.46      matthew  2472:     return if (!&initialize_keywords());
                   2473:     my $word=lc(shift());
                   2474:     $word=~s/\W//g;
                   2475:     return exists($Keywords{$word});
1.20      www      2476: }
1.46      matthew  2477: 
                   2478: ###############################################################
                   2479: 
                   2480: =pod 
1.20      www      2481: 
1.648     raeburn  2482: =item * &get_related_words()
1.46      matthew  2483: 
1.160     matthew  2484: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  2485: an array of words.  If the keyword is not in the thesaurus, an empty array
                   2486: will be returned.  The order of the words returned is determined by the
                   2487: database which holds them.
                   2488: 
                   2489: Uses global $thesaurus_db_file.
                   2490: 
                   2491: =cut
                   2492: 
                   2493: ###############################################################
                   2494: sub get_related_words {
                   2495:     my $keyword = shift;
                   2496:     my %thesaurus_db;
                   2497:     if (! -e $thesaurus_db_file) {
                   2498:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   2499:                                  "failed because the file does not exist");
                   2500:         return ();
                   2501:     }
                   2502:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 2503:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  2504:         return ();
                   2505:     } 
                   2506:     my @Words=();
1.429     www      2507:     my $count=0;
1.46      matthew  2508:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 2509: 	# The first element is the number of times
                   2510: 	# the word appears.  We do not need it now.
1.429     www      2511: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   2512: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   2513: 	my $threshold=$mostfrequentcount/10;
                   2514:         foreach my $possibleword (@RelatedWords) {
                   2515:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   2516:             if ($wordcount>$threshold) {
                   2517: 		push(@Words,$word);
                   2518:                 $count++;
                   2519:                 if ($count>10) { last; }
                   2520: 	    }
1.20      www      2521:         }
                   2522:     }
1.46      matthew  2523:     untie %thesaurus_db;
                   2524:     return @Words;
1.14      harris41 2525: }
1.46      matthew  2526: 
1.112     bowersj2 2527: =pod
                   2528: 
                   2529: =back
                   2530: 
                   2531: =cut
1.61      www      2532: 
                   2533: # -------------------------------------------------------------- Plaintext name
1.81      albertel 2534: =pod
                   2535: 
1.112     bowersj2 2536: =head1 User Name Functions
                   2537: 
                   2538: =over 4
                   2539: 
1.648     raeburn  2540: =item * &plainname($uname,$udom,$first)
1.81      albertel 2541: 
1.112     bowersj2 2542: Takes a users logon name and returns it as a string in
1.226     albertel 2543: "first middle last generation" form 
                   2544: if $first is set to 'lastname' then it returns it as
                   2545: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 2546: 
                   2547: =cut
1.61      www      2548: 
1.295     www      2549: 
1.81      albertel 2550: ###############################################################
1.61      www      2551: sub plainname {
1.226     albertel 2552:     my ($uname,$udom,$first)=@_;
1.537     albertel 2553:     return if (!defined($uname) || !defined($udom));
1.295     www      2554:     my %names=&getnames($uname,$udom);
1.226     albertel 2555:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   2556: 					  $names{'middlename'},
                   2557: 					  $names{'lastname'},
                   2558: 					  $names{'generation'},$first);
                   2559:     $name=~s/^\s+//;
1.62      www      2560:     $name=~s/\s+$//;
                   2561:     $name=~s/\s+/ /g;
1.353     albertel 2562:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      2563:     return $name;
1.61      www      2564: }
1.66      www      2565: 
                   2566: # -------------------------------------------------------------------- Nickname
1.81      albertel 2567: =pod
                   2568: 
1.648     raeburn  2569: =item * &nickname($uname,$udom)
1.81      albertel 2570: 
                   2571: Gets a users name and returns it as a string as
                   2572: 
                   2573: "&quot;nickname&quot;"
1.66      www      2574: 
1.81      albertel 2575: if the user has a nickname or
                   2576: 
                   2577: "first middle last generation"
                   2578: 
                   2579: if the user does not
                   2580: 
                   2581: =cut
1.66      www      2582: 
                   2583: sub nickname {
                   2584:     my ($uname,$udom)=@_;
1.537     albertel 2585:     return if (!defined($uname) || !defined($udom));
1.295     www      2586:     my %names=&getnames($uname,$udom);
1.68      albertel 2587:     my $name=$names{'nickname'};
1.66      www      2588:     if ($name) {
                   2589:        $name='&quot;'.$name.'&quot;'; 
                   2590:     } else {
                   2591:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   2592: 	     $names{'lastname'}.' '.$names{'generation'};
                   2593:        $name=~s/\s+$//;
                   2594:        $name=~s/\s+/ /g;
                   2595:     }
                   2596:     return $name;
                   2597: }
                   2598: 
1.295     www      2599: sub getnames {
                   2600:     my ($uname,$udom)=@_;
1.537     albertel 2601:     return if (!defined($uname) || !defined($udom));
1.433     albertel 2602:     if ($udom eq 'public' && $uname eq 'public') {
                   2603: 	return ('lastname' => &mt('Public'));
                   2604:     }
1.295     www      2605:     my $id=$uname.':'.$udom;
                   2606:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   2607:     if ($cached) {
                   2608: 	return %{$names};
                   2609:     } else {
                   2610: 	my %loadnames=&Apache::lonnet::get('environment',
                   2611:                     ['firstname','middlename','lastname','generation','nickname'],
                   2612: 					 $udom,$uname);
                   2613: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   2614: 	return %loadnames;
                   2615:     }
                   2616: }
1.61      www      2617: 
1.542     raeburn  2618: # -------------------------------------------------------------------- getemails
1.648     raeburn  2619: 
1.542     raeburn  2620: =pod
                   2621: 
1.648     raeburn  2622: =item * &getemails($uname,$udom)
1.542     raeburn  2623: 
                   2624: Gets a user's email information and returns it as a hash with keys:
                   2625: notification, critnotification, permanentemail
                   2626: 
                   2627: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  2628: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  2629:  
1.648     raeburn  2630: 
1.542     raeburn  2631: =cut
                   2632: 
1.648     raeburn  2633: 
1.466     albertel 2634: sub getemails {
                   2635:     my ($uname,$udom)=@_;
                   2636:     if ($udom eq 'public' && $uname eq 'public') {
                   2637: 	return;
                   2638:     }
1.467     www      2639:     if (!$udom) { $udom=$env{'user.domain'}; }
                   2640:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 2641:     my $id=$uname.':'.$udom;
                   2642:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   2643:     if ($cached) {
                   2644: 	return %{$names};
                   2645:     } else {
                   2646: 	my %loadnames=&Apache::lonnet::get('environment',
                   2647:                     			   ['notification','critnotification',
                   2648: 					    'permanentemail'],
                   2649: 					   $udom,$uname);
                   2650: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   2651: 	return %loadnames;
                   2652:     }
                   2653: }
                   2654: 
1.551     albertel 2655: sub flush_email_cache {
                   2656:     my ($uname,$udom)=@_;
                   2657:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   2658:     if (!$uname) { $uname=$env{'user.name'};   }
                   2659:     return if ($udom eq 'public' && $uname eq 'public');
                   2660:     my $id=$uname.':'.$udom;
                   2661:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   2662: }
                   2663: 
1.61      www      2664: # ------------------------------------------------------------------ Screenname
1.81      albertel 2665: 
                   2666: =pod
                   2667: 
1.648     raeburn  2668: =item * &screenname($uname,$udom)
1.81      albertel 2669: 
                   2670: Gets a users screenname and returns it as a string
                   2671: 
                   2672: =cut
1.61      www      2673: 
                   2674: sub screenname {
                   2675:     my ($uname,$udom)=@_;
1.258     albertel 2676:     if ($uname eq $env{'user.name'} &&
                   2677: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 2678:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 2679:     return $names{'screenname'};
1.62      www      2680: }
                   2681: 
1.212     albertel 2682: 
1.62      www      2683: # ------------------------------------------------------------- Message Wrapper
                   2684: 
                   2685: sub messagewrapper {
1.369     www      2686:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      2687:     return 
1.441     albertel 2688:         '<a href="/adm/email?compose=individual&amp;'.
                   2689:         'recname='.$username.'&amp;recdom='.$domain.
                   2690: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  2691:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      2692: }
                   2693: # --------------------------------------------------------------- Notes Wrapper
                   2694: 
                   2695: sub noteswrapper {
                   2696:     my ($link,$un,$do)=@_;
                   2697:     return 
                   2698: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
1.62      www      2699: }
                   2700: # ------------------------------------------------------------- Aboutme Wrapper
                   2701: 
                   2702: sub aboutmewrapper {
1.166     www      2703:     my ($link,$username,$domain,$target)=@_;
1.447     raeburn  2704:     if (!defined($username)  && !defined($domain)) {
                   2705:         return;
                   2706:     }
1.205     www      2707:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.454     banghart 2708: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal page").'">'.$link.'</a>';
1.62      www      2709: }
                   2710: 
                   2711: # ------------------------------------------------------------ Syllabus Wrapper
                   2712: 
                   2713: 
                   2714: sub syllabuswrapper {
1.109     matthew  2715:     my ($linktext,$coursedir,$domain,$fontcolor)=@_;
                   2716:     if ($fontcolor) { 
                   2717:         $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>'; 
                   2718:     }
1.208     matthew  2719:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      2720: }
1.14      harris41 2721: 
1.208     matthew  2722: sub track_student_link {
1.268     albertel 2723:     my ($linktext,$sname,$sdom,$target,$start) = @_;
                   2724:     my $link ="/adm/trackstudent?";
1.208     matthew  2725:     my $title = 'View recent activity';
                   2726:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   2727:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 2728:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  2729:         $title .= ' of this student';
1.268     albertel 2730:     } 
1.208     matthew  2731:     if (defined($target) && $target !~ /^\s*$/) {
                   2732:         $target = qq{target="$target"};
                   2733:     } else {
                   2734:         $target = '';
                   2735:     }
1.268     albertel 2736:     if ($start) { $link.='&amp;start='.$start; }
1.554     albertel 2737:     $title = &mt($title);
                   2738:     $linktext = &mt($linktext);
1.448     albertel 2739:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   2740: 	&help_open_topic('View_recent_activity');
1.208     matthew  2741: }
                   2742: 
1.508     www      2743: # ===================================================== Display a student photo
                   2744: 
                   2745: 
1.509     albertel 2746: sub student_image_tag {
1.508     www      2747:     my ($domain,$user)=@_;
                   2748:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   2749:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   2750: 	return '<img src="'.$imgsrc.'" align="right" />';
                   2751:     } else {
                   2752: 	return '';
                   2753:     }
                   2754: }
                   2755: 
1.112     bowersj2 2756: =pod
                   2757: 
                   2758: =back
                   2759: 
                   2760: =head1 Access .tab File Data
                   2761: 
                   2762: =over 4
                   2763: 
1.648     raeburn  2764: =item * &languageids() 
1.112     bowersj2 2765: 
                   2766: returns list of all language ids
                   2767: 
                   2768: =cut
                   2769: 
1.14      harris41 2770: sub languageids {
1.16      harris41 2771:     return sort(keys(%language));
1.14      harris41 2772: }
                   2773: 
1.112     bowersj2 2774: =pod
                   2775: 
1.648     raeburn  2776: =item * &languagedescription() 
1.112     bowersj2 2777: 
                   2778: returns description of a specified language id
                   2779: 
                   2780: =cut
                   2781: 
1.14      harris41 2782: sub languagedescription {
1.125     www      2783:     my $code=shift;
                   2784:     return  ($supported_language{$code}?'* ':'').
                   2785:             $language{$code}.
1.126     www      2786: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      2787: }
                   2788: 
                   2789: sub plainlanguagedescription {
                   2790:     my $code=shift;
                   2791:     return $language{$code};
                   2792: }
                   2793: 
                   2794: sub supportedlanguagecode {
                   2795:     my $code=shift;
                   2796:     return $supported_language{$code};
1.97      www      2797: }
                   2798: 
1.112     bowersj2 2799: =pod
                   2800: 
1.648     raeburn  2801: =item * &copyrightids() 
1.112     bowersj2 2802: 
                   2803: returns list of all copyrights
                   2804: 
                   2805: =cut
                   2806: 
                   2807: sub copyrightids {
                   2808:     return sort(keys(%cprtag));
                   2809: }
                   2810: 
                   2811: =pod
                   2812: 
1.648     raeburn  2813: =item * &copyrightdescription() 
1.112     bowersj2 2814: 
                   2815: returns description of a specified copyright id
                   2816: 
                   2817: =cut
                   2818: 
                   2819: sub copyrightdescription {
1.166     www      2820:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 2821: }
1.197     matthew  2822: 
                   2823: =pod
                   2824: 
1.648     raeburn  2825: =item * &source_copyrightids() 
1.192     taceyjo1 2826: 
                   2827: returns list of all source copyrights
                   2828: 
                   2829: =cut
                   2830: 
                   2831: sub source_copyrightids {
                   2832:     return sort(keys(%scprtag));
                   2833: }
                   2834: 
                   2835: =pod
                   2836: 
1.648     raeburn  2837: =item * &source_copyrightdescription() 
1.192     taceyjo1 2838: 
                   2839: returns description of a specified source copyright id
                   2840: 
                   2841: =cut
                   2842: 
                   2843: sub source_copyrightdescription {
                   2844:     return &mt($scprtag{shift(@_)});
                   2845: }
1.112     bowersj2 2846: 
                   2847: =pod
                   2848: 
1.648     raeburn  2849: =item * &filecategories() 
1.112     bowersj2 2850: 
                   2851: returns list of all file categories
                   2852: 
                   2853: =cut
                   2854: 
                   2855: sub filecategories {
                   2856:     return sort(keys(%category_extensions));
                   2857: }
                   2858: 
                   2859: =pod
                   2860: 
1.648     raeburn  2861: =item * &filecategorytypes() 
1.112     bowersj2 2862: 
                   2863: returns list of file types belonging to a given file
                   2864: category
                   2865: 
                   2866: =cut
                   2867: 
                   2868: sub filecategorytypes {
1.356     albertel 2869:     my ($cat) = @_;
                   2870:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 2871: }
                   2872: 
                   2873: =pod
                   2874: 
1.648     raeburn  2875: =item * &fileembstyle() 
1.112     bowersj2 2876: 
                   2877: returns embedding style for a specified file type
                   2878: 
                   2879: =cut
                   2880: 
                   2881: sub fileembstyle {
                   2882:     return $fe{lc(shift(@_))};
1.169     www      2883: }
                   2884: 
1.351     www      2885: sub filemimetype {
                   2886:     return $fm{lc(shift(@_))};
                   2887: }
                   2888: 
1.169     www      2889: 
                   2890: sub filecategoryselect {
                   2891:     my ($name,$value)=@_;
1.189     matthew  2892:     return &select_form($value,$name,
1.169     www      2893: 			'' => &mt('Any category'),
                   2894: 			map { $_,$_ } sort(keys(%category_extensions)));
1.112     bowersj2 2895: }
                   2896: 
                   2897: =pod
                   2898: 
1.648     raeburn  2899: =item * &filedescription() 
1.112     bowersj2 2900: 
                   2901: returns description for a specified file type
                   2902: 
                   2903: =cut
                   2904: 
                   2905: sub filedescription {
1.188     matthew  2906:     my $file_description = $fd{lc(shift())};
                   2907:     $file_description =~ s:([\[\]]):~$1:g;
                   2908:     return &mt($file_description);
1.112     bowersj2 2909: }
                   2910: 
                   2911: =pod
                   2912: 
1.648     raeburn  2913: =item * &filedescriptionex() 
1.112     bowersj2 2914: 
                   2915: returns description for a specified file type with
                   2916: extra formatting
                   2917: 
                   2918: =cut
                   2919: 
                   2920: sub filedescriptionex {
                   2921:     my $ex=shift;
1.188     matthew  2922:     my $file_description = $fd{lc($ex)};
                   2923:     $file_description =~ s:([\[\]]):~$1:g;
                   2924:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 2925: }
                   2926: 
                   2927: # End of .tab access
                   2928: =pod
                   2929: 
                   2930: =back
                   2931: 
                   2932: =cut
                   2933: 
                   2934: # ------------------------------------------------------------------ File Types
                   2935: sub fileextensions {
                   2936:     return sort(keys(%fe));
                   2937: }
                   2938: 
1.97      www      2939: # ----------------------------------------------------------- Display Languages
                   2940: # returns a hash with all desired display languages
                   2941: #
                   2942: 
                   2943: sub display_languages {
                   2944:     my %languages=();
1.356     albertel 2945:     foreach my $lang (&preferred_languages()) {
                   2946: 	$languages{$lang}=1;
1.97      www      2947:     }
                   2948:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 2949:     if ($env{'form.displaylanguage'}) {
1.356     albertel 2950: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   2951: 	    $languages{$lang}=1;
1.97      www      2952:         }
                   2953:     }
                   2954:     return %languages;
1.14      harris41 2955: }
                   2956: 
1.117     www      2957: sub preferred_languages {
                   2958:     my @languages=();
1.654     www      2959:     if (($env{'request.role.adv'}) && ($env{'form.languages'})) {
                   2960:         @languages=(@languages,split(/\s*(\,|\;|\:)\s*/,$env{'form.languages'}));
                   2961:     }
1.258     albertel 2962:     if ($env{'course.'.$env{'request.course.id'}.'.languages'}) {
1.117     www      2963: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,
1.258     albertel 2964: 	         $env{'course.'.$env{'request.course.id'}.'.languages'}));
1.177     www      2965:     }
1.654     www      2966: 
1.258     albertel 2967:     if ($env{'environment.languages'}) {
1.459     albertel 2968: 	@languages=(@languages,
                   2969: 		    split(/\s*(\,|\;|\:)\s*/,$env{'environment.languages'}));
1.118     www      2970:     }
1.583     albertel 2971:     my $browser=$ENV{'HTTP_ACCEPT_LANGUAGE'};
1.162     www      2972:     if ($browser) {
1.583     albertel 2973: 	my @browser = 
                   2974: 	    map { (split(/\s*;\s*/,$_))[0] } (split(/\s*,\s*/,$browser));
                   2975: 	push(@languages,@browser);
1.162     www      2976:     }
1.641     raeburn  2977: 
                   2978:     foreach my $domtype ($env{'user.domain'},$env{'request.role.domain'},
                   2979:                          $Apache::lonnet::perlvar{'lonDefDomain'}) {
                   2980:         if ($domtype ne '') {
                   2981:             my %domdefs = &Apache::lonnet::get_domain_defaults($domtype);
                   2982:             if ($domdefs{'lang_def'} ne '') {
                   2983:                 push(@languages,$domdefs{'lang_def'});
                   2984:             }
                   2985:         }
1.118     www      2986:     }
                   2987: # turn "en-ca" into "en-ca,en"
                   2988:     my @genlanguages;
1.356     albertel 2989:     foreach my $lang (@languages) {
                   2990: 	unless ($lang=~/\w/) { next; }
1.583     albertel 2991: 	push(@genlanguages,$lang);
1.356     albertel 2992: 	if ($lang=~/(\-|\_)/) {
                   2993: 	    push(@genlanguages,(split(/(\-|\_)/,$lang))[0]);
1.118     www      2994: 	}
                   2995:     }
1.583     albertel 2996:     #uniqueify the languages list
                   2997:     my %count;
                   2998:     @genlanguages = map { $count{$_}++ == 0 ? $_ : () } @genlanguages;
1.118     www      2999:     return @genlanguages;
1.117     www      3000: }
                   3001: 
1.582     albertel 3002: sub languages {
                   3003:     my ($possible_langs) = @_;
                   3004:     my @preferred_langs = &preferred_languages();
                   3005:     if (!ref($possible_langs)) {
                   3006: 	if( wantarray ) {
                   3007: 	    return @preferred_langs;
                   3008: 	} else {
                   3009: 	    return $preferred_langs[0];
                   3010: 	}
                   3011:     }
                   3012:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3013:     my @preferred_possibilities;
                   3014:     foreach my $preferred_lang (@preferred_langs) {
                   3015: 	if (exists($possibilities{$preferred_lang})) {
                   3016: 	    push(@preferred_possibilities, $preferred_lang);
                   3017: 	}
                   3018:     }
                   3019:     if( wantarray ) {
                   3020: 	return @preferred_possibilities;
                   3021:     }
                   3022:     return $preferred_possibilities[0];
                   3023: }
                   3024: 
1.112     bowersj2 3025: ###############################################################
                   3026: ##               Student Answer Attempts                     ##
                   3027: ###############################################################
                   3028: 
                   3029: =pod
                   3030: 
                   3031: =head1 Alternate Problem Views
                   3032: 
                   3033: =over 4
                   3034: 
1.648     raeburn  3035: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.112     bowersj2 3036:     $getattempt, $regexp, $gradesub)
                   3037: 
                   3038: Return string with previous attempt on problem. Arguments:
                   3039: 
                   3040: =over 4
                   3041: 
                   3042: =item * $symb: Problem, including path
                   3043: 
                   3044: =item * $username: username of the desired student
                   3045: 
                   3046: =item * $domain: domain of the desired student
1.14      harris41 3047: 
1.112     bowersj2 3048: =item * $course: Course ID
1.14      harris41 3049: 
1.112     bowersj2 3050: =item * $getattempt: Leave blank for all attempts, otherwise put
                   3051:     something
1.14      harris41 3052: 
1.112     bowersj2 3053: =item * $regexp: if string matches this regexp, the string will be
                   3054:     sent to $gradesub
1.14      harris41 3055: 
1.112     bowersj2 3056: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 3057: 
1.112     bowersj2 3058: =back
1.14      harris41 3059: 
1.112     bowersj2 3060: The output string is a table containing all desired attempts, if any.
1.16      harris41 3061: 
1.112     bowersj2 3062: =cut
1.1       albertel 3063: 
                   3064: sub get_previous_attempt {
1.43      ng       3065:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
1.1       albertel 3066:   my $prevattempts='';
1.43      ng       3067:   no strict 'refs';
1.1       albertel 3068:   if ($symb) {
1.3       albertel 3069:     my (%returnhash)=
                   3070:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 3071:     if ($returnhash{'version'}) {
                   3072:       my %lasthash=();
                   3073:       my $version;
                   3074:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.356     albertel 3075:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   3076: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
1.19      harris41 3077:         }
1.1       albertel 3078:       }
1.596     albertel 3079:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   3080:       $prevattempts.='<th>'.&mt('History').'</th>';
1.356     albertel 3081:       foreach my $key (sort(keys(%lasthash))) {
                   3082: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       3083: 	if ($#parts > 0) {
1.31      albertel 3084: 	  my $data=$parts[-1];
                   3085: 	  pop(@parts);
1.596     albertel 3086: 	  $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.31      albertel 3087: 	} else {
1.41      ng       3088: 	  if ($#parts == 0) {
                   3089: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   3090: 	  } else {
                   3091: 	    $prevattempts.='<th>'.$ign.'</th>';
                   3092: 	  }
1.31      albertel 3093: 	}
1.16      harris41 3094:       }
1.596     albertel 3095:       $prevattempts.=&end_data_table_header_row();
1.40      ng       3096:       if ($getattempt eq '') {
                   3097: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.596     albertel 3098: 	  $prevattempts.=&start_data_table_row().
                   3099: 	      '<td>'.&mt('Transaction [_1]',$version).'</td>';
1.356     albertel 3100: 	    foreach my $key (sort(keys(%lasthash))) {
1.581     albertel 3101: 		my $value = &format_previous_attempt_value($key,
                   3102: 							   $returnhash{$version.':'.$key});
                   3103: 		$prevattempts.='<td>'.$value.'&nbsp;</td>';   
1.40      ng       3104: 	    }
1.596     albertel 3105: 	  $prevattempts.=&end_data_table_row();
1.40      ng       3106: 	 }
1.1       albertel 3107:       }
1.596     albertel 3108:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 3109:       foreach my $key (sort(keys(%lasthash))) {
1.581     albertel 3110: 	my $value = &format_previous_attempt_value($key,$lasthash{$key});
1.356     albertel 3111: 	if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
1.40      ng       3112: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
1.16      harris41 3113:       }
1.596     albertel 3114:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 3115:     } else {
1.596     albertel 3116:       $prevattempts=
                   3117: 	  &start_data_table().&start_data_table_row().
                   3118: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   3119: 	  &end_data_table_row().&end_data_table();
1.1       albertel 3120:     }
                   3121:   } else {
1.596     albertel 3122:     $prevattempts=
                   3123: 	  &start_data_table().&start_data_table_row().
                   3124: 	  '<td>'.&mt('No data.').'</td>'.
                   3125: 	  &end_data_table_row().&end_data_table();
1.1       albertel 3126:   }
1.10      albertel 3127: }
                   3128: 
1.581     albertel 3129: sub format_previous_attempt_value {
                   3130:     my ($key,$value) = @_;
                   3131:     if ($key =~ /timestamp/) {
                   3132: 	$value = &Apache::lonlocal::locallocaltime($value);
                   3133:     } elsif (ref($value) eq 'ARRAY') {
                   3134: 	$value = '('.join(', ', @{ $value }).')';
                   3135:     } else {
                   3136: 	$value = &unescape($value);
                   3137:     }
                   3138:     return $value;
                   3139: }
                   3140: 
                   3141: 
1.107     albertel 3142: sub relative_to_absolute {
                   3143:     my ($url,$output)=@_;
                   3144:     my $parser=HTML::TokeParser->new(\$output);
                   3145:     my $token;
                   3146:     my $thisdir=$url;
                   3147:     my @rlinks=();
                   3148:     while ($token=$parser->get_token) {
                   3149: 	if ($token->[0] eq 'S') {
                   3150: 	    if ($token->[1] eq 'a') {
                   3151: 		if ($token->[2]->{'href'}) {
                   3152: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   3153: 		}
                   3154: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   3155: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   3156: 	    } elsif ($token->[1] eq 'base') {
                   3157: 		$thisdir=$token->[2]->{'href'};
                   3158: 	    }
                   3159: 	}
                   3160:     }
                   3161:     $thisdir=~s-/[^/]*$--;
1.356     albertel 3162:     foreach my $link (@rlinks) {
                   3163: 	unless (($link=~/^http:\/\//i) ||
                   3164: 		($link=~/^\//) ||
                   3165: 		($link=~/^javascript:/i) ||
                   3166: 		($link=~/^mailto:/i) ||
                   3167: 		($link=~/^\#/)) {
                   3168: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   3169: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 3170: 	}
                   3171:     }
                   3172: # -------------------------------------------------- Deal with Applet codebases
                   3173:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   3174:     return $output;
                   3175: }
                   3176: 
1.112     bowersj2 3177: =pod
                   3178: 
1.648     raeburn  3179: =item * &get_student_view()
1.112     bowersj2 3180: 
                   3181: show a snapshot of what student was looking at
                   3182: 
                   3183: =cut
                   3184: 
1.10      albertel 3185: sub get_student_view {
1.186     albertel 3186:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      3187:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 3188:   my (%form);
1.10      albertel 3189:   my @elements=('symb','courseid','domain','username');
                   3190:   foreach my $element (@elements) {
1.186     albertel 3191:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 3192:   }
1.186     albertel 3193:   if (defined($moreenv)) {
                   3194:       %form=(%form,%{$moreenv});
                   3195:   }
1.236     albertel 3196:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 3197:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      3198:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 3199:   $userview=~s/\<body[^\>]*\>//gi;
                   3200:   $userview=~s/\<\/body\>//gi;
                   3201:   $userview=~s/\<html\>//gi;
                   3202:   $userview=~s/\<\/html\>//gi;
                   3203:   $userview=~s/\<head\>//gi;
                   3204:   $userview=~s/\<\/head\>//gi;
                   3205:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 3206:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      3207:   if (wantarray) {
                   3208:      return ($userview,$response);
                   3209:   } else {
                   3210:      return $userview;
                   3211:   }
                   3212: }
                   3213: 
                   3214: sub get_student_view_with_retries {
                   3215:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   3216: 
                   3217:     my $ok = 0;                 # True if we got a good response.
                   3218:     my $content;
                   3219:     my $response;
                   3220: 
                   3221:     # Try to get the student_view done. within the retries count:
                   3222:     
                   3223:     do {
                   3224:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   3225:          $ok      = $response->is_success;
                   3226:          if (!$ok) {
                   3227:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   3228:          }
                   3229:          $retries--;
                   3230:     } while (!$ok && ($retries > 0));
                   3231:     
                   3232:     if (!$ok) {
                   3233:        $content = '';          # On error return an empty content.
                   3234:     }
1.651     www      3235:     if (wantarray) {
                   3236:        return ($content, $response);
                   3237:     } else {
                   3238:        return $content;
                   3239:     }
1.11      albertel 3240: }
                   3241: 
1.112     bowersj2 3242: =pod
                   3243: 
1.648     raeburn  3244: =item * &get_student_answers() 
1.112     bowersj2 3245: 
                   3246: show a snapshot of how student was answering problem
                   3247: 
                   3248: =cut
                   3249: 
1.11      albertel 3250: sub get_student_answers {
1.100     sakharuk 3251:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      3252:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 3253:   my (%moreenv);
1.11      albertel 3254:   my @elements=('symb','courseid','domain','username');
                   3255:   foreach my $element (@elements) {
1.186     albertel 3256:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 3257:   }
1.186     albertel 3258:   $moreenv{'grade_target'}='answer';
                   3259:   %moreenv=(%form,%moreenv);
1.497     raeburn  3260:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   3261:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 3262:   return $userview;
1.1       albertel 3263: }
1.116     albertel 3264: 
                   3265: =pod
                   3266: 
                   3267: =item * &submlink()
                   3268: 
1.242     albertel 3269: Inputs: $text $uname $udom $symb $target
1.116     albertel 3270: 
                   3271: Returns: A link to grades.pm such as to see the SUBM view of a student
                   3272: 
                   3273: =cut
                   3274: 
                   3275: ###############################################
                   3276: sub submlink {
1.242     albertel 3277:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 3278:     if (!($uname && $udom)) {
                   3279: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 3280: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 3281: 	if (!$symb) { $symb=$cursymb; }
                   3282:     }
1.254     matthew  3283:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      3284:     $symb=&escape($symb);
1.242     albertel 3285:     if ($target) { $target="target=\"$target\""; }
                   3286:     return '<a href="/adm/grades?&command=submission&'.
                   3287: 	'symb='.$symb.'&student='.$uname.
                   3288: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
                   3289: }
                   3290: ##############################################
                   3291: 
                   3292: =pod
                   3293: 
                   3294: =item * &pgrdlink()
                   3295: 
                   3296: Inputs: $text $uname $udom $symb $target
                   3297: 
                   3298: Returns: A link to grades.pm such as to see the PGRD view of a student
                   3299: 
                   3300: =cut
                   3301: 
                   3302: ###############################################
                   3303: sub pgrdlink {
                   3304:     my $link=&submlink(@_);
                   3305:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   3306:     return $link;
                   3307: }
                   3308: ##############################################
                   3309: 
                   3310: =pod
                   3311: 
                   3312: =item * &pprmlink()
                   3313: 
                   3314: Inputs: $text $uname $udom $symb $target
                   3315: 
                   3316: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 3317: student and a specific resource
1.242     albertel 3318: 
                   3319: =cut
                   3320: 
                   3321: ###############################################
                   3322: sub pprmlink {
                   3323:     my ($text,$uname,$udom,$symb,$target)=@_;
                   3324:     if (!($uname && $udom)) {
                   3325: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 3326: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 3327: 	if (!$symb) { $symb=$cursymb; }
                   3328:     }
1.254     matthew  3329:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      3330:     $symb=&escape($symb);
1.242     albertel 3331:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 3332:     return '<a href="/adm/parmset?command=set&amp;'.
                   3333: 	'symb='.$symb.'&amp;uname='.$uname.
                   3334: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 3335: }
                   3336: ##############################################
1.37      matthew  3337: 
1.112     bowersj2 3338: =pod
                   3339: 
                   3340: =back
                   3341: 
                   3342: =cut
                   3343: 
1.37      matthew  3344: ###############################################
1.51      www      3345: 
                   3346: 
                   3347: sub timehash {
                   3348:     my @ltime=localtime(shift);
                   3349:     return ( 'seconds' => $ltime[0],
                   3350:              'minutes' => $ltime[1],
                   3351:              'hours'   => $ltime[2],
                   3352:              'day'     => $ltime[3],
                   3353:              'month'   => $ltime[4]+1,
                   3354:              'year'    => $ltime[5]+1900,
                   3355:              'weekday' => $ltime[6],
                   3356:              'dayyear' => $ltime[7]+1,
                   3357:              'dlsav'   => $ltime[8] );
                   3358: }
                   3359: 
1.370     www      3360: sub utc_string {
                   3361:     my ($date)=@_;
1.371     www      3362:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      3363: }
                   3364: 
1.51      www      3365: sub maketime {
                   3366:     my %th=@_;
                   3367:     return POSIX::mktime(
                   3368:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      3369:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      3370: }
                   3371: 
                   3372: #########################################
1.51      www      3373: 
                   3374: sub findallcourses {
1.482     raeburn  3375:     my ($roles,$uname,$udom) = @_;
1.355     albertel 3376:     my %roles;
                   3377:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 3378:     my %courses;
1.51      www      3379:     my $now=time;
1.482     raeburn  3380:     if (!defined($uname)) {
                   3381:         $uname = $env{'user.name'};
                   3382:     }
                   3383:     if (!defined($udom)) {
                   3384:         $udom = $env{'user.domain'};
                   3385:     }
                   3386:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   3387:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
                   3388:         if (!%roles) {
                   3389:             %roles = (
                   3390:                        cc => 1,
                   3391:                        in => 1,
                   3392:                        ep => 1,
                   3393:                        ta => 1,
                   3394:                        cr => 1,
                   3395:                        st => 1,
                   3396:              );
                   3397:         }
                   3398:         foreach my $entry (keys(%roleshash)) {
                   3399:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   3400:             if ($trole =~ /^cr/) { 
                   3401:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   3402:             } else {
                   3403:                 next if (!exists($roles{$trole}));
                   3404:             }
                   3405:             if ($tend) {
                   3406:                 next if ($tend < $now);
                   3407:             }
                   3408:             if ($tstart) {
                   3409:                 next if ($tstart > $now);
                   3410:             }
                   3411:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
                   3412:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
                   3413:             if ($secpart eq '') {
                   3414:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   3415:                 $sec = 'none';
                   3416:                 $realsec = '';
                   3417:             } else {
                   3418:                 $cnum = $cnumpart;
                   3419:                 ($sec,$role) = split(/_/,$secpart);
                   3420:                 $realsec = $sec;
1.490     raeburn  3421:             }
1.482     raeburn  3422:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
                   3423:         }
                   3424:     } else {
                   3425:         foreach my $key (keys(%env)) {
1.483     albertel 3426: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   3427:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  3428: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   3429: 	        next if ($role eq 'ca' || $role eq 'aa');
                   3430: 	        next if (%roles && !exists($roles{$role}));
                   3431: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   3432:                 my $active=1;
                   3433:                 if ($starttime) {
                   3434: 		    if ($now<$starttime) { $active=0; }
                   3435:                 }
                   3436:                 if ($endtime) {
                   3437:                     if ($now>$endtime) { $active=0; }
                   3438:                 }
                   3439:                 if ($active) {
                   3440:                     if ($sec eq '') {
                   3441:                         $sec = 'none';
                   3442:                     }
                   3443:                     $courses{$cdom.'_'.$cnum}{$sec} = 
                   3444:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
1.474     raeburn  3445:                 }
                   3446:             }
1.51      www      3447:         }
                   3448:     }
1.474     raeburn  3449:     return %courses;
1.51      www      3450: }
1.37      matthew  3451: 
1.54      www      3452: ###############################################
1.474     raeburn  3453: 
                   3454: sub blockcheck {
1.482     raeburn  3455:     my ($setters,$activity,$uname,$udom) = @_;
1.490     raeburn  3456: 
                   3457:     if (!defined($udom)) {
                   3458:         $udom = $env{'user.domain'};
                   3459:     }
                   3460:     if (!defined($uname)) {
                   3461:         $uname = $env{'user.name'};
                   3462:     }
                   3463: 
                   3464:     # If uname and udom are for a course, check for blocks in the course.
                   3465: 
                   3466:     if (&Apache::lonnet::is_course($udom,$uname)) {
                   3467:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
1.502     raeburn  3468:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
1.490     raeburn  3469:         return ($startblock,$endblock);
                   3470:     }
1.474     raeburn  3471: 
1.502     raeburn  3472:     my $startblock = 0;
                   3473:     my $endblock = 0;
1.482     raeburn  3474:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  3475: 
1.490     raeburn  3476:     # If uname is for a user, and activity is course-specific, i.e.,
                   3477:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  3478: 
1.490     raeburn  3479:     if (($activity eq 'boards' || $activity eq 'chat' ||
                   3480:          $activity eq 'groups') && ($env{'request.course.id'})) {
                   3481:         foreach my $key (keys(%live_courses)) {
                   3482:             if ($key ne $env{'request.course.id'}) {
                   3483:                 delete($live_courses{$key});
                   3484:             }
                   3485:         }
                   3486:     }
                   3487: 
                   3488:     my $otheruser = 0;
                   3489:     my %own_courses;
                   3490:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   3491:         # Resource belongs to user other than current user.
                   3492:         $otheruser = 1;
                   3493:         # Gather courses for current user
                   3494:         %own_courses = 
                   3495:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   3496:     }
                   3497: 
                   3498:     # Gather active course roles - course coordinator, instructor, 
                   3499:     # exam proctor, ta, student, or custom role.
1.474     raeburn  3500: 
                   3501:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  3502:         my ($cdom,$cnum);
                   3503:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   3504:             $cdom = $env{'course.'.$course.'.domain'};
                   3505:             $cnum = $env{'course.'.$course.'.num'};
                   3506:         } else {
1.490     raeburn  3507:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  3508:         }
                   3509:         my $no_ownblock = 0;
                   3510:         my $no_userblock = 0;
1.533     raeburn  3511:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  3512:             # Check if current user has 'evb' priv for this
                   3513:             if (defined($own_courses{$course})) {
                   3514:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   3515:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   3516:                     if ($sec ne 'none') {
                   3517:                         $checkrole .= '/'.$sec;
                   3518:                     }
                   3519:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   3520:                         $no_ownblock = 1;
                   3521:                         last;
                   3522:                     }
                   3523:                 }
                   3524:             }
                   3525:             # if they have 'evb' priv and are currently not playing student
                   3526:             next if (($no_ownblock) &&
                   3527:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   3528:         }
1.474     raeburn  3529:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  3530:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  3531:             if ($sec ne 'none') {
1.482     raeburn  3532:                 $checkrole .= '/'.$sec;
1.474     raeburn  3533:             }
1.490     raeburn  3534:             if ($otheruser) {
                   3535:                 # Resource belongs to user other than current user.
                   3536:                 # Assemble privs for that user, and check for 'evb' priv.
1.482     raeburn  3537:                 my ($trole,$tdom,$tnum,$tsec);
                   3538:                 my $entry = $live_courses{$course}{$sec};
                   3539:                 if ($entry =~ /^cr/) {
                   3540:                     ($trole,$tdom,$tnum,$tsec) = 
                   3541:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   3542:                 } else {
                   3543:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   3544:                 }
                   3545:                 my ($spec,$area,$trest,%allroles,%userroles);
                   3546:                 $area = '/'.$tdom.'/'.$tnum;
                   3547:                 $trest = $tnum;
                   3548:                 if ($tsec ne '') {
                   3549:                     $area .= '/'.$tsec;
                   3550:                     $trest .= '/'.$tsec;
                   3551:                 }
                   3552:                 $spec = $trole.'.'.$area;
                   3553:                 if ($trole =~ /^cr/) {
                   3554:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   3555:                                                       $tdom,$spec,$trest,$area);
                   3556:                 } else {
                   3557:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   3558:                                                        $tdom,$spec,$trest,$area);
                   3559:                 }
                   3560:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.486     raeburn  3561:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   3562:                     if ($1) {
                   3563:                         $no_userblock = 1;
                   3564:                         last;
                   3565:                     }
                   3566:                 }
1.490     raeburn  3567:             } else {
                   3568:                 # Resource belongs to current user
                   3569:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  3570:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   3571:                     $no_ownblock = 1;
                   3572:                     last;
                   3573:                 }
1.474     raeburn  3574:             }
                   3575:         }
                   3576:         # if they have the evb priv and are currently not playing student
1.482     raeburn  3577:         next if (($no_ownblock) &&
1.491     albertel 3578:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  3579:         next if ($no_userblock);
1.474     raeburn  3580: 
1.490     raeburn  3581:         # Retrieve blocking times and identity of blocker for course
                   3582:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  3583:         
                   3584:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
                   3585:         if (($start != 0) && 
                   3586:             (($startblock == 0) || ($startblock > $start))) {
                   3587:             $startblock = $start;
                   3588:         }
                   3589:         if (($end != 0)  &&
                   3590:             (($endblock == 0) || ($endblock < $end))) {
                   3591:             $endblock = $end;
                   3592:         }
1.490     raeburn  3593:     }
                   3594:     return ($startblock,$endblock);
                   3595: }
                   3596: 
                   3597: sub get_blocks {
                   3598:     my ($setters,$activity,$cdom,$cnum) = @_;
                   3599:     my $startblock = 0;
                   3600:     my $endblock = 0;
                   3601:     my $course = $cdom.'_'.$cnum;
                   3602:     $setters->{$course} = {};
                   3603:     $setters->{$course}{'staff'} = [];
                   3604:     $setters->{$course}{'times'} = [];
                   3605:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   3606:     foreach my $record (keys(%records)) {
                   3607:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
                   3608:         if ($start <= time && $end >= time) {
                   3609:             my ($staff_name,$staff_dom,$title,$blocks) =
                   3610:                 &parse_block_record($records{$record});
                   3611:             if ($blocks->{$activity} eq 'on') {
                   3612:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   3613:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
1.491     albertel 3614:                 if ( ($startblock == 0) || ($startblock > $start) ) {
                   3615:                     $startblock = $start;
1.490     raeburn  3616:                 }
1.491     albertel 3617:                 if ( ($endblock == 0) || ($endblock < $end) ) {
                   3618:                     $endblock = $end;
1.474     raeburn  3619:                 }
                   3620:             }
                   3621:         }
                   3622:     }
                   3623:     return ($startblock,$endblock);
                   3624: }
                   3625: 
                   3626: sub parse_block_record {
                   3627:     my ($record) = @_;
                   3628:     my ($setuname,$setudom,$title,$blocks);
                   3629:     if (ref($record) eq 'HASH') {
                   3630:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   3631:         $title = &unescape($record->{'event'});
                   3632:         $blocks = $record->{'blocks'};
                   3633:     } else {
                   3634:         my @data = split(/:/,$record,3);
                   3635:         if (scalar(@data) eq 2) {
                   3636:             $title = $data[1];
                   3637:             ($setuname,$setudom) = split(/@/,$data[0]);
                   3638:         } else {
                   3639:             ($setuname,$setudom,$title) = @data;
                   3640:         }
                   3641:         $blocks = { 'com' => 'on' };
                   3642:     }
                   3643:     return ($setuname,$setudom,$title,$blocks);
                   3644: }
                   3645: 
                   3646: sub build_block_table {
                   3647:     my ($startblock,$endblock,$setters) = @_;
                   3648:     my %lt = &Apache::lonlocal::texthash(
                   3649:         'cacb' => 'Currently active communication blocks',
                   3650:         'cour' => 'Course',
                   3651:         'dura' => 'Duration',
                   3652:         'blse' => 'Block set by'
                   3653:     );
                   3654:     my $output;
1.476     raeburn  3655:     $output = '<br />'.$lt{'cacb'}.':<br />';
1.474     raeburn  3656:     $output .= &start_data_table();
                   3657:     $output .= '
                   3658: <tr>
                   3659:  <th>'.$lt{'cour'}.'</th>
                   3660:  <th>'.$lt{'dura'}.'</th>
                   3661:  <th>'.$lt{'blse'}.'</th>
                   3662: </tr>
                   3663: ';
                   3664:     foreach my $course (keys(%{$setters})) {
                   3665:         my %courseinfo=&Apache::lonnet::coursedescription($course);
                   3666:         for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
                   3667:             my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
1.490     raeburn  3668:             my $fullname = &plainname($uname,$udom);
                   3669:             if (defined($env{'user.name'}) && defined($env{'user.domain'})
                   3670:                 && $env{'user.name'} ne 'public' 
                   3671:                 && $env{'user.domain'} ne 'public') {
                   3672:                 $fullname = &aboutmewrapper($fullname,$uname,$udom);
                   3673:             }
1.474     raeburn  3674:             my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
                   3675:             $openblock = &Apache::lonlocal::locallocaltime($openblock);
                   3676:             $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
                   3677:             $output .= &Apache::loncommon::start_data_table_row().
                   3678:                        '<td>'.$courseinfo{'description'}.'</td>'.
                   3679:                        '<td>'.$openblock.' to '.$closeblock.'</td>'.
1.490     raeburn  3680:                        '<td>'.$fullname.'</td>'.
1.474     raeburn  3681:                         &Apache::loncommon::end_data_table_row();
                   3682:         }
                   3683:     }
                   3684:     $output .= &end_data_table();
                   3685: }
                   3686: 
1.490     raeburn  3687: sub blocking_status {
                   3688:     my ($activity,$uname,$udom) = @_;
                   3689:     my %setters;
                   3690:     my ($blocked,$output,$ownitem,$is_course);
                   3691:     my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
                   3692:     if ($startblock && $endblock) {
                   3693:         $blocked = 1;
                   3694:         if (wantarray) {
                   3695:             my $category;
                   3696:             if ($activity eq 'boards') {
                   3697:                 $category = 'Discussion posts in this course';
                   3698:             } elsif ($activity eq 'blogs') {
                   3699:                 $category = 'Blogs';
                   3700:             } elsif ($activity eq 'port') {
                   3701:                 if (defined($uname) && defined($udom)) {
                   3702:                     if ($uname eq $env{'user.name'} &&
                   3703:                         $udom eq $env{'user.domain'}) {
                   3704:                         $ownitem = 1;
                   3705:                     }
                   3706:                 }
                   3707:                 $is_course = &Apache::lonnet::is_course($udom,$uname);
                   3708:                 if ($ownitem) { 
                   3709:                     $category = 'Your portfolio files';  
                   3710:                 } elsif ($is_course) {
                   3711:                     my $coursedesc;
                   3712:                     foreach my $course (keys(%setters)) {
                   3713:                         my %courseinfo =
                   3714:                              &Apache::lonnet::coursedescription($course);
                   3715:                         $coursedesc = $courseinfo{'description'};
                   3716:                     }
                   3717:                     $category = "Group files in the course '$coursedesc'";
                   3718:                 } else {
                   3719:                     $category = 'Portfolio files belonging to ';
                   3720:                     if ($env{'user.name'} eq 'public' && 
                   3721:                         $env{'user.domain'} eq 'public') {
                   3722:                         $category .= &plainname($uname,$udom);
                   3723:                     } else {
                   3724:                         $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);  
                   3725:                     }
                   3726:                 }
                   3727:             } elsif ($activity eq 'groups') {
                   3728:                 $category = 'Groups in this course';
                   3729:             }
                   3730:             my $showstart = &Apache::lonlocal::locallocaltime($startblock);
                   3731:             my $showend = &Apache::lonlocal::locallocaltime($endblock);
                   3732:             $output = '<br />'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'<br />';
                   3733:             if (!($activity eq 'port' && !($ownitem) && !($is_course))) { 
                   3734:                 $output .= &build_block_table($startblock,$endblock,\%setters);
                   3735:             }
                   3736:         }
                   3737:     }
                   3738:     if (wantarray) {
                   3739:         return ($blocked,$output);
                   3740:     } else {
                   3741:         return $blocked;
                   3742:     }
                   3743: }
                   3744: 
1.60      matthew  3745: ###############################################
                   3746: 
                   3747: =pod
                   3748: 
1.112     bowersj2 3749: =head1 Domain Template Functions
                   3750: 
                   3751: =over 4
                   3752: 
                   3753: =item * &determinedomain()
1.60      matthew  3754: 
                   3755: Inputs: $domain (usually will be undef)
                   3756: 
1.63      www      3757: Returns: Determines which domain should be used for designs
1.60      matthew  3758: 
                   3759: =cut
1.54      www      3760: 
1.60      matthew  3761: ###############################################
1.63      www      3762: sub determinedomain {
                   3763:     my $domain=shift;
1.531     albertel 3764:     if (! $domain) {
1.60      matthew  3765:         # Determine domain if we have not been given one
                   3766:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
1.258     albertel 3767:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   3768:         if ($env{'request.role.domain'}) { 
                   3769:             $domain=$env{'request.role.domain'}; 
1.60      matthew  3770:         }
                   3771:     }
1.63      www      3772:     return $domain;
                   3773: }
                   3774: ###############################################
1.517     raeburn  3775: 
1.518     albertel 3776: sub devalidate_domconfig_cache {
                   3777:     my ($udom)=@_;
                   3778:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   3779: }
                   3780: 
                   3781: # ---------------------- Get domain configuration for a domain
                   3782: sub get_domainconf {
                   3783:     my ($udom) = @_;
                   3784:     my $cachetime=1800;
                   3785:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   3786:     if (defined($cached)) { return %{$result}; }
                   3787: 
                   3788:     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   3789: 					     ['login','rolecolors'],$udom);
1.632     raeburn  3790:     my (%designhash,%legacy);
1.518     albertel 3791:     if (keys(%domconfig) > 0) {
                   3792:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  3793:             if (keys(%{$domconfig{'login'}})) {
                   3794:                 foreach my $key (keys(%{$domconfig{'login'}})) {
                   3795:                     $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   3796:                 }
                   3797:             } else {
                   3798:                 $legacy{'login'} = 1;
1.518     albertel 3799:             }
1.632     raeburn  3800:         } else {
                   3801:             $legacy{'login'} = 1;
1.518     albertel 3802:         }
                   3803:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  3804:             if (keys(%{$domconfig{'rolecolors'}})) {
                   3805:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   3806:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   3807:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   3808:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   3809:                         }
1.518     albertel 3810:                     }
                   3811:                 }
1.632     raeburn  3812:             } else {
                   3813:                 $legacy{'rolecolors'} = 1;
1.518     albertel 3814:             }
1.632     raeburn  3815:         } else {
                   3816:             $legacy{'rolecolors'} = 1;
1.518     albertel 3817:         }
1.632     raeburn  3818:         if (keys(%legacy) > 0) {
                   3819:             my %legacyhash = &get_legacy_domconf($udom);
                   3820:             foreach my $item (keys(%legacyhash)) {
                   3821:                 if ($item =~ /^\Q$udom\E\.login/) {
                   3822:                     if ($legacy{'login'}) { 
                   3823:                         $designhash{$item} = $legacyhash{$item};
                   3824:                     }
                   3825:                 } else {
                   3826:                     if ($legacy{'rolecolors'}) {
                   3827:                         $designhash{$item} = $legacyhash{$item};
                   3828:                     }
1.518     albertel 3829:                 }
                   3830:             }
                   3831:         }
1.632     raeburn  3832:     } else {
                   3833:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 3834:     }
                   3835:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   3836: 				  $cachetime);
                   3837:     return %designhash;
                   3838: }
                   3839: 
1.632     raeburn  3840: sub get_legacy_domconf {
                   3841:     my ($udom) = @_;
                   3842:     my %legacyhash;
                   3843:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   3844:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   3845:     if (-e $designfile) {
                   3846:         if ( open (my $fh,"<$designfile") ) {
                   3847:             while (my $line = <$fh>) {
                   3848:                 next if ($line =~ /^\#/);
                   3849:                 chomp($line);
                   3850:                 my ($key,$val)=(split(/\=/,$line));
                   3851:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   3852:             }
                   3853:             close($fh);
                   3854:         }
                   3855:     }
                   3856:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
                   3857:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   3858:     }
                   3859:     return %legacyhash;
                   3860: }
                   3861: 
1.63      www      3862: =pod
                   3863: 
1.112     bowersj2 3864: =item * &domainlogo()
1.63      www      3865: 
                   3866: Inputs: $domain (usually will be undef)
                   3867: 
                   3868: Returns: A link to a domain logo, if the domain logo exists.
                   3869: If the domain logo does not exist, a description of the domain.
                   3870: 
                   3871: =cut
1.112     bowersj2 3872: 
1.63      www      3873: ###############################################
                   3874: sub domainlogo {
1.517     raeburn  3875:     my $domain = &determinedomain(shift);
1.518     albertel 3876:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  3877:     # See if there is a logo
                   3878:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  3879:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 3880:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   3881: 	    if ($imgsrc =~ m{^/res/}) {
                   3882: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   3883: 		&Apache::lonnet::repcopy($local_name);
                   3884: 	    }
                   3885: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  3886:         } 
                   3887:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 3888:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   3889:         return &Apache::lonnet::domain($domain,'description');
1.59      www      3890:     } else {
1.60      matthew  3891:         return '';
1.59      www      3892:     }
                   3893: }
1.63      www      3894: ##############################################
                   3895: 
                   3896: =pod
                   3897: 
1.112     bowersj2 3898: =item * &designparm()
1.63      www      3899: 
                   3900: Inputs: $which parameter; $domain (usually will be undef)
                   3901: 
                   3902: Returns: value of designparamter $which
                   3903: 
                   3904: =cut
1.112     bowersj2 3905: 
1.397     albertel 3906: 
1.400     albertel 3907: ##############################################
1.397     albertel 3908: sub designparm {
                   3909:     my ($which,$domain)=@_;
1.258     albertel 3910:     if ($env{'browser.blackwhite'} eq 'on') {
1.635     raeburn  3911: 	if ($which=~/\.(font|alink|vlink|link|textcol)$/) {
1.110     www      3912: 	    return '#000000';
                   3913: 	}
1.635     raeburn  3914: 	if ($which=~/\.(pgbg|sidebg|bgcol)$/) {
1.110     www      3915: 	    return '#FFFFFF';
                   3916: 	}
                   3917: 	if ($which=~/\.tabbg$/) {
                   3918: 	    return '#CCCCCC';
                   3919: 	}
                   3920:     }
1.397     albertel 3921:     if (exists($env{'environment.color.'.$which})) {
1.258     albertel 3922: 	return $env{'environment.color.'.$which};
1.96      www      3923:     }
1.63      www      3924:     $domain=&determinedomain($domain);
1.518     albertel 3925:     my %domdesign = &get_domainconf($domain);
1.520     raeburn  3926:     my $output;
1.517     raeburn  3927:     if ($domdesign{$domain.'.'.$which} ne '') {
1.520     raeburn  3928: 	$output = $domdesign{$domain.'.'.$which};
1.63      www      3929:     } else {
1.520     raeburn  3930:         $output = $defaultdesign{$which};
                   3931:     }
                   3932:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  3933:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 3934:         if ($output =~ m{^/(adm|res)/}) {
                   3935: 	    if ($output =~ m{^/res/}) {
                   3936: 		my $local_name = &Apache::lonnet::filelocation('',$output);
                   3937: 		&Apache::lonnet::repcopy($local_name);
                   3938: 	    }
1.520     raeburn  3939:             $output = &lonhttpdurl($output);
                   3940:         }
1.63      www      3941:     }
1.520     raeburn  3942:     return $output;
1.63      www      3943: }
1.59      www      3944: 
1.60      matthew  3945: ###############################################
                   3946: ###############################################
                   3947: 
                   3948: =pod
                   3949: 
1.112     bowersj2 3950: =back
                   3951: 
1.549     albertel 3952: =head1 HTML Helpers
1.112     bowersj2 3953: 
                   3954: =over 4
                   3955: 
                   3956: =item * &bodytag()
1.60      matthew  3957: 
                   3958: Returns a uniform header for LON-CAPA web pages.
                   3959: 
                   3960: Inputs: 
                   3961: 
1.112     bowersj2 3962: =over 4
                   3963: 
                   3964: =item * $title, A title to be displayed on the page.
                   3965: 
                   3966: =item * $function, the current role (can be undef).
                   3967: 
                   3968: =item * $addentries, extra parameters for the <body> tag.
                   3969: 
                   3970: =item * $bodyonly, if defined, only return the <body> tag.
                   3971: 
                   3972: =item * $domain, if defined, force a given domain.
                   3973: 
                   3974: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      3975:             text interface only)
1.60      matthew  3976: 
1.326     albertel 3977: =item * $customtitle, alternate text to use instead of $title
                   3978:                       in the title box that appears, this text
                   3979:                       is not auto translated like the $title is
1.309     albertel 3980: 
                   3981: =item * $notopbar, if true, keep the 'what is this' info but remove the
                   3982:                    navigational links
1.317     albertel 3983: 
1.338     albertel 3984: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   3985: 
                   3986: =item * $notitle, if true keep the nav controls, but remove the title bar
                   3987: 
1.361     albertel 3988: =item * $no_inline_link, if true and in remote mode, don't show the 
                   3989:          'Switch To Inline Menu' link
                   3990: 
1.460     albertel 3991: =item * $args, optional argument valid values are
                   3992:             no_auto_mt_title -> prevents &mt()ing the title arg
1.562     albertel 3993:             inherit_jsmath -> when creating popup window in a page,
                   3994:                               should it have jsmath forced on by the
                   3995:                               current page
1.460     albertel 3996: 
1.112     bowersj2 3997: =back
                   3998: 
1.60      matthew  3999: Returns: A uniform header for LON-CAPA web pages.  
                   4000: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   4001: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   4002: other decorations will be returned.
                   4003: 
                   4004: =cut
                   4005: 
1.54      www      4006: sub bodytag {
1.309     albertel 4007:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
1.460     albertel 4008: 	$notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
1.339     albertel 4009: 
1.460     albertel 4010:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.339     albertel 4011: 
1.183     matthew  4012:     $function = &get_users_function() if (!$function);
1.339     albertel 4013:     my $img =    &designparm($function.'.img',$domain);
                   4014:     my $font =   &designparm($function.'.font',$domain);
                   4015:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   4016: 
                   4017:     my %design = ( 'style'   => 'margin-top: 0px',
1.535     albertel 4018: 		   'bgcolor' => $pgbg,
1.339     albertel 4019: 		   'text'    => $font,
                   4020:                    'alink'   => &designparm($function.'.alink',$domain),
                   4021: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   4022: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 4023:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 4024: 
1.63      www      4025:  # role and realm
1.378     raeburn  4026:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
                   4027:     if ($role  eq 'ca') {
1.479     albertel 4028:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 4029:         $realm = &plainname($rname,$rdom);
1.378     raeburn  4030:     } 
1.55      www      4031: # realm
1.258     albertel 4032:     if ($env{'request.course.id'}) {
1.378     raeburn  4033:         if ($env{'request.role'} !~ /^cr/) {
                   4034:             $role = &Apache::lonnet::plaintext($role,&course_type());
                   4035:         }
1.359     albertel 4036: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  4037:     } else {
                   4038:         $role = &Apache::lonnet::plaintext($role);
1.54      www      4039:     }
1.433     albertel 4040: 
1.359     albertel 4041:     if (!$realm) { $realm='&nbsp;'; }
1.55      www      4042: # Set messages
1.60      matthew  4043:     my $messages=&domainlogo($domain);
1.330     albertel 4044: 
1.438     albertel 4045:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 4046: 
1.101     www      4047: # construct main body tag
1.359     albertel 4048:     my $bodytag = "<body $extra_body_attr>".
1.562     albertel 4049: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
1.252     albertel 4050: 
1.530     albertel 4051:     if ($bodyonly) {
1.60      matthew  4052:         return $bodytag;
1.258     albertel 4053:     } elsif ($env{'browser.interface'} eq 'textual') {
1.95      www      4054: # Accessibility
1.224     raeburn  4055:           
1.337     albertel 4056: 	$bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
1.338     albertel 4057: 	if (!$notitle) {
1.337     albertel 4058: 	    $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
                   4059: 	}
                   4060: 	return $bodytag;
1.359     albertel 4061:     }
                   4062: 
1.410     albertel 4063:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
1.433     albertel 4064:     if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4065: 	undef($role);
1.434     albertel 4066:     } else {
                   4067: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
1.433     albertel 4068:     }
1.359     albertel 4069:     
                   4070:     my $roleinfo=(<<ENDROLE);
                   4071: <td class="LC_title_bar_who">
                   4072: <div class="LC_title_bar_name">
1.410     albertel 4073:     $name
1.361     albertel 4074:     &nbsp;
1.359     albertel 4075: </div>
                   4076: <div class="LC_title_bar_role">
1.361     albertel 4077: $role&nbsp;
1.359     albertel 4078: </div>
                   4079: <div class="LC_title_bar_realm">
1.361     albertel 4080: $realm&nbsp;
1.359     albertel 4081: </div>
1.206     albertel 4082: </td>
                   4083: ENDROLE
1.235     raeburn  4084: 
1.359     albertel 4085:     my $titleinfo = '<span class="LC_title_bar_title">'.$title.'</span>';
                   4086:     if ($customtitle) {
                   4087:         $titleinfo = $customtitle;
                   4088:     }
                   4089:     #
                   4090:     # Extra info if you are the DC
                   4091:     my $dc_info = '';
                   4092:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   4093:                         $env{'course.'.$env{'request.course.id'}.
                   4094:                                  '.domain'}.'/'})) {
                   4095:         my $cid = $env{'request.course.id'};
                   4096:         $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      4097:         $dc_info =~ s/\s+$//;
1.359     albertel 4098:         $dc_info = '('.$dc_info.')';
                   4099:     }
                   4100: 
1.644     www      4101:     if (($env{'environment.remote'} eq 'off') || ($args->{'suppress_header_logos'})) {
1.359     albertel 4102:         # No Remote
1.258     albertel 4103: 	if ($env{'request.state'} eq 'construct') {
1.359     albertel 4104: 	    $forcereg=1;
                   4105: 	}
                   4106: 
                   4107: 	if (!$customtitle && $env{'request.state'} eq 'construct') {
                   4108: 	    # this is for resources; directories have customtitle, and crumbs
                   4109:             # and select recent are created in lonpubdir.pm  
1.229     albertel 4110: 	    my ($uname,$thisdisfn)=
1.258     albertel 4111: 		($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
1.229     albertel 4112: 	    my $formaction='/priv/'.$uname.'/'.$thisdisfn;
                   4113: 	    $formaction=~s/\/+/\//g;
                   4114: 
1.359     albertel 4115: 	    my $parentpath = '';
                   4116: 	    my $lastitem = '';
                   4117: 	    if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   4118: 		$parentpath = $1;
                   4119: 		$lastitem = $2;
                   4120: 	    } else {
                   4121: 		$lastitem = $thisdisfn;
                   4122: 	    }
                   4123: 	    $titleinfo = 
1.640     bisitz   4124: 		&Apache::loncommon::help_open_menu('','',3,'Authoring')
                   4125: 		.'<b>'.&mt('Construction Space').'</b>:&nbsp;'
                   4126: 		.'<form name="dirs" method="post" action="'.$formaction
1.359     albertel 4127: 		.'" target="_top"><tt><b>'
                   4128: 		.&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<font size=\"+1\">$lastitem</font></b></tt><br />"
                   4129: 		.&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   4130: 		.'</form>'
                   4131: 		.&Apache::lonmenu::constspaceform();
1.235     raeburn  4132:         }
1.359     albertel 4133: 
1.337     albertel 4134:         my $titletable;
1.338     albertel 4135: 	if (!$notitle) {
1.337     albertel 4136: 	    $titletable =
1.359     albertel 4137: 		'<table id="LC_title_bar">'.
                   4138:                          "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
                   4139: 			 '</tr></table>';
1.337     albertel 4140: 	}
1.359     albertel 4141: 	if ($notopbar) {
                   4142: 	    $bodytag .= $titletable;
                   4143: 	} else {
                   4144: 	    if ($env{'request.state'} eq 'construct') {
1.337     albertel 4145:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
                   4146: 							  $titletable);
1.272     raeburn  4147:             } else {
1.336     albertel 4148:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
1.359     albertel 4149: 		    $titletable;
1.272     raeburn  4150:             }
1.235     raeburn  4151:         }
                   4152:         return $bodytag;
1.94      www      4153:     }
1.95      www      4154: 
1.93      www      4155: #
1.95      www      4156: # Top frame rendering, Remote is up
1.93      www      4157: #
1.359     albertel 4158: 
1.517     raeburn  4159:     my $imgsrc = $img;
                   4160:     if ($img =~ /^\/adm/) {
1.575     albertel 4161:         $imgsrc = &lonhttpdurl($img);
1.517     raeburn  4162:     }
                   4163:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
1.359     albertel 4164: 
1.305     www      4165:     # Explicit link to get inline menu
1.361     albertel 4166:     my $menu= ($no_inline_link?''
                   4167: 	       :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
1.245     matthew  4168:     #
1.338     albertel 4169:     if ($notitle) {
1.337     albertel 4170: 	return $bodytag;
                   4171:     }
1.94      www      4172:     return(<<ENDBODY);
1.60      matthew  4173: $bodytag
1.359     albertel 4174: <table id="LC_title_bar" class="LC_with_remote">
1.368     albertel 4175: <tr><td class="LC_title_bar_role_logo">$upperleft</td>
1.359     albertel 4176:     <td class="LC_title_bar_domain_logo">$messages&nbsp;</td>
1.54      www      4177: </tr>
1.359     albertel 4178: <tr><td>$titleinfo $dc_info $menu</td>
                   4179: $roleinfo
1.368     albertel 4180: </tr>
1.356     albertel 4181: </table>
1.54      www      4182: ENDBODY
1.182     matthew  4183: }
                   4184: 
1.330     albertel 4185: sub make_attr_string {
                   4186:     my ($register,$attr_ref) = @_;
                   4187: 
                   4188:     if ($attr_ref && !ref($attr_ref)) {
                   4189: 	die("addentries Must be a hash ref ".
                   4190: 	    join(':',caller(1))." ".
                   4191: 	    join(':',caller(0))." ");
                   4192:     }
                   4193: 
                   4194:     if ($register) {
1.339     albertel 4195: 	my ($on_load,$on_unload);
                   4196: 	foreach my $key (keys(%{$attr_ref})) {
                   4197: 	    if      (lc($key) eq 'onload') {
                   4198: 		$on_load.=$attr_ref->{$key}.';';
                   4199: 		delete($attr_ref->{$key});
                   4200: 
                   4201: 	    } elsif (lc($key) eq 'onunload') {
                   4202: 		$on_unload.=$attr_ref->{$key}.';';
                   4203: 		delete($attr_ref->{$key});
                   4204: 	    }
                   4205: 	}
                   4206: 	$attr_ref->{'onload'}  =
                   4207: 	    &Apache::lonmenu::loadevents().  $on_load;
                   4208: 	$attr_ref->{'onunload'}=
                   4209: 	    &Apache::lonmenu::unloadevents().$on_unload;
                   4210:     }
                   4211: 
                   4212: # Accessibility font enhance
                   4213:     if ($env{'browser.fontenhance'} eq 'on') {
                   4214: 	my $style;
                   4215: 	foreach my $key (keys(%{$attr_ref})) {
                   4216: 	    if (lc($key) eq 'style') {
                   4217: 		$style.=$attr_ref->{$key}.';';
                   4218: 		delete($attr_ref->{$key});
                   4219: 	    }
                   4220: 	}
                   4221: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
1.330     albertel 4222:     }
1.339     albertel 4223: 
                   4224:     if ($env{'browser.blackwhite'} eq 'on') {
                   4225: 	delete($attr_ref->{'font'});
                   4226: 	delete($attr_ref->{'link'});
                   4227: 	delete($attr_ref->{'alink'});
                   4228: 	delete($attr_ref->{'vlink'});
                   4229: 	delete($attr_ref->{'bgcolor'});
                   4230: 	delete($attr_ref->{'background'});
                   4231:     }
                   4232: 
1.330     albertel 4233:     my $attr_string;
                   4234:     foreach my $attr (keys(%$attr_ref)) {
                   4235: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   4236:     }
                   4237:     return $attr_string;
                   4238: }
                   4239: 
                   4240: 
1.182     matthew  4241: ###############################################
1.251     albertel 4242: ###############################################
                   4243: 
                   4244: =pod
                   4245: 
                   4246: =item * &endbodytag()
                   4247: 
                   4248: Returns a uniform footer for LON-CAPA web pages.
                   4249: 
1.635     raeburn  4250: Inputs: 1 - optional reference to an args hash
                   4251: If in the hash, key for noredirectlink has a value which evaluates to true,
                   4252: a 'Continue' link is not displayed if the page contains an
                   4253: internal redirect in the <head></head> section,
                   4254: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 4255: 
                   4256: =cut
                   4257: 
                   4258: sub endbodytag {
1.635     raeburn  4259:     my ($args) = @_;
1.251     albertel 4260:     my $endbodytag='</body>';
1.269     albertel 4261:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
1.315     albertel 4262:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  4263:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   4264: 	    $endbodytag=
                   4265: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   4266: 	        &mt('Continue').'</a>'.
                   4267: 	        $endbodytag;
                   4268:         }
1.315     albertel 4269:     }
1.251     albertel 4270:     return $endbodytag;
                   4271: }
                   4272: 
1.352     albertel 4273: =pod
                   4274: 
                   4275: =item * &standard_css()
                   4276: 
                   4277: Returns a style sheet
                   4278: 
                   4279: Inputs: (all optional)
                   4280:             domain         -> force to color decorate a page for a specific
                   4281:                                domain
                   4282:             function       -> force usage of a specific rolish color scheme
                   4283:             bgcolor        -> override the default page bgcolor
                   4284: 
                   4285: =cut
                   4286: 
1.343     albertel 4287: sub standard_css {
1.345     albertel 4288:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 4289:     $function  = &get_users_function() if (!$function);
                   4290:     my $img    = &designparm($function.'.img',   $domain);
                   4291:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   4292:     my $font   = &designparm($function.'.font',  $domain);
1.345     albertel 4293:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 4294:     my $pgbg_or_bgcolor =
                   4295: 	         $bgcolor ||
1.352     albertel 4296: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 4297:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 4298:     my $alink  = &designparm($function.'.alink', $domain);
                   4299:     my $vlink  = &designparm($function.'.vlink', $domain);
                   4300:     my $link   = &designparm($function.'.link',  $domain);
                   4301: 
1.602     albertel 4302:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 4303:     my $mono                 = 'monospace';
1.352     albertel 4304:     my $data_table_head      = $tabbg;
                   4305:     my $data_table_light     = '#EEEEEE';
1.470     banghart 4306:     my $data_table_dark      = '#DDDDDD';
                   4307:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 4308:     my $data_table_highlight = '#FFFF00';
1.352     albertel 4309:     my $mail_new             = '#FFBB77';
                   4310:     my $mail_new_hover       = '#DD9955';
                   4311:     my $mail_read            = '#BBBB77';
                   4312:     my $mail_read_hover      = '#999944';
                   4313:     my $mail_replied         = '#AAAA88';
                   4314:     my $mail_replied_hover   = '#888855';
                   4315:     my $mail_other           = '#99BBBB';
                   4316:     my $mail_other_hover     = '#669999';
1.391     albertel 4317:     my $table_header         = '#DDDDDD';
1.489     raeburn  4318:     my $feedback_link_bg     = '#BBBBBB';
1.392     albertel 4319: 
1.608     albertel 4320:     my $border = ($env{'browser.type'} eq 'explorer' ||
                   4321: 		  $env{'browser.type'} eq 'safari'     ) ? '0px 2px 0px 2px'
                   4322: 	                                                 : '0px 3px 0px 4px';
1.448     albertel 4323: 
1.523     albertel 4324: 
1.343     albertel 4325:     return <<END;
1.345     albertel 4326: h1, h2, h3, th { font-family: $sans }
1.343     albertel 4327: a:focus { color: red; background: yellow } 
1.510     albertel 4328: table.thinborder,
1.523     albertel 4329: 
1.510     albertel 4330: table.thinborder tr th {
                   4331:   border-style: solid;
                   4332:   border-width: 1px;
                   4333:   background: $tabbg;
                   4334: }
1.523     albertel 4335: table.thinborder tr td {
1.510     albertel 4336:   border-style: solid;
                   4337:   border-width: 1px
                   4338: }
1.426     albertel 4339: 
1.343     albertel 4340: form, .inline { display: inline; }
                   4341: .center { text-align: center; }
1.593     albertel 4342: .LC_filename {font-family: $mono; white-space:pre;}
1.350     albertel 4343: .LC_error {
                   4344:   color: red;
                   4345:   font-size: larger;
                   4346: }
1.457     albertel 4347: .LC_warning,
                   4348: .LC_diff_removed {
1.394     albertel 4349:   color: red;
                   4350: }
1.532     albertel 4351: 
                   4352: .LC_info,
1.457     albertel 4353: .LC_success,
                   4354: .LC_diff_added {
1.350     albertel 4355:   color: green;
                   4356: }
1.543     albertel 4357: .LC_unknown {
                   4358:   color: yellow;
                   4359: }
                   4360: 
1.440     albertel 4361: .LC_icon {
                   4362:   border: 0px;
                   4363: }
1.539     albertel 4364: .LC_indexer_icon {
                   4365:   border: 0px;
                   4366:   height: 22px;
                   4367: }
1.543     albertel 4368: .LC_docs_spacer {
                   4369:   width: 25px;
                   4370:   height: 1px;
                   4371:   border: 0px;
                   4372: }
1.346     albertel 4373: 
1.532     albertel 4374: .LC_internal_info {
                   4375:   color: #999;
                   4376: }
                   4377: 
1.458     albertel 4378: table.LC_pastsubmission {
                   4379:   border: 1px solid black;
                   4380:   margin: 2px;
                   4381: }
                   4382: 
1.606     albertel 4383: table#LC_top_nav, table#LC_menubuttons,table#LC_nav_location {
1.345     albertel 4384:   width: 100%;
                   4385:   background: $pgbg;
1.392     albertel 4386:   border: 2px;
1.402     albertel 4387:   border-collapse: separate;
1.403     albertel 4388:   padding: 0px;
1.345     albertel 4389: }
1.392     albertel 4390: 
1.606     albertel 4391: table#LC_title_bar, table.LC_breadcrumbs, 
1.393     albertel 4392: table#LC_title_bar.LC_with_remote {
1.359     albertel 4393:   width: 100%;
1.392     albertel 4394:   border-color: $pgbg;
                   4395:   border-style: solid;
                   4396:   border-width: $border;
                   4397: 
1.379     albertel 4398:   background: $pgbg;
                   4399:   font-family: $sans;
1.392     albertel 4400:   border-collapse: collapse;
1.403     albertel 4401:   padding: 0px;
1.359     albertel 4402: }
1.392     albertel 4403: 
1.409     albertel 4404: table.LC_docs_path {
                   4405:   width: 100%;
                   4406:   border: 0;
                   4407:   background: $pgbg;
                   4408:   font-family: $sans;
                   4409:   border-collapse: collapse;
                   4410:   padding: 0px;
                   4411: }
                   4412: 
1.359     albertel 4413: table#LC_title_bar td {
                   4414:   background: $tabbg;
                   4415: }
                   4416: table#LC_title_bar td.LC_title_bar_who {
                   4417:   background: $tabbg;
                   4418:   color: $font;
1.427     albertel 4419:   font: small $sans;
1.359     albertel 4420:   text-align: right;
                   4421: }
1.469     banghart 4422: span.LC_metadata {
                   4423:     font-family: $sans;
                   4424: }
1.359     albertel 4425: span.LC_title_bar_title {
1.416     albertel 4426:   font: bold x-large $sans;
1.359     albertel 4427: }
                   4428: table#LC_title_bar td.LC_title_bar_domain_logo {
                   4429:   background: $sidebg;
                   4430:   text-align: right;
1.368     albertel 4431:   padding: 0px;
                   4432: }
                   4433: table#LC_title_bar td.LC_title_bar_role_logo {
                   4434:   background: $sidebg;
                   4435:   padding: 0px;
1.359     albertel 4436: }
                   4437: 
1.346     albertel 4438: table#LC_menubuttons_mainmenu {
1.526     www      4439:   width: 100%;
1.346     albertel 4440:   border: 0px;
                   4441:   border-spacing: 1px;
1.372     albertel 4442:   padding: 0px 1px;
1.346     albertel 4443:   margin: 0px;
                   4444:   border-collapse: separate;
                   4445: }
                   4446: table#LC_menubuttons img, table#LC_menubuttons_mainmenu img {
                   4447:   border: 0px;
                   4448: }
1.345     albertel 4449: table#LC_top_nav td {
                   4450:   background: $tabbg;
1.392     albertel 4451:   border: 0px;
1.407     albertel 4452:   font-size: small;
1.345     albertel 4453: }
                   4454: table#LC_top_nav td a, div#LC_top_nav a {
                   4455:   color: $font;
                   4456:   font-family: $sans;
                   4457: }
1.364     albertel 4458: table#LC_top_nav td.LC_top_nav_logo {
                   4459:   background: $tabbg;
1.432     albertel 4460:   text-align: left;
1.408     albertel 4461:   white-space: nowrap;
1.432     albertel 4462:   width: 31px;
1.408     albertel 4463: }
                   4464: table#LC_top_nav td.LC_top_nav_logo img {
1.432     albertel 4465:   border: 0px;
1.408     albertel 4466:   vertical-align: bottom;
1.364     albertel 4467: }
1.432     albertel 4468: table#LC_top_nav td.LC_top_nav_exit,
                   4469: table#LC_top_nav td.LC_top_nav_help {
                   4470:   width: 2.0em;
                   4471: }
1.442     albertel 4472: table#LC_top_nav td.LC_top_nav_login {
                   4473:   width: 4.0em;
                   4474:   text-align: center;
                   4475: }
1.409     albertel 4476: table.LC_breadcrumbs td, table.LC_docs_path td  {
1.357     albertel 4477:   background: $tabbg;
                   4478:   color: $font;
                   4479:   font-family: $sans;
1.358     albertel 4480:   font-size: smaller;
1.357     albertel 4481: }
1.411     albertel 4482: table.LC_breadcrumbs td.LC_breadcrumbs_component,
1.409     albertel 4483: table.LC_docs_path td.LC_docs_path_component {
1.357     albertel 4484:   background: $tabbg;
                   4485:   color: $font;
                   4486:   font-family: $sans;
                   4487:   font-size: larger;
                   4488:   text-align: right;
                   4489: }
1.383     albertel 4490: td.LC_table_cell_checkbox {
                   4491:   text-align: center;
                   4492: }
                   4493: 
1.522     albertel 4494: table#LC_mainmenu td.LC_mainmenu_column {
                   4495:     vertical-align: top;
                   4496: }
                   4497: 
1.346     albertel 4498: .LC_menubuttons_inline_text {
                   4499:   color: $font;
                   4500:   font-family: $sans;
                   4501:   font-size: smaller;
                   4502: }
                   4503: 
1.526     www      4504: .LC_menubuttons_link {
                   4505:   text-decoration: none;
                   4506: }
                   4507: 
1.522     albertel 4508: .LC_menubuttons_category {
1.521     www      4509:   color: $font;
1.526     www      4510:   background: $pgbg;
1.521     www      4511:   font-family: $sans;
                   4512:   font-size: larger;
                   4513:   font-weight: bold;
                   4514: }
                   4515: 
1.346     albertel 4516: td.LC_menubuttons_text {
1.526     www      4517:   width: 90%;
1.346     albertel 4518:   color: $font;
                   4519:   font-family: $sans;
                   4520: }
1.526     www      4521: 
1.346     albertel 4522: td.LC_menubuttons_img {
                   4523: }
1.526     www      4524: 
1.346     albertel 4525: .LC_current_location {
                   4526:   font-family: $sans;
                   4527:   background: $tabbg;
                   4528: }
                   4529: .LC_new_mail {
                   4530:   font-family: $sans;
1.634     www      4531:   background: $tabbg;
1.346     albertel 4532:   font-weight: bold;
                   4533: }
1.347     albertel 4534: 
1.526     www      4535: .LC_rolesmenu_is {
                   4536:   font-family: $sans;
                   4537: }
                   4538: 
                   4539: .LC_rolesmenu_selected {
                   4540:   font-family: $sans;
                   4541: }
                   4542: 
                   4543: .LC_rolesmenu_future {
                   4544:   font-family: $sans;
                   4545: }
                   4546: 
                   4547: 
                   4548: .LC_rolesmenu_will {
                   4549:   font-family: $sans;
                   4550: }
                   4551: 
                   4552: .LC_rolesmenu_will_not {
                   4553:   font-family: $sans;
                   4554: }
                   4555: 
                   4556: .LC_rolesmenu_expired {
                   4557:   font-family: $sans;
                   4558: }
                   4559: 
                   4560: .LC_rolesinfo {
                   4561:   font-family: $sans;
                   4562: }
                   4563: 
1.527     www      4564: .LC_dropadd_labeltext {
                   4565:   font-family: $sans;
                   4566:   text-align: right;
                   4567: }
                   4568: 
                   4569: .LC_preferences_labeltext {
                   4570:   font-family: $sans;
                   4571:   text-align: right;
                   4572: }
                   4573: 
1.666     raeburn  4574: .LC_roleslog_note {
                   4575:   font-size: smaller;
                   4576: }
                   4577: 
1.440     albertel 4578: table.LC_aboutme_port {
                   4579:   border: 0px;
                   4580:   border-collapse: collapse;
                   4581:   border-spacing: 0px;
                   4582: }
1.349     albertel 4583: table.LC_data_table, table.LC_mail_list {
1.347     albertel 4584:   border: 1px solid #000000;
1.402     albertel 4585:   border-collapse: separate;
1.426     albertel 4586:   border-spacing: 1px;
1.610     albertel 4587:   background: $pgbg;
1.347     albertel 4588: }
1.422     albertel 4589: .LC_data_table_dense {
                   4590:   font-size: small;
                   4591: }
1.507     raeburn  4592: table.LC_nested_outer {
                   4593:   border: 1px solid #000000;
1.589     raeburn  4594:   border-collapse: collapse;
1.507     raeburn  4595:   border-spacing: 0px;
                   4596:   width: 100%;
                   4597: }
                   4598: table.LC_nested {
                   4599:   border: 0px;
1.589     raeburn  4600:   border-collapse: collapse;
1.507     raeburn  4601:   border-spacing: 0px;
                   4602:   width: 100%;
                   4603: }
1.523     albertel 4604: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th,
                   4605: table.LC_prior_tries tr th {
1.349     albertel 4606:   font-weight: bold;
                   4607:   background-color: $data_table_head;
1.421     albertel 4608:   font-size: smaller;
1.347     albertel 4609: }
1.610     albertel 4610: table.LC_data_table tr.LC_odd_row > td, 
1.440     albertel 4611: table.LC_aboutme_port tr td {
1.349     albertel 4612:   background-color: $data_table_light;
1.425     albertel 4613:   padding: 2px;
1.347     albertel 4614: }
1.610     albertel 4615: table.LC_data_table tr.LC_even_row > td,
1.440     albertel 4616: table.LC_aboutme_port tr.LC_even_row td {
1.349     albertel 4617:   background-color: $data_table_dark;
1.347     albertel 4618: }
1.425     albertel 4619: table.LC_data_table tr.LC_data_table_highlight td {
                   4620:   background-color: $data_table_darker;
                   4621: }
1.639     raeburn  4622: table.LC_data_table tr td.LC_leftcol_header {
                   4623:   background-color: $data_table_head;
                   4624:   font-weight: bold;
                   4625: }
1.451     albertel 4626: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  4627: table.LC_nested tr.LC_empty_row td {
1.347     albertel 4628:   background-color: #FFFFFF;
1.421     albertel 4629:   font-weight: bold;
                   4630:   font-style: italic;
                   4631:   text-align: center;
                   4632:   padding: 8px;
1.347     albertel 4633: }
1.507     raeburn  4634: table.LC_nested tr.LC_empty_row td {
1.465     albertel 4635:   padding: 4ex
                   4636: }
1.507     raeburn  4637: table.LC_nested_outer tr th {
                   4638:   font-weight: bold;
                   4639:   background-color: $data_table_head;
                   4640:   font-size: smaller;
                   4641:   border-bottom: 1px solid #000000;
                   4642: }
                   4643: table.LC_nested_outer tr td.LC_subheader {
                   4644:   background-color: $data_table_head;
                   4645:   font-weight: bold;
                   4646:   font-size: small;
                   4647:   border-bottom: 1px solid #000000;
                   4648:   text-align: right;
1.451     albertel 4649: }
1.507     raeburn  4650: table.LC_nested tr.LC_info_row td {
1.451     albertel 4651:   background-color: #CCC;
                   4652:   font-weight: bold;
                   4653:   font-size: small;
1.507     raeburn  4654:   text-align: center;
                   4655: }
1.589     raeburn  4656: table.LC_nested tr.LC_info_row td.LC_left_item,
                   4657: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  4658:   text-align: left;
1.451     albertel 4659: }
1.507     raeburn  4660: table.LC_nested td {
1.451     albertel 4661:   background-color: #FFF;
                   4662:   font-size: small;
1.507     raeburn  4663: }
                   4664: table.LC_nested_outer tr th.LC_right_item,
                   4665: table.LC_nested tr.LC_info_row td.LC_right_item,
                   4666: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   4667: table.LC_nested tr td.LC_right_item {
1.451     albertel 4668:   text-align: right;
                   4669: }
                   4670: 
1.507     raeburn  4671: table.LC_nested tr.LC_odd_row td {
1.451     albertel 4672:   background-color: #EEE;
                   4673: }
                   4674: 
1.473     raeburn  4675: table.LC_createuser {
                   4676: }
                   4677: 
                   4678: table.LC_createuser tr.LC_section_row td {
                   4679:   font-size: smaller;
                   4680: }
                   4681: 
                   4682: table.LC_createuser tr.LC_info_row td  {
                   4683:   background-color: #CCC;
                   4684:   font-weight: bold;
                   4685:   text-align: center;
                   4686: }
                   4687: 
1.349     albertel 4688: table.LC_calendar {
                   4689:   border: 1px solid #000000;
                   4690:   border-collapse: collapse;
                   4691: }
                   4692: table.LC_calendar_pickdate {
                   4693:   font-size: xx-small;
                   4694: }
                   4695: table.LC_calendar tr td {
                   4696:   border: 1px solid #000000;
                   4697:   vertical-align: top;
                   4698: }
                   4699: table.LC_calendar tr td.LC_calendar_day_empty {
                   4700:   background-color: $data_table_dark;
                   4701: }
                   4702: table.LC_calendar tr td.LC_calendar_day_current {
                   4703:   background-color: $data_table_highlight;
                   4704: }
                   4705: 
                   4706: table.LC_mail_list tr.LC_mail_new {
                   4707:   background-color: $mail_new;
                   4708: }
                   4709: table.LC_mail_list tr.LC_mail_new:hover {
                   4710:   background-color: $mail_new_hover;
                   4711: }
                   4712: table.LC_mail_list tr.LC_mail_read {
                   4713:   background-color: $mail_read;
                   4714: }
                   4715: table.LC_mail_list tr.LC_mail_read:hover {
                   4716:   background-color: $mail_read_hover;
                   4717: }
                   4718: table.LC_mail_list tr.LC_mail_replied {
                   4719:   background-color: $mail_replied;
                   4720: }
                   4721: table.LC_mail_list tr.LC_mail_replied:hover {
                   4722:   background-color: $mail_replied_hover;
                   4723: }
                   4724: table.LC_mail_list tr.LC_mail_other {
                   4725:   background-color: $mail_other;
                   4726: }
                   4727: table.LC_mail_list tr.LC_mail_other:hover {
                   4728:   background-color: $mail_other_hover;
                   4729: }
1.494     raeburn  4730: table.LC_mail_list tr.LC_mail_even {
                   4731: }
                   4732: table.LC_mail_list tr.LC_mail_odd {
                   4733: }
                   4734: 
1.385     albertel 4735: 
1.386     albertel 4736: table#LC_portfolio_actions {
                   4737:   width: auto;
                   4738:   background: $pgbg;
                   4739:   border: 0px;
                   4740:   border-spacing: 2px 2px;
                   4741:   padding: 0px;
                   4742:   margin: 0px;
                   4743:   border-collapse: separate;
                   4744: }
                   4745: table#LC_portfolio_actions td.LC_label {
                   4746:   background: $tabbg;
                   4747:   text-align: right;
                   4748: }
                   4749: table#LC_portfolio_actions td.LC_value {
                   4750:   background: $tabbg;
                   4751: }
1.385     albertel 4752: 
1.391     albertel 4753: table#LC_cstr_controls {
                   4754:   width: 100%;
                   4755:   border-collapse: collapse;
                   4756: }
                   4757: table#LC_cstr_controls tr td {
                   4758:   border: 4px solid $pgbg;
                   4759:   padding: 4px;
                   4760:   text-align: center;
                   4761:   background: $tabbg;
                   4762: }
                   4763: table#LC_cstr_controls tr th {
                   4764:   border: 4px solid $pgbg;
                   4765:   background: $table_header;
                   4766:   text-align: center;
                   4767:   font-family: $sans;
                   4768:   font-size: smaller;
                   4769: }
                   4770: 
1.389     albertel 4771: table#LC_browser {
                   4772:  
                   4773: }
                   4774: table#LC_browser tr th {
1.391     albertel 4775:   background: $table_header;
1.389     albertel 4776: }
1.390     albertel 4777: table#LC_browser tr td {
                   4778:   padding: 2px;
                   4779: }
1.389     albertel 4780: table#LC_browser tr.LC_browser_file,
                   4781: table#LC_browser tr.LC_browser_file_published {
                   4782:   background: #CCFF88;
                   4783: }
                   4784: table#LC_browser tr.LC_browser_file_locked,
                   4785: table#LC_browser tr.LC_browser_file_unpublished {
                   4786:   background: #FFAA99;
1.387     albertel 4787: }
1.389     albertel 4788: table#LC_browser tr.LC_browser_file_obsolete {
                   4789:   background: #AAAAAA;
1.387     albertel 4790: }
1.455     albertel 4791: table#LC_browser tr.LC_browser_file_modified,
                   4792: table#LC_browser tr.LC_browser_file_metamodified {
1.389     albertel 4793:   background: #FFFF77;
1.387     albertel 4794: }
1.389     albertel 4795: table#LC_browser tr.LC_browser_folder {
                   4796:   background: #CCCCFF;
1.387     albertel 4797: }
1.388     albertel 4798: span.LC_current_location {
                   4799:   font-size: x-large;
                   4800:   background: $pgbg;
                   4801: }
1.387     albertel 4802: 
1.395     albertel 4803: span.LC_parm_menu_item {
                   4804:   font-size: larger;
                   4805:   font-family: $sans;
                   4806: }
                   4807: span.LC_parm_scope_all {
                   4808:   color: red;
                   4809: }
                   4810: span.LC_parm_scope_folder {
                   4811:   color: green;
                   4812: }
                   4813: span.LC_parm_scope_resource {
                   4814:   color: orange;
                   4815: }
                   4816: span.LC_parm_part {
                   4817:   color: blue;
                   4818: }
                   4819: span.LC_parm_folder, span.LC_parm_symb {
                   4820:   font-size: x-small;
                   4821:   font-family: $mono;
                   4822:   color: #AAAAAA;
                   4823: }
                   4824: 
1.396     albertel 4825: td.LC_parm_overview_level_menu, td.LC_parm_overview_map_menu,
                   4826: td.LC_parm_overview_parm_selectors, td.LC_parm_overview_parm_restrictions {
                   4827:   border: 1px solid black;
                   4828:   border-collapse: collapse;
                   4829: }
                   4830: table.LC_parm_overview_restrictions td {
                   4831:   border-width: 1px 4px 1px 4px;
                   4832:   border-style: solid;
                   4833:   border-color: $pgbg;
                   4834:   text-align: center;
                   4835: }
                   4836: table.LC_parm_overview_restrictions th {
                   4837:   background: $tabbg;
                   4838:   border-width: 1px 4px 1px 4px;
                   4839:   border-style: solid;
                   4840:   border-color: $pgbg;
                   4841: }
1.398     albertel 4842: table#LC_helpmenu {
                   4843:   border: 0px;
                   4844:   height: 55px;
                   4845:   border-spacing: 0px;
                   4846: }
                   4847: 
                   4848: table#LC_helpmenu fieldset legend {
                   4849:   font-size: larger;
                   4850:   font-weight: bold;
                   4851: }
1.397     albertel 4852: table#LC_helpmenu_links {
                   4853:   width: 100%;
                   4854:   border: 1px solid black;
                   4855:   background: $pgbg;
                   4856:   padding: 0px;
                   4857:   border-spacing: 1px;
                   4858: }
                   4859: table#LC_helpmenu_links tr td {
                   4860:   padding: 1px;
                   4861:   background: $tabbg;
1.399     albertel 4862:   text-align: center;
                   4863:   font-weight: bold;
1.397     albertel 4864: }
1.396     albertel 4865: 
1.397     albertel 4866: table#LC_helpmenu_links a:link, table#LC_helpmenu_links a:visited,
                   4867: table#LC_helpmenu_links a:active {
                   4868:   text-decoration: none;
                   4869:   color: $font;
                   4870: }
                   4871: table#LC_helpmenu_links a:hover {
                   4872:   text-decoration: underline;
                   4873:   color: $vlink;
                   4874: }
1.396     albertel 4875: 
1.417     albertel 4876: .LC_chrt_popup_exists {
                   4877:   border: 1px solid #339933;
                   4878:   margin: -1px;
                   4879: }
                   4880: .LC_chrt_popup_up {
                   4881:   border: 1px solid yellow;
                   4882:   margin: -1px;
                   4883: }
                   4884: .LC_chrt_popup {
                   4885:   border: 1px solid #8888FF;
                   4886:   background: #CCCCFF;
                   4887: }
1.421     albertel 4888: table.LC_pick_box {
                   4889:   border-collapse: separate;
                   4890:   background: white;
                   4891:   border: 1px solid black;
                   4892:   border-spacing: 1px;
                   4893: }
                   4894: table.LC_pick_box td.LC_pick_box_title {
                   4895:   background: $tabbg;
                   4896:   font-weight: bold;
                   4897:   text-align: right;
                   4898:   width: 184px;
                   4899:   padding: 8px;
                   4900: }
1.645     raeburn  4901: table.LC_pick_box td.LC_selfenroll_pick_box_title {
                   4902:   background: $tabbg;
                   4903:   font-weight: bold;
                   4904:   text-align: right;
                   4905:   width: 350px;
                   4906:   padding: 8px;
                   4907: }
                   4908: 
1.579     raeburn  4909: table.LC_pick_box td.LC_pick_box_value {
                   4910:   text-align: left;
                   4911:   padding: 8px;
                   4912: }
                   4913: table.LC_pick_box td.LC_pick_box_select {
                   4914:   text-align: left;
                   4915:   padding: 8px;
                   4916: }
1.424     albertel 4917: table.LC_pick_box td.LC_pick_box_separator {
1.421     albertel 4918:   padding: 0px;
                   4919:   height: 1px;
                   4920:   background: black;
                   4921: }
                   4922: table.LC_pick_box td.LC_pick_box_submit {
                   4923:   text-align: right;
                   4924: }
1.579     raeburn  4925: table.LC_pick_box td.LC_evenrow_value {
                   4926:   text-align: left;
                   4927:   padding: 8px;
                   4928:   background-color: $data_table_light;
                   4929: }
                   4930: table.LC_pick_box td.LC_oddrow_value {
                   4931:   text-align: left;
                   4932:   padding: 8px;
                   4933:   background-color: $data_table_light;
                   4934: }
                   4935: table.LC_helpform_receipt {
                   4936:   width: 620px;
                   4937:   border-collapse: separate;
                   4938:   background: white;
                   4939:   border: 1px solid black;
                   4940:   border-spacing: 1px;
                   4941: }
                   4942: table.LC_helpform_receipt td.LC_pick_box_title {
                   4943:   background: $tabbg;
                   4944:   font-weight: bold;
                   4945:   text-align: right;
                   4946:   width: 184px;
                   4947:   padding: 8px;
                   4948: }
                   4949: table.LC_helpform_receipt td.LC_evenrow_value {
                   4950:   text-align: left;
                   4951:   padding: 8px;
                   4952:   background-color: $data_table_light;
                   4953: }
                   4954: table.LC_helpform_receipt td.LC_oddrow_value {
                   4955:   text-align: left;
                   4956:   padding: 8px;
                   4957:   background-color: $data_table_light;
                   4958: }
                   4959: table.LC_helpform_receipt td.LC_pick_box_separator {
                   4960:   padding: 0px;
                   4961:   height: 1px;
                   4962:   background: black;
                   4963: }
                   4964: span.LC_helpform_receipt_cat {
                   4965:   font-weight: bold;
                   4966: }
1.424     albertel 4967: table.LC_group_priv_box {
                   4968:   background: white;
                   4969:   border: 1px solid black;
                   4970:   border-spacing: 1px;
                   4971: }
                   4972: table.LC_group_priv_box td.LC_pick_box_title {
                   4973:   background: $tabbg;
                   4974:   font-weight: bold;
                   4975:   text-align: right;
                   4976:   width: 184px;
                   4977: }
                   4978: table.LC_group_priv_box td.LC_groups_fixed {
                   4979:   background: $data_table_light;
                   4980:   text-align: center;
                   4981: }
                   4982: table.LC_group_priv_box td.LC_groups_optional {
                   4983:   background: $data_table_dark;
                   4984:   text-align: center;
                   4985: }
                   4986: table.LC_group_priv_box td.LC_groups_functionality {
                   4987:   background: $data_table_darker;
                   4988:   text-align: center;
                   4989:   font-weight: bold;
                   4990: }
                   4991: table.LC_group_priv td {
                   4992:   text-align: left;
                   4993:   padding: 0px;
                   4994: }
                   4995: 
1.421     albertel 4996: table.LC_notify_front_page {
                   4997:   background: white;
                   4998:   border: 1px solid black;
                   4999:   padding: 8px;
                   5000: }
                   5001: table.LC_notify_front_page td {
                   5002:   padding: 8px;
                   5003: }
1.424     albertel 5004: .LC_navbuttons {
                   5005:   margin: 2ex 0ex 2ex 0ex;
                   5006: }
1.423     albertel 5007: .LC_topic_bar {
                   5008:   font-family: $sans;
                   5009:   font-weight: bold;
                   5010:   width: 100%;
                   5011:   background: $tabbg;
                   5012:   vertical-align: middle;
                   5013:   margin: 2ex 0ex 2ex 0ex;
                   5014: }
                   5015: .LC_topic_bar span {
                   5016:   vertical-align: middle;
                   5017: }
                   5018: .LC_topic_bar img {
                   5019:   vertical-align: bottom;
                   5020: }
                   5021: table.LC_course_group_status {
                   5022:   margin: 20px;
                   5023: }
                   5024: table.LC_status_selector td {
                   5025:   vertical-align: top;
                   5026:   text-align: center;
1.424     albertel 5027:   padding: 4px;
                   5028: }
                   5029: table.LC_descriptive_input td.LC_description {
                   5030:   vertical-align: top;
                   5031:   text-align: right;
                   5032:   font-weight: bold;
1.423     albertel 5033: }
1.599     albertel 5034: div.LC_feedback_link {
1.616     albertel 5035:   clear: both;
1.599     albertel 5036:   background: white;
                   5037:   width: 100%;  
1.489     raeburn  5038: }
                   5039: span.LC_feedback_link {
1.599     albertel 5040:   background: $feedback_link_bg;
                   5041:   font-size: larger;
                   5042: }
                   5043: span.LC_message_link {
                   5044:   background: $feedback_link_bg;
                   5045:   font-size: larger;
                   5046:   position: absolute;
                   5047:   right: 1em;
1.489     raeburn  5048: }
1.421     albertel 5049: 
1.515     albertel 5050: table.LC_prior_tries {
1.524     albertel 5051:   border: 1px solid #000000;
                   5052:   border-collapse: separate;
                   5053:   border-spacing: 1px;
1.515     albertel 5054: }
1.523     albertel 5055: 
1.515     albertel 5056: table.LC_prior_tries td {
1.524     albertel 5057:   padding: 2px;
1.515     albertel 5058: }
1.523     albertel 5059: 
                   5060: .LC_answer_correct {
                   5061:   background: #AAFFAA;
                   5062:   color: black;
                   5063: }
                   5064: .LC_answer_charged_try {
                   5065:   background: #FFAAAA ! important;
                   5066:   color: black;
                   5067: }
                   5068: .LC_answer_not_charged_try, 
                   5069: .LC_answer_no_grade,
                   5070: .LC_answer_late {
                   5071:   background: #FFFFAA;
                   5072:   color: black;
                   5073: }
                   5074: .LC_answer_previous {
                   5075:   background: #AAAAFF;
                   5076:   color: black;
                   5077: }
                   5078: .LC_answer_no_message {
                   5079:   background: #FFFFFF;
                   5080:   color: black;
                   5081: }
                   5082: .LC_answer_unknown {
                   5083:   background: orange;
                   5084:   color: black;
                   5085: }
                   5086: 
                   5087: 
1.529     albertel 5088: span.LC_prior_numerical,
                   5089: span.LC_prior_string,
                   5090: span.LC_prior_custom,
                   5091: span.LC_prior_reaction,
                   5092: span.LC_prior_math {
1.523     albertel 5093:   font-family: monospace;
                   5094:   white-space: pre;
                   5095: }
                   5096: 
1.525     albertel 5097: span.LC_prior_string {
                   5098:   font-family: monospace;
                   5099:   white-space: pre;
                   5100: }
                   5101: 
1.523     albertel 5102: table.LC_prior_option {
                   5103:   width: 100%;
                   5104:   border-collapse: collapse;
                   5105: }
1.528     albertel 5106: table.LC_prior_rank, table.LC_prior_match {
                   5107:   border-collapse: collapse;
                   5108: }
                   5109: table.LC_prior_option tr td,
                   5110: table.LC_prior_rank tr td,
                   5111: table.LC_prior_match tr td {
1.524     albertel 5112:   border: 1px solid #000000;
1.515     albertel 5113: }
                   5114: 
1.519     raeburn  5115: span.LC_nobreak {
1.544     albertel 5116:   white-space: nowrap;
1.519     raeburn  5117: }
                   5118: 
1.576     raeburn  5119: span.LC_cusr_emph {
                   5120:   font-style: italic;
                   5121: }
                   5122: 
1.633     raeburn  5123: span.LC_cusr_subheading {
                   5124:   font-weight: normal;
                   5125:   font-size: 85%;
                   5126: }
                   5127: 
1.545     albertel 5128: table.LC_docs_documents {
                   5129:   background: #BBBBBB;
1.547     albertel 5130:   border-width: 0px;
1.545     albertel 5131:   border-collapse: collapse;
                   5132: }
                   5133: 
                   5134: table.LC_docs_documents td.LC_docs_document {
                   5135:   border: 2px solid black;
                   5136:   padding: 4px;
                   5137: }
                   5138: 
                   5139: .LC_docs_course_commands div {
                   5140:   float: left;
                   5141:   border: 4px solid #AAAAAA;
                   5142:   padding: 4px;
                   5143:   background: #DDDDCC;
                   5144: }
                   5145: 
                   5146: .LC_docs_entry_move {
                   5147:   border: 0px;
                   5148:   border-collapse: collapse;
1.544     albertel 5149: }
                   5150: 
1.545     albertel 5151: .LC_docs_entry_move td {
                   5152:   border: 2px solid #BBBBBB;
                   5153:   background: #DDDDDD;
                   5154: }
                   5155: 
                   5156: .LC_docs_editor td.LC_docs_entry_commands {
                   5157:   background: #DDDDDD;
                   5158:   font-size: x-small;
                   5159: }
1.544     albertel 5160: .LC_docs_copy {
1.545     albertel 5161:   color: #000099;
1.544     albertel 5162: }
                   5163: .LC_docs_cut {
1.545     albertel 5164:   color: #550044;
1.544     albertel 5165: }
                   5166: .LC_docs_rename {
1.545     albertel 5167:   color: #009900;
1.544     albertel 5168: }
                   5169: .LC_docs_remove {
1.545     albertel 5170:   color: #990000;
                   5171: }
                   5172: 
1.547     albertel 5173: .LC_docs_reinit_warn,
                   5174: .LC_docs_ext_edit {
                   5175:   font-size: x-small;
                   5176: }
                   5177: 
1.545     albertel 5178: .LC_docs_editor td.LC_docs_entry_title,
                   5179: .LC_docs_editor td.LC_docs_entry_icon {
                   5180:   background: #FFFFBB;
                   5181: }
                   5182: .LC_docs_editor td.LC_docs_entry_parameter {
                   5183:   background: #BBBBFF;
                   5184:   font-size: x-small;
                   5185:   white-space: nowrap;
                   5186: }
                   5187: 
                   5188: table.LC_docs_adddocs td,
                   5189: table.LC_docs_adddocs th {
                   5190:   border: 1px solid #BBBBBB;
                   5191:   padding: 4px;
                   5192:   background: #DDDDDD;
1.543     albertel 5193: }
                   5194: 
1.584     albertel 5195: table.LC_sty_begin {
                   5196:   background: #BBFFBB;
                   5197: }
                   5198: table.LC_sty_end {
                   5199:   background: #FFBBBB;
                   5200: }
                   5201: 
1.589     raeburn  5202: table.LC_double_column {
                   5203:   border-width: 0px;
                   5204:   border-collapse: collapse;
                   5205:   width: 100%;
                   5206:   padding: 2px;
                   5207: }
                   5208: 
                   5209: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  5210:   top: 2px;
1.589     raeburn  5211:   left: 2px;
                   5212:   width: 47%;
                   5213:   vertical-align: top;
                   5214: }
                   5215: 
                   5216: table.LC_double_column tr td.LC_right_col {
                   5217:   top: 2px;
                   5218:   right: 2px; 
                   5219:   width: 47%;
                   5220:   vertical-align: top;
                   5221: }
                   5222: 
1.594     raeburn  5223: span.LC_role_level {
                   5224:   font-weight: bold;
                   5225: }
                   5226: 
1.591     raeburn  5227: div.LC_left_float {
                   5228:   float: left;
                   5229:   padding-right: 5%;
1.597     albertel 5230:   padding-bottom: 4px;
1.591     raeburn  5231: }
                   5232: 
                   5233: div.LC_clear_float_header {
1.597     albertel 5234:   padding-bottom: 2px;
1.591     raeburn  5235: }
                   5236: 
                   5237: div.LC_clear_float_footer {
1.597     albertel 5238:   padding-top: 10px;
1.591     raeburn  5239:   clear: both;
                   5240: }
                   5241: 
1.597     albertel 5242: 
1.601     albertel 5243: div.LC_grade_select_mode {
1.604     albertel 5244:   font-family: $sans;
1.601     albertel 5245: }
                   5246: div.LC_grade_select_mode div div {
                   5247:   margin: 5px;
                   5248: }
                   5249: div.LC_grade_select_mode_selector {
                   5250:   margin: 5px;
                   5251:   float: left;
                   5252: }
                   5253: div.LC_grade_select_mode_selector_header {
                   5254:   font: bold medium $sans;
                   5255: }
                   5256: div.LC_grade_select_mode_type {
                   5257:   clear: left;
                   5258: }
                   5259: 
1.597     albertel 5260: div.LC_grade_show_user {
                   5261:   margin-top: 20px;
                   5262:   border: 1px solid black;
                   5263: }
                   5264: div.LC_grade_user_name {
                   5265:   background: #DDDDEE;
                   5266:   border-bottom: 1px solid black;
                   5267:   font: bold large $sans;
                   5268: }
                   5269: div.LC_grade_show_user_odd_row div.LC_grade_user_name {
                   5270:   background: #DDEEDD;
                   5271: }
                   5272: 
                   5273: div.LC_grade_show_problem,
                   5274: div.LC_grade_submissions,
                   5275: div.LC_grade_message_center,
                   5276: div.LC_grade_info_links,
                   5277: div.LC_grade_assign {
                   5278:   margin: 5px;
                   5279:   width: 99%;
                   5280:   background: #FFFFFF;
                   5281: }
                   5282: div.LC_grade_show_problem_header,
                   5283: div.LC_grade_submissions_header,
                   5284: div.LC_grade_message_center_header,
                   5285: div.LC_grade_assign_header {
                   5286:   font: bold large $sans;
                   5287: }
                   5288: div.LC_grade_show_problem_problem,
                   5289: div.LC_grade_submissions_body,
                   5290: div.LC_grade_message_center_body,
                   5291: div.LC_grade_assign_body {
                   5292:   border: 1px solid black;
                   5293:   width: 99%;
                   5294:   background: #FFFFFF;
                   5295: }
1.598     albertel 5296: span.LC_grade_check_note {
                   5297:   font: normal medium $sans;
                   5298:   display: inline;
                   5299:   position: absolute;
                   5300:   right: 1em;
                   5301: }
1.597     albertel 5302: 
1.613     albertel 5303: table.LC_scantron_action {
                   5304:   width: 100%;
                   5305: }
                   5306: table.LC_scantron_action tr th {
                   5307:   font: normal bold $sans;
                   5308: }
1.600     albertel 5309: 
1.614     albertel 5310: div.LC_edit_problem_header, 
                   5311: div.LC_edit_problem_footer {
1.600     albertel 5312:   font: normal medium $sans;
1.602     albertel 5313:   margin: 2px;
1.600     albertel 5314: }
                   5315: div.LC_edit_problem_header,
1.602     albertel 5316: div.LC_edit_problem_header div,
1.614     albertel 5317: div.LC_edit_problem_footer,
                   5318: div.LC_edit_problem_footer div,
1.602     albertel 5319: div.LC_edit_problem_editxml_header,
                   5320: div.LC_edit_problem_editxml_header div {
1.600     albertel 5321:   margin-top: 5px;
                   5322: }
1.602     albertel 5323: div.LC_edit_problem_header_edit_row {
                   5324:   background: $tabbg;
                   5325:   padding: 3px;
                   5326:   margin-bottom: 5px;
                   5327: }
1.600     albertel 5328: div.LC_edit_problem_header_title {
1.602     albertel 5329:   font: larger bold $sans;
                   5330:   background: $tabbg;
                   5331:   padding: 3px;
                   5332: }
                   5333: table.LC_edit_problem_header_title {
                   5334:   font: larger bold $sans;
                   5335:   width: 100%;
                   5336:   border-color: $pgbg;
                   5337:   border-style: solid;
                   5338:   border-width: $border;
                   5339: 
1.600     albertel 5340:   background: $tabbg;
1.602     albertel 5341:   border-collapse: collapse;
                   5342:   padding: 0px
                   5343: }
                   5344: 
                   5345: div.LC_edit_problem_discards {
                   5346:   float: left;
                   5347:   padding-bottom: 5px;
                   5348: }
                   5349: div.LC_edit_problem_saves {
                   5350:   float: right;
                   5351:   padding-bottom: 5px;
1.600     albertel 5352: }
                   5353: hr.LC_edit_problem_divide {
1.602     albertel 5354:   clear: both;
1.600     albertel 5355:   color: $tabbg;
                   5356:   background-color: $tabbg;
                   5357:   height: 3px;
                   5358:   border: 0px;
                   5359: }
1.343     albertel 5360: END
                   5361: }
                   5362: 
1.306     albertel 5363: =pod
                   5364: 
                   5365: =item * &headtag()
                   5366: 
                   5367: Returns a uniform footer for LON-CAPA web pages.
                   5368: 
1.307     albertel 5369: Inputs: $title - optional title for the head
                   5370:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 5371:         $args - optional arguments
1.319     albertel 5372:             force_register - if is true call registerurl so the remote is 
                   5373:                              informed
1.415     albertel 5374:             redirect       -> array ref of
                   5375:                                    1- seconds before redirect occurs
                   5376:                                    2- url to redirect to
                   5377:                                    3- whether the side effect should occur
1.315     albertel 5378:                            (side effect of setting 
                   5379:                                $env{'internal.head.redirect'} to the url 
                   5380:                                redirected too)
1.352     albertel 5381:             domain         -> force to color decorate a page for a specific
                   5382:                                domain
                   5383:             function       -> force usage of a specific rolish color scheme
                   5384:             bgcolor        -> override the default page bgcolor
1.460     albertel 5385:             no_auto_mt_title
                   5386:                            -> prevent &mt()ing the title arg
1.464     albertel 5387: 
1.306     albertel 5388: =cut
                   5389: 
                   5390: sub headtag {
1.313     albertel 5391:     my ($title,$head_extra,$args) = @_;
1.306     albertel 5392:     
1.363     albertel 5393:     my $function = $args->{'function'} || &get_users_function();
                   5394:     my $domain   = $args->{'domain'}   || &determinedomain();
                   5395:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.418     albertel 5396:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 5397: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 5398: 		   #time(),
1.418     albertel 5399: 		   $env{'environment.color.timestamp'},
1.363     albertel 5400: 		   $function,$domain,$bgcolor);
                   5401: 
1.369     www      5402:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 5403: 
1.308     albertel 5404:     my $result =
                   5405: 	'<head>'.
1.461     albertel 5406: 	&font_settings();
1.319     albertel 5407: 
1.461     albertel 5408:     if (!$args->{'frameset'}) {
                   5409: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   5410:     }
1.319     albertel 5411:     if ($args->{'force_register'}) {
                   5412: 	$result .= &Apache::lonmenu::registerurl(1);
                   5413:     }
1.436     albertel 5414:     if (!$args->{'no_nav_bar'} 
                   5415: 	&& !$args->{'only_body'}
                   5416: 	&& !$args->{'frameset'}) {
                   5417: 	$result .= &help_menu_js();
                   5418:     }
1.319     albertel 5419: 
1.314     albertel 5420:     if (ref($args->{'redirect'})) {
1.414     albertel 5421: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 5422: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 5423: 	if (!$inhibit_continue) {
                   5424: 	    $env{'internal.head.redirect'} = $url;
                   5425: 	}
1.313     albertel 5426: 	$result.=<<ADDMETA
                   5427: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 5428: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 5429: ADDMETA
                   5430:     }
1.306     albertel 5431:     if (!defined($title)) {
                   5432: 	$title = 'The LearningOnline Network with CAPA';
                   5433:     }
1.460     albertel 5434:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   5435:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.414     albertel 5436: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
                   5437: 	.$head_extra;
1.306     albertel 5438:     return $result;
                   5439: }
                   5440: 
                   5441: =pod
                   5442: 
1.340     albertel 5443: =item * &font_settings()
                   5444: 
                   5445: Returns neccessary <meta> to set the proper encoding
                   5446: 
                   5447: Inputs: none
                   5448: 
                   5449: =cut
                   5450: 
                   5451: sub font_settings {
                   5452:     my $headerstring='';
1.647     www      5453:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
1.340     albertel 5454: 	$headerstring.=
                   5455: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
                   5456:     }
                   5457:     return $headerstring;
                   5458: }
                   5459: 
1.341     albertel 5460: =pod
                   5461: 
                   5462: =item * &xml_begin()
                   5463: 
                   5464: Returns the needed doctype and <html>
                   5465: 
                   5466: Inputs: none
                   5467: 
                   5468: =cut
                   5469: 
                   5470: sub xml_begin {
                   5471:     my $output='';
                   5472: 
1.592     albertel 5473:     if ($env{'internal.start_page'}==1) {
                   5474: 	&Apache::lonhtmlcommon::init_htmlareafields();
                   5475:     }
1.342     albertel 5476: 
1.341     albertel 5477:     if ($env{'browser.mathml'}) {
                   5478: 	$output='<?xml version="1.0"?>'
                   5479:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   5480: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   5481:             
                   5482: #	    .'<!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">] >'
                   5483: 	    .'<!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">'
                   5484:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   5485: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
                   5486:     } else {
                   5487: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
                   5488:     }
                   5489:     return $output;
                   5490: }
1.340     albertel 5491: 
                   5492: =pod
                   5493: 
1.306     albertel 5494: =item * &endheadtag()
                   5495: 
                   5496: Returns a uniform </head> for LON-CAPA web pages.
                   5497: 
                   5498: Inputs: none
                   5499: 
                   5500: =cut
                   5501: 
                   5502: sub endheadtag {
                   5503:     return '</head>';
                   5504: }
                   5505: 
                   5506: =pod
                   5507: 
                   5508: =item * &head()
                   5509: 
                   5510: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
                   5511: 
1.648     raeburn  5512: Inputs:
                   5513: 
                   5514: =over 4
                   5515: 
                   5516: $title - optional title for the page
                   5517: 
                   5518: $head_extra - optional extra HTML to put inside the <head>
                   5519: 
                   5520: =back
1.405     albertel 5521: 
1.306     albertel 5522: =cut
                   5523: 
                   5524: sub head {
1.325     albertel 5525:     my ($title,$head_extra,$args) = @_;
                   5526:     return &headtag($title,$head_extra,$args).&endheadtag();
1.306     albertel 5527: }
                   5528: 
                   5529: =pod
                   5530: 
                   5531: =item * &start_page()
                   5532: 
                   5533: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   5534: 
1.648     raeburn  5535: Inputs:
                   5536: 
                   5537: =over 4
                   5538: 
                   5539: $title - optional title for the page
                   5540: 
                   5541: $head_extra - optional extra HTML to incude inside the <head>
                   5542: 
                   5543: $args - additional optional args supported are:
                   5544: 
                   5545: =over 8
                   5546: 
                   5547:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 5548:                                     arg on
1.648     raeburn  5549:              no_nav_bar     -> is true will set &bodytag() notopbar arg on
                   5550:              add_entries    -> additional attributes to add to the  <body>
                   5551:              domain         -> force to color decorate a page for a 
1.317     albertel 5552:                                     specific domain
1.648     raeburn  5553:              function       -> force usage of a specific rolish color
1.317     albertel 5554:                                     scheme
1.648     raeburn  5555:              redirect       -> see &headtag()
                   5556:              bgcolor        -> override the default page bg color
                   5557:              js_ready       -> return a string ready for being used in 
1.317     albertel 5558:                                     a javascript writeln
1.648     raeburn  5559:              html_encode    -> return a string ready for being used in 
1.320     albertel 5560:                                     a html attribute
1.648     raeburn  5561:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 5562:                                     $forcereg arg
1.648     raeburn  5563:              body_title     -> alternate text to use instead of $title
1.326     albertel 5564:                                     in the title box that appears, this text
                   5565:                                     is not auto translated like the $title is
1.648     raeburn  5566:              frameset       -> if true will start with a <frameset>
1.330     albertel 5567:                                     rather than <body>
1.648     raeburn  5568:              no_title       -> if true the title bar won't be shown
                   5569:              skip_phases    -> hash ref of 
1.338     albertel 5570:                                     head -> skip the <html><head> generation
                   5571:                                     body -> skip all <body> generation
1.648     raeburn  5572:              no_inline_link -> if true and in remote mode, don't show the 
1.361     albertel 5573:                                     'Switch To Inline Menu' link
1.648     raeburn  5574:              no_auto_mt_title -> prevent &mt()ing the title arg
                   5575:              inherit_jsmath -> when creating popup window in a page,
                   5576:                                     should it have jsmath forced on by the
                   5577:                                     current page
1.361     albertel 5578: 
1.648     raeburn  5579: =back
1.460     albertel 5580: 
1.648     raeburn  5581: =back
1.562     albertel 5582: 
1.306     albertel 5583: =cut
                   5584: 
                   5585: sub start_page {
1.309     albertel 5586:     my ($title,$head_extra,$args) = @_;
1.318     albertel 5587:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.313     albertel 5588:     my %head_args;
1.352     albertel 5589:     foreach my $arg ('redirect','force_register','domain','function',
1.460     albertel 5590: 		     'bgcolor','frameset','no_nav_bar','only_body',
                   5591: 		     'no_auto_mt_title') {
1.319     albertel 5592: 	if (defined($args->{$arg})) {
1.324     raeburn  5593: 	    $head_args{$arg} = $args->{$arg};
1.319     albertel 5594: 	}
1.313     albertel 5595:     }
1.319     albertel 5596: 
1.315     albertel 5597:     $env{'internal.start_page'}++;
1.338     albertel 5598:     my $result;
                   5599:     if (! exists($args->{'skip_phases'}{'head'}) ) {
                   5600: 	$result.=
1.341     albertel 5601: 	    &xml_begin().
1.338     albertel 5602: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
                   5603:     }
                   5604:     
                   5605:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   5606: 	if ($args->{'frameset'}) {
                   5607: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   5608: 						$args->{'add_entries'});
                   5609: 	    $result .= "\n<frameset $attr_string>\n";
                   5610: 	} else {
                   5611: 	    $result .=
                   5612: 		&bodytag($title, 
                   5613: 			 $args->{'function'},       $args->{'add_entries'},
                   5614: 			 $args->{'only_body'},      $args->{'domain'},
                   5615: 			 $args->{'force_register'}, $args->{'body_title'},
                   5616: 			 $args->{'no_nav_bar'},     $args->{'bgcolor'},
1.460     albertel 5617: 			 $args->{'no_title'},       $args->{'no_inline_link'},
                   5618: 			 $args);
1.338     albertel 5619: 	}
1.330     albertel 5620:     }
1.338     albertel 5621: 
1.315     albertel 5622:     if ($args->{'js_ready'}) {
1.317     albertel 5623: 	$result = &js_ready($result);
1.315     albertel 5624:     }
1.320     albertel 5625:     if ($args->{'html_encode'}) {
                   5626: 	$result = &html_encode($result);
                   5627:     }
1.315     albertel 5628:     return $result;
1.306     albertel 5629: }
                   5630: 
1.330     albertel 5631: 
1.306     albertel 5632: =pod
                   5633: 
                   5634: =item * &head()
                   5635: 
                   5636: Returns a complete </body></html> section for LON-CAPA web pages.
                   5637: 
1.315     albertel 5638: Inputs:         $args - additional optional args supported are:
                   5639:                  js_ready     -> return a string ready for being used in 
                   5640:                                  a javascript writeln
1.320     albertel 5641:                  html_encode  -> return a string ready for being used in 
                   5642:                                  a html attribute
1.330     albertel 5643:                  frameset     -> if true will start with a <frameset>
                   5644:                                  rather than <body>
1.493     albertel 5645:                  dicsussion   -> if true will get discussion from
                   5646:                                   lonxml::xmlend
                   5647:                                  (you can pass the target and parser arguments
                   5648:                                   through optional 'target' and 'parser' args
                   5649:                                   to this routine)
1.306     albertel 5650: 
                   5651: =cut
                   5652: 
                   5653: sub end_page {
1.315     albertel 5654:     my ($args) = @_;
                   5655:     $env{'internal.end_page'}++;
1.330     albertel 5656:     my $result;
1.335     albertel 5657:     if ($args->{'discussion'}) {
                   5658: 	my ($target,$parser);
                   5659: 	if (ref($args->{'discussion'})) {
                   5660: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   5661: 				$args->{'discussion'}{'parser'});
                   5662: 	}
                   5663: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   5664:     }
                   5665: 
1.330     albertel 5666:     if ($args->{'frameset'}) {
                   5667: 	$result .= '</frameset>';
                   5668:     } else {
1.635     raeburn  5669: 	$result .= &endbodytag($args);
1.330     albertel 5670:     }
                   5671:     $result .= "\n</html>";
                   5672: 
1.315     albertel 5673:     if ($args->{'js_ready'}) {
1.317     albertel 5674: 	$result = &js_ready($result);
1.315     albertel 5675:     }
1.335     albertel 5676: 
1.320     albertel 5677:     if ($args->{'html_encode'}) {
                   5678: 	$result = &html_encode($result);
                   5679:     }
1.335     albertel 5680: 
1.315     albertel 5681:     return $result;
                   5682: }
                   5683: 
1.320     albertel 5684: sub html_encode {
                   5685:     my ($result) = @_;
                   5686: 
1.322     albertel 5687:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 5688:     
                   5689:     return $result;
                   5690: }
1.317     albertel 5691: sub js_ready {
                   5692:     my ($result) = @_;
                   5693: 
1.323     albertel 5694:     $result =~ s/[\n\r]/ /xmsg;
                   5695:     $result =~ s/\\/\\\\/xmsg;
                   5696:     $result =~ s/'/\\'/xmsg;
1.372     albertel 5697:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 5698:     
                   5699:     return $result;
                   5700: }
                   5701: 
1.315     albertel 5702: sub validate_page {
                   5703:     if (  exists($env{'internal.start_page'})
1.316     albertel 5704: 	  &&     $env{'internal.start_page'} > 1) {
                   5705: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 5706: 				 $env{'internal.start_page'}.' '.
1.316     albertel 5707: 				 $ENV{'request.filename'});
1.315     albertel 5708:     }
                   5709:     if (  exists($env{'internal.end_page'})
1.316     albertel 5710: 	  &&     $env{'internal.end_page'} > 1) {
                   5711: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 5712: 				 $env{'internal.end_page'}.' '.
1.316     albertel 5713: 				 $env{'request.filename'});
1.315     albertel 5714:     }
                   5715:     if (     exists($env{'internal.start_page'})
                   5716: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 5717: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   5718: 				 $env{'request.filename'});
1.315     albertel 5719:     }
                   5720:     if (   ! exists($env{'internal.start_page'})
                   5721: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 5722: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   5723: 				 $env{'request.filename'});
1.315     albertel 5724:     }
1.306     albertel 5725: }
1.315     albertel 5726: 
1.318     albertel 5727: sub simple_error_page {
                   5728:     my ($r,$title,$msg) = @_;
                   5729:     my $page =
                   5730: 	&Apache::loncommon::start_page($title).
                   5731: 	&mt($msg).
                   5732: 	&Apache::loncommon::end_page();
                   5733:     if (ref($r)) {
                   5734: 	$r->print($page);
1.327     albertel 5735: 	return;
1.318     albertel 5736:     }
                   5737:     return $page;
                   5738: }
1.347     albertel 5739: 
                   5740: {
1.610     albertel 5741:     my @row_count;
1.347     albertel 5742:     sub start_data_table {
1.422     albertel 5743: 	my ($add_class) = @_;
                   5744: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.610     albertel 5745: 	unshift(@row_count,0);
1.422     albertel 5746: 	return '<table class="'.$css_class.'">'."\n";
1.347     albertel 5747:     }
                   5748: 
                   5749:     sub end_data_table {
1.610     albertel 5750: 	shift(@row_count);
1.389     albertel 5751: 	return '</table>'."\n";;
1.347     albertel 5752:     }
                   5753: 
                   5754:     sub start_data_table_row {
1.422     albertel 5755: 	my ($add_class) = @_;
1.610     albertel 5756: 	$row_count[0]++;
                   5757: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.428     albertel 5758: 	$css_class = (join(' ',$css_class,$add_class));
1.422     albertel 5759: 	return  '<tr class="'.$css_class.'">'."\n";;
1.347     albertel 5760:     }
1.471     banghart 5761:     
                   5762:     sub continue_data_table_row {
                   5763: 	my ($add_class) = @_;
1.610     albertel 5764: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.471     banghart 5765: 	$css_class = (join(' ',$css_class,$add_class));
                   5766: 	return  '<tr class="'.$css_class.'">'."\n";;
                   5767:     }
1.347     albertel 5768: 
                   5769:     sub end_data_table_row {
1.389     albertel 5770: 	return '</tr>'."\n";;
1.347     albertel 5771:     }
1.367     www      5772: 
1.421     albertel 5773:     sub start_data_table_empty_row {
1.610     albertel 5774: 	$row_count[0]++;
1.421     albertel 5775: 	return  '<tr class="LC_empty_row" >'."\n";;
                   5776:     }
                   5777: 
                   5778:     sub end_data_table_empty_row {
                   5779: 	return '</tr>'."\n";;
                   5780:     }
                   5781: 
1.367     www      5782:     sub start_data_table_header_row {
1.389     albertel 5783: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      5784:     }
                   5785: 
                   5786:     sub end_data_table_header_row {
1.389     albertel 5787: 	return '</tr>'."\n";;
1.367     www      5788:     }
1.347     albertel 5789: }
                   5790: 
1.548     albertel 5791: =pod
                   5792: 
                   5793: =item * &inhibit_menu_check($arg)
                   5794: 
                   5795: Checks for a inhibitmenu state and generates output to preserve it
                   5796: 
                   5797: Inputs:         $arg - can be any of
                   5798:                      - undef - in which case the return value is a string 
                   5799:                                to add  into arguments list of a uri
                   5800:                      - 'input' - in which case the return value is a HTML
                   5801:                                  <form> <input> field of type hidden to
                   5802:                                  preserve the value
                   5803:                      - a url - in which case the return value is the url with
                   5804:                                the neccesary cgi args added to preserve the
                   5805:                                inhibitmenu state
                   5806:                      - a ref to a url - no return value, but the string is
                   5807:                                         updated to include the neccessary cgi
                   5808:                                         args to preserve the inhibitmenu state
                   5809: 
                   5810: =cut
                   5811: 
                   5812: sub inhibit_menu_check {
                   5813:     my ($arg) = @_;
                   5814:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5815:     if ($arg eq 'input') {
                   5816: 	if ($env{'form.inhibitmenu'}) {
                   5817: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   5818: 	} else {
                   5819: 	    return
                   5820: 	}
                   5821:     }
                   5822:     if ($env{'form.inhibitmenu'}) {
                   5823: 	if (ref($arg)) {
                   5824: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   5825: 	} elsif ($arg eq '') {
                   5826: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   5827: 	} else {
                   5828: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   5829: 	}
                   5830:     }
                   5831:     if (!ref($arg)) {
                   5832: 	return $arg;
                   5833:     }
                   5834: }
                   5835: 
1.251     albertel 5836: ###############################################
1.182     matthew  5837: 
                   5838: =pod
                   5839: 
1.549     albertel 5840: =back
                   5841: 
                   5842: =head1 User Information Routines
                   5843: 
                   5844: =over 4
                   5845: 
1.405     albertel 5846: =item * &get_users_function()
1.182     matthew  5847: 
                   5848: Used by &bodytag to determine the current users primary role.
                   5849: Returns either 'student','coordinator','admin', or 'author'.
                   5850: 
                   5851: =cut
                   5852: 
                   5853: ###############################################
                   5854: sub get_users_function {
                   5855:     my $function = 'student';
1.258     albertel 5856:     if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
1.182     matthew  5857:         $function='coordinator';
                   5858:     }
1.258     albertel 5859:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  5860:         $function='admin';
                   5861:     }
1.258     albertel 5862:     if (($env{'request.role'}=~/^(au|ca)/) ||
1.182     matthew  5863:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
                   5864:         $function='author';
                   5865:     }
                   5866:     return $function;
1.54      www      5867: }
1.99      www      5868: 
                   5869: ###############################################
                   5870: 
1.233     raeburn  5871: =pod
                   5872: 
1.542     raeburn  5873: =item * &check_user_status()
1.274     raeburn  5874: 
                   5875: Determines current status of supplied role for a
                   5876: specific user. Roles can be active, previous or future.
                   5877: 
                   5878: Inputs: 
                   5879: user's domain, user's username, course's domain,
1.375     raeburn  5880: course's number, optional section ID.
1.274     raeburn  5881: 
                   5882: Outputs:
                   5883: role status: active, previous or future. 
                   5884: 
                   5885: =cut
                   5886: 
                   5887: sub check_user_status {
1.412     raeburn  5888:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.274     raeburn  5889:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
                   5890:     my @uroles = keys %userinfo;
                   5891:     my $srchstr;
                   5892:     my $active_chk = 'none';
1.412     raeburn  5893:     my $now = time;
1.274     raeburn  5894:     if (@uroles > 0) {
1.412     raeburn  5895:         if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  5896:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   5897:         } else {
1.412     raeburn  5898:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   5899:         }
                   5900:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  5901:             my $role_end = 0;
                   5902:             my $role_start = 0;
                   5903:             $active_chk = 'active';
1.412     raeburn  5904:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   5905:                 $role_end = $1;
                   5906:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   5907:                     $role_start = $1;
1.274     raeburn  5908:                 }
                   5909:             }
                   5910:             if ($role_start > 0) {
1.412     raeburn  5911:                 if ($now < $role_start) {
1.274     raeburn  5912:                     $active_chk = 'future';
                   5913:                 }
                   5914:             }
                   5915:             if ($role_end > 0) {
1.412     raeburn  5916:                 if ($now > $role_end) {
1.274     raeburn  5917:                     $active_chk = 'previous';
                   5918:                 }
                   5919:             }
                   5920:         }
                   5921:     }
                   5922:     return $active_chk;
                   5923: }
                   5924: 
                   5925: ###############################################
                   5926: 
                   5927: =pod
                   5928: 
1.405     albertel 5929: =item * &get_sections()
1.233     raeburn  5930: 
                   5931: Determines all the sections for a course including
                   5932: sections with students and sections containing other roles.
1.419     raeburn  5933: Incoming parameters: 
                   5934: 
                   5935: 1. domain
                   5936: 2. course number 
                   5937: 3. reference to array containing roles for which sections should 
                   5938: be gathered (optional).
                   5939: 4. reference to array containing status types for which sections 
                   5940: should be gathered (optional).
                   5941: 
                   5942: If the third argument is undefined, sections are gathered for any role. 
                   5943: If the fourth argument is undefined, sections are gathered for any status.
                   5944: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  5945:  
1.374     raeburn  5946: Returns section hash (keys are section IDs, values are
                   5947: number of users in each section), subject to the
1.419     raeburn  5948: optional roles filter, optional status filter 
1.233     raeburn  5949: 
                   5950: =cut
                   5951: 
                   5952: ###############################################
                   5953: sub get_sections {
1.419     raeburn  5954:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 5955:     if (!defined($cdom) || !defined($cnum)) {
                   5956:         my $cid =  $env{'request.course.id'};
                   5957: 
                   5958: 	return if (!defined($cid));
                   5959: 
                   5960:         $cdom = $env{'course.'.$cid.'.domain'};
                   5961:         $cnum = $env{'course.'.$cid.'.num'};
                   5962:     }
                   5963: 
                   5964:     my %sectioncount;
1.419     raeburn  5965:     my $now = time;
1.240     albertel 5966: 
1.366     albertel 5967:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
1.276     albertel 5968: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 5969: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   5970: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  5971:         my $start_index = &Apache::loncoursedata::CL_START();
                   5972:         my $end_index = &Apache::loncoursedata::CL_END();
                   5973:         my $status;
1.366     albertel 5974: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  5975: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   5976: 				                     $data->[$status_index],
                   5977:                                                      $data->[$start_index],
                   5978:                                                      $data->[$end_index]);
                   5979:             if ($stu_status eq 'Active') {
                   5980:                 $status = 'active';
                   5981:             } elsif ($end < $now) {
                   5982:                 $status = 'previous';
                   5983:             } elsif ($start > $now) {
                   5984:                 $status = 'future';
                   5985:             } 
                   5986: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   5987:                 if ((!defined($possible_status)) || (($status ne '') && 
                   5988:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   5989: 		    $sectioncount{$section}++;
                   5990:                 }
1.240     albertel 5991: 	    }
                   5992: 	}
                   5993:     }
                   5994:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   5995:     foreach my $user (sort(keys(%courseroles))) {
                   5996: 	if ($user !~ /^(\w{2})/) { next; }
                   5997: 	my ($role) = ($user =~ /^(\w{2})/);
                   5998: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  5999: 	my ($section,$status);
1.240     albertel 6000: 	if ($role eq 'cr' &&
                   6001: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   6002: 	    $section=$1;
                   6003: 	}
                   6004: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   6005: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  6006:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   6007:         if ($end == -1 && $start == -1) {
                   6008:             next; #deleted role
                   6009:         }
                   6010:         if (!defined($possible_status)) { 
                   6011:             $sectioncount{$section}++;
                   6012:         } else {
                   6013:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   6014:                 $status = 'active';
                   6015:             } elsif ($end < $now) {
                   6016:                 $status = 'future';
                   6017:             } elsif ($start > $now) {
                   6018:                 $status = 'previous';
                   6019:             }
                   6020:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   6021:                 $sectioncount{$section}++;
                   6022:             }
                   6023:         }
1.233     raeburn  6024:     }
1.366     albertel 6025:     return %sectioncount;
1.233     raeburn  6026: }
                   6027: 
1.274     raeburn  6028: ###############################################
1.294     raeburn  6029: 
                   6030: =pod
1.405     albertel 6031: 
                   6032: =item * &get_course_users()
                   6033: 
1.275     raeburn  6034: Retrieves usernames:domains for users in the specified course
                   6035: with specific role(s), and access status. 
                   6036: 
                   6037: Incoming parameters:
1.277     albertel 6038: 1. course domain
                   6039: 2. course number
                   6040: 3. access status: users must have - either active, 
1.275     raeburn  6041: previous, future, or all.
1.277     albertel 6042: 4. reference to array of permissible roles
1.288     raeburn  6043: 5. reference to array of section restrictions (optional)
                   6044: 6. reference to results object (hash of hashes).
                   6045: 7. reference to optional userdata hash
1.609     raeburn  6046: 8. reference to optional statushash
1.630     raeburn  6047: 9. flag if privileged users (except those set to unhide in
                   6048:    course settings) should be excluded    
1.609     raeburn  6049: Keys of top level results hash are roles.
1.275     raeburn  6050: Keys of inner hashes are username:domain, with 
                   6051: values set to access type.
1.288     raeburn  6052: Optional userdata hash returns an array with arguments in the 
                   6053: same order as loncoursedata::get_classlist() for student data.
                   6054: 
1.609     raeburn  6055: Optional statushash returns
                   6056: 
1.288     raeburn  6057: Entries for end, start, section and status are blank because
                   6058: of the possibility of multiple values for non-student roles.
                   6059: 
1.275     raeburn  6060: =cut
1.405     albertel 6061: 
1.275     raeburn  6062: ###############################################
1.405     albertel 6063: 
1.275     raeburn  6064: sub get_course_users {
1.630     raeburn  6065:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  6066:     my %idx = ();
1.419     raeburn  6067:     my %seclists;
1.288     raeburn  6068: 
                   6069:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   6070:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   6071:     $idx{end} = &Apache::loncoursedata::CL_END();
                   6072:     $idx{start} = &Apache::loncoursedata::CL_START();
                   6073:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   6074:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   6075:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   6076:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   6077: 
1.290     albertel 6078:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 6079:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  6080:         my $now = time;
1.277     albertel 6081:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  6082:             my $match = 0;
1.412     raeburn  6083:             my $secmatch = 0;
1.419     raeburn  6084:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  6085:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  6086:             if ($section eq '') {
                   6087:                 $section = 'none';
                   6088:             }
1.291     albertel 6089:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 6090:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  6091:                     $secmatch = 1;
                   6092:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 6093:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  6094:                         $secmatch = 1;
                   6095:                     }
                   6096:                 } else {  
1.419     raeburn  6097: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  6098: 		        $secmatch = 1;
                   6099:                     }
1.290     albertel 6100: 		}
1.412     raeburn  6101:                 if (!$secmatch) {
                   6102:                     next;
                   6103:                 }
1.419     raeburn  6104:             }
1.275     raeburn  6105:             if (defined($$types{'active'})) {
1.288     raeburn  6106:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  6107:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  6108:                     $match = 1;
1.275     raeburn  6109:                 }
                   6110:             }
                   6111:             if (defined($$types{'previous'})) {
1.609     raeburn  6112:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  6113:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  6114:                     $match = 1;
1.275     raeburn  6115:                 }
                   6116:             }
                   6117:             if (defined($$types{'future'})) {
1.609     raeburn  6118:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  6119:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  6120:                     $match = 1;
1.275     raeburn  6121:                 }
                   6122:             }
1.609     raeburn  6123:             if ($match) {
                   6124:                 push(@{$seclists{$student}},$section);
                   6125:                 if (ref($userdata) eq 'HASH') {
                   6126:                     $$userdata{$student} = $$classlist{$student};
                   6127:                 }
                   6128:                 if (ref($statushash) eq 'HASH') {
                   6129:                     $statushash->{$student}{'st'}{$section} = $status;
                   6130:                 }
1.288     raeburn  6131:             }
1.275     raeburn  6132:         }
                   6133:     }
1.412     raeburn  6134:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  6135:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   6136:         my $now = time;
1.609     raeburn  6137:         my %displaystatus = ( previous => 'Expired',
                   6138:                               active   => 'Active',
                   6139:                               future   => 'Future',
                   6140:                             );
1.630     raeburn  6141:         my %nothide;
                   6142:         if ($hidepriv) {
                   6143:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   6144:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   6145:                 if ($user !~ /:/) {
                   6146:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   6147:                 } else {
                   6148:                     $nothide{$user} = 1;
                   6149:                 }
                   6150:             }
                   6151:         }
1.439     raeburn  6152:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  6153:             my $match = 0;
1.412     raeburn  6154:             my $secmatch = 0;
1.439     raeburn  6155:             my $status;
1.412     raeburn  6156:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  6157:             $user =~ s/:$//;
1.439     raeburn  6158:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   6159:             if ($end == -1 || $start == -1) {
                   6160:                 next;
                   6161:             }
                   6162:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   6163:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  6164:                 my ($uname,$udom) = split(/:/,$user);
                   6165:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 6166:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  6167:                         $secmatch = 1;
                   6168:                     } elsif ($usec eq '') {
1.420     albertel 6169:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  6170:                             $secmatch = 1;
                   6171:                         }
                   6172:                     } else {
                   6173:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   6174:                             $secmatch = 1;
                   6175:                         }
                   6176:                     }
                   6177:                     if (!$secmatch) {
                   6178:                         next;
                   6179:                     }
1.288     raeburn  6180:                 }
1.419     raeburn  6181:                 if ($usec eq '') {
                   6182:                     $usec = 'none';
                   6183:                 }
1.275     raeburn  6184:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  6185:                     if ($hidepriv) {
                   6186:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
                   6187:                             (!$nothide{$uname.':'.$udom})) {
                   6188:                             next;
                   6189:                         }
                   6190:                     }
1.503     raeburn  6191:                     if ($end > 0 && $end < $now) {
1.439     raeburn  6192:                         $status = 'previous';
                   6193:                     } elsif ($start > $now) {
                   6194:                         $status = 'future';
                   6195:                     } else {
                   6196:                         $status = 'active';
                   6197:                     }
1.277     albertel 6198:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  6199:                         if ($status eq $type) {
1.420     albertel 6200:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  6201:                                 push(@{$$users{$role}{$user}},$type);
                   6202:                             }
1.288     raeburn  6203:                             $match = 1;
                   6204:                         }
                   6205:                     }
1.419     raeburn  6206:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   6207:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   6208: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   6209:                         }
1.420     albertel 6210:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  6211:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   6212:                         }
1.609     raeburn  6213:                         if (ref($statushash) eq 'HASH') {
                   6214:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   6215:                         }
1.275     raeburn  6216:                     }
                   6217:                 }
                   6218:             }
                   6219:         }
1.290     albertel 6220:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  6221:             if ((defined($cdom)) && (defined($cnum))) {
                   6222:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   6223:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   6224:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  6225:                     next if ($owner eq '');
                   6226:                     my ($ownername,$ownerdom);
                   6227:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   6228:                         $ownername = $1;
                   6229:                         $ownerdom = $2;
                   6230:                     } else {
                   6231:                         $ownername = $owner;
                   6232:                         $ownerdom = $cdom;
                   6233:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  6234:                     }
                   6235:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 6236:                     if (defined($userdata) && 
1.609     raeburn  6237: 			!exists($$userdata{$owner})) {
                   6238: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   6239:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   6240:                             push(@{$seclists{$owner}},'none');
                   6241:                         }
                   6242:                         if (ref($statushash) eq 'HASH') {
                   6243:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  6244:                         }
1.290     albertel 6245: 		    }
1.279     raeburn  6246:                 }
                   6247:             }
                   6248:         }
1.419     raeburn  6249:         foreach my $user (keys(%seclists)) {
                   6250:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   6251:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   6252:         }
1.275     raeburn  6253:     }
                   6254:     return;
                   6255: }
                   6256: 
1.288     raeburn  6257: sub get_user_info {
                   6258:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 6259:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   6260: 	&plainname($uname,$udom,'lastname');
1.291     albertel 6261:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  6262:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  6263:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   6264:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  6265:     return;
                   6266: }
1.275     raeburn  6267: 
1.472     raeburn  6268: ###############################################
                   6269: 
                   6270: =pod
                   6271: 
                   6272: =item * &get_user_quota()
                   6273: 
                   6274: Retrieves quota assigned for storage of portfolio files for a user  
                   6275: 
                   6276: Incoming parameters:
                   6277: 1. user's username
                   6278: 2. user's domain
                   6279: 
                   6280: Returns:
1.536     raeburn  6281: 1. Disk quota (in Mb) assigned to student.
                   6282: 2. (Optional) Type of setting: custom or default
                   6283:    (individually assigned or default for user's 
                   6284:    institutional status).
                   6285: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   6286:    or student - types as defined in localenroll::inst_usertypes 
                   6287:    for user's domain, which determines default quota for user.
                   6288: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  6289: 
                   6290: If a value has been stored in the user's environment, 
1.536     raeburn  6291: it will return that, otherwise it returns the maximal default
                   6292: defined for the user's instituional status(es) in the domain.
1.472     raeburn  6293: 
                   6294: =cut
                   6295: 
                   6296: ###############################################
                   6297: 
                   6298: 
                   6299: sub get_user_quota {
                   6300:     my ($uname,$udom) = @_;
1.536     raeburn  6301:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  6302:     if (!defined($udom)) {
                   6303:         $udom = $env{'user.domain'};
                   6304:     }
                   6305:     if (!defined($uname)) {
                   6306:         $uname = $env{'user.name'};
                   6307:     }
                   6308:     if (($udom eq '' || $uname eq '') ||
                   6309:         ($udom eq 'public') && ($uname eq 'public')) {
                   6310:         $quota = 0;
1.536     raeburn  6311:         $quotatype = 'default';
                   6312:         $defquota = 0; 
1.472     raeburn  6313:     } else {
1.536     raeburn  6314:         my $inststatus;
1.472     raeburn  6315:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   6316:             $quota = $env{'environment.portfolioquota'};
1.536     raeburn  6317:             $inststatus = $env{'environment.inststatus'};
1.472     raeburn  6318:         } else {
1.536     raeburn  6319:             my %userenv = 
                   6320:                 &Apache::lonnet::get('environment',['portfolioquota',
                   6321:                                      'inststatus'],$udom,$uname);
1.472     raeburn  6322:             my ($tmp) = keys(%userenv);
                   6323:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   6324:                 $quota = $userenv{'portfolioquota'};
1.536     raeburn  6325:                 $inststatus = $userenv{'inststatus'};
1.472     raeburn  6326:             } else {
                   6327:                 undef(%userenv);
                   6328:             }
                   6329:         }
1.536     raeburn  6330:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
1.472     raeburn  6331:         if ($quota eq '') {
1.536     raeburn  6332:             $quota = $defquota;
                   6333:             $quotatype = 'default';
                   6334:         } else {
                   6335:             $quotatype = 'custom';
1.472     raeburn  6336:         }
                   6337:     }
1.536     raeburn  6338:     if (wantarray) {
                   6339:         return ($quota,$quotatype,$settingstatus,$defquota);
                   6340:     } else {
                   6341:         return $quota;
                   6342:     }
1.472     raeburn  6343: }
                   6344: 
                   6345: ###############################################
                   6346: 
                   6347: =pod
                   6348: 
                   6349: =item * &default_quota()
                   6350: 
1.536     raeburn  6351: Retrieves default quota assigned for storage of user portfolio files,
                   6352: given an (optional) user's institutional status.
1.472     raeburn  6353: 
                   6354: Incoming parameters:
                   6355: 1. domain
1.536     raeburn  6356: 2. (Optional) institutional status(es).  This is a : separated list of 
                   6357:    status types (e.g., faculty, staff, student etc.)
                   6358:    which apply to the user for whom the default is being retrieved.
                   6359:    If the institutional status string in undefined, the domain
                   6360:    default quota will be returned. 
1.472     raeburn  6361: 
                   6362: Returns:
                   6363: 1. Default disk quota (in Mb) for user portfolios in the domain.
1.536     raeburn  6364: 2. (Optional) institutional type which determined the value of the
                   6365:    default quota.
1.472     raeburn  6366: 
                   6367: If a value has been stored in the domain's configuration db,
                   6368: it will return that, otherwise it returns 20 (for backwards 
                   6369: compatibility with domains which have not set up a configuration
                   6370: db file; the original statically defined portfolio quota was 20 Mb). 
                   6371: 
1.536     raeburn  6372: If the user's status includes multiple types (e.g., staff and student),
                   6373: the largest default quota which applies to the user determines the
                   6374: default quota returned.
                   6375: 
1.472     raeburn  6376: =cut
                   6377: 
                   6378: ###############################################
                   6379: 
                   6380: 
                   6381: sub default_quota {
1.536     raeburn  6382:     my ($udom,$inststatus) = @_;
                   6383:     my ($defquota,$settingstatus);
                   6384:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  6385:                                             ['quotas'],$udom);
                   6386:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  6387:         if ($inststatus ne '') {
                   6388:             my @statuses = split(/:/,$inststatus);
                   6389:             foreach my $item (@statuses) {
1.622     raeburn  6390:                 if ($quotahash{'quotas'}{$item} ne '') {
1.536     raeburn  6391:                     if ($defquota eq '') {
1.622     raeburn  6392:                         $defquota = $quotahash{'quotas'}{$item};
1.536     raeburn  6393:                         $settingstatus = $item;
1.622     raeburn  6394:                     } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   6395:                         $defquota = $quotahash{'quotas'}{$item};
1.536     raeburn  6396:                         $settingstatus = $item;
                   6397:                     }
                   6398:                 }
                   6399:             }
                   6400:         }
                   6401:         if ($defquota eq '') {
1.622     raeburn  6402:             $defquota = $quotahash{'quotas'}{'default'};
1.536     raeburn  6403:             $settingstatus = 'default';
                   6404:         }
                   6405:     } else {
                   6406:         $settingstatus = 'default';
                   6407:         $defquota = 20;
                   6408:     }
                   6409:     if (wantarray) {
                   6410:         return ($defquota,$settingstatus);
1.472     raeburn  6411:     } else {
1.536     raeburn  6412:         return $defquota;
1.472     raeburn  6413:     }
                   6414: }
                   6415: 
1.384     raeburn  6416: sub get_secgrprole_info {
                   6417:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   6418:     my %sections_count = &get_sections($cdom,$cnum);
                   6419:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   6420:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   6421:     my @groups = sort(keys(%curr_groups));
                   6422:     my $allroles = [];
                   6423:     my $rolehash;
                   6424:     my $accesshash = {
                   6425:                      active => 'Currently has access',
                   6426:                      future => 'Will have future access',
                   6427:                      previous => 'Previously had access',
                   6428:                   };
                   6429:     if ($needroles) {
                   6430:         $rolehash = {'all' => 'all'};
1.385     albertel 6431:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   6432: 	if (&Apache::lonnet::error(%user_roles)) {
                   6433: 	    undef(%user_roles);
                   6434: 	}
                   6435:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  6436:             my ($role)=split(/\:/,$item,2);
                   6437:             if ($role eq 'cr') { next; }
                   6438:             if ($role =~ /^cr/) {
                   6439:                 $$rolehash{$role} = (split('/',$role))[3];
                   6440:             } else {
                   6441:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   6442:             }
                   6443:         }
                   6444:         foreach my $key (sort(keys(%{$rolehash}))) {
                   6445:             push(@{$allroles},$key);
                   6446:         }
                   6447:         push (@{$allroles},'st');
                   6448:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   6449:     }
                   6450:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   6451: }
                   6452: 
1.555     raeburn  6453: sub user_picker {
1.627     raeburn  6454:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
1.555     raeburn  6455:     my $currdom = $dom;
                   6456:     my %curr_selected = (
                   6457:                         srchin => 'dom',
1.580     raeburn  6458:                         srchby => 'lastname',
1.555     raeburn  6459:                       );
                   6460:     my $srchterm;
1.625     raeburn  6461:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  6462:         if ($srch->{'srchby'} ne '') {
                   6463:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   6464:         }
                   6465:         if ($srch->{'srchin'} ne '') {
                   6466:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   6467:         }
                   6468:         if ($srch->{'srchtype'} ne '') {
                   6469:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   6470:         }
                   6471:         if ($srch->{'srchdomain'} ne '') {
                   6472:             $currdom = $srch->{'srchdomain'};
                   6473:         }
                   6474:         $srchterm = $srch->{'srchterm'};
                   6475:     }
                   6476:     my %lt=&Apache::lonlocal::texthash(
1.573     raeburn  6477:                     'usr'       => 'Search criteria',
1.563     raeburn  6478:                     'doma'      => 'Domain/institution to search',
1.558     albertel 6479:                     'uname'     => 'username',
                   6480:                     'lastname'  => 'last name',
1.555     raeburn  6481:                     'lastfirst' => 'last name, first name',
1.558     albertel 6482:                     'crs'       => 'in this course',
1.576     raeburn  6483:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 6484:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  6485:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 6486:                     'exact'     => 'is',
                   6487:                     'contains'  => 'contains',
1.569     raeburn  6488:                     'begins'    => 'begins with',
1.571     raeburn  6489:                     'youm'      => "You must include some text to search for.",
                   6490:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   6491:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   6492:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   6493:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   6494:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   6495:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   6496:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  6497:                                        );
1.563     raeburn  6498:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   6499:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  6500: 
                   6501:     my @srchins = ('crs','dom','alc','instd');
                   6502: 
                   6503:     foreach my $option (@srchins) {
                   6504:         # FIXME 'alc' option unavailable until 
                   6505:         #       loncreateuser::print_user_query_page()
                   6506:         #       has been completed.
                   6507:         next if ($option eq 'alc');
                   6508:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  6509:         if ($curr_selected{'srchin'} eq $option) {
                   6510:             $srchinsel .= ' 
                   6511:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   6512:         } else {
                   6513:             $srchinsel .= '
                   6514:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   6515:         }
1.555     raeburn  6516:     }
1.563     raeburn  6517:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  6518: 
                   6519:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  6520:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  6521:         if ($curr_selected{'srchby'} eq $option) {
                   6522:             $srchbysel .= '
                   6523:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   6524:         } else {
                   6525:             $srchbysel .= '
                   6526:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   6527:          }
                   6528:     }
                   6529:     $srchbysel .= "\n  </select>\n";
                   6530: 
                   6531:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  6532:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  6533:         if ($curr_selected{'srchtype'} eq $option) {
                   6534:             $srchtypesel .= '
                   6535:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   6536:         } else {
                   6537:             $srchtypesel .= '
                   6538:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   6539:         }
                   6540:     }
                   6541:     $srchtypesel .= "\n  </select>\n";
                   6542: 
1.558     albertel 6543:     my ($newuserscript,$new_user_create);
1.556     raeburn  6544: 
                   6545:     if ($forcenewuser) {
1.576     raeburn  6546:         if (ref($srch) eq 'HASH') {
                   6547:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
1.627     raeburn  6548:                 if ($cancreate) {
                   6549:                     $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>';
                   6550:                 } else {
                   6551:                     my $helplink = ' href="javascript:helpMenu('."'display'".')"';
                   6552:                     my %usertypetext = (
                   6553:                         official   => 'institutional',
                   6554:                         unofficial => 'non-institutional',
                   6555:                     );
                   6556:                     $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 />';
                   6557:                 }
1.576     raeburn  6558:             }
                   6559:         }
                   6560: 
1.556     raeburn  6561:         $newuserscript = <<"ENDSCRIPT";
                   6562: 
1.570     raeburn  6563: function setSearch(createnew,callingForm) {
1.556     raeburn  6564:     if (createnew == 1) {
1.570     raeburn  6565:         for (var i=0; i<callingForm.srchby.length; i++) {
                   6566:             if (callingForm.srchby.options[i].value == 'uname') {
                   6567:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  6568:             }
                   6569:         }
1.570     raeburn  6570:         for (var i=0; i<callingForm.srchin.length; i++) {
                   6571:             if ( callingForm.srchin.options[i].value == 'dom') {
                   6572: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  6573:             }
                   6574:         }
1.570     raeburn  6575:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   6576:             if (callingForm.srchtype.options[i].value == 'exact') {
                   6577:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  6578:             }
                   6579:         }
1.570     raeburn  6580:         for (var i=0; i<callingForm.srchdomain.length; i++) {
                   6581:             if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
                   6582:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  6583:             }
                   6584:         }
                   6585:     }
                   6586: }
                   6587: ENDSCRIPT
1.558     albertel 6588: 
1.556     raeburn  6589:     }
                   6590: 
1.555     raeburn  6591:     my $output = <<"END_BLOCK";
1.556     raeburn  6592: <script type="text/javascript">
1.570     raeburn  6593: function validateEntry(callingForm) {
1.558     albertel 6594: 
1.556     raeburn  6595:     var checkok = 1;
1.558     albertel 6596:     var srchin;
1.570     raeburn  6597:     for (var i=0; i<callingForm.srchin.length; i++) {
                   6598: 	if ( callingForm.srchin[i].checked ) {
                   6599: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 6600: 	}
                   6601:     }
                   6602: 
1.570     raeburn  6603:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   6604:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   6605:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   6606:     var srchterm =  callingForm.srchterm.value;
                   6607:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  6608:     var msg = "";
                   6609: 
                   6610:     if (srchterm == "") {
                   6611:         checkok = 0;
1.571     raeburn  6612:         msg += "$lt{'youm'}\\n";
1.556     raeburn  6613:     }
                   6614: 
1.569     raeburn  6615:     if (srchtype== 'begins') {
                   6616:         if (srchterm.length < 2) {
                   6617:             checkok = 0;
1.571     raeburn  6618:             msg += "$lt{'thte'}\\n";
1.569     raeburn  6619:         }
                   6620:     }
                   6621: 
1.556     raeburn  6622:     if (srchtype== 'contains') {
                   6623:         if (srchterm.length < 3) {
                   6624:             checkok = 0;
1.571     raeburn  6625:             msg += "$lt{'thet'}\\n";
1.556     raeburn  6626:         }
                   6627:     }
                   6628:     if (srchin == 'instd') {
                   6629:         if (srchdomain == '') {
                   6630:             checkok = 0;
1.571     raeburn  6631:             msg += "$lt{'yomc'}\\n";
1.556     raeburn  6632:         }
                   6633:     }
                   6634:     if (srchin == 'dom') {
                   6635:         if (srchdomain == '') {
                   6636:             checkok = 0;
1.571     raeburn  6637:             msg += "$lt{'ymcd'}\\n";
1.556     raeburn  6638:         }
                   6639:     }
                   6640:     if (srchby == 'lastfirst') {
                   6641:         if (srchterm.indexOf(",") == -1) {
                   6642:             checkok = 0;
1.571     raeburn  6643:             msg += "$lt{'whus'}\\n";
1.556     raeburn  6644:         }
                   6645:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   6646:             checkok = 0;
1.571     raeburn  6647:             msg += "$lt{'whse'}\\n";
1.556     raeburn  6648:         }
                   6649:     }
                   6650:     if (checkok == 0) {
1.571     raeburn  6651:         alert("$lt{'thfo'}\\n"+msg);
1.556     raeburn  6652:         return;
                   6653:     }
                   6654:     if (checkok == 1) {
1.570     raeburn  6655:         callingForm.submit();
1.556     raeburn  6656:     }
                   6657: }
                   6658: 
                   6659: $newuserscript
                   6660: 
                   6661: </script>
1.558     albertel 6662: 
                   6663: $new_user_create
                   6664: 
1.555     raeburn  6665: <table>
1.558     albertel 6666:  <tr>
1.573     raeburn  6667:   <td>$lt{'doma'}:</td>
                   6668:   <td>$domform</td>
                   6669:   </td>
                   6670:  </tr>
                   6671:  <tr>
                   6672:   <td>$lt{'usr'}:</td>
1.563     raeburn  6673:   <td>$srchbysel
                   6674:       $srchtypesel 
                   6675:       <input type="text" size="15" name="srchterm" value="$srchterm" />
1.564     albertel 6676:       $srchinsel 
1.563     raeburn  6677:   </td>
                   6678:  </tr>
1.555     raeburn  6679: </table>
                   6680: <br />
                   6681: END_BLOCK
1.558     albertel 6682: 
1.555     raeburn  6683:     return $output;
                   6684: }
                   6685: 
1.612     raeburn  6686: sub user_rule_check {
1.615     raeburn  6687:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.612     raeburn  6688:     my $response;
                   6689:     if (ref($usershash) eq 'HASH') {
                   6690:         foreach my $user (keys(%{$usershash})) {
                   6691:             my ($uname,$udom) = split(/:/,$user);
                   6692:             next if ($udom eq '' || $uname eq '');
1.615     raeburn  6693:             my ($id,$newuser);
1.612     raeburn  6694:             if (ref($usershash->{$user}) eq 'HASH') {
1.615     raeburn  6695:                 $newuser = $usershash->{$user}->{'newuser'};
1.612     raeburn  6696:                 $id = $usershash->{$user}->{'id'};
                   6697:             }
                   6698:             my $inst_response;
                   6699:             if (ref($checks) eq 'HASH') {
                   6700:                 if (defined($checks->{'username'})) {
1.615     raeburn  6701:                     ($inst_response,%{$inst_results->{$user}}) = 
1.612     raeburn  6702:                         &Apache::lonnet::get_instuser($udom,$uname);
                   6703:                 } elsif (defined($checks->{'id'})) {
1.615     raeburn  6704:                     ($inst_response,%{$inst_results->{$user}}) =
1.612     raeburn  6705:                         &Apache::lonnet::get_instuser($udom,undef,$id);
                   6706:                 }
1.615     raeburn  6707:             } else {
                   6708:                 ($inst_response,%{$inst_results->{$user}}) =
                   6709:                     &Apache::lonnet::get_instuser($udom,$uname);
                   6710:                 return;
1.612     raeburn  6711:             }
1.615     raeburn  6712:             if (!$got_rules->{$udom}) {
1.612     raeburn  6713:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
                   6714:                                                   ['usercreation'],$udom);
                   6715:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
1.615     raeburn  6716:                     foreach my $item ('username','id') {
1.612     raeburn  6717:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   6718:                             $$curr_rules{$udom}{$item} = 
                   6719:                                 $domconfig{'usercreation'}{$item.'_rule'};
1.585     raeburn  6720:                         }
                   6721:                     }
                   6722:                 }
1.615     raeburn  6723:                 $got_rules->{$udom} = 1;  
1.585     raeburn  6724:             }
1.612     raeburn  6725:             foreach my $item (keys(%{$checks})) {
                   6726:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   6727:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   6728:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
                   6729:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
                   6730:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   6731:                                 if ($rule_check{$rule}) {
                   6732:                                     $$rulematch{$user}{$item} = $rule;
                   6733:                                     if ($inst_response eq 'ok') {
1.615     raeburn  6734:                                         if (ref($inst_results) eq 'HASH') {
                   6735:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   6736:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   6737:                                                     $$alerts{$item}{$udom}{$uname} = 1;
                   6738:                                                 }
1.612     raeburn  6739:                                             }
                   6740:                                         }
1.615     raeburn  6741:                                     }
                   6742:                                     last;
1.585     raeburn  6743:                                 }
                   6744:                             }
                   6745:                         }
                   6746:                     }
                   6747:                 }
                   6748:             }
                   6749:         }
                   6750:     }
1.612     raeburn  6751:     return;
                   6752: }
                   6753: 
                   6754: sub user_rule_formats {
                   6755:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   6756:     my %text = ( 
                   6757:                  'username' => 'Usernames',
                   6758:                  'id'       => 'IDs',
                   6759:                );
                   6760:     my $output;
                   6761:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   6762:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   6763:         if (@{$ruleorder} > 0) {
                   6764:             $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>';
                   6765:             foreach my $rule (@{$ruleorder}) {
                   6766:                 if (ref($curr_rules) eq 'ARRAY') {
                   6767:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   6768:                         if (ref($rules->{$rule}) eq 'HASH') {
                   6769:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   6770:                                         $rules->{$rule}{'desc'}.'</li>';
                   6771:                         }
                   6772:                     }
                   6773:                 }
                   6774:             }
                   6775:             $output .= '</ul>';
                   6776:         }
                   6777:     }
                   6778:     return $output;
                   6779: }
                   6780: 
                   6781: sub instrule_disallow_msg {
1.615     raeburn  6782:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  6783:     my $response;
                   6784:     my %text = (
                   6785:                   item   => 'username',
                   6786:                   items  => 'usernames',
                   6787:                   match  => 'matches',
                   6788:                   do     => 'does',
                   6789:                   action => 'a username',
                   6790:                   one    => 'one',
                   6791:                );
                   6792:     if ($count > 1) {
                   6793:         $text{'item'} = 'usernames';
                   6794:         $text{'match'} ='match';
                   6795:         $text{'do'} = 'do';
                   6796:         $text{'action'} = 'usernames',
                   6797:         $text{'one'} = 'ones';
                   6798:     }
                   6799:     if ($checkitem eq 'id') {
                   6800:         $text{'items'} = 'IDs';
                   6801:         $text{'item'} = 'ID';
                   6802:         $text{'action'} = 'an ID';
1.615     raeburn  6803:         if ($count > 1) {
                   6804:             $text{'item'} = 'IDs';
                   6805:             $text{'action'} = 'IDs';
                   6806:         }
1.612     raeburn  6807:     }
                   6808:     $response = &mt("The $text{'item'} you chose $text{'match'} the format of $text{'items'} defined for <span class=\"LC_cusr_emph\">[_1]</span>, but the $text{'item'} $text{'do'} not exist in the institutional directory.",$domdesc).'<br />';
1.615     raeburn  6809:     if ($mode eq 'upload') {
                   6810:         if ($checkitem eq 'username') {
                   6811:             $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'}.");
                   6812:         } elsif ($checkitem eq 'id') {
                   6813:             $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 ID/Student Number field.");
                   6814:         }
1.669     raeburn  6815:     } elsif ($mode eq 'selfcreate') {
                   6816:         if ($checkitem eq 'id') {
                   6817:             $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.");
                   6818:         }
1.615     raeburn  6819:     } else {
                   6820:         if ($checkitem eq 'username') {
                   6821:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   6822:         } elsif ($checkitem eq 'id') {
                   6823:             $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.");
                   6824:         }
1.612     raeburn  6825:     }
                   6826:     return $response;
1.585     raeburn  6827: }
                   6828: 
1.624     raeburn  6829: sub personal_data_fieldtitles {
                   6830:     my %fieldtitles = &Apache::lonlocal::texthash (
                   6831:                         id => 'Student/Employee ID',
                   6832:                         permanentemail => 'E-mail address',
                   6833:                         lastname => 'Last Name',
                   6834:                         firstname => 'First Name',
                   6835:                         middlename => 'Middle Name',
                   6836:                         generation => 'Generation',
                   6837:                         gen => 'Generation',
                   6838:                    );
                   6839:     return %fieldtitles;
                   6840: }
                   6841: 
1.642     raeburn  6842: sub sorted_inst_types {
                   6843:     my ($dom) = @_;
                   6844:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   6845:     my $othertitle = &mt('All users');
                   6846:     if ($env{'request.course.id'}) {
1.668     raeburn  6847:         $othertitle  = &mt('Any users');
1.642     raeburn  6848:     }
                   6849:     my @types;
                   6850:     if (ref($order) eq 'ARRAY') {
                   6851:         @types = @{$order};
                   6852:     }
                   6853:     if (@types == 0) {
                   6854:         if (ref($usertypes) eq 'HASH') {
                   6855:             @types = sort(keys(%{$usertypes}));
                   6856:         }
                   6857:     }
                   6858:     if (keys(%{$usertypes}) > 0) {
                   6859:         $othertitle = &mt('Other users');
                   6860:     }
                   6861:     return ($othertitle,$usertypes,\@types);
                   6862: }
                   6863: 
1.645     raeburn  6864: sub get_institutional_codes {
                   6865:     my ($settings,$allcourses,$LC_code) = @_;
                   6866: # Get complete list of course sections to update
                   6867:     my @currsections = ();
                   6868:     my @currxlists = ();
                   6869:     my $coursecode = $$settings{'internal.coursecode'};
                   6870: 
                   6871:     if ($$settings{'internal.sectionnums'} ne '') {
                   6872:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   6873:     }
                   6874: 
                   6875:     if ($$settings{'internal.crosslistings'} ne '') {
                   6876:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   6877:     }
                   6878: 
                   6879:     if (@currxlists > 0) {
                   6880:         foreach (@currxlists) {
                   6881:             if (m/^([^:]+):(\w*)$/) {
                   6882:                 unless (grep/^$1$/,@{$allcourses}) {
                   6883:                     push @{$allcourses},$1;
                   6884:                     $$LC_code{$1} = $2;
                   6885:                 }
                   6886:             }
                   6887:         }
                   6888:     }
                   6889:  
                   6890:     if (@currsections > 0) {
                   6891:         foreach (@currsections) {
                   6892:             if (m/^(\w+):(\w*)$/) {
                   6893:                 my $sec = $coursecode.$1;
                   6894:                 my $lc_sec = $2;
                   6895:                 unless (grep/^$sec$/,@{$allcourses}) {
                   6896:                     push @{$allcourses},$sec;
                   6897:                     $$LC_code{$sec} = $lc_sec;
                   6898:                 }
                   6899:             }
                   6900:         }
                   6901:     }
                   6902:     return;
                   6903: }
                   6904: 
1.112     bowersj2 6905: =pod
                   6906: 
1.549     albertel 6907: =back
                   6908: 
                   6909: =head1 HTTP Helpers
                   6910: 
                   6911: =over 4
                   6912: 
1.648     raeburn  6913: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 6914: 
1.258     albertel 6915: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 6916: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 6917: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 6918: 
                   6919: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   6920: $possible_names is an ref to an array of form element names.  As an example:
                   6921: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 6922: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 6923: 
                   6924: =cut
1.1       albertel 6925: 
1.6       albertel 6926: sub get_unprocessed_cgi {
1.25      albertel 6927:   my ($query,$possible_names)= @_;
1.26      matthew  6928:   # $Apache::lonxml::debug=1;
1.356     albertel 6929:   foreach my $pair (split(/&/,$query)) {
                   6930:     my ($name, $value) = split(/=/,$pair);
1.369     www      6931:     $name = &unescape($name);
1.25      albertel 6932:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   6933:       $value =~ tr/+/ /;
                   6934:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 6935:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 6936:     }
1.16      harris41 6937:   }
1.6       albertel 6938: }
                   6939: 
1.112     bowersj2 6940: =pod
                   6941: 
1.648     raeburn  6942: =item * &cacheheader() 
1.112     bowersj2 6943: 
                   6944: returns cache-controlling header code
                   6945: 
                   6946: =cut
                   6947: 
1.7       albertel 6948: sub cacheheader {
1.258     albertel 6949:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 6950:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   6951:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 6952:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   6953:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 6954:     return $output;
1.7       albertel 6955: }
                   6956: 
1.112     bowersj2 6957: =pod
                   6958: 
1.648     raeburn  6959: =item * &no_cache($r) 
1.112     bowersj2 6960: 
                   6961: specifies header code to not have cache
                   6962: 
                   6963: =cut
                   6964: 
1.9       albertel 6965: sub no_cache {
1.216     albertel 6966:     my ($r) = @_;
                   6967:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 6968: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 6969:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   6970:     $r->no_cache(1);
                   6971:     $r->header_out("Expires" => $date);
                   6972:     $r->header_out("Pragma" => "no-cache");
1.123     www      6973: }
                   6974: 
                   6975: sub content_type {
1.181     albertel 6976:     my ($r,$type,$charset) = @_;
1.299     foxr     6977:     if ($r) {
                   6978: 	#  Note that printout.pl calls this with undef for $r.
                   6979: 	&no_cache($r);
                   6980:     }
1.258     albertel 6981:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 6982:     unless ($charset) {
                   6983: 	$charset=&Apache::lonlocal::current_encoding;
                   6984:     }
                   6985:     if ($charset) { $type.='; charset='.$charset; }
                   6986:     if ($r) {
                   6987: 	$r->content_type($type);
                   6988:     } else {
                   6989: 	print("Content-type: $type\n\n");
                   6990:     }
1.9       albertel 6991: }
1.25      albertel 6992: 
1.112     bowersj2 6993: =pod
                   6994: 
1.648     raeburn  6995: =item * &add_to_env($name,$value) 
1.112     bowersj2 6996: 
1.258     albertel 6997: adds $name to the %env hash with value
1.112     bowersj2 6998: $value, if $name already exists, the entry is converted to an array
                   6999: reference and $value is added to the array.
                   7000: 
                   7001: =cut
                   7002: 
1.25      albertel 7003: sub add_to_env {
                   7004:   my ($name,$value)=@_;
1.258     albertel 7005:   if (defined($env{$name})) {
                   7006:     if (ref($env{$name})) {
1.25      albertel 7007:       #already have multiple values
1.258     albertel 7008:       push(@{ $env{$name} },$value);
1.25      albertel 7009:     } else {
                   7010:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 7011:       my $first=$env{$name};
                   7012:       undef($env{$name});
                   7013:       push(@{ $env{$name} },$first,$value);
1.25      albertel 7014:     }
                   7015:   } else {
1.258     albertel 7016:     $env{$name}=$value;
1.25      albertel 7017:   }
1.31      albertel 7018: }
1.149     albertel 7019: 
                   7020: =pod
                   7021: 
1.648     raeburn  7022: =item * &get_env_multiple($name) 
1.149     albertel 7023: 
1.258     albertel 7024: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 7025: values may be defined and end up as an array ref.
                   7026: 
                   7027: returns an array of values
                   7028: 
                   7029: =cut
                   7030: 
                   7031: sub get_env_multiple {
                   7032:     my ($name) = @_;
                   7033:     my @values;
1.258     albertel 7034:     if (defined($env{$name})) {
1.149     albertel 7035:         # exists is it an array
1.258     albertel 7036:         if (ref($env{$name})) {
                   7037:             @values=@{ $env{$name} };
1.149     albertel 7038:         } else {
1.258     albertel 7039:             $values[0]=$env{$name};
1.149     albertel 7040:         }
                   7041:     }
                   7042:     return(@values);
                   7043: }
                   7044: 
1.660     raeburn  7045: sub ask_for_embedded_content {
                   7046:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
                   7047:     my $upload_output = '
                   7048:    <form name="upload_embedded" action="'.$actionurl.'"
                   7049:                   method="post" enctype="multipart/form-data">';
                   7050:     $upload_output .= $state;
1.661     raeburn  7051:     $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
1.660     raeburn  7052: 
                   7053:     my $num = 0;
                   7054:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
                   7055:         $upload_output .= &start_data_table_row().
                   7056:             '<td>'.$embed_file.'</td><td>';
                   7057:         if ($args->{'ignore_remote_references'}
                   7058:             && $embed_file =~ m{^\w+://}) {
                   7059:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
                   7060:         } elsif ($args->{'error_on_invalid_names'}
                   7061:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
                   7062: 
                   7063:             $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
                   7064: 
                   7065:         } else {
                   7066:             $upload_output .='
1.661     raeburn  7067:            <input name="embedded_item_'.$num.'" type="file" value="" />
1.660     raeburn  7068:            <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
                   7069:             my $attrib = join(':',@{$$allfiles{$embed_file}});
                   7070:             $upload_output .=
                   7071:                 "\n\t\t".
                   7072:                 '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   7073:                 $attrib.'" />';
                   7074:             if (exists($$codebase{$embed_file})) {
                   7075:                 $upload_output .=
                   7076:                     "\n\t\t".
                   7077:                     '<input name="codebase_'.$num.'" type="hidden" value="'.
                   7078:                     &escape($$codebase{$embed_file}).'" />';
                   7079:             }
                   7080:         }
                   7081:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
                   7082:         $num++;
                   7083:     }
                   7084:     $upload_output .= &Apache::loncommon::end_data_table().'<br />
                   7085:    <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
                   7086:    <input type ="submit" value="'.&mt('Upload Listed Files').'" />
                   7087:    '.&mt('(only files for which a location has been provided will be uploaded)').'
                   7088:    </form>';
                   7089:     return $upload_output;
                   7090: }
                   7091: 
1.661     raeburn  7092: sub upload_embedded {
                   7093:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
                   7094:         $current_disk_usage) = @_;
                   7095:     my $output;
                   7096:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   7097:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   7098:         my $orig_uploaded_filename =
                   7099:             $env{'form.embedded_item_'.$i.'.filename'};
                   7100: 
                   7101:         $env{'form.embedded_orig_'.$i} =
                   7102:             &unescape($env{'form.embedded_orig_'.$i});
                   7103:         my ($path,$fname) =
                   7104:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   7105:         # no path, whole string is fname
                   7106:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   7107: 
                   7108:         $path = $env{'form.currentpath'}.$path;
                   7109:         $fname = &Apache::lonnet::clean_filename($fname);
                   7110:         # See if there is anything left
                   7111:         next if ($fname eq '');
                   7112: 
                   7113:         # Check if file already exists as a file or directory.
                   7114:         my ($state,$msg);
                   7115:         if ($context eq 'portfolio') {
                   7116:             my $port_path = $dirpath;
                   7117:             if ($group ne '') {
                   7118:                 $port_path = "groups/$group/$port_path";
                   7119:             }
                   7120:             ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
                   7121:                                               $dir_root,$port_path,$disk_quota,
                   7122:                                               $current_disk_usage,$uname,$udom);
                   7123:             if ($state eq 'will_exceed_quota'
                   7124:                 || $state eq 'file_locked'
                   7125:                 || $state eq 'file_exists' ) {
                   7126:                 $output .= $msg;
                   7127:                 next;
                   7128:             }
                   7129:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   7130:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   7131:             if ($state eq 'exists') {
                   7132:                 $output .= $msg;
                   7133:                 next;
                   7134:             }
                   7135:         }
                   7136:         # Check if extension is valid
                   7137:         if (($fname =~ /\.(\w+)$/) &&
                   7138:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
                   7139:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
                   7140:             next;
                   7141:         } elsif (($fname =~ /\.(\w+)$/) &&
                   7142:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
                   7143:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
                   7144:             next;
                   7145:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
                   7146:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
                   7147:             next;
                   7148:         }
                   7149: 
                   7150:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
                   7151:         if ($context eq 'portfolio') {
                   7152:             my $result=
                   7153:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
                   7154:                                                 $dirpath.$path);
                   7155:             if ($result !~ m|^/uploaded/|) {
                   7156:                 $output .= '<span class="LC_error">'
                   7157:                       .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   7158:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   7159:                       .'</span><br />';
                   7160:                 next;
                   7161:             } else {
                   7162:                 $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
                   7163:                            $path.$fname.'</span>').'</p>';     
                   7164:             }
                   7165:         } else {
                   7166: # Save the file
                   7167:             my $target = $env{'form.embedded_item_'.$i};
                   7168:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   7169:             my $dest = $fullpath.$fname;
                   7170:             my $url = $url_root.$dirpath.'/'.$path.$fname;
                   7171:             my @parts=split(/\//,$fullpath);
                   7172:             my $count;
                   7173:             my $filepath = $dir_root;
                   7174:             for ($count=4;$count<=$#parts;$count++) {
                   7175:                 $filepath .= "/$parts[$count]";
                   7176:                 if ((-e $filepath)!=1) {
                   7177:                     mkdir($filepath,0770);
                   7178:                 }
                   7179:             }
                   7180:             my $fh;
                   7181:             if (!open($fh,'>'.$dest)) {
                   7182:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   7183:                 $output .= '<span class="LC_error">'.
                   7184:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
                   7185:                            '</span><br />';
                   7186:             } else {
                   7187:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   7188:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   7189:                     $output .= '<span class="LC_error">'.
                   7190:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
                   7191:                               '</span><br />';
                   7192:                 } else {
                   7193:                     if ($context eq 'testbank') {
                   7194:                         $output .= &mt('Embedded file uploaded successfully:').
                   7195:                                    '&nbsp;<a href="'.$url.'">'.
                   7196:                                    $orig_uploaded_filename.'</a><br />';
                   7197:                     } else {
                   7198:                         $output .= '<font size="+2">'.
                   7199:                                    &mt('View embedded file: [_1]','<a href="'.$url.'">'.
                   7200:                                    $orig_uploaded_filename.'</a>').'</font><br />';
                   7201:                     }
                   7202:                 }
                   7203:                 close($fh);
                   7204:             }
                   7205:         }
                   7206:     }
                   7207:     return $output;
                   7208: }
                   7209: 
                   7210: sub check_for_existing {
                   7211:     my ($path,$fname,$element) = @_;
                   7212:     my ($state,$msg);
                   7213:     if (-d $path.'/'.$fname) {
                   7214:         $state = 'exists';
                   7215:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   7216:     } elsif (-e $path.'/'.$fname) {
                   7217:         $state = 'exists';
                   7218:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   7219:     }
                   7220:     if ($state eq 'exists') {
                   7221:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   7222:     }
                   7223:     return ($state,$msg);
                   7224: }
                   7225: 
                   7226: sub check_for_upload {
                   7227:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   7228:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
                   7229:     my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
                   7230:     my $getpropath = 1;
                   7231:     my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
                   7232:                                             $getpropath);
                   7233:     my $found_file = 0;
                   7234:     my $locked_file = 0;
                   7235:     foreach my $line (@dir_list) {
                   7236:         my ($file_name)=split(/\&/,$line,2);
                   7237:         if ($file_name eq $fname){
                   7238:             $file_name = $path.$file_name;
                   7239:             if ($group ne '') {
                   7240:                 $file_name = $group.$file_name;
                   7241:             }
                   7242:             $found_file = 1;
                   7243:             if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
                   7244:                 $locked_file = 1;
                   7245:             }
                   7246:         }
                   7247:     }
                   7248:     if (($current_disk_usage + $filesize) > $disk_quota){
                   7249:         my $msg = '<span class="LC_error">'.
                   7250:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
                   7251:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
                   7252:         return ('will_exceed_quota',$msg);
                   7253:     } elsif ($found_file) {
                   7254:         if ($locked_file) {
                   7255:             my $msg = '<span class="LC_error">';
                   7256:             $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>');
                   7257:             $msg .= '</span><br />';
                   7258:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   7259:             return ('file_locked',$msg);
                   7260:         } else {
                   7261:             my $msg = '<span class="LC_error">';
                   7262:             $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'});
                   7263:             $msg .= '</span>';
                   7264:             $msg .= '<br />';
                   7265:             $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
                   7266:             return ('file_exists',$msg);
                   7267:         }
                   7268:     }
                   7269: }
                   7270: 
1.31      albertel 7271: 
1.41      ng       7272: =pod
1.45      matthew  7273: 
1.464     albertel 7274: =back
1.41      ng       7275: 
1.112     bowersj2 7276: =head1 CSV Upload/Handling functions
1.38      albertel 7277: 
1.41      ng       7278: =over 4
                   7279: 
1.648     raeburn  7280: =item * &upfile_store($r)
1.41      ng       7281: 
                   7282: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 7283: needs $env{'form.upfile'}
1.41      ng       7284: returns $datatoken to be put into hidden field
                   7285: 
                   7286: =cut
1.31      albertel 7287: 
                   7288: sub upfile_store {
                   7289:     my $r=shift;
1.258     albertel 7290:     $env{'form.upfile'}=~s/\r/\n/gs;
                   7291:     $env{'form.upfile'}=~s/\f/\n/gs;
                   7292:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   7293:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 7294: 
1.258     albertel 7295:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   7296: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 7297:     {
1.158     raeburn  7298:         my $datafile = $r->dir_config('lonDaemons').
                   7299:                            '/tmp/'.$datatoken.'.tmp';
                   7300:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 7301:             print $fh $env{'form.upfile'};
1.158     raeburn  7302:             close($fh);
                   7303:         }
1.31      albertel 7304:     }
                   7305:     return $datatoken;
                   7306: }
                   7307: 
1.56      matthew  7308: =pod
                   7309: 
1.648     raeburn  7310: =item * &load_tmp_file($r)
1.41      ng       7311: 
                   7312: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 7313: needs $env{'form.datatoken'},
                   7314: sets $env{'form.upfile'} to the contents of the file
1.41      ng       7315: 
                   7316: =cut
1.31      albertel 7317: 
                   7318: sub load_tmp_file {
                   7319:     my $r=shift;
                   7320:     my @studentdata=();
                   7321:     {
1.158     raeburn  7322:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 7323:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  7324:         if ( open(my $fh,"<$studentfile") ) {
                   7325:             @studentdata=<$fh>;
                   7326:             close($fh);
                   7327:         }
1.31      albertel 7328:     }
1.258     albertel 7329:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 7330: }
                   7331: 
1.56      matthew  7332: =pod
                   7333: 
1.648     raeburn  7334: =item * &upfile_record_sep()
1.41      ng       7335: 
                   7336: Separate uploaded file into records
                   7337: returns array of records,
1.258     albertel 7338: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       7339: 
                   7340: =cut
1.31      albertel 7341: 
                   7342: sub upfile_record_sep {
1.258     albertel 7343:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 7344:     } else {
1.248     albertel 7345: 	my @records;
1.258     albertel 7346: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 7347: 	    if ($line=~/^\s*$/) { next; }
                   7348: 	    push(@records,$line);
                   7349: 	}
                   7350: 	return @records;
1.31      albertel 7351:     }
                   7352: }
                   7353: 
1.56      matthew  7354: =pod
                   7355: 
1.648     raeburn  7356: =item * &record_sep($record)
1.41      ng       7357: 
1.258     albertel 7358: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       7359: 
                   7360: =cut
                   7361: 
1.263     www      7362: sub takeleft {
                   7363:     my $index=shift;
                   7364:     return substr('0000'.$index,-4,4);
                   7365: }
                   7366: 
1.31      albertel 7367: sub record_sep {
                   7368:     my $record=shift;
                   7369:     my %components=();
1.258     albertel 7370:     if ($env{'form.upfiletype'} eq 'xml') {
                   7371:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 7372:         my $i=0;
1.356     albertel 7373:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 7374:             $field=~s/^(\"|\')//;
                   7375:             $field=~s/(\"|\')$//;
1.263     www      7376:             $components{&takeleft($i)}=$field;
1.31      albertel 7377:             $i++;
                   7378:         }
1.258     albertel 7379:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 7380:         my $i=0;
1.356     albertel 7381:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 7382:             $field=~s/^(\"|\')//;
                   7383:             $field=~s/(\"|\')$//;
1.263     www      7384:             $components{&takeleft($i)}=$field;
1.31      albertel 7385:             $i++;
                   7386:         }
                   7387:     } else {
1.561     www      7388:         my $separator=',';
1.480     banghart 7389:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      7390:             $separator=';';
1.480     banghart 7391:         }
1.31      albertel 7392:         my $i=0;
1.561     www      7393: # the character we are looking for to indicate the end of a quote or a record 
                   7394:         my $looking_for=$separator;
                   7395: # do not add the characters to the fields
                   7396:         my $ignore=0;
                   7397: # we just encountered a separator (or the beginning of the record)
                   7398:         my $just_found_separator=1;
                   7399: # store the field we are working on here
                   7400:         my $field='';
                   7401: # work our way through all characters in record
                   7402:         foreach my $character ($record=~/(.)/g) {
                   7403:             if ($character eq $looking_for) {
                   7404:                if ($character ne $separator) {
                   7405: # Found the end of a quote, again looking for separator
                   7406:                   $looking_for=$separator;
                   7407:                   $ignore=1;
                   7408:                } else {
                   7409: # Found a separator, store away what we got
                   7410:                   $components{&takeleft($i)}=$field;
                   7411: 	          $i++;
                   7412:                   $just_found_separator=1;
                   7413:                   $ignore=0;
                   7414:                   $field='';
                   7415:                }
                   7416:                next;
                   7417:             }
                   7418: # single or double quotation marks after a separator indicate beginning of a quote
                   7419: # we are now looking for the end of the quote and need to ignore separators
                   7420:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   7421:                $looking_for=$character;
                   7422:                next;
                   7423:             }
                   7424: # ignore would be true after we reached the end of a quote
                   7425:             if ($ignore) { next; }
                   7426:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   7427:             $field.=$character;
                   7428:             $just_found_separator=0; 
1.31      albertel 7429:         }
1.561     www      7430: # catch the very last entry, since we never encountered the separator
                   7431:         $components{&takeleft($i)}=$field;
1.31      albertel 7432:     }
                   7433:     return %components;
                   7434: }
                   7435: 
1.144     matthew  7436: ######################################################
                   7437: ######################################################
                   7438: 
1.56      matthew  7439: =pod
                   7440: 
1.648     raeburn  7441: =item * &upfile_select_html()
1.41      ng       7442: 
1.144     matthew  7443: Return HTML code to select a file from the users machine and specify 
                   7444: the file type.
1.41      ng       7445: 
                   7446: =cut
                   7447: 
1.144     matthew  7448: ######################################################
                   7449: ######################################################
1.31      albertel 7450: sub upfile_select_html {
1.144     matthew  7451:     my %Types = (
                   7452:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 7453:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  7454:                  space => &mt('Space separated'),
                   7455:                  tab   => &mt('Tabulator separated'),
                   7456: #                 xml   => &mt('HTML/XML'),
                   7457:                  );
                   7458:     my $Str = '<input type="file" name="upfile" size="50" />'.
                   7459:         '<br />Type: <select name="upfiletype">';
                   7460:     foreach my $type (sort(keys(%Types))) {
                   7461:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   7462:     }
                   7463:     $Str .= "</select>\n";
                   7464:     return $Str;
1.31      albertel 7465: }
                   7466: 
1.301     albertel 7467: sub get_samples {
                   7468:     my ($records,$toget) = @_;
                   7469:     my @samples=({});
                   7470:     my $got=0;
                   7471:     foreach my $rec (@$records) {
                   7472: 	my %temp = &record_sep($rec);
                   7473: 	if (! grep(/\S/, values(%temp))) { next; }
                   7474: 	if (%temp) {
                   7475: 	    $samples[$got]=\%temp;
                   7476: 	    $got++;
                   7477: 	    if ($got == $toget) { last; }
                   7478: 	}
                   7479:     }
                   7480:     return \@samples;
                   7481: }
                   7482: 
1.144     matthew  7483: ######################################################
                   7484: ######################################################
                   7485: 
1.56      matthew  7486: =pod
                   7487: 
1.648     raeburn  7488: =item * &csv_print_samples($r,$records)
1.41      ng       7489: 
                   7490: Prints a table of sample values from each column uploaded $r is an
                   7491: Apache Request ref, $records is an arrayref from
                   7492: &Apache::loncommon::upfile_record_sep
                   7493: 
                   7494: =cut
                   7495: 
1.144     matthew  7496: ######################################################
                   7497: ######################################################
1.31      albertel 7498: sub csv_print_samples {
                   7499:     my ($r,$records) = @_;
1.662     bisitz   7500:     my $samples = &get_samples($records,5);
1.301     albertel 7501: 
1.594     raeburn  7502:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   7503:               &start_data_table_header_row());
1.356     albertel 7504:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
                   7505:         $r->print('<th>'.&mt('Column&nbsp;[_1]',($sample+1)).'</th>'); }
1.594     raeburn  7506:     $r->print(&end_data_table_header_row());
1.301     albertel 7507:     foreach my $hash (@$samples) {
1.594     raeburn  7508: 	$r->print(&start_data_table_row());
1.356     albertel 7509: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 7510: 	    $r->print('<td>');
1.356     albertel 7511: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 7512: 	    $r->print('</td>');
                   7513: 	}
1.594     raeburn  7514: 	$r->print(&end_data_table_row());
1.31      albertel 7515:     }
1.594     raeburn  7516:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 7517: }
                   7518: 
1.144     matthew  7519: ######################################################
                   7520: ######################################################
                   7521: 
1.56      matthew  7522: =pod
                   7523: 
1.648     raeburn  7524: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       7525: 
                   7526: Prints a table to create associations between values and table columns.
1.144     matthew  7527: 
1.41      ng       7528: $r is an Apache Request ref,
                   7529: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  7530: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       7531: 
                   7532: =cut
                   7533: 
1.144     matthew  7534: ######################################################
                   7535: ######################################################
1.31      albertel 7536: sub csv_print_select_table {
                   7537:     my ($r,$records,$d) = @_;
1.301     albertel 7538:     my $i=0;
                   7539:     my $samples = &get_samples($records,1);
1.144     matthew  7540:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  7541: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  7542:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  7543:               '<th>'.&mt('Column').'</th>'.
                   7544:               &end_data_table_header_row()."\n");
1.356     albertel 7545:     foreach my $array_ref (@$d) {
                   7546: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.594     raeburn  7547: 	$r->print(&start_data_table_row().'<tr><td>'.$display.'</td>');
1.31      albertel 7548: 
                   7549: 	$r->print('<td><select name=f'.$i.
1.32      matthew  7550: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 7551: 	$r->print('<option value="none"></option>');
1.356     albertel 7552: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   7553: 	    $r->print('<option value="'.$sample.'"'.
                   7554:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   7555:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 7556: 	}
1.594     raeburn  7557: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 7558: 	$i++;
                   7559:     }
1.594     raeburn  7560:     $r->print(&end_data_table());
1.31      albertel 7561:     $i--;
                   7562:     return $i;
                   7563: }
1.56      matthew  7564: 
1.144     matthew  7565: ######################################################
                   7566: ######################################################
                   7567: 
1.56      matthew  7568: =pod
1.31      albertel 7569: 
1.648     raeburn  7570: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       7571: 
                   7572: Prints a table of sample values from the upload and can make associate samples to internal names.
                   7573: 
                   7574: $r is an Apache Request ref,
                   7575: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   7576: $d is an array of 2 element arrays (internal name, displayed name)
                   7577: 
                   7578: =cut
                   7579: 
1.144     matthew  7580: ######################################################
                   7581: ######################################################
1.31      albertel 7582: sub csv_samples_select_table {
                   7583:     my ($r,$records,$d) = @_;
                   7584:     my $i=0;
1.144     matthew  7585:     #
1.662     bisitz   7586:     my $max_samples = 5;
                   7587:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  7588:     $r->print(&start_data_table().
                   7589:               &start_data_table_header_row().'<th>'.
                   7590:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   7591:               &end_data_table_header_row());
1.301     albertel 7592: 
                   7593:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  7594: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  7595: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 7596: 	foreach my $option (@$d) {
                   7597: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  7598: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 7599:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  7600:                       $display.'</option>');
1.31      albertel 7601: 	}
                   7602: 	$r->print('</select></td><td>');
1.662     bisitz   7603: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 7604: 	    if (defined($samples->[$line]{$key})) { 
                   7605: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   7606: 	    }
                   7607: 	}
1.594     raeburn  7608: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 7609: 	$i++;
                   7610:     }
1.594     raeburn  7611:     $r->print(&end_data_table());
1.31      albertel 7612:     $i--;
                   7613:     return($i);
1.115     matthew  7614: }
                   7615: 
1.144     matthew  7616: ######################################################
                   7617: ######################################################
                   7618: 
1.115     matthew  7619: =pod
                   7620: 
1.648     raeburn  7621: =item * &clean_excel_name($name)
1.115     matthew  7622: 
                   7623: Returns a replacement for $name which does not contain any illegal characters.
                   7624: 
                   7625: =cut
                   7626: 
1.144     matthew  7627: ######################################################
                   7628: ######################################################
1.115     matthew  7629: sub clean_excel_name {
                   7630:     my ($name) = @_;
                   7631:     $name =~ s/[:\*\?\/\\]//g;
                   7632:     if (length($name) > 31) {
                   7633:         $name = substr($name,0,31);
                   7634:     }
                   7635:     return $name;
1.25      albertel 7636: }
1.84      albertel 7637: 
1.85      albertel 7638: =pod
                   7639: 
1.648     raeburn  7640: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 7641: 
                   7642: Returns either 1 or undef
                   7643: 
                   7644: 1 if the part is to be hidden, undef if it is to be shown
                   7645: 
                   7646: Arguments are:
                   7647: 
                   7648: $id the id of the part to be checked
                   7649: $symb, optional the symb of the resource to check
                   7650: $udom, optional the domain of the user to check for
                   7651: $uname, optional the username of the user to check for
                   7652: 
                   7653: =cut
1.84      albertel 7654: 
                   7655: sub check_if_partid_hidden {
                   7656:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 7657:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 7658: 					 $symb,$udom,$uname);
1.141     albertel 7659:     my $truth=1;
                   7660:     #if the string starts with !, then the list is the list to show not hide
                   7661:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 7662:     my @hiddenlist=split(/,/,$hiddenparts);
                   7663:     foreach my $checkid (@hiddenlist) {
1.141     albertel 7664: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 7665:     }
1.141     albertel 7666:     return !$truth;
1.84      albertel 7667: }
1.127     matthew  7668: 
1.138     matthew  7669: 
                   7670: ############################################################
                   7671: ############################################################
                   7672: 
                   7673: =pod
                   7674: 
1.157     matthew  7675: =back 
                   7676: 
1.138     matthew  7677: =head1 cgi-bin script and graphing routines
                   7678: 
1.157     matthew  7679: =over 4
                   7680: 
1.648     raeburn  7681: =item * &get_cgi_id()
1.138     matthew  7682: 
                   7683: Inputs: none
                   7684: 
                   7685: Returns an id which can be used to pass environment variables
                   7686: to various cgi-bin scripts.  These environment variables will
                   7687: be removed from the users environment after a given time by
                   7688: the routine &Apache::lonnet::transfer_profile_to_env.
                   7689: 
                   7690: =cut
                   7691: 
                   7692: ############################################################
                   7693: ############################################################
1.152     albertel 7694: my $uniq=0;
1.136     matthew  7695: sub get_cgi_id {
1.154     albertel 7696:     $uniq=($uniq+1)%100000;
1.280     albertel 7697:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  7698: }
                   7699: 
1.127     matthew  7700: ############################################################
                   7701: ############################################################
                   7702: 
                   7703: =pod
                   7704: 
1.648     raeburn  7705: =item * &DrawBarGraph()
1.127     matthew  7706: 
1.138     matthew  7707: Facilitates the plotting of data in a (stacked) bar graph.
                   7708: Puts plot definition data into the users environment in order for 
                   7709: graph.png to plot it.  Returns an <img> tag for the plot.
                   7710: The bars on the plot are labeled '1','2',...,'n'.
                   7711: 
                   7712: Inputs:
                   7713: 
                   7714: =over 4
                   7715: 
                   7716: =item $Title: string, the title of the plot
                   7717: 
                   7718: =item $xlabel: string, text describing the X-axis of the plot
                   7719: 
                   7720: =item $ylabel: string, text describing the Y-axis of the plot
                   7721: 
                   7722: =item $Max: scalar, the maximum Y value to use in the plot
                   7723: If $Max is < any data point, the graph will not be rendered.
                   7724: 
1.140     matthew  7725: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  7726: they are plotted.  If undefined, default values will be used.
                   7727: 
1.178     matthew  7728: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   7729: 
1.138     matthew  7730: =item @Values: An array of array references.  Each array reference holds data
                   7731: to be plotted in a stacked bar chart.
                   7732: 
1.239     matthew  7733: =item If the final element of @Values is a hash reference the key/value
                   7734: pairs will be added to the graph definition.
                   7735: 
1.138     matthew  7736: =back
                   7737: 
                   7738: Returns:
                   7739: 
                   7740: An <img> tag which references graph.png and the appropriate identifying
                   7741: information for the plot.
                   7742: 
1.127     matthew  7743: =cut
                   7744: 
                   7745: ############################################################
                   7746: ############################################################
1.134     matthew  7747: sub DrawBarGraph {
1.178     matthew  7748:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  7749:     #
                   7750:     if (! defined($colors)) {
                   7751:         $colors = ['#33ff00', 
                   7752:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   7753:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   7754:                   ]; 
                   7755:     }
1.228     matthew  7756:     my $extra_settings = {};
                   7757:     if (ref($Values[-1]) eq 'HASH') {
                   7758:         $extra_settings = pop(@Values);
                   7759:     }
1.127     matthew  7760:     #
1.136     matthew  7761:     my $identifier = &get_cgi_id();
                   7762:     my $id = 'cgi.'.$identifier;        
1.129     matthew  7763:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  7764:         return '';
                   7765:     }
1.225     matthew  7766:     #
                   7767:     my @Labels;
                   7768:     if (defined($labels)) {
                   7769:         @Labels = @$labels;
                   7770:     } else {
                   7771:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   7772:             push (@Labels,$i+1);
                   7773:         }
                   7774:     }
                   7775:     #
1.129     matthew  7776:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  7777:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  7778:     my %ValuesHash;
                   7779:     my $NumSets=1;
                   7780:     foreach my $array (@Values) {
                   7781:         next if (! ref($array));
1.136     matthew  7782:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  7783:             join(',',@$array);
1.129     matthew  7784:     }
1.127     matthew  7785:     #
1.136     matthew  7786:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  7787:     if ($NumBars < 3) {
                   7788:         $width = 120+$NumBars*32;
1.220     matthew  7789:         $xskip = 1;
1.225     matthew  7790:         $bar_width = 30;
                   7791:     } elsif ($NumBars < 5) {
                   7792:         $width = 120+$NumBars*20;
                   7793:         $xskip = 1;
                   7794:         $bar_width = 20;
1.220     matthew  7795:     } elsif ($NumBars < 10) {
1.136     matthew  7796:         $width = 120+$NumBars*15;
                   7797:         $xskip = 1;
                   7798:         $bar_width = 15;
                   7799:     } elsif ($NumBars <= 25) {
                   7800:         $width = 120+$NumBars*11;
                   7801:         $xskip = 5;
                   7802:         $bar_width = 8;
                   7803:     } elsif ($NumBars <= 50) {
                   7804:         $width = 120+$NumBars*8;
                   7805:         $xskip = 5;
                   7806:         $bar_width = 4;
                   7807:     } else {
                   7808:         $width = 120+$NumBars*8;
                   7809:         $xskip = 5;
                   7810:         $bar_width = 4;
                   7811:     }
                   7812:     #
1.137     matthew  7813:     $Max = 1 if ($Max < 1);
                   7814:     if ( int($Max) < $Max ) {
                   7815:         $Max++;
                   7816:         $Max = int($Max);
                   7817:     }
1.127     matthew  7818:     $Title  = '' if (! defined($Title));
                   7819:     $xlabel = '' if (! defined($xlabel));
                   7820:     $ylabel = '' if (! defined($ylabel));
1.369     www      7821:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   7822:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   7823:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  7824:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  7825:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   7826:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   7827:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   7828:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   7829:     $ValuesHash{$id.'.height'}   = $height;
                   7830:     $ValuesHash{$id.'.width'}    = $width;
                   7831:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   7832:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   7833:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  7834:     #
1.228     matthew  7835:     # Deal with other parameters
                   7836:     while (my ($key,$value) = each(%$extra_settings)) {
                   7837:         $ValuesHash{$id.'.'.$key} = $value;
                   7838:     }
                   7839:     #
1.646     raeburn  7840:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  7841:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   7842: }
                   7843: 
                   7844: ############################################################
                   7845: ############################################################
                   7846: 
                   7847: =pod
                   7848: 
1.648     raeburn  7849: =item * &DrawXYGraph()
1.137     matthew  7850: 
1.138     matthew  7851: Facilitates the plotting of data in an XY graph.
                   7852: Puts plot definition data into the users environment in order for 
                   7853: graph.png to plot it.  Returns an <img> tag for the plot.
                   7854: 
                   7855: Inputs:
                   7856: 
                   7857: =over 4
                   7858: 
                   7859: =item $Title: string, the title of the plot
                   7860: 
                   7861: =item $xlabel: string, text describing the X-axis of the plot
                   7862: 
                   7863: =item $ylabel: string, text describing the Y-axis of the plot
                   7864: 
                   7865: =item $Max: scalar, the maximum Y value to use in the plot
                   7866: If $Max is < any data point, the graph will not be rendered.
                   7867: 
                   7868: =item $colors: Array ref containing the hex color codes for the data to be 
                   7869: plotted in.  If undefined, default values will be used.
                   7870: 
                   7871: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   7872: 
                   7873: =item $Ydata: Array ref containing Array refs.  
1.185     www      7874: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  7875: 
                   7876: =item %Values: hash indicating or overriding any default values which are 
                   7877: passed to graph.png.  
                   7878: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   7879: 
                   7880: =back
                   7881: 
                   7882: Returns:
                   7883: 
                   7884: An <img> tag which references graph.png and the appropriate identifying
                   7885: information for the plot.
                   7886: 
1.137     matthew  7887: =cut
                   7888: 
                   7889: ############################################################
                   7890: ############################################################
                   7891: sub DrawXYGraph {
                   7892:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   7893:     #
                   7894:     # Create the identifier for the graph
                   7895:     my $identifier = &get_cgi_id();
                   7896:     my $id = 'cgi.'.$identifier;
                   7897:     #
                   7898:     $Title  = '' if (! defined($Title));
                   7899:     $xlabel = '' if (! defined($xlabel));
                   7900:     $ylabel = '' if (! defined($ylabel));
                   7901:     my %ValuesHash = 
                   7902:         (
1.369     www      7903:          $id.'.title'  => &escape($Title),
                   7904:          $id.'.xlabel' => &escape($xlabel),
                   7905:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  7906:          $id.'.y_max_value'=> $Max,
                   7907:          $id.'.labels'     => join(',',@$Xlabels),
                   7908:          $id.'.PlotType'   => 'XY',
                   7909:          );
                   7910:     #
                   7911:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   7912:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   7913:     }
                   7914:     #
                   7915:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   7916:         return '';
                   7917:     }
                   7918:     my $NumSets=1;
1.138     matthew  7919:     foreach my $array (@{$Ydata}){
1.137     matthew  7920:         next if (! ref($array));
                   7921:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   7922:     }
1.138     matthew  7923:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  7924:     #
                   7925:     # Deal with other parameters
                   7926:     while (my ($key,$value) = each(%Values)) {
                   7927:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  7928:     }
                   7929:     #
1.646     raeburn  7930:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  7931:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   7932: }
                   7933: 
                   7934: ############################################################
                   7935: ############################################################
                   7936: 
                   7937: =pod
                   7938: 
1.648     raeburn  7939: =item * &DrawXYYGraph()
1.138     matthew  7940: 
                   7941: Facilitates the plotting of data in an XY graph with two Y axes.
                   7942: Puts plot definition data into the users environment in order for 
                   7943: graph.png to plot it.  Returns an <img> tag for the plot.
                   7944: 
                   7945: Inputs:
                   7946: 
                   7947: =over 4
                   7948: 
                   7949: =item $Title: string, the title of the plot
                   7950: 
                   7951: =item $xlabel: string, text describing the X-axis of the plot
                   7952: 
                   7953: =item $ylabel: string, text describing the Y-axis of the plot
                   7954: 
                   7955: =item $colors: Array ref containing the hex color codes for the data to be 
                   7956: plotted in.  If undefined, default values will be used.
                   7957: 
                   7958: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   7959: 
                   7960: =item $Ydata1: The first data set
                   7961: 
                   7962: =item $Min1: The minimum value of the left Y-axis
                   7963: 
                   7964: =item $Max1: The maximum value of the left Y-axis
                   7965: 
                   7966: =item $Ydata2: The second data set
                   7967: 
                   7968: =item $Min2: The minimum value of the right Y-axis
                   7969: 
                   7970: =item $Max2: The maximum value of the left Y-axis
                   7971: 
                   7972: =item %Values: hash indicating or overriding any default values which are 
                   7973: passed to graph.png.  
                   7974: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   7975: 
                   7976: =back
                   7977: 
                   7978: Returns:
                   7979: 
                   7980: An <img> tag which references graph.png and the appropriate identifying
                   7981: information for the plot.
1.136     matthew  7982: 
                   7983: =cut
                   7984: 
                   7985: ############################################################
                   7986: ############################################################
1.137     matthew  7987: sub DrawXYYGraph {
                   7988:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   7989:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  7990:     #
                   7991:     # Create the identifier for the graph
                   7992:     my $identifier = &get_cgi_id();
                   7993:     my $id = 'cgi.'.$identifier;
                   7994:     #
                   7995:     $Title  = '' if (! defined($Title));
                   7996:     $xlabel = '' if (! defined($xlabel));
                   7997:     $ylabel = '' if (! defined($ylabel));
                   7998:     my %ValuesHash = 
                   7999:         (
1.369     www      8000:          $id.'.title'  => &escape($Title),
                   8001:          $id.'.xlabel' => &escape($xlabel),
                   8002:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  8003:          $id.'.labels' => join(',',@$Xlabels),
                   8004:          $id.'.PlotType' => 'XY',
                   8005:          $id.'.NumSets' => 2,
1.137     matthew  8006:          $id.'.two_axes' => 1,
                   8007:          $id.'.y1_max_value' => $Max1,
                   8008:          $id.'.y1_min_value' => $Min1,
                   8009:          $id.'.y2_max_value' => $Max2,
                   8010:          $id.'.y2_min_value' => $Min2,
1.136     matthew  8011:          );
                   8012:     #
1.137     matthew  8013:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   8014:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   8015:     }
                   8016:     #
                   8017:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   8018:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  8019:         return '';
                   8020:     }
                   8021:     my $NumSets=1;
1.137     matthew  8022:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  8023:         next if (! ref($array));
                   8024:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  8025:     }
                   8026:     #
                   8027:     # Deal with other parameters
                   8028:     while (my ($key,$value) = each(%Values)) {
                   8029:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  8030:     }
                   8031:     #
1.646     raeburn  8032:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 8033:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  8034: }
                   8035: 
                   8036: ############################################################
                   8037: ############################################################
                   8038: 
                   8039: =pod
                   8040: 
1.157     matthew  8041: =back 
                   8042: 
1.139     matthew  8043: =head1 Statistics helper routines?  
                   8044: 
                   8045: Bad place for them but what the hell.
                   8046: 
1.157     matthew  8047: =over 4
                   8048: 
1.648     raeburn  8049: =item * &chartlink()
1.139     matthew  8050: 
                   8051: Returns a link to the chart for a specific student.  
                   8052: 
                   8053: Inputs:
                   8054: 
                   8055: =over 4
                   8056: 
                   8057: =item $linktext: The text of the link
                   8058: 
                   8059: =item $sname: The students username
                   8060: 
                   8061: =item $sdomain: The students domain
                   8062: 
                   8063: =back
                   8064: 
1.157     matthew  8065: =back
                   8066: 
1.139     matthew  8067: =cut
                   8068: 
                   8069: ############################################################
                   8070: ############################################################
                   8071: sub chartlink {
                   8072:     my ($linktext, $sname, $sdomain) = @_;
                   8073:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      8074:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 8075:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  8076:        '">'.$linktext.'</a>';
1.153     matthew  8077: }
                   8078: 
                   8079: #######################################################
                   8080: #######################################################
                   8081: 
                   8082: =pod
                   8083: 
                   8084: =head1 Course Environment Routines
1.157     matthew  8085: 
                   8086: =over 4
1.153     matthew  8087: 
1.648     raeburn  8088: =item * &restore_course_settings()
1.153     matthew  8089: 
1.648     raeburn  8090: =item * &store_course_settings()
1.153     matthew  8091: 
                   8092: Restores/Store indicated form parameters from the course environment.
                   8093: Will not overwrite existing values of the form parameters.
                   8094: 
                   8095: Inputs: 
                   8096: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   8097: 
                   8098: a hash ref describing the data to be stored.  For example:
                   8099:    
                   8100: %Save_Parameters = ('Status' => 'scalar',
                   8101:     'chartoutputmode' => 'scalar',
                   8102:     'chartoutputdata' => 'scalar',
                   8103:     'Section' => 'array',
1.373     raeburn  8104:     'Group' => 'array',
1.153     matthew  8105:     'StudentData' => 'array',
                   8106:     'Maps' => 'array');
                   8107: 
                   8108: Returns: both routines return nothing
                   8109: 
1.631     raeburn  8110: =back
                   8111: 
1.153     matthew  8112: =cut
                   8113: 
                   8114: #######################################################
                   8115: #######################################################
                   8116: sub store_course_settings {
1.496     albertel 8117:     return &store_settings($env{'request.course.id'},@_);
                   8118: }
                   8119: 
                   8120: sub store_settings {
1.153     matthew  8121:     # save to the environment
                   8122:     # appenv the same items, just to be safe
1.300     albertel 8123:     my $udom  = $env{'user.domain'};
                   8124:     my $uname = $env{'user.name'};
1.496     albertel 8125:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  8126:     my %SaveHash;
                   8127:     my %AppHash;
                   8128:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 8129:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 8130:         my $envname = 'environment.'.$basename;
1.258     albertel 8131:         if (exists($env{'form.'.$setting})) {
1.153     matthew  8132:             # Save this value away
                   8133:             if ($type eq 'scalar' &&
1.258     albertel 8134:                 (! exists($env{$envname}) || 
                   8135:                  $env{$envname} ne $env{'form.'.$setting})) {
                   8136:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   8137:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  8138:             } elsif ($type eq 'array') {
                   8139:                 my $stored_form;
1.258     albertel 8140:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  8141:                     $stored_form = join(',',
                   8142:                                         map {
1.369     www      8143:                                             &escape($_);
1.258     albertel 8144:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  8145:                 } else {
                   8146:                     $stored_form = 
1.369     www      8147:                         &escape($env{'form.'.$setting});
1.153     matthew  8148:                 }
                   8149:                 # Determine if the array contents are the same.
1.258     albertel 8150:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  8151:                     $SaveHash{$basename} = $stored_form;
                   8152:                     $AppHash{$envname}   = $stored_form;
                   8153:                 }
                   8154:             }
                   8155:         }
                   8156:     }
                   8157:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 8158:                                           $udom,$uname);
1.153     matthew  8159:     if ($put_result !~ /^(ok|delayed)/) {
                   8160:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   8161:                                  'got error:'.$put_result);
                   8162:     }
                   8163:     # Make sure these settings stick around in this session, too
1.646     raeburn  8164:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  8165:     return;
                   8166: }
                   8167: 
                   8168: sub restore_course_settings {
1.499     albertel 8169:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 8170: }
                   8171: 
                   8172: sub restore_settings {
                   8173:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  8174:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 8175:         next if (exists($env{'form.'.$setting}));
1.496     albertel 8176:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  8177:             '.'.$setting;
1.258     albertel 8178:         if (exists($env{$envname})) {
1.153     matthew  8179:             if ($type eq 'scalar') {
1.258     albertel 8180:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  8181:             } elsif ($type eq 'array') {
1.258     albertel 8182:                 $env{'form.'.$setting} = [ 
1.153     matthew  8183:                                            map { 
1.369     www      8184:                                                &unescape($_); 
1.258     albertel 8185:                                            } split(',',$env{$envname})
1.153     matthew  8186:                                            ];
                   8187:             }
                   8188:         }
                   8189:     }
1.127     matthew  8190: }
                   8191: 
1.618     raeburn  8192: #######################################################
                   8193: #######################################################
                   8194: 
                   8195: =pod
                   8196: 
                   8197: =head1 Domain E-mail Routines  
                   8198: 
                   8199: =over 4
                   8200: 
1.648     raeburn  8201: =item * &build_recipient_list()
1.618     raeburn  8202: 
                   8203: Build recipient lists for three types of e-mail:
                   8204: (a) Error Reports, (b) Package Updates, (c) Help requests, generated by
1.619     raeburn  8205: lonerrorhandler.pm, CHECKRPMS and lonsupportreq.pm respectively.
1.618     raeburn  8206: 
                   8207: Inputs:
1.619     raeburn  8208: defmail (scalar - email address of default recipient), 
1.618     raeburn  8209: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
1.619     raeburn  8210: defdom (domain for which to retrieve configuration settings),
                   8211: origmail (scalar - email address of recipient from loncapa.conf, 
                   8212: i.e., predates configuration by DC via domainprefs.pm 
1.618     raeburn  8213: 
1.655     raeburn  8214: Returns: comma separated list of addresses to which to send e-mail.
                   8215: 
                   8216: =back
1.618     raeburn  8217: 
                   8218: =cut
                   8219: 
                   8220: ############################################################
                   8221: ############################################################
                   8222: sub build_recipient_list {
1.619     raeburn  8223:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  8224:     my @recipients;
                   8225:     my $otheremails;
                   8226:     my %domconfig =
                   8227:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
                   8228:     if (ref($domconfig{'contacts'}) eq 'HASH') {
                   8229:         if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   8230:             my @contacts = ('adminemail','supportemail');
                   8231:             foreach my $item (@contacts) {
                   8232:                 if ($domconfig{'contacts'}{$mailing}{$item}) {
1.619     raeburn  8233:                     my $addr = $domconfig{'contacts'}{$item}; 
                   8234:                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   8235:                         push(@recipients,$addr);
                   8236:                     }
1.618     raeburn  8237:                 }
                   8238:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   8239:             }
                   8240:         }
1.619     raeburn  8241:     } elsif ($origmail ne '') {
                   8242:         push(@recipients,$origmail);
1.618     raeburn  8243:     }
                   8244:     if ($defmail ne '') {
                   8245:         push(@recipients,$defmail);
                   8246:     }
                   8247:     if ($otheremails) {
1.619     raeburn  8248:         my @others;
                   8249:         if ($otheremails =~ /,/) {
                   8250:             @others = split(/,/,$otheremails);
1.618     raeburn  8251:         } else {
1.619     raeburn  8252:             push(@others,$otheremails);
                   8253:         }
                   8254:         foreach my $addr (@others) {
                   8255:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   8256:                 push(@recipients,$addr);
                   8257:             }
1.618     raeburn  8258:         }
                   8259:     }
1.619     raeburn  8260:     my $recipientlist = join(',',@recipients); 
1.618     raeburn  8261:     return $recipientlist;
                   8262: }
                   8263: 
1.127     matthew  8264: ############################################################
                   8265: ############################################################
1.154     albertel 8266: 
1.655     raeburn  8267: =pod
                   8268: 
                   8269: =head1 Course Catalog Routines
                   8270: 
                   8271: =over 4
                   8272: 
                   8273: =item * &gather_categories()
                   8274: 
                   8275: Converts category definitions - keys of categories hash stored in  
                   8276: coursecategories in configuration.db on the primary library server in a 
                   8277: domain - to an array.  Also generates javascript and idx hash used to 
                   8278: generate Domain Coordinator interface for editing Course Categories.
                   8279: 
                   8280: Inputs:
1.663     raeburn  8281: 
1.655     raeburn  8282: categories (reference to hash of category definitions).
1.663     raeburn  8283: 
1.655     raeburn  8284: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   8285:       categories and subcategories).
1.663     raeburn  8286: 
1.655     raeburn  8287: idx (reference to hash of counters used in Domain Coordinator interface for 
                   8288:       editing Course Categories).
1.663     raeburn  8289: 
1.655     raeburn  8290: jsarray (reference to array of categories used to create Javascript arrays for
                   8291:          Domain Coordinator interface for editing Course Categories).
                   8292: 
                   8293: Returns: nothing
                   8294: 
                   8295: Side effects: populates cats, idx and jsarray. 
                   8296: 
                   8297: =cut
                   8298: 
                   8299: sub gather_categories {
                   8300:     my ($categories,$cats,$idx,$jsarray) = @_;
                   8301:     my %counters;
                   8302:     my $num = 0;
                   8303:     foreach my $item (keys(%{$categories})) {
                   8304:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   8305:         if ($container eq '' && $depth == 0) {
                   8306:             $cats->[$depth][$categories->{$item}] = $cat;
                   8307:         } else {
                   8308:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   8309:         }
                   8310:         my ($escitem,$tail) = split(/:/,$item,2);
                   8311:         if ($counters{$tail} eq '') {
                   8312:             $counters{$tail} = $num;
                   8313:             $num ++;
                   8314:         }
                   8315:         if (ref($idx) eq 'HASH') {
                   8316:             $idx->{$item} = $counters{$tail};
                   8317:         }
                   8318:         if (ref($jsarray) eq 'ARRAY') {
                   8319:             push(@{$jsarray->[$counters{$tail}]},$item);
                   8320:         }
                   8321:     }
                   8322:     return;
                   8323: }
                   8324: 
                   8325: =pod
                   8326: 
                   8327: =item * &extract_categories()
                   8328: 
                   8329: Used to generate breadcrumb trails for course categories.
                   8330: 
                   8331: Inputs:
1.663     raeburn  8332: 
1.655     raeburn  8333: categories (reference to hash of category definitions).
1.663     raeburn  8334: 
1.655     raeburn  8335: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   8336:       categories and subcategories).
1.663     raeburn  8337: 
1.655     raeburn  8338: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  8339: 
1.655     raeburn  8340: allitems (reference to hash - key is category key 
                   8341:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  8342: 
1.655     raeburn  8343: idx (reference to hash of counters used in Domain Coordinator interface for
                   8344:       editing Course Categories).
1.663     raeburn  8345: 
1.655     raeburn  8346: jsarray (reference to array of categories used to create Javascript arrays for
                   8347:          Domain Coordinator interface for editing Course Categories).
                   8348: 
1.665     raeburn  8349: subcats (reference to hash of arrays containing all subcategories within each 
                   8350:          category, -recursive)
                   8351: 
1.655     raeburn  8352: Returns: nothing
                   8353: 
                   8354: Side effects: populates trails and allitems hash references.
                   8355: 
                   8356: =cut
                   8357: 
                   8358: sub extract_categories {
1.665     raeburn  8359:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  8360:     if (ref($categories) eq 'HASH') {
                   8361:         &gather_categories($categories,$cats,$idx,$jsarray);
                   8362:         if (ref($cats->[0]) eq 'ARRAY') {
                   8363:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   8364:                 my $name = $cats->[0][$i];
                   8365:                 my $item = &escape($name).'::0';
                   8366:                 my $trailstr;
                   8367:                 if ($name eq 'instcode') {
                   8368:                     $trailstr = &mt('Official courses (with institutional codes)');
                   8369:                 } else {
                   8370:                     $trailstr = $name;
                   8371:                 }
                   8372:                 if ($allitems->{$item} eq '') {
                   8373:                     push(@{$trails},$trailstr);
                   8374:                     $allitems->{$item} = scalar(@{$trails})-1;
                   8375:                 }
                   8376:                 my @parents = ($name);
                   8377:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   8378:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   8379:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  8380:                         if (ref($subcats) eq 'HASH') {
                   8381:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   8382:                         }
                   8383:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   8384:                     }
                   8385:                 } else {
                   8386:                     if (ref($subcats) eq 'HASH') {
                   8387:                         $subcats->{$item} = [];
1.655     raeburn  8388:                     }
                   8389:                 }
                   8390:             }
                   8391:         }
                   8392:     }
                   8393:     return;
                   8394: }
                   8395: 
                   8396: =pod
                   8397: 
                   8398: =item *&recurse_categories()
                   8399: 
                   8400: Recursively used to generate breadcrumb trails for course categories.
                   8401: 
                   8402: Inputs:
1.663     raeburn  8403: 
1.655     raeburn  8404: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   8405:       categories and subcategories).
1.663     raeburn  8406: 
1.655     raeburn  8407: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  8408: 
                   8409: category (current course category, for which breadcrumb trail is being generated).
                   8410: 
                   8411: trails (reference to array of breadcrumb trails for each category).
                   8412: 
1.655     raeburn  8413: allitems (reference to hash - key is category key
                   8414:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  8415: 
1.655     raeburn  8416: parents (array containing containers directories for current category, 
                   8417:          back to top level). 
                   8418: 
                   8419: Returns: nothing
                   8420: 
                   8421: Side effects: populates trails and allitems hash references
                   8422: 
                   8423: =cut
                   8424: 
                   8425: sub recurse_categories {
1.665     raeburn  8426:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  8427:     my $shallower = $depth - 1;
                   8428:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   8429:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   8430:             my $name = $cats->[$depth]{$category}[$k];
                   8431:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   8432:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   8433:             if ($allitems->{$item} eq '') {
                   8434:                 push(@{$trails},$trailstr);
                   8435:                 $allitems->{$item} = scalar(@{$trails})-1;
                   8436:             }
                   8437:             my $deeper = $depth+1;
                   8438:             push(@{$parents},$category);
1.665     raeburn  8439:             if (ref($subcats) eq 'HASH') {
                   8440:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   8441:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   8442:                     my $higher;
                   8443:                     if ($j > 0) {
                   8444:                         $higher = &escape($parents->[$j]).':'.
                   8445:                                   &escape($parents->[$j-1]).':'.$j;
                   8446:                     } else {
                   8447:                         $higher = &escape($parents->[$j]).'::'.$j;
                   8448:                     }
                   8449:                     push(@{$subcats->{$higher}},$subcat);
                   8450:                 }
                   8451:             }
                   8452:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   8453:                                 $subcats);
1.655     raeburn  8454:             pop(@{$parents});
                   8455:         }
                   8456:     } else {
                   8457:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   8458:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   8459:         if ($allitems->{$item} eq '') {
                   8460:             push(@{$trails},$trailstr);
                   8461:             $allitems->{$item} = scalar(@{$trails})-1;
                   8462:         }
                   8463:     }
                   8464:     return;
                   8465: }
                   8466: 
1.663     raeburn  8467: =pod
                   8468: 
                   8469: =item *&assign_categories_table()
                   8470: 
                   8471: Create a datatable for display of hierarchical categories in a domain,
                   8472: with checkboxes to allow a course to be categorized. 
                   8473: 
                   8474: Inputs:
                   8475: 
                   8476: cathash - reference to hash of categories defined for the domain (from
                   8477:           configuration.db)
                   8478: 
                   8479: currcat - scalar with an & separated list of categories assigned to a course. 
                   8480: 
                   8481: Returns: $output (markup to be displayed) 
                   8482: 
                   8483: =cut
                   8484: 
                   8485: sub assign_categories_table {
                   8486:     my ($cathash,$currcat) = @_;
                   8487:     my $output;
                   8488:     if (ref($cathash) eq 'HASH') {
                   8489:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   8490:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   8491:         $maxdepth = scalar(@cats);
                   8492:         if (@cats > 0) {
                   8493:             my $itemcount = 0;
                   8494:             if (ref($cats[0]) eq 'ARRAY') {
                   8495:                 $output = &Apache::loncommon::start_data_table();
                   8496:                 my @currcategories;
                   8497:                 if ($currcat ne '') {
                   8498:                     @currcategories = split('&',$currcat);
                   8499:                 }
                   8500:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   8501:                     my $parent = $cats[0][$i];
                   8502:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   8503:                     next if ($parent eq 'instcode');
                   8504:                     my $item = &escape($parent).'::0';
                   8505:                     my $checked = '';
                   8506:                     if (@currcategories > 0) {
                   8507:                         if (grep(/^\Q$item\E$/,@currcategories)) {
                   8508:                             $checked = ' checked="checked" ';
                   8509:                         }
                   8510:                     }
                   8511:                     $output .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
                   8512:                                .'<input type="checkbox" name="usecategory" value="'.
1.670     raeburn  8513:                                $item.'"'.$checked.' />'.$parent.'</span></td>';
1.663     raeburn  8514:                     my $depth = 1;
                   8515:                     push(@path,$parent);
                   8516:                     $output .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
                   8517:                     pop(@path);
                   8518:                     $output .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
                   8519:                     $itemcount ++;
                   8520:                 }
                   8521:                 $output .= &Apache::loncommon::end_data_table();
                   8522:             }
                   8523:         }
                   8524:     }
                   8525:     return $output;
                   8526: }
                   8527: 
                   8528: =pod
                   8529: 
                   8530: =item *&assign_category_rows()
                   8531: 
                   8532: Create a datatable row for display of nested categories in a domain,
                   8533: with checkboxes to allow a course to be categorized,called recursively.
                   8534: 
                   8535: Inputs:
                   8536: 
                   8537: itemcount - track row number for alternating colors
                   8538: 
                   8539: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   8540:       categories and subcategories.
                   8541: 
                   8542: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   8543: 
                   8544: parent - parent of current category item
                   8545: 
                   8546: path - Array containing all categories back up through the hierarchy from the
                   8547:        current category to the top level.
                   8548: 
                   8549: currcategories - reference to array of current categories assigned to the course
                   8550: 
                   8551: Returns: $output (markup to be displayed).
                   8552: 
                   8553: =cut
                   8554: 
                   8555: sub assign_category_rows {
                   8556:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
                   8557:     my ($text,$name,$item,$chgstr);
                   8558:     if (ref($cats) eq 'ARRAY') {
                   8559:         my $maxdepth = scalar(@{$cats});
                   8560:         if (ref($cats->[$depth]) eq 'HASH') {
                   8561:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   8562:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   8563:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   8564:                 $text .= '<td><table class="LC_datatable">';
                   8565:                 for (my $j=0; $j<$numchildren; $j++) {
                   8566:                     $name = $cats->[$depth]{$parent}[$j];
                   8567:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   8568:                     my $deeper = $depth+1;
                   8569:                     my $checked = '';
                   8570:                     if (ref($currcategories) eq 'ARRAY') {
                   8571:                         if (@{$currcategories} > 0) {
                   8572:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
                   8573:                                 $checked = ' checked="checked" ';
                   8574:                             }
                   8575:                         }
                   8576:                     }
1.664     raeburn  8577:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   8578:                              '<input type="checkbox" name="usecategory" value="'.
                   8579:                              $item.'"'.$checked.' />'.$name.'</label></span></td><td>';
1.663     raeburn  8580:                     if (ref($path) eq 'ARRAY') {
                   8581:                         push(@{$path},$name);
                   8582:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
                   8583:                         pop(@{$path});
                   8584:                     }
                   8585:                     $text .= '</td></tr>';
                   8586:                 }
                   8587:                 $text .= '</table></td>';
                   8588:             }
                   8589:         }
                   8590:     }
                   8591:     return $text;
                   8592: }
                   8593: 
1.655     raeburn  8594: ############################################################
                   8595: ############################################################
                   8596: 
                   8597: 
1.443     albertel 8598: sub commit_customrole {
1.664     raeburn  8599:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  8600:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 8601:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   8602:                          ($end?', ending '.localtime($end):'').': <b>'.
                   8603:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  8604:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 8605:                  '</b><br />';
                   8606:     return $output;
                   8607: }
                   8608: 
                   8609: sub commit_standardrole {
1.541     raeburn  8610:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
                   8611:     my ($output,$logmsg,$linefeed);
                   8612:     if ($context eq 'auto') {
                   8613:         $linefeed = "\n";
                   8614:     } else {
                   8615:         $linefeed = "<br />\n";
                   8616:     }  
1.443     albertel 8617:     if ($three eq 'st') {
1.541     raeburn  8618:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
                   8619:                                          $one,$two,$sec,$context);
                   8620:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  8621:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   8622:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 8623:         } else {
1.541     raeburn  8624:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 8625:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  8626:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   8627:             if ($context eq 'auto') {
                   8628:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   8629:             } else {
                   8630:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   8631:                &mt('Add to classlist').': <b>ok</b>';
                   8632:             }
                   8633:             $output .= $linefeed;
1.443     albertel 8634:         }
                   8635:     } else {
                   8636:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   8637:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  8638:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  8639:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  8640:         if ($context eq 'auto') {
                   8641:             $output .= $result.$linefeed;
                   8642:         } else {
                   8643:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   8644:         }
1.443     albertel 8645:     }
                   8646:     return $output;
                   8647: }
                   8648: 
                   8649: sub commit_studentrole {
1.541     raeburn  8650:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
1.626     raeburn  8651:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  8652:     if ($context eq 'auto') {
                   8653:         $linefeed = "\n";
                   8654:     } else {
                   8655:         $linefeed = '<br />'."\n";
                   8656:     }
1.443     albertel 8657:     if (defined($one) && defined($two)) {
                   8658:         my $cid=$one.'_'.$two;
                   8659:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   8660:         my $secchange = 0;
                   8661:         my $expire_role_result;
                   8662:         my $modify_section_result;
1.628     raeburn  8663:         if ($oldsec ne '-1') { 
                   8664:             if ($oldsec ne $sec) {
1.443     albertel 8665:                 $secchange = 1;
1.628     raeburn  8666:                 my $now = time;
1.443     albertel 8667:                 my $uurl='/'.$cid;
                   8668:                 $uurl=~s/\_/\//g;
                   8669:                 if ($oldsec) {
                   8670:                     $uurl.='/'.$oldsec;
                   8671:                 }
1.626     raeburn  8672:                 $oldsecurl = $uurl;
1.628     raeburn  8673:                 $expire_role_result = 
1.652     raeburn  8674:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  8675:                 if ($env{'request.course.sec'} ne '') { 
                   8676:                     if ($expire_role_result eq 'refused') {
                   8677:                         my @roles = ('st');
                   8678:                         my @statuses = ('previous');
                   8679:                         my @roledoms = ($one);
                   8680:                         my $withsec = 1;
                   8681:                         my %roleshash = 
                   8682:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   8683:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   8684:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   8685:                             my ($oldstart,$oldend) = 
                   8686:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   8687:                             if ($oldend > 0 && $oldend <= $now) {
                   8688:                                 $expire_role_result = 'ok';
                   8689:                             }
                   8690:                         }
                   8691:                     }
                   8692:                 }
1.443     albertel 8693:                 $result = $expire_role_result;
                   8694:             }
                   8695:         }
                   8696:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.652     raeburn  8697:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
1.443     albertel 8698:             if ($modify_section_result =~ /^ok/) {
                   8699:                 if ($secchange == 1) {
1.628     raeburn  8700:                     if ($sec eq '') {
                   8701:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   8702:                     } else {
                   8703:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   8704:                     }
1.443     albertel 8705:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  8706:                     if ($sec eq '') {
                   8707:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   8708:                     } else {
                   8709:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   8710:                     }
1.443     albertel 8711:                 } else {
1.628     raeburn  8712:                     if ($sec eq '') {
                   8713:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   8714:                     } else {
                   8715:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   8716:                     }
1.443     albertel 8717:                 }
                   8718:             } else {
1.628     raeburn  8719:                 if ($secchange) {       
                   8720:                     $$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;
                   8721:                 } else {
                   8722:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   8723:                 }
1.443     albertel 8724:             }
                   8725:             $result = $modify_section_result;
                   8726:         } elsif ($secchange == 1) {
1.628     raeburn  8727:             if ($oldsec eq '') {
                   8728:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
                   8729:             } else {
                   8730:                 $$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;
                   8731:             }
1.626     raeburn  8732:             if ($expire_role_result eq 'refused') {
                   8733:                 my $newsecurl = '/'.$cid;
                   8734:                 $newsecurl =~ s/\_/\//g;
                   8735:                 if ($sec ne '') {
                   8736:                     $newsecurl.='/'.$sec;
                   8737:                 }
                   8738:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   8739:                     if ($sec eq '') {
                   8740:                         $$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;
                   8741:                     } else {
                   8742:                         $$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;
                   8743:                     }
                   8744:                 }
                   8745:             }
1.443     albertel 8746:         }
                   8747:     } else {
1.626     raeburn  8748:         $$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 8749:         $result = "error: incomplete course id\n";
                   8750:     }
                   8751:     return $result;
                   8752: }
                   8753: 
                   8754: ############################################################
                   8755: ############################################################
                   8756: 
1.566     albertel 8757: sub check_clone {
1.578     raeburn  8758:     my ($args,$linefeed) = @_;
1.566     albertel 8759:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   8760:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   8761:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   8762:     my $clonemsg;
                   8763:     my $can_clone = 0;
                   8764: 
                   8765:     if ($clonehome eq 'no_host') {
1.578     raeburn  8766:         $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 8767:     } else {
                   8768: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.568     albertel 8769: 	if ($env{'request.role.domain'} eq $args->{'clonedomain'}) {
1.566     albertel 8770: 	    $can_clone = 1;
                   8771: 	} else {
                   8772: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
                   8773: 						 $args->{'clonedomain'},$args->{'clonecourse'});
                   8774: 	    my @cloners = split(/,/,$clonehash{'cloners'});
1.578     raeburn  8775:             if (grep(/^\*$/,@cloners)) {
                   8776:                 $can_clone = 1;
                   8777:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   8778:                 $can_clone = 1;
                   8779:             } else {
                   8780: 	        my %roleshash =
                   8781: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   8782: 					 $args->{'ccdomain'},
                   8783:                                          'userroles',['active'],['cc'],
                   8784: 					 [$args->{'clonedomain'}]);
                   8785: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
                   8786: 		    $can_clone = 1;
                   8787: 	        } else {
                   8788:                     $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'});
                   8789: 	        }
1.566     albertel 8790: 	    }
1.578     raeburn  8791:         }
1.566     albertel 8792:     }
                   8793:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   8794: }
                   8795: 
1.444     albertel 8796: sub construct_course {
1.541     raeburn  8797:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context) = @_;
1.444     albertel 8798:     my $outcome;
1.541     raeburn  8799:     my $linefeed =  '<br />'."\n";
                   8800:     if ($context eq 'auto') {
                   8801:         $linefeed = "\n";
                   8802:     }
1.566     albertel 8803: 
                   8804: #
                   8805: # Are we cloning?
                   8806: #
                   8807:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   8808:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  8809: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 8810: 	if ($context ne 'auto') {
1.578     raeburn  8811:             if ($clonemsg ne '') {
                   8812: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   8813:             }
1.566     albertel 8814: 	}
                   8815: 	$outcome .= $clonemsg.$linefeed;
                   8816: 
                   8817:         if (!$can_clone) {
                   8818: 	    return (0,$outcome);
                   8819: 	}
                   8820:     }
                   8821: 
1.444     albertel 8822: #
                   8823: # Open course
                   8824: #
                   8825:     my $crstype = lc($args->{'crstype'});
                   8826:     my %cenv=();
                   8827:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   8828:                                              $args->{'cdescr'},
                   8829:                                              $args->{'curl'},
                   8830:                                              $args->{'course_home'},
                   8831:                                              $args->{'nonstandard'},
                   8832:                                              $args->{'crscode'},
                   8833:                                              $args->{'ccuname'}.':'.
                   8834:                                              $args->{'ccdomain'},
                   8835:                                              $args->{'crstype'});
                   8836: 
                   8837:     # Note: The testing routines depend on this being output; see 
                   8838:     # Utils::Course. This needs to at least be output as a comment
                   8839:     # if anyone ever decides to not show this, and Utils::Course::new
                   8840:     # will need to be suitably modified.
1.541     raeburn  8841:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.444     albertel 8842: #
                   8843: # Check if created correctly
                   8844: #
1.479     albertel 8845:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 8846:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.541     raeburn  8847:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 8848: 
1.444     albertel 8849: #
1.566     albertel 8850: # Do the cloning
                   8851: #   
                   8852:     if ($can_clone && $cloneid) {
                   8853: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   8854: 	if ($context ne 'auto') {
                   8855: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   8856: 	}
                   8857: 	$outcome .= $clonemsg.$linefeed;
                   8858: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 8859: # Copy all files
1.637     www      8860: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 8861: # Restore URL
1.566     albertel 8862: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 8863: # Restore title
1.566     albertel 8864: 	$cenv{'description'}=$oldcenv{'description'};
1.444     albertel 8865: # Mark as cloned
1.566     albertel 8866: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      8867: # Need to clone grading mode
                   8868:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   8869:         $cenv{'grading'}=$newenv{'grading'};
                   8870: # Do not clone these environment entries
                   8871:         &Apache::lonnet::del('environment',
                   8872:                   ['default_enrollment_start_date',
                   8873:                    'default_enrollment_end_date',
                   8874:                    'question.email',
                   8875:                    'policy.email',
                   8876:                    'comment.email',
                   8877:                    'pch.users.denied',
                   8878:                    'plc.users.denied'],
                   8879:                    $$crsudom,$$crsunum);
1.444     albertel 8880:     }
1.566     albertel 8881: 
1.444     albertel 8882: #
                   8883: # Set environment (will override cloned, if existing)
                   8884: #
                   8885:     my @sections = ();
                   8886:     my @xlists = ();
                   8887:     if ($args->{'crstype'}) {
                   8888:         $cenv{'type'}=$args->{'crstype'};
                   8889:     }
                   8890:     if ($args->{'crsid'}) {
                   8891:         $cenv{'courseid'}=$args->{'crsid'};
                   8892:     }
                   8893:     if ($args->{'crscode'}) {
                   8894:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   8895:     }
                   8896:     if ($args->{'crsquota'} ne '') {
                   8897:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   8898:     } else {
                   8899:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   8900:     }
                   8901:     if ($args->{'ccuname'}) {
                   8902:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   8903:                                         ':'.$args->{'ccdomain'};
                   8904:     } else {
                   8905:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   8906:     }
                   8907:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   8908:     if ($args->{'crssections'}) {
                   8909:         $cenv{'internal.sectionnums'} = '';
                   8910:         if ($args->{'crssections'} =~ m/,/) {
                   8911:             @sections = split/,/,$args->{'crssections'};
                   8912:         } else {
                   8913:             $sections[0] = $args->{'crssections'};
                   8914:         }
                   8915:         if (@sections > 0) {
                   8916:             foreach my $item (@sections) {
                   8917:                 my ($sec,$gp) = split/:/,$item;
                   8918:                 my $class = $args->{'crscode'}.$sec;
                   8919:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   8920:                 $cenv{'internal.sectionnums'} .= $item.',';
                   8921:                 unless ($addcheck eq 'ok') {
                   8922:                     push @badclasses, $class;
                   8923:                 }
                   8924:             }
                   8925:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   8926:         }
                   8927:     }
                   8928: # do not hide course coordinator from staff listing, 
                   8929: # even if privileged
                   8930:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   8931: # add crosslistings
                   8932:     if ($args->{'crsxlist'}) {
                   8933:         $cenv{'internal.crosslistings'}='';
                   8934:         if ($args->{'crsxlist'} =~ m/,/) {
                   8935:             @xlists = split/,/,$args->{'crsxlist'};
                   8936:         } else {
                   8937:             $xlists[0] = $args->{'crsxlist'};
                   8938:         }
                   8939:         if (@xlists > 0) {
                   8940:             foreach my $item (@xlists) {
                   8941:                 my ($xl,$gp) = split/:/,$item;
                   8942:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   8943:                 $cenv{'internal.crosslistings'} .= $item.',';
                   8944:                 unless ($addcheck eq 'ok') {
                   8945:                     push @badclasses, $xl;
                   8946:                 }
                   8947:             }
                   8948:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   8949:         }
                   8950:     }
                   8951:     if ($args->{'autoadds'}) {
                   8952:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   8953:     }
                   8954:     if ($args->{'autodrops'}) {
                   8955:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   8956:     }
                   8957: # check for notification of enrollment changes
                   8958:     my @notified = ();
                   8959:     if ($args->{'notify_owner'}) {
                   8960:         if ($args->{'ccuname'} ne '') {
                   8961:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   8962:         }
                   8963:     }
                   8964:     if ($args->{'notify_dc'}) {
                   8965:         if ($uname ne '') { 
1.630     raeburn  8966:             push(@notified,$uname.':'.$udom);
1.444     albertel 8967:         }
                   8968:     }
                   8969:     if (@notified > 0) {
                   8970:         my $notifylist;
                   8971:         if (@notified > 1) {
                   8972:             $notifylist = join(',',@notified);
                   8973:         } else {
                   8974:             $notifylist = $notified[0];
                   8975:         }
                   8976:         $cenv{'internal.notifylist'} = $notifylist;
                   8977:     }
                   8978:     if (@badclasses > 0) {
                   8979:         my %lt=&Apache::lonlocal::texthash(
                   8980:                 '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',
                   8981:                 'dnhr' => 'does not have rights to access enrollment in these classes',
                   8982:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
                   8983:         );
1.541     raeburn  8984:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
                   8985:                            ' ('.$lt{'adby'}.')';
                   8986:         if ($context eq 'auto') {
                   8987:             $outcome .= $badclass_msg.$linefeed;
1.566     albertel 8988:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.541     raeburn  8989:             foreach my $item (@badclasses) {
                   8990:                 if ($context eq 'auto') {
                   8991:                     $outcome .= " - $item\n";
                   8992:                 } else {
                   8993:                     $outcome .= "<li>$item</li>\n";
                   8994:                 }
                   8995:             }
                   8996:             if ($context eq 'auto') {
                   8997:                 $outcome .= $linefeed;
                   8998:             } else {
1.566     albertel 8999:                 $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  9000:             }
                   9001:         } 
1.444     albertel 9002:     }
                   9003:     if ($args->{'no_end_date'}) {
                   9004:         $args->{'endaccess'} = 0;
                   9005:     }
                   9006:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   9007:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   9008:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   9009:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   9010:     if ($args->{'showphotos'}) {
                   9011:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   9012:     }
                   9013:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   9014:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   9015:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   9016:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  9017:             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'); 
                   9018:             if ($context eq 'auto') {
                   9019:                 $outcome .= $krb_msg;
                   9020:             } else {
1.566     albertel 9021:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  9022:             }
                   9023:             $outcome .= $linefeed;
1.444     albertel 9024:         }
                   9025:     }
                   9026:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   9027:        if ($args->{'setpolicy'}) {
                   9028:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   9029:        }
                   9030:        if ($args->{'setcontent'}) {
                   9031:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   9032:        }
                   9033:     }
                   9034:     if ($args->{'reshome'}) {
                   9035: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   9036: 	$cenv{'reshome'}=~s/\/+$/\//;
                   9037:     }
                   9038: #
                   9039: # course has keyed access
                   9040: #
                   9041:     if ($args->{'setkeys'}) {
                   9042:        $cenv{'keyaccess'}='yes';
                   9043:     }
                   9044: # if specified, key authority is not course, but user
                   9045: # only active if keyaccess is yes
                   9046:     if ($args->{'keyauth'}) {
1.487     albertel 9047: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   9048: 	$user = &LONCAPA::clean_username($user);
                   9049: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     9050: 	if ($user ne '' && $domain ne '') {
1.487     albertel 9051: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 9052: 	}
                   9053:     }
                   9054: 
                   9055:     if ($args->{'disresdis'}) {
                   9056:         $cenv{'pch.roles.denied'}='st';
                   9057:     }
                   9058:     if ($args->{'disablechat'}) {
                   9059:         $cenv{'plc.roles.denied'}='st';
                   9060:     }
                   9061: 
                   9062:     # Record we've not yet viewed the Course Initialization Helper for this 
                   9063:     # course
                   9064:     $cenv{'course.helper.not.run'} = 1;
                   9065:     #
                   9066:     # Use new Randomseed
                   9067:     #
                   9068:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   9069:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   9070:     #
                   9071:     # The encryption code and receipt prefix for this course
                   9072:     #
                   9073:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   9074:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   9075:     #
                   9076:     # By default, use standard grading
                   9077:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   9078: 
1.541     raeburn  9079:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   9080:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 9081: #
                   9082: # Open all assignments
                   9083: #
                   9084:     if ($args->{'openall'}) {
                   9085:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   9086:        my %storecontent = ($storeunder         => time,
                   9087:                            $storeunder.'.type' => 'date_start');
                   9088:        
                   9089:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  9090:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 9091:    }
                   9092: #
                   9093: # Set first page
                   9094: #
                   9095:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   9096: 	    || ($cloneid)) {
1.445     albertel 9097: 	use LONCAPA::map;
1.444     albertel 9098: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 9099: 
                   9100: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   9101:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   9102: 
1.444     albertel 9103:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   9104:         my $title; my $url;
                   9105:         if ($args->{'firstres'} eq 'syl') {
                   9106: 	    $title='Syllabus';
                   9107:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   9108:         } else {
                   9109:             $title='Navigate Contents';
                   9110:             $url='/adm/navmaps';
                   9111:         }
1.445     albertel 9112: 
                   9113:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   9114: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   9115: 
                   9116: 	if ($errtext) { $fatal=2; }
1.541     raeburn  9117:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 9118:     }
1.566     albertel 9119: 
                   9120:     return (1,$outcome);
1.444     albertel 9121: }
                   9122: 
                   9123: ############################################################
                   9124: ############################################################
                   9125: 
1.378     raeburn  9126: sub course_type {
                   9127:     my ($cid) = @_;
                   9128:     if (!defined($cid)) {
                   9129:         $cid = $env{'request.course.id'};
                   9130:     }
1.404     albertel 9131:     if (defined($env{'course.'.$cid.'.type'})) {
                   9132:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  9133:     } else {
                   9134:         return 'Course';
1.377     raeburn  9135:     }
                   9136: }
1.156     albertel 9137: 
1.406     raeburn  9138: sub group_term {
                   9139:     my $crstype = &course_type();
                   9140:     my %names = (
                   9141:                   'Course' => 'group',
                   9142:                   'Group' => 'team',
                   9143:                 );
                   9144:     return $names{$crstype};
                   9145: }
                   9146: 
1.156     albertel 9147: sub icon {
                   9148:     my ($file)=@_;
1.505     albertel 9149:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 9150:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 9151:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 9152:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   9153: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   9154: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   9155: 	            $curfext.".gif") {
                   9156: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   9157: 		$curfext.".gif";
                   9158: 	}
                   9159:     }
1.249     albertel 9160:     return &lonhttpdurl($iconname);
1.154     albertel 9161: } 
1.84      albertel 9162: 
1.575     albertel 9163: sub lonhttpd_port {
1.215     albertel 9164:     my $lonhttpd_port=$Apache::lonnet::perlvar{'lonhttpdPort'};
                   9165:     if (!defined($lonhttpd_port)) { $lonhttpd_port='8080'; }
1.574     albertel 9166:     # IE doesn't like a secure page getting images from a non-secure
                   9167:     # port (when logging we haven't parsed the browser type so default
                   9168:     # back to secure
                   9169:     if ((!exists($env{'browser.type'}) || $env{'browser.type'} eq 'explorer')
                   9170: 	&& $ENV{'SERVER_PORT'} == 443) {
1.575     albertel 9171: 	return 443;
                   9172:     }
                   9173:     return $lonhttpd_port;
                   9174: 
                   9175: }
                   9176: 
                   9177: sub lonhttpdurl {
                   9178:     my ($url)=@_;
                   9179: 
                   9180:     my $lonhttpd_port = &lonhttpd_port();
                   9181:     if ($lonhttpd_port == 443) {
1.574     albertel 9182: 	return 'https://'.$ENV{'SERVER_NAME'}.$url;
                   9183:     }
1.215     albertel 9184:     return 'http://'.$ENV{'SERVER_NAME'}.':'.$lonhttpd_port.$url;
                   9185: }
                   9186: 
1.213     albertel 9187: sub connection_aborted {
                   9188:     my ($r)=@_;
                   9189:     $r->print(" ");$r->rflush();
                   9190:     my $c = $r->connection;
                   9191:     return $c->aborted();
                   9192: }
                   9193: 
1.221     foxr     9194: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     9195: #    strings as 'strings'.
                   9196: sub escape_single {
1.221     foxr     9197:     my ($input) = @_;
1.223     albertel 9198:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     9199:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   9200:     return $input;
                   9201: }
1.223     albertel 9202: 
1.222     foxr     9203: #  Same as escape_single, but escape's "'s  This 
                   9204: #  can be used for  "strings"
                   9205: sub escape_double {
                   9206:     my ($input) = @_;
                   9207:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   9208:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   9209:     return $input;
                   9210: }
1.223     albertel 9211:  
1.222     foxr     9212: #   Escapes the last element of a full URL.
                   9213: sub escape_url {
                   9214:     my ($url)   = @_;
1.238     raeburn  9215:     my @urlslices = split(/\//, $url,-1);
1.369     www      9216:     my $lastitem = &escape(pop(@urlslices));
1.223     albertel 9217:     return join('/',@urlslices).'/'.$lastitem;
1.222     foxr     9218: }
1.462     albertel 9219: 
                   9220: # -------------------------------------------------------- Initliaze user login
                   9221: sub init_user_environment {
1.463     albertel 9222:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 9223:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   9224: 
                   9225:     my $public=($username eq 'public' && $domain eq 'public');
                   9226: 
                   9227: # See if old ID present, if so, remove
                   9228: 
                   9229:     my ($filename,$cookie,$userroles);
                   9230:     my $now=time;
                   9231: 
                   9232:     if ($public) {
                   9233: 	my $max_public=100;
                   9234: 	my $oldest;
                   9235: 	my $oldest_time=0;
                   9236: 	for(my $next=1;$next<=$max_public;$next++) {
                   9237: 	    if (-e $lonids."/publicuser_$next.id") {
                   9238: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   9239: 		if ($mtime<$oldest_time || !$oldest_time) {
                   9240: 		    $oldest_time=$mtime;
                   9241: 		    $oldest=$next;
                   9242: 		}
                   9243: 	    } else {
                   9244: 		$cookie="publicuser_$next";
                   9245: 		last;
                   9246: 	    }
                   9247: 	}
                   9248: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   9249:     } else {
1.463     albertel 9250: 	# if this isn't a robot, kill any existing non-robot sessions
                   9251: 	if (!$args->{'robot'}) {
                   9252: 	    opendir(DIR,$lonids);
                   9253: 	    while ($filename=readdir(DIR)) {
                   9254: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   9255: 		    unlink($lonids.'/'.$filename);
                   9256: 		}
1.462     albertel 9257: 	    }
1.463     albertel 9258: 	    closedir(DIR);
1.462     albertel 9259: 	}
                   9260: # Give them a new cookie
1.463     albertel 9261: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
                   9262: 		                   : $now);
                   9263: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 9264:     
                   9265: # Initialize roles
                   9266: 
                   9267: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
                   9268:     }
                   9269: # ------------------------------------ Check browser type and MathML capability
                   9270: 
                   9271:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
                   9272:         $clientunicode,$clientos) = &decode_user_agent($r);
                   9273: 
                   9274: # -------------------------------------- Any accessibility options to remember?
                   9275:     if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
                   9276: 	foreach my $option ('imagesuppress','appletsuppress',
                   9277: 			    'embedsuppress','fontenhance','blackwhite') {
                   9278: 	    if ($form->{$option} eq 'true') {
                   9279: 		&Apache::lonnet::put('environment',{$option => 'on'},
                   9280: 				     $domain,$username);
                   9281: 	    } else {
                   9282: 		&Apache::lonnet::del('environment',[$option],
                   9283: 				     $domain,$username);
                   9284: 	    }
                   9285: 	}
                   9286:     }
                   9287: # ------------------------------------------------------------- Get environment
                   9288: 
                   9289:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   9290:     my ($tmp) = keys(%userenv);
                   9291:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9292: 	# default remote control to off
                   9293: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
                   9294:     } else {
                   9295: 	undef(%userenv);
                   9296:     }
                   9297:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   9298: 	$form->{'interface'}=$userenv{'interface'};
                   9299:     }
                   9300:     $env{'environment.remote'}=$userenv{'remote'};
                   9301:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   9302: 
                   9303: # --------------- Do not trust query string to be put directly into environment
                   9304:     foreach my $option ('imagesuppress','appletsuppress',
                   9305: 			'embedsuppress','fontenhance','blackwhite',
                   9306: 			'interface','localpath','localres') {
                   9307: 	$form->{$option}=~s/[\n\r\=]//gs;
                   9308:     }
                   9309: # --------------------------------------------------------- Write first profile
                   9310: 
                   9311:     {
                   9312: 	my %initial_env = 
                   9313: 	    ("user.name"          => $username,
                   9314: 	     "user.domain"        => $domain,
                   9315: 	     "user.home"          => $authhost,
                   9316: 	     "browser.type"       => $clientbrowser,
                   9317: 	     "browser.version"    => $clientversion,
                   9318: 	     "browser.mathml"     => $clientmathml,
                   9319: 	     "browser.unicode"    => $clientunicode,
                   9320: 	     "browser.os"         => $clientos,
                   9321: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   9322: 	     "request.course.fn"  => '',
                   9323: 	     "request.course.uri" => '',
                   9324: 	     "request.course.sec" => '',
                   9325: 	     "request.role"       => 'cm',
                   9326: 	     "request.role.adv"   => $env{'user.adv'},
                   9327: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   9328: 
                   9329:         if ($form->{'localpath'}) {
                   9330: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   9331: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   9332:         }
                   9333: 	
                   9334: 	if ($public) {
                   9335: 	    $initial_env{"environment.remote"} = "off";
                   9336: 	}
                   9337: 	if ($form->{'interface'}) {
                   9338: 	    $form->{'interface'}=~s/\W//gs;
                   9339: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   9340: 	    $env{'browser.interface'}=$form->{'interface'};
                   9341: 	    foreach my $option ('imagesuppress','appletsuppress',
                   9342: 				'embedsuppress','fontenhance','blackwhite') {
                   9343: 		if (($form->{$option} eq 'true') ||
                   9344: 		    ($userenv{$option} eq 'on')) {
                   9345: 		    $initial_env{"browser.$option"} = "on";
                   9346: 		}
                   9347: 	    }
                   9348: 	}
                   9349: 
                   9350: 	$env{'user.environment'} = "$lonids/$cookie.id";
                   9351: 	
                   9352: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   9353: 		 &GDBM_WRCREAT(),0640)) {
                   9354: 	    &_add_to_env(\%disk_env,\%initial_env);
                   9355: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   9356: 	    &_add_to_env(\%disk_env,$userroles);
1.463     albertel 9357: 	    if (ref($args->{'extra_env'})) {
                   9358: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   9359: 	    }
1.462     albertel 9360: 	    untie(%disk_env);
                   9361: 	} else {
                   9362: 	    &Apache::lonnet::logthis("<font color=\"blue\">WARNING: ".
                   9363: 			   'Could not create environment storage in lonauth: '.$!.'</font>');
                   9364: 	    return 'error: '.$!;
                   9365: 	}
                   9366:     }
                   9367:     $env{'request.role'}='cm';
                   9368:     $env{'request.role.adv'}=$env{'user.adv'};
                   9369:     $env{'browser.type'}=$clientbrowser;
                   9370: 
                   9371:     return $cookie;
                   9372: 
                   9373: }
                   9374: 
                   9375: sub _add_to_env {
                   9376:     my ($idf,$env_data,$prefix) = @_;
                   9377:     while (my ($key,$value) = each(%$env_data)) {
                   9378: 	$idf->{$prefix.$key} = $value;
                   9379: 	$env{$prefix.$key}   = $value;
                   9380:     }
                   9381: }
                   9382: 
                   9383: 
1.41      ng       9384: =pod
                   9385: 
                   9386: =back
                   9387: 
1.112     bowersj2 9388: =cut
1.41      ng       9389: 
1.112     bowersj2 9390: 1;
                   9391: __END__;
1.41      ng       9392: 

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