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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1089  ! foxr        4: # $Id: loncommon.pm,v 1.1088 2012/08/06 11:09:10 foxr 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.685     tempelho   64: use Apache::lonnet();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.479     albertel   70: use LONCAPA qw(:DEFAULT :match);
1.657     raeburn    71: use DateTime::TimeZone;
1.687     raeburn    72: use DateTime::Locale::Catalog;
1.117     www        73: 
1.517     raeburn    74: # ---------------------------------------------- Designs
                     75: use vars qw(%defaultdesign);
                     76: 
1.22      www        77: my $readit;
                     78: 
1.517     raeburn    79: 
1.157     matthew    80: ##
                     81: ## Global Variables
                     82: ##
1.46      matthew    83: 
1.643     foxr       84: 
                     85: # ----------------------------------------------- SSI with retries:
                     86: #
                     87: 
                     88: =pod
                     89: 
1.648     raeburn    90: =head1 Server Side include with retries:
1.643     foxr       91: 
                     92: =over 4
                     93: 
1.648     raeburn    94: =item * &ssi_with_retries(resource,retries form)
1.643     foxr       95: 
                     96: Performs an ssi with some number of retries.  Retries continue either
                     97: until the result is ok or until the retry count supplied by the
                     98: caller is exhausted.  
                     99: 
                    100: Inputs:
1.648     raeburn   101: 
                    102: =over 4
                    103: 
1.643     foxr      104: resource   - Identifies the resource to insert.
1.648     raeburn   105: 
1.643     foxr      106: retries    - Count of the number of retries allowed.
1.648     raeburn   107: 
1.643     foxr      108: form       - Hash that identifies the rendering options.
                    109: 
1.648     raeburn   110: =back
                    111: 
                    112: Returns:
                    113: 
                    114: =over 4
                    115: 
1.643     foxr      116: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   117: 
1.643     foxr      118: response   - The response from the last attempt (which may or may not have been successful.
                    119: 
1.648     raeburn   120: =back
                    121: 
                    122: =back
                    123: 
1.643     foxr      124: =cut
                    125: 
                    126: sub ssi_with_retries {
                    127:     my ($resource, $retries, %form) = @_;
                    128: 
                    129: 
                    130:     my $ok = 0;			# True if we got a good response.
                    131:     my $content;
                    132:     my $response;
                    133: 
                    134:     # Try to get the ssi done. within the retries count:
                    135: 
                    136:     do {
                    137: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    138: 	$ok      = $response->is_success;
1.650     www       139:         if (!$ok) {
                    140:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    141:         }
1.643     foxr      142: 	$retries--;
                    143:     } while (!$ok && ($retries > 0));
                    144: 
                    145:     if (!$ok) {
                    146: 	$content = '';		# On error return an empty content.
                    147:     }
                    148:     return ($content, $response);
                    149: 
                    150: }
                    151: 
                    152: 
                    153: 
1.20      www       154: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  155: my %language;
1.124     www       156: my %supported_language;
1.1088    foxr      157: my %supported_codes;
1.1048    foxr      158: my %latex_language;		# For choosing hyphenation in <transl..>
                    159: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  160: my %cprtag;
1.192     taceyjo1  161: my %scprtag;
1.351     www       162: my %fe; my %fd; my %fm;
1.41      ng        163: my %category_extensions;
1.12      harris41  164: 
1.46      matthew   165: # ---------------------------------------------- Thesaurus variables
1.144     matthew   166: #
                    167: # %Keywords:
                    168: #      A hash used by &keyword to determine if a word is considered a keyword.
                    169: # $thesaurus_db_file 
                    170: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   171: 
                    172: my %Keywords;
                    173: my $thesaurus_db_file;
                    174: 
1.144     matthew   175: #
                    176: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    177: # thesaurus.tab, and filecategories.tab.
                    178: #
1.18      www       179: BEGIN {
1.46      matthew   180:     # Variable initialization
                    181:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    182:     #
1.22      www       183:     unless ($readit) {
1.12      harris41  184: # ------------------------------------------------------------------- languages
                    185:     {
1.158     raeburn   186:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    187:                                    '/language.tab';
                    188:         if ( open(my $fh,"<$langtabfile") ) {
1.356     albertel  189:             while (my $line = <$fh>) {
                    190:                 next if ($line=~/^\#/);
                    191:                 chomp($line);
1.1088    foxr      192:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   193:                 $language{$key}=$val.' - '.$enc;
                    194:                 if ($sup) {
                    195:                     $supported_language{$key}=$sup;
1.1088    foxr      196: 		    $supported_codes{$key}   = $code;
1.158     raeburn   197:                 }
1.1048    foxr      198: 		if ($latex) {
                    199: 		    $latex_language_bykey{$key} = $latex;
1.1088    foxr      200: 		    $latex_language{$code} = $latex;
1.1048    foxr      201: 		}
1.158     raeburn   202:             }
                    203:             close($fh);
                    204:         }
1.12      harris41  205:     }
                    206: # ------------------------------------------------------------------ copyrights
                    207:     {
1.158     raeburn   208:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    209:                                   '/copyright.tab';
                    210:         if ( open (my $fh,"<$copyrightfile") ) {
1.356     albertel  211:             while (my $line = <$fh>) {
                    212:                 next if ($line=~/^\#/);
                    213:                 chomp($line);
                    214:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   215:                 $cprtag{$key}=$val;
                    216:             }
                    217:             close($fh);
                    218:         }
1.12      harris41  219:     }
1.351     www       220: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  221:     {
                    222:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    223:                                   '/source_copyright.tab';
                    224:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
1.356     albertel  225:             while (my $line = <$fh>) {
                    226:                 next if ($line =~ /^\#/);
                    227:                 chomp($line);
                    228:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  229:                 $scprtag{$key}=$val;
                    230:             }
                    231:             close($fh);
                    232:         }
                    233:     }
1.63      www       234: 
1.517     raeburn   235: # -------------------------------------------------------------- default domain designs
1.63      www       236:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   237:     my $designfile = $designdir.'/default.tab';
                    238:     if ( open (my $fh,"<$designfile") ) {
                    239:         while (my $line = <$fh>) {
                    240:             next if ($line =~ /^\#/);
                    241:             chomp($line);
                    242:             my ($key,$val)=(split(/\=/,$line));
                    243:             if ($val) { $defaultdesign{$key}=$val; }
                    244:         }
                    245:         close($fh);
1.63      www       246:     }
                    247: 
1.15      harris41  248: # ------------------------------------------------------------- file categories
                    249:     {
1.158     raeburn   250:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    251:                                   '/filecategories.tab';
                    252:         if ( open (my $fh,"<$categoryfile") ) {
1.356     albertel  253: 	    while (my $line = <$fh>) {
                    254: 		next if ($line =~ /^\#/);
                    255: 		chomp($line);
                    256:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.158     raeburn   257:                 push @{$category_extensions{lc($category)}},$extension;
                    258:             }
                    259:             close($fh);
                    260:         }
                    261: 
1.15      harris41  262:     }
1.12      harris41  263: # ------------------------------------------------------------------ file types
                    264:     {
1.158     raeburn   265:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    266:                '/filetypes.tab';
                    267:         if ( open (my $fh,"<$typesfile") ) {
1.356     albertel  268:             while (my $line = <$fh>) {
                    269: 		next if ($line =~ /^\#/);
                    270: 		chomp($line);
                    271:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   272:                 if ($descr ne '') {
                    273:                     $fe{$ending}=lc($emb);
                    274:                     $fd{$ending}=$descr;
1.351     www       275:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   276:                 }
                    277:             }
                    278:             close($fh);
                    279:         }
1.12      harris41  280:     }
1.22      www       281:     &Apache::lonnet::logthis(
1.705     tempelho  282:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       283:     $readit=1;
1.46      matthew   284:     }  # end of unless($readit) 
1.32      matthew   285:     
                    286: }
1.112     bowersj2  287: 
1.42      matthew   288: ###############################################################
                    289: ##           HTML and Javascript Helper Functions            ##
                    290: ###############################################################
                    291: 
                    292: =pod 
                    293: 
1.112     bowersj2  294: =head1 HTML and Javascript Functions
1.42      matthew   295: 
1.112     bowersj2  296: =over 4
                    297: 
1.648     raeburn   298: =item * &browser_and_searcher_javascript()
1.112     bowersj2  299: 
                    300: X<browsing, javascript>X<searching, javascript>Returns a string
                    301: containing javascript with two functions, C<openbrowser> and
                    302: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    303: tags.
1.42      matthew   304: 
1.648     raeburn   305: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   306: 
                    307: inputs: formname, elementname, only, omit
                    308: 
                    309: formname and elementname indicate the name of the html form and name of
                    310: the element that the results of the browsing selection are to be placed in. 
                    311: 
                    312: Specifying 'only' will restrict the browser to displaying only files
1.185     www       313: with the given extension.  Can be a comma separated list.
1.42      matthew   314: 
                    315: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       316: with the given extension.  Can be a comma separated list.
1.42      matthew   317: 
1.648     raeburn   318: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   319: 
                    320: Inputs: formname, elementname
                    321: 
                    322: formname and elementname specify the name of the html form and the name
                    323: of the element the selection from the search results will be placed in.
1.542     raeburn   324: 
1.42      matthew   325: =cut
                    326: 
                    327: sub browser_and_searcher_javascript {
1.199     albertel  328:     my ($mode)=@_;
                    329:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  330:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   331:     return <<END;
1.219     albertel  332: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   333:     var editbrowser = null;
1.135     albertel  334:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       335:         var url = '$resurl/?';
1.42      matthew   336:         if (editbrowser == null) {
                    337:             url += 'launch=1&';
                    338:         }
                    339:         url += 'catalogmode=interactive&';
1.199     albertel  340:         url += 'mode=$mode&';
1.611     albertel  341:         url += 'inhibitmenu=yes&';
1.42      matthew   342:         url += 'form=' + formname + '&';
                    343:         if (only != null) {
                    344:             url += 'only=' + only + '&';
1.217     albertel  345:         } else {
                    346:             url += 'only=&';
                    347: 	}
1.42      matthew   348:         if (omit != null) {
                    349:             url += 'omit=' + omit + '&';
1.217     albertel  350:         } else {
                    351:             url += 'omit=&';
                    352: 	}
1.135     albertel  353:         if (titleelement != null) {
                    354:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  355:         } else {
                    356: 	    url += 'titleelement=&';
                    357: 	}
1.42      matthew   358:         url += 'element=' + elementname + '';
                    359:         var title = 'Browser';
1.435     albertel  360:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   361:         options += ',width=700,height=600';
                    362:         editbrowser = open(url,title,options,'1');
                    363:         editbrowser.focus();
                    364:     }
                    365:     var editsearcher;
1.135     albertel  366:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   367:         var url = '/adm/searchcat?';
                    368:         if (editsearcher == null) {
                    369:             url += 'launch=1&';
                    370:         }
                    371:         url += 'catalogmode=interactive&';
1.199     albertel  372:         url += 'mode=$mode&';
1.42      matthew   373:         url += 'form=' + formname + '&';
1.135     albertel  374:         if (titleelement != null) {
                    375:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  376:         } else {
                    377: 	    url += 'titleelement=&';
                    378: 	}
1.42      matthew   379:         url += 'element=' + elementname + '';
                    380:         var title = 'Search';
1.435     albertel  381:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   382:         options += ',width=700,height=600';
                    383:         editsearcher = open(url,title,options,'1');
                    384:         editsearcher.focus();
                    385:     }
1.219     albertel  386: // END LON-CAPA Internal -->
1.42      matthew   387: END
1.170     www       388: }
                    389: 
                    390: sub lastresurl {
1.258     albertel  391:     if ($env{'environment.lastresurl'}) {
                    392: 	return $env{'environment.lastresurl'}
1.170     www       393:     } else {
                    394: 	return '/res';
                    395:     }
                    396: }
                    397: 
                    398: sub storeresurl {
                    399:     my $resurl=&Apache::lonnet::clutter(shift);
                    400:     unless ($resurl=~/^\/res/) { return 0; }
                    401:     $resurl=~s/\/$//;
                    402:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   403:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       404:     return 1;
1.42      matthew   405: }
                    406: 
1.74      www       407: sub studentbrowser_javascript {
1.111     www       408:    unless (
1.258     albertel  409:             (($env{'request.course.id'}) && 
1.302     albertel  410:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    411: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    412: 					  '/'.$env{'request.course.sec'})
                    413: 	      ))
1.258     albertel  414:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       415:           ) { return ''; }  
1.74      www       416:    return (<<'ENDSTDBRW');
1.776     bisitz    417: <script type="text/javascript" language="Javascript">
1.824     bisitz    418: // <![CDATA[
1.74      www       419:     var stdeditbrowser;
1.999     www       420:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
1.74      www       421:         var url = '/adm/pickstudent?';
                    422:         var filter;
1.558     albertel  423: 	if (!ignorefilter) {
                    424: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    425: 	}
1.74      www       426:         if (filter != null) {
                    427:            if (filter != '') {
                    428:                url += 'filter='+filter+'&';
                    429: 	   }
                    430:         }
                    431:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       432:                                     '&udomelement='+udom+
                    433:                                     '&clicker='+clicker;
1.111     www       434: 	if (roleflag) { url+="&roles=1"; }
1.793     raeburn   435:         if (courseadvonly) { url+="&courseadvonly=1"; }
1.102     www       436:         var title = 'Student_Browser';
1.74      www       437:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    438:         options += ',width=700,height=600';
                    439:         stdeditbrowser = open(url,title,options,'1');
                    440:         stdeditbrowser.focus();
                    441:     }
1.824     bisitz    442: // ]]>
1.74      www       443: </script>
                    444: ENDSTDBRW
                    445: }
1.42      matthew   446: 
1.1003    www       447: sub resourcebrowser_javascript {
                    448:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       449:    return (<<'ENDRESBRW');
1.1003    www       450: <script type="text/javascript" language="Javascript">
                    451: // <![CDATA[
                    452:     var reseditbrowser;
1.1004    www       453:     function openresbrowser(formname,reslink) {
1.1005    www       454:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       455:         var title = 'Resource_Browser';
                    456:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       457:         options += ',width=700,height=500';
1.1004    www       458:         reseditbrowser = open(url,title,options,'1');
                    459:         reseditbrowser.focus();
1.1003    www       460:     }
                    461: // ]]>
                    462: </script>
1.1004    www       463: ENDRESBRW
1.1003    www       464: }
                    465: 
1.74      www       466: sub selectstudent_link {
1.999     www       467:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
                    468:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    469:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    470:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  471:    if ($env{'request.course.id'}) {  
1.302     albertel  472:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    473: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    474: 					'/'.$env{'request.course.sec'})) {
1.111     www       475: 	   return '';
                    476:        }
1.999     www       477:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.793     raeburn   478:        if ($courseadvonly)  {
                    479:            $callargs .= ",'',1,1";
                    480:        }
                    481:        return '<span class="LC_nobreak">'.
                    482:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    483:               &mt('Select User').'</a></span>';
1.74      www       484:    }
1.258     albertel  485:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       486:        $callargs .= ",'',1"; 
1.793     raeburn   487:        return '<span class="LC_nobreak">'.
                    488:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    489:               &mt('Select User').'</a></span>';
1.111     www       490:    }
                    491:    return '';
1.91      www       492: }
                    493: 
1.1004    www       494: sub selectresource_link {
                    495:    my ($form,$reslink,$arg)=@_;
                    496:    
                    497:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    498:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    499:    unless ($env{'request.course.id'}) { return $arg; }
                    500:    return '<span class="LC_nobreak">'.
                    501:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    502:               $arg.'</a></span>';
                    503: }
                    504: 
                    505: 
                    506: 
1.653     raeburn   507: sub authorbrowser_javascript {
                    508:     return <<"ENDAUTHORBRW";
1.776     bisitz    509: <script type="text/javascript" language="JavaScript">
1.824     bisitz    510: // <![CDATA[
1.653     raeburn   511: var stdeditbrowser;
                    512: 
                    513: function openauthorbrowser(formname,udom) {
                    514:     var url = '/adm/pickauthor?';
                    515:     url += 'form='+formname+'&roledom='+udom;
                    516:     var title = 'Author_Browser';
                    517:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    518:     options += ',width=700,height=600';
                    519:     stdeditbrowser = open(url,title,options,'1');
                    520:     stdeditbrowser.focus();
                    521: }
                    522: 
1.824     bisitz    523: // ]]>
1.653     raeburn   524: </script>
                    525: ENDAUTHORBRW
                    526: }
                    527: 
1.91      www       528: sub coursebrowser_javascript {
1.909     raeburn   529:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype) = @_;
1.932     raeburn   530:     my $wintitle = 'Course_Browser';
1.931     raeburn   531:     if ($crstype eq 'Community') {
1.932     raeburn   532:         $wintitle = 'Community_Browser';
1.909     raeburn   533:     }
1.876     raeburn   534:     my $id_functions = &javascript_index_functions();
                    535:     my $output = '
1.776     bisitz    536: <script type="text/javascript" language="JavaScript">
1.824     bisitz    537: // <![CDATA[
1.468     raeburn   538:     var stdeditbrowser;'."\n";
1.876     raeburn   539: 
                    540:     $output .= <<"ENDSTDBRW";
1.909     raeburn   541:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       542:         var url = '/adm/pickcourse?';
1.895     raeburn   543:         var formid = getFormIdByName(formname);
1.876     raeburn   544:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  545:         if (domainfilter != null) {
                    546:            if (domainfilter != '') {
                    547:                url += 'domainfilter='+domainfilter+'&';
                    548: 	   }
                    549:         }
1.91      www       550:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  551: 	                            '&cdomelement='+udom+
                    552:                                     '&cnameelement='+desc;
1.468     raeburn   553:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   554:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   555:                 url += '&roleelement='+extra_element;
                    556:                 if (domainfilter == null || domainfilter == '') {
                    557:                     url += '&domainfilter='+extra_element;
                    558:                 }
1.234     raeburn   559:             }
1.468     raeburn   560:             else {
                    561:                 if (formname == 'portform') {
                    562:                     url += '&setroles='+extra_element;
1.800     raeburn   563:                 } else {
                    564:                     if (formname == 'rules') {
                    565:                         url += '&fixeddom='+extra_element; 
                    566:                     }
1.468     raeburn   567:                 }
                    568:             }     
1.230     raeburn   569:         }
1.909     raeburn   570:         if (type != null && type != '') {
                    571:             url += '&type='+type;
                    572:         }
                    573:         if (type_elem != null && type_elem != '') {
                    574:             url += '&typeelement='+type_elem;
                    575:         }
1.872     raeburn   576:         if (formname == 'ccrs') {
                    577:             var ownername = document.forms[formid].ccuname.value;
                    578:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
                    579:             url += '&cloner='+ownername+':'+ownerdom;
                    580:         }
1.293     raeburn   581:         if (multflag !=null && multflag != '') {
                    582:             url += '&multiple='+multflag;
                    583:         }
1.909     raeburn   584:         var title = '$wintitle';
1.91      www       585:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    586:         options += ',width=700,height=600';
                    587:         stdeditbrowser = open(url,title,options,'1');
                    588:         stdeditbrowser.focus();
                    589:     }
1.876     raeburn   590: $id_functions
                    591: ENDSTDBRW
1.905     raeburn   592:     if (($sec_element ne '') || ($role_element ne '')) {
                    593:         $output .= &setsec_javascript($sec_element,$formname,$role_element);
1.876     raeburn   594:     }
                    595:     $output .= '
                    596: // ]]>
                    597: </script>';
                    598:     return $output;
                    599: }
                    600: 
                    601: sub javascript_index_functions {
                    602:     return <<"ENDJS";
                    603: 
                    604: function getFormIdByName(formname) {
                    605:     for (var i=0;i<document.forms.length;i++) {
                    606:         if (document.forms[i].name == formname) {
                    607:             return i;
                    608:         }
                    609:     }
                    610:     return -1;
                    611: }
                    612: 
                    613: function getIndexByName(formid,item) {
                    614:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    615:         if (document.forms[formid].elements[i].name == item) {
                    616:             return i;
                    617:         }
                    618:     }
                    619:     return -1;
                    620: }
1.468     raeburn   621: 
1.876     raeburn   622: function getDomainFromSelectbox(formname,udom) {
                    623:     var userdom;
                    624:     var formid = getFormIdByName(formname);
                    625:     if (formid > -1) {
                    626:         var domid = getIndexByName(formid,udom);
                    627:         if (domid > -1) {
                    628:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    629:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    630:             }
                    631:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    632:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   633:             }
                    634:         }
                    635:     }
1.876     raeburn   636:     return userdom;
                    637: }
                    638: 
                    639: ENDJS
1.468     raeburn   640: 
1.876     raeburn   641: }
                    642: 
1.1017    raeburn   643: sub javascript_array_indexof {
1.1018    raeburn   644:     return <<ENDJS;
1.1017    raeburn   645: <script type="text/javascript" language="JavaScript">
                    646: // <![CDATA[
                    647: 
                    648: if (!Array.prototype.indexOf) {
                    649:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    650:         "use strict";
                    651:         if (this === void 0 || this === null) {
                    652:             throw new TypeError();
                    653:         }
                    654:         var t = Object(this);
                    655:         var len = t.length >>> 0;
                    656:         if (len === 0) {
                    657:             return -1;
                    658:         }
                    659:         var n = 0;
                    660:         if (arguments.length > 0) {
                    661:             n = Number(arguments[1]);
1.1088    foxr      662:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   663:                 n = 0;
                    664:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    665:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    666:             }
                    667:         }
                    668:         if (n >= len) {
                    669:             return -1;
                    670:         }
                    671:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    672:         for (; k < len; k++) {
                    673:             if (k in t && t[k] === searchElement) {
                    674:                 return k;
                    675:             }
                    676:         }
                    677:         return -1;
                    678:     }
                    679: }
                    680: 
                    681: // ]]>
                    682: </script>
                    683: 
                    684: ENDJS
                    685: 
                    686: }
                    687: 
1.876     raeburn   688: sub userbrowser_javascript {
                    689:     my $id_functions = &javascript_index_functions();
                    690:     return <<"ENDUSERBRW";
                    691: 
1.888     raeburn   692: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   693:     var url = '/adm/pickuser?';
                    694:     var userdom = getDomainFromSelectbox(formname,udom);
                    695:     if (userdom != null) {
                    696:        if (userdom != '') {
                    697:            url += 'srchdom='+userdom+'&';
                    698:        }
                    699:     }
                    700:     url += 'form=' + formname + '&unameelement='+uname+
                    701:                                 '&udomelement='+udom+
                    702:                                 '&ulastelement='+ulast+
                    703:                                 '&ufirstelement='+ufirst+
                    704:                                 '&uemailelement='+uemail+
1.881     raeburn   705:                                 '&hideudomelement='+hideudom+
                    706:                                 '&coursedom='+crsdom;
1.888     raeburn   707:     if ((caller != null) && (caller != undefined)) {
                    708:         url += '&caller='+caller;
                    709:     }
1.876     raeburn   710:     var title = 'User_Browser';
                    711:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    712:     options += ',width=700,height=600';
                    713:     var stdeditbrowser = open(url,title,options,'1');
                    714:     stdeditbrowser.focus();
                    715: }
                    716: 
1.888     raeburn   717: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   718:     var formid = getFormIdByName(formname);
                    719:     if (formid > -1) {
1.888     raeburn   720:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   721:         var domid = getIndexByName(formid,udom);
                    722:         var hidedomid = getIndexByName(formid,origdom);
                    723:         if (hidedomid > -1) {
                    724:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   725:             var unameval = document.forms[formid].elements[unameid].value;
                    726:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    727:                 if (domid > -1) {
                    728:                     var slct = document.forms[formid].elements[domid];
                    729:                     if (slct.type == 'select-one') {
                    730:                         var i;
                    731:                         for (i=0;i<slct.length;i++) {
                    732:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    733:                         }
                    734:                     }
                    735:                     if (slct.type == 'hidden') {
                    736:                         slct.value = fixeddom;
1.876     raeburn   737:                     }
                    738:                 }
1.468     raeburn   739:             }
                    740:         }
                    741:     }
1.876     raeburn   742:     return;
                    743: }
                    744: 
                    745: $id_functions
                    746: ENDUSERBRW
1.468     raeburn   747: }
                    748: 
                    749: sub setsec_javascript {
1.905     raeburn   750:     my ($sec_element,$formname,$role_element) = @_;
                    751:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    752:         $communityrolestr);
                    753:     if ($role_element ne '') {
                    754:         my @allroles = ('st','ta','ep','in','ad');
                    755:         foreach my $crstype ('Course','Community') {
                    756:             if ($crstype eq 'Community') {
                    757:                 foreach my $role (@allroles) {
                    758:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    759:                 }
                    760:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    761:             } else {
                    762:                 foreach my $role (@allroles) {
                    763:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    764:                 }
                    765:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    766:             }
                    767:         }
                    768:         $rolestr = '"'.join('","',@allroles).'"';
                    769:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    770:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    771:     }
1.468     raeburn   772:     my $setsections = qq|
                    773: function setSect(sectionlist) {
1.629     raeburn   774:     var sectionsArray = new Array();
                    775:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    776:         sectionsArray = sectionlist.split(",");
                    777:     }
1.468     raeburn   778:     var numSections = sectionsArray.length;
                    779:     document.$formname.$sec_element.length = 0;
                    780:     if (numSections == 0) {
                    781:         document.$formname.$sec_element.multiple=false;
                    782:         document.$formname.$sec_element.size=1;
                    783:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    784:     } else {
                    785:         if (numSections == 1) {
                    786:             document.$formname.$sec_element.multiple=false;
                    787:             document.$formname.$sec_element.size=1;
                    788:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    789:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    790:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    791:         } else {
                    792:             for (var i=0; i<numSections; i++) {
                    793:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    794:             }
                    795:             document.$formname.$sec_element.multiple=true
                    796:             if (numSections < 3) {
                    797:                 document.$formname.$sec_element.size=numSections;
                    798:             } else {
                    799:                 document.$formname.$sec_element.size=3;
                    800:             }
                    801:             document.$formname.$sec_element.options[0].selected = false
                    802:         }
                    803:     }
1.91      www       804: }
1.905     raeburn   805: 
                    806: function setRole(crstype) {
1.468     raeburn   807: |;
1.905     raeburn   808:     if ($role_element eq '') {
                    809:         $setsections .= '    return;
                    810: }
                    811: ';
                    812:     } else {
                    813:         $setsections .= qq|
                    814:     var elementLength = document.$formname.$role_element.length;
                    815:     var allroles = Array($rolestr);
                    816:     var courserolenames = Array($courserolestr);
                    817:     var communityrolenames = Array($communityrolestr);
                    818:     if (elementLength != undefined) {
                    819:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    820:             if (crstype == 'Course') {
                    821:                 return;
                    822:             } else {
                    823:                 allroles[5] = 'co';
                    824:                 for (var i=0; i<6; i++) {
                    825:                     document.$formname.$role_element.options[i].value = allroles[i];
                    826:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    827:                 }
                    828:             }
                    829:         } else {
                    830:             if (crstype == 'Community') {
                    831:                 return;
                    832:             } else {
                    833:                 allroles[5] = 'cc';
                    834:                 for (var i=0; i<6; i++) {
                    835:                     document.$formname.$role_element.options[i].value = allroles[i];
                    836:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    837:                 }
                    838:             }
                    839:         }
                    840:     }
                    841:     return;
                    842: }
                    843: |;
                    844:     }
1.468     raeburn   845:     return $setsections;
                    846: }
                    847: 
1.91      www       848: sub selectcourse_link {
1.909     raeburn   849:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    850:        $typeelement) = @_;
                    851:    my $type = $selecttype;
1.871     raeburn   852:    my $linktext = &mt('Select Course');
                    853:    if ($selecttype eq 'Community') {
1.909     raeburn   854:        $linktext = &mt('Select Community');
1.906     raeburn   855:    } elsif ($selecttype eq 'Course/Community') {
                    856:        $linktext = &mt('Select Course/Community');
1.909     raeburn   857:        $type = '';
1.1019    raeburn   858:    } elsif ($selecttype eq 'Select') {
                    859:        $linktext = &mt('Select');
                    860:        $type = '';
1.871     raeburn   861:    }
1.787     bisitz    862:    return '<span class="LC_nobreak">'
                    863:          ."<a href='"
                    864:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    865:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   866:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   867:          ."'>".$linktext.'</a>'
1.787     bisitz    868:          .'</span>';
1.74      www       869: }
1.42      matthew   870: 
1.653     raeburn   871: sub selectauthor_link {
                    872:    my ($form,$udom)=@_;
                    873:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    874:           &mt('Select Author').'</a>';
                    875: }
                    876: 
1.876     raeburn   877: sub selectuser_link {
1.881     raeburn   878:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   879:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   880:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   881:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   882:            ');">'.$linktext.'</a>';
1.876     raeburn   883: }
                    884: 
1.273     raeburn   885: sub check_uncheck_jscript {
                    886:     my $jscript = <<"ENDSCRT";
                    887: function checkAll(field) {
                    888:     if (field.length > 0) {
                    889:         for (i = 0; i < field.length; i++) {
                    890:             field[i].checked = true ;
                    891:         }
                    892:     } else {
                    893:         field.checked = true
                    894:     }
                    895: }
                    896:  
                    897: function uncheckAll(field) {
                    898:     if (field.length > 0) {
                    899:         for (i = 0; i < field.length; i++) {
                    900:             field[i].checked = false ;
1.543     albertel  901:         }
                    902:     } else {
1.273     raeburn   903:         field.checked = false ;
                    904:     }
                    905: }
                    906: ENDSCRT
                    907:     return $jscript;
                    908: }
                    909: 
1.656     www       910: sub select_timezone {
1.659     raeburn   911:    my ($name,$selected,$onchange,$includeempty)=@_;
                    912:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    913:    if ($includeempty) {
                    914:        $output .= '<option value=""';
                    915:        if (($selected eq '') || ($selected eq 'local')) {
                    916:            $output .= ' selected="selected" ';
                    917:        }
                    918:        $output .= '> </option>';
                    919:    }
1.657     raeburn   920:    my @timezones = DateTime::TimeZone->all_names;
                    921:    foreach my $tzone (@timezones) {
                    922:        $output.= '<option value="'.$tzone.'"';
                    923:        if ($tzone eq $selected) {
                    924:            $output.=' selected="selected"';
                    925:        }
                    926:        $output.=">$tzone</option>\n";
1.656     www       927:    }
                    928:    $output.="</select>";
                    929:    return $output;
                    930: }
1.273     raeburn   931: 
1.687     raeburn   932: sub select_datelocale {
                    933:     my ($name,$selected,$onchange,$includeempty)=@_;
                    934:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    935:     if ($includeempty) {
                    936:         $output .= '<option value=""';
                    937:         if ($selected eq '') {
                    938:             $output .= ' selected="selected" ';
                    939:         }
                    940:         $output .= '> </option>';
                    941:     }
                    942:     my (@possibles,%locale_names);
                    943:     my @locales = DateTime::Locale::Catalog::Locales;
                    944:     foreach my $locale (@locales) {
                    945:         if (ref($locale) eq 'HASH') {
                    946:             my $id = $locale->{'id'};
                    947:             if ($id ne '') {
                    948:                 my $en_terr = $locale->{'en_territory'};
                    949:                 my $native_terr = $locale->{'native_territory'};
1.695     raeburn   950:                 my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   951:                 if (grep(/^en$/,@languages) || !@languages) {
                    952:                     if ($en_terr ne '') {
                    953:                         $locale_names{$id} = '('.$en_terr.')';
                    954:                     } elsif ($native_terr ne '') {
                    955:                         $locale_names{$id} = $native_terr;
                    956:                     }
                    957:                 } else {
                    958:                     if ($native_terr ne '') {
                    959:                         $locale_names{$id} = $native_terr.' ';
                    960:                     } elsif ($en_terr ne '') {
                    961:                         $locale_names{$id} = '('.$en_terr.')';
                    962:                     }
                    963:                 }
                    964:                 push (@possibles,$id);
                    965:             }
                    966:         }
                    967:     }
                    968:     foreach my $item (sort(@possibles)) {
                    969:         $output.= '<option value="'.$item.'"';
                    970:         if ($item eq $selected) {
                    971:             $output.=' selected="selected"';
                    972:         }
                    973:         $output.=">$item";
                    974:         if ($locale_names{$item} ne '') {
                    975:             $output.="  $locale_names{$item}</option>\n";
                    976:         }
                    977:         $output.="</option>\n";
                    978:     }
                    979:     $output.="</select>";
                    980:     return $output;
                    981: }
                    982: 
1.792     raeburn   983: sub select_language {
                    984:     my ($name,$selected,$includeempty) = @_;
                    985:     my %langchoices;
                    986:     if ($includeempty) {
                    987:         %langchoices = ('' => 'No language preference');
                    988:     }
                    989:     foreach my $id (&languageids()) {
                    990:         my $code = &supportedlanguagecode($id);
                    991:         if ($code) {
                    992:             $langchoices{$code} = &plainlanguagedescription($id);
                    993:         }
                    994:     }
1.970     raeburn   995:     return &select_form($selected,$name,\%langchoices);
1.792     raeburn   996: }
                    997: 
1.42      matthew   998: =pod
1.36      matthew   999: 
1.1088    foxr     1000: 
                   1001: =item * &list_languages()
                   1002: 
                   1003: Returns an array reference that is suitable for use in language prompters.
                   1004: Each array element is itself a two element array.  The first element
                   1005: is the language code.  The second element a descsriptiuon of the 
                   1006: language itself.  This is suitable for use in e.g.
                   1007: &Apache::edit::select_arg (once dereferenced that is).
                   1008: 
                   1009: =cut 
                   1010: 
                   1011: sub list_languages {
                   1012:     my @lang_choices;
                   1013: 
                   1014:     foreach my $id (&languageids()) {
                   1015: 	my $code = &supportedlanguagecode($id);
                   1016: 	if ($code) {
                   1017: 	    my $selector    = $supported_codes{$id};
                   1018: 	    my $description = &plainlanguagedescription($id);
                   1019: 	    push (@lang_choices, [$selector, $description]);
                   1020: 	}
                   1021:     }
                   1022:     return \@lang_choices;
                   1023: }
                   1024: 
                   1025: =pod
                   1026: 
1.648     raeburn  1027: =item * &linked_select_forms(...)
1.36      matthew  1028: 
                   1029: linked_select_forms returns a string containing a <script></script> block
                   1030: and html for two <select> menus.  The select menus will be linked in that
                   1031: changing the value of the first menu will result in new values being placed
                   1032: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1033: order unless a defined order is provided.
1.36      matthew  1034: 
                   1035: linked_select_forms takes the following ordered inputs:
                   1036: 
                   1037: =over 4
                   1038: 
1.112     bowersj2 1039: =item * $formname, the name of the <form> tag
1.36      matthew  1040: 
1.112     bowersj2 1041: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1042: 
1.112     bowersj2 1043: =item * $firstdefault, the default value for the first menu
1.36      matthew  1044: 
1.112     bowersj2 1045: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1046: 
1.112     bowersj2 1047: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1048: 
1.112     bowersj2 1049: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1050: 
1.609     raeburn  1051: =item * $menuorder, the order of values in the first menu
                   1052: 
1.41      ng       1053: =back 
                   1054: 
1.36      matthew  1055: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1056: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1057: values for the first select menu.  The text that coincides with the 
1.41      ng       1058: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1059: and text for the second menu are given in the hash pointed to by 
                   1060: $menu{$choice1}->{'select2'}.  
                   1061: 
1.112     bowersj2 1062:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1063:                        default => "B3",
                   1064:                        select2 => { 
                   1065:                            B1 => "Choice B1",
                   1066:                            B2 => "Choice B2",
                   1067:                            B3 => "Choice B3",
                   1068:                            B4 => "Choice B4"
1.609     raeburn  1069:                            },
                   1070:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1071:                    },
                   1072:                A2 => { text =>"Choice A2" ,
                   1073:                        default => "C2",
                   1074:                        select2 => { 
                   1075:                            C1 => "Choice C1",
                   1076:                            C2 => "Choice C2",
                   1077:                            C3 => "Choice C3"
1.609     raeburn  1078:                            },
                   1079:                        order => ['C2','C1','C3'],
1.112     bowersj2 1080:                    },
                   1081:                A3 => { text =>"Choice A3" ,
                   1082:                        default => "D6",
                   1083:                        select2 => { 
                   1084:                            D1 => "Choice D1",
                   1085:                            D2 => "Choice D2",
                   1086:                            D3 => "Choice D3",
                   1087:                            D4 => "Choice D4",
                   1088:                            D5 => "Choice D5",
                   1089:                            D6 => "Choice D6",
                   1090:                            D7 => "Choice D7"
1.609     raeburn  1091:                            },
                   1092:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1093:                    }
                   1094:                );
1.36      matthew  1095: 
                   1096: =cut
                   1097: 
                   1098: sub linked_select_forms {
                   1099:     my ($formname,
                   1100:         $middletext,
                   1101:         $firstdefault,
                   1102:         $firstselectname,
                   1103:         $secondselectname, 
1.609     raeburn  1104:         $hashref,
                   1105:         $menuorder,
1.36      matthew  1106:         ) = @_;
                   1107:     my $second = "document.$formname.$secondselectname";
                   1108:     my $first = "document.$formname.$firstselectname";
                   1109:     # output the javascript to do the changing
                   1110:     my $result = '';
1.776     bisitz   1111:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1112:     $result.="// <![CDATA[\n";
1.36      matthew  1113:     $result.="var select2data = new Object();\n";
                   1114:     $" = '","';
                   1115:     my $debug = '';
                   1116:     foreach my $s1 (sort(keys(%$hashref))) {
                   1117:         $result.="select2data.d_$s1 = new Object();\n";        
                   1118:         $result.="select2data.d_$s1.def = new String('".
                   1119:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1120:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1121:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1122:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1123:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1124:         }
1.36      matthew  1125:         $result.="\"@s2values\");\n";
                   1126:         $result.="select2data.d_$s1.texts = new Array(";        
                   1127:         my @s2texts;
                   1128:         foreach my $value (@s2values) {
                   1129:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
                   1130:         }
                   1131:         $result.="\"@s2texts\");\n";
                   1132:     }
                   1133:     $"=' ';
                   1134:     $result.= <<"END";
                   1135: 
                   1136: function select1_changed() {
                   1137:     // Determine new choice
                   1138:     var newvalue = "d_" + $first.value;
                   1139:     // update select2
                   1140:     var values     = select2data[newvalue].values;
                   1141:     var texts      = select2data[newvalue].texts;
                   1142:     var select2def = select2data[newvalue].def;
                   1143:     var i;
                   1144:     // out with the old
                   1145:     for (i = 0; i < $second.options.length; i++) {
                   1146:         $second.options[i] = null;
                   1147:     }
                   1148:     // in with the nuclear
                   1149:     for (i=0;i<values.length; i++) {
                   1150:         $second.options[i] = new Option(values[i]);
1.143     matthew  1151:         $second.options[i].value = values[i];
1.36      matthew  1152:         $second.options[i].text = texts[i];
                   1153:         if (values[i] == select2def) {
                   1154:             $second.options[i].selected = true;
                   1155:         }
                   1156:     }
                   1157: }
1.824     bisitz   1158: // ]]>
1.36      matthew  1159: </script>
                   1160: END
                   1161:     # output the initial values for the selection lists
                   1162:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
1.609     raeburn  1163:     my @order = sort(keys(%{$hashref}));
                   1164:     if (ref($menuorder) eq 'ARRAY') {
                   1165:         @order = @{$menuorder};
                   1166:     }
                   1167:     foreach my $value (@order) {
1.36      matthew  1168:         $result.="    <option value=\"$value\" ";
1.253     albertel 1169:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1170:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1171:     }
                   1172:     $result .= "</select>\n";
                   1173:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1174:     $result .= $middletext;
                   1175:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
                   1176:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1177:     
                   1178:     my @secondorder = sort(keys(%select2));
                   1179:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1180:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1181:     }
                   1182:     foreach my $value (@secondorder) {
1.36      matthew  1183:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1184:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1185:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1186:     }
                   1187:     $result .= "</select>\n";
                   1188:     #    return $debug;
                   1189:     return $result;
                   1190: }   #  end of sub linked_select_forms {
                   1191: 
1.45      matthew  1192: =pod
1.44      bowersj2 1193: 
1.973     raeburn  1194: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1195: 
1.112     bowersj2 1196: Returns a string corresponding to an HTML link to the given help
                   1197: $topic, where $topic corresponds to the name of a .tex file in
                   1198: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1199: spaces. 
                   1200: 
                   1201: $text will optionally be linked to the same topic, allowing you to
                   1202: link text in addition to the graphic. If you do not want to link
                   1203: text, but wish to specify one of the later parameters, pass an
                   1204: empty string. 
                   1205: 
                   1206: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1207: the link will not open a new window. If false, the link will open
                   1208: a new window using Javascript. (Default is false.) 
                   1209: 
                   1210: $width and $height are optional numerical parameters that will
                   1211: override the width and height of the popped up window, which may
1.973     raeburn  1212: be useful for certain help topics with big pictures included.
                   1213: 
                   1214: $imgid is the id of the img tag used for the help icon. This may be
                   1215: used in a javascript call to switch the image src.  See 
                   1216: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1217: 
                   1218: =cut
                   1219: 
                   1220: sub help_open_topic {
1.973     raeburn  1221:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1222:     $text = "" if (not defined $text);
1.44      bowersj2 1223:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1224:     $width = 500 if (not defined $width);
1.44      bowersj2 1225:     $height = 400 if (not defined $height);
                   1226:     my $filename = $topic;
                   1227:     $filename =~ s/ /_/g;
                   1228: 
1.48      bowersj2 1229:     my $template = "";
                   1230:     my $link;
1.572     banghart 1231:     
1.159     www      1232:     $topic=~s/\W/\_/g;
1.44      bowersj2 1233: 
1.572     banghart 1234:     if (!$stayOnPage) {
1.1033    www      1235: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1236:     } elsif ($stayOnPage eq 'popup') {
                   1237:         $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 1238:     } else {
1.48      bowersj2 1239: 	$link = "/adm/help/${filename}.hlp";
                   1240:     }
                   1241: 
                   1242:     # Add the text
1.755     neumanie 1243:     if ($text ne "") {	
1.763     bisitz   1244: 	$template.='<span class="LC_help_open_topic">'
                   1245:                   .'<a target="_top" href="'.$link.'">'
                   1246:                   .$text.'</a>';
1.48      bowersj2 1247:     }
                   1248: 
1.763     bisitz   1249:     # (Always) Add the graphic
1.179     matthew  1250:     my $title = &mt('Online Help');
1.667     raeburn  1251:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1252:     if ($imgid ne '') {
                   1253:         $imgid = ' id="'.$imgid.'"';
                   1254:     }
1.763     bisitz   1255:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1256:               .'<img src="'.$helpicon.'" border="0"'
                   1257:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1258:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1259:               .' /></a>';
                   1260:     if ($text ne "") {	
                   1261:         $template.='</span>';
                   1262:     }
1.44      bowersj2 1263:     return $template;
                   1264: 
1.106     bowersj2 1265: }
                   1266: 
                   1267: # This is a quicky function for Latex cheatsheet editing, since it 
                   1268: # appears in at least four places
                   1269: sub helpLatexCheatsheet {
1.1037    www      1270:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1271:     my $out;
1.106     bowersj2 1272:     my $addOther = '';
1.732     raeburn  1273:     if ($topic) {
1.1037    www      1274: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1275:     }
                   1276:     $out = '<span>' # Start cheatsheet
                   1277: 	  .$addOther
                   1278:           .'<span>'
1.1037    www      1279: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1280: 	  .'</span> <span>'
1.1037    www      1281: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1282: 	  .'</span>';
1.732     raeburn  1283:     unless ($not_author) {
1.763     bisitz   1284:         $out .= ' <span>'
1.1037    www      1285: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1.763     bisitz   1286: 	       .'</span>';
1.732     raeburn  1287:     }
1.763     bisitz   1288:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1289:     return $out;
1.172     www      1290: }
                   1291: 
1.430     albertel 1292: sub general_help {
                   1293:     my $helptopic='Student_Intro';
                   1294:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1295: 	$helptopic='Authoring_Intro';
1.907     raeburn  1296:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1297: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1298:     } elsif ($env{'request.role'}=~/^dc/) {
                   1299:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1300:     }
                   1301:     return $helptopic;
                   1302: }
                   1303: 
                   1304: sub update_help_link {
                   1305:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1306:     my $origurl = $ENV{'REQUEST_URI'};
                   1307:     $origurl=~s|^/~|/priv/|;
                   1308:     my $timestamp = time;
                   1309:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1310:         $$datum = &escape($$datum);
                   1311:     }
                   1312: 
                   1313:     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";
                   1314:     my $output .= <<"ENDOUTPUT";
                   1315: <script type="text/javascript">
1.824     bisitz   1316: // <![CDATA[
1.430     albertel 1317: banner_link = '$banner_link';
1.824     bisitz   1318: // ]]>
1.430     albertel 1319: </script>
                   1320: ENDOUTPUT
                   1321:     return $output;
                   1322: }
                   1323: 
                   1324: # now just updates the help link and generates a blue icon
1.193     raeburn  1325: sub help_open_menu {
1.430     albertel 1326:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1327: 	= @_;    
1.949     droeschl 1328:     $stayOnPage = 1;
1.430     albertel 1329:     my $output;
                   1330:     if ($component_help) {
                   1331: 	if (!$text) {
                   1332: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1333: 				       $width,$height);
                   1334: 	} else {
                   1335: 	    my $help_text;
                   1336: 	    $help_text=&unescape($topic);
                   1337: 	    $output='<table><tr><td>'.
                   1338: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1339: 				 $width,$height).'</td></tr></table>';
                   1340: 	}
                   1341:     }
                   1342:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1343:     return $output.$banner_link;
                   1344: }
                   1345: 
                   1346: sub top_nav_help {
                   1347:     my ($text) = @_;
1.436     albertel 1348:     $text = &mt($text);
1.949     droeschl 1349:     my $stay_on_page = 1;
                   1350: 
1.572     banghart 1351:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1.436     albertel 1352: 	                     : "javascript:helpMenu('open')";
1.572     banghart 1353:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1.436     albertel 1354: 
1.201     raeburn  1355:     my $title = &mt('Get help');
1.436     albertel 1356: 
                   1357:     return <<"END";
                   1358: $banner_link
                   1359:  <a href="$link" title="$title">$text</a>
                   1360: END
                   1361: }
                   1362: 
                   1363: sub help_menu_js {
                   1364:     my ($text) = @_;
1.949     droeschl 1365:     my $stayOnPage = 1;
1.436     albertel 1366:     my $width = 620;
                   1367:     my $height = 600;
1.430     albertel 1368:     my $helptopic=&general_help();
                   1369:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1370:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1371:     my $start_page =
                   1372:         &Apache::loncommon::start_page('Help Menu', undef,
                   1373: 				       {'frameset'    => 1,
                   1374: 					'js_ready'    => 1,
                   1375: 					'add_entries' => {
                   1376: 					    'border' => '0',
1.579     raeburn  1377: 					    'rows'   => "110,*",},});
1.331     albertel 1378:     my $end_page =
                   1379:         &Apache::loncommon::end_page({'frameset' => 1,
                   1380: 				      'js_ready' => 1,});
                   1381: 
1.436     albertel 1382:     my $template .= <<"ENDTEMPLATE";
                   1383: <script type="text/javascript">
1.877     bisitz   1384: // <![CDATA[
1.253     albertel 1385: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1386: var banner_link = '';
1.243     raeburn  1387: function helpMenu(target) {
                   1388:     var caller = this;
                   1389:     if (target == 'open') {
                   1390:         var newWindow = null;
                   1391:         try {
1.262     albertel 1392:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1393:         }
                   1394:         catch(error) {
                   1395:             writeHelp(caller);
                   1396:             return;
                   1397:         }
                   1398:         if (newWindow) {
                   1399:             caller = newWindow;
                   1400:         }
1.193     raeburn  1401:     }
1.243     raeburn  1402:     writeHelp(caller);
                   1403:     return;
                   1404: }
                   1405: function writeHelp(caller) {
1.1072    raeburn  1406:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" />\\n<frame name="bodyframe" src="$details_link" />\\n$end_page')
1.243     raeburn  1407:     caller.document.close()
                   1408:     caller.focus()
1.193     raeburn  1409: }
1.877     bisitz   1410: // END LON-CAPA Internal -->
1.253     albertel 1411: // ]]>
1.436     albertel 1412: </script>
1.193     raeburn  1413: ENDTEMPLATE
                   1414:     return $template;
                   1415: }
                   1416: 
1.172     www      1417: sub help_open_bug {
                   1418:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1419:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1420:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1421:     $text = "" if (not defined $text);
                   1422: 	$stayOnPage=1;
1.184     albertel 1423:     $width = 600 if (not defined $width);
                   1424:     $height = 600 if (not defined $height);
1.172     www      1425: 
                   1426:     $topic=~s/\W+/\+/g;
                   1427:     my $link='';
                   1428:     my $template='';
1.379     albertel 1429:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1430: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1431:     if (!$stayOnPage)
                   1432:     {
                   1433: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1434:     }
                   1435:     else
                   1436:     {
                   1437: 	$link = $url;
                   1438:     }
                   1439:     # Add the text
                   1440:     if ($text ne "")
                   1441:     {
                   1442: 	$template .= 
                   1443:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1444:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1445:     }
                   1446: 
                   1447:     # Add the graphic
1.179     matthew  1448:     my $title = &mt('Report a Bug');
1.215     albertel 1449:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1450:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1451:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1452: ENDTEMPLATE
                   1453:     if ($text ne '') { $template.='</td></tr></table>' };
                   1454:     return $template;
                   1455: 
                   1456: }
                   1457: 
                   1458: sub help_open_faq {
                   1459:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1460:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1461:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1462:     $text = "" if (not defined $text);
                   1463: 	$stayOnPage=1;
                   1464:     $width = 350 if (not defined $width);
                   1465:     $height = 400 if (not defined $height);
                   1466: 
                   1467:     $topic=~s/\W+/\+/g;
                   1468:     my $link='';
                   1469:     my $template='';
                   1470:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1471:     if (!$stayOnPage)
                   1472:     {
                   1473: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1474:     }
                   1475:     else
                   1476:     {
                   1477: 	$link = $url;
                   1478:     }
                   1479: 
                   1480:     # Add the text
                   1481:     if ($text ne "")
                   1482:     {
                   1483: 	$template .= 
1.173     www      1484:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1485:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1486:     }
                   1487: 
                   1488:     # Add the graphic
1.179     matthew  1489:     my $title = &mt('View the FAQ');
1.215     albertel 1490:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1491:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1492:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1493: ENDTEMPLATE
                   1494:     if ($text ne '') { $template.='</td></tr></table>' };
                   1495:     return $template;
                   1496: 
1.44      bowersj2 1497: }
1.37      matthew  1498: 
1.180     matthew  1499: ###############################################################
                   1500: ###############################################################
                   1501: 
1.45      matthew  1502: =pod
                   1503: 
1.648     raeburn  1504: =item * &change_content_javascript():
1.256     matthew  1505: 
                   1506: This and the next function allow you to create small sections of an
                   1507: otherwise static HTML page that you can update on the fly with
                   1508: Javascript, even in Netscape 4.
                   1509: 
                   1510: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1511: must be written to the HTML page once. It will prove the Javascript
                   1512: function "change(name, content)". Calling the change function with the
                   1513: name of the section 
                   1514: you want to update, matching the name passed to C<changable_area>, and
                   1515: the new content you want to put in there, will put the content into
                   1516: that area.
                   1517: 
                   1518: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1519: to contain room for the original contents. You need to "make space"
                   1520: for whatever changes you wish to make, and be B<sure> to check your
                   1521: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1522: it's adequate for updating a one-line status display, but little more.
                   1523: This script will set the space to 100% width, so you only need to
                   1524: worry about height in Netscape 4.
                   1525: 
                   1526: Modern browsers are much less limiting, and if you can commit to the
                   1527: user not using Netscape 4, this feature may be used freely with
                   1528: pretty much any HTML.
                   1529: 
                   1530: =cut
                   1531: 
                   1532: sub change_content_javascript {
                   1533:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1534:     if ($env{'browser.type'} eq 'netscape' &&
                   1535: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1536: 	return (<<NETSCAPE4);
                   1537: 	function change(name, content) {
                   1538: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1539: 	    doc.open();
                   1540: 	    doc.write(content);
                   1541: 	    doc.close();
                   1542: 	}
                   1543: NETSCAPE4
                   1544:     } else {
                   1545: 	# Otherwise, we need to use semi-standards-compliant code
                   1546: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1547: 	# is really scary, and every useful browser supports it
                   1548: 	return (<<DOMBASED);
                   1549: 	function change(name, content) {
                   1550: 	    element = document.getElementById(name);
                   1551: 	    element.innerHTML = content;
                   1552: 	}
                   1553: DOMBASED
                   1554:     }
                   1555: }
                   1556: 
                   1557: =pod
                   1558: 
1.648     raeburn  1559: =item * &changable_area($name,$origContent):
1.256     matthew  1560: 
                   1561: This provides a "changable area" that can be modified on the fly via
                   1562: the Javascript code provided in C<change_content_javascript>. $name is
                   1563: the name you will use to reference the area later; do not repeat the
                   1564: same name on a given HTML page more then once. $origContent is what
                   1565: the area will originally contain, which can be left blank.
                   1566: 
                   1567: =cut
                   1568: 
                   1569: sub changable_area {
                   1570:     my ($name, $origContent) = @_;
                   1571: 
1.258     albertel 1572:     if ($env{'browser.type'} eq 'netscape' &&
                   1573: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1574: 	# If this is netscape 4, we need to use the Layer tag
                   1575: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1576:     } else {
                   1577: 	return "<span id='$name'>$origContent</span>";
                   1578:     }
                   1579: }
                   1580: 
                   1581: =pod
                   1582: 
1.648     raeburn  1583: =item * &viewport_geometry_js 
1.590     raeburn  1584: 
                   1585: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1586: 
                   1587: =cut
                   1588: 
                   1589: 
                   1590: sub viewport_geometry_js { 
                   1591:     return <<"GEOMETRY";
                   1592: var Geometry = {};
                   1593: function init_geometry() {
                   1594:     if (Geometry.init) { return };
                   1595:     Geometry.init=1;
                   1596:     if (window.innerHeight) {
                   1597:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1598:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1599:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1600:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1601:     }
                   1602:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1603:         Geometry.getViewportHeight =
                   1604:             function() { return document.documentElement.clientHeight; };
                   1605:         Geometry.getViewportWidth =
                   1606:             function() { return document.documentElement.clientWidth; };
                   1607: 
                   1608:         Geometry.getHorizontalScroll =
                   1609:             function() { return document.documentElement.scrollLeft; };
                   1610:         Geometry.getVerticalScroll =
                   1611:             function() { return document.documentElement.scrollTop; };
                   1612:     }
                   1613:     else if (document.body.clientHeight) {
                   1614:         Geometry.getViewportHeight =
                   1615:             function() { return document.body.clientHeight; };
                   1616:         Geometry.getViewportWidth =
                   1617:             function() { return document.body.clientWidth; };
                   1618:         Geometry.getHorizontalScroll =
                   1619:             function() { return document.body.scrollLeft; };
                   1620:         Geometry.getVerticalScroll =
                   1621:             function() { return document.body.scrollTop; };
                   1622:     }
                   1623: }
                   1624: 
                   1625: GEOMETRY
                   1626: }
                   1627: 
                   1628: =pod
                   1629: 
1.648     raeburn  1630: =item * &viewport_size_js()
1.590     raeburn  1631: 
                   1632: 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. 
                   1633: 
                   1634: =cut
                   1635: 
                   1636: sub viewport_size_js {
                   1637:     my $geometry = &viewport_geometry_js();
                   1638:     return <<"DIMS";
                   1639: 
                   1640: $geometry
                   1641: 
                   1642: function getViewportDims(width,height) {
                   1643:     init_geometry();
                   1644:     width.value = Geometry.getViewportWidth();
                   1645:     height.value = Geometry.getViewportHeight();
                   1646:     return;
                   1647: }
                   1648: 
                   1649: DIMS
                   1650: }
                   1651: 
                   1652: =pod
                   1653: 
1.648     raeburn  1654: =item * &resize_textarea_js()
1.565     albertel 1655: 
                   1656: emits the needed javascript to resize a textarea to be as big as possible
                   1657: 
                   1658: creates a function resize_textrea that takes two IDs first should be
                   1659: the id of the element to resize, second should be the id of a div that
                   1660: surrounds everything that comes after the textarea, this routine needs
                   1661: to be attached to the <body> for the onload and onresize events.
                   1662: 
1.648     raeburn  1663: =back
1.565     albertel 1664: 
                   1665: =cut
                   1666: 
                   1667: sub resize_textarea_js {
1.590     raeburn  1668:     my $geometry = &viewport_geometry_js();
1.565     albertel 1669:     return <<"RESIZE";
                   1670:     <script type="text/javascript">
1.824     bisitz   1671: // <![CDATA[
1.590     raeburn  1672: $geometry
1.565     albertel 1673: 
1.588     albertel 1674: function getX(element) {
                   1675:     var x = 0;
                   1676:     while (element) {
                   1677: 	x += element.offsetLeft;
                   1678: 	element = element.offsetParent;
                   1679:     }
                   1680:     return x;
                   1681: }
                   1682: function getY(element) {
                   1683:     var y = 0;
                   1684:     while (element) {
                   1685: 	y += element.offsetTop;
                   1686: 	element = element.offsetParent;
                   1687:     }
                   1688:     return y;
                   1689: }
                   1690: 
                   1691: 
1.565     albertel 1692: function resize_textarea(textarea_id,bottom_id) {
                   1693:     init_geometry();
                   1694:     var textarea        = document.getElementById(textarea_id);
                   1695:     //alert(textarea);
                   1696: 
1.588     albertel 1697:     var textarea_top    = getY(textarea);
1.565     albertel 1698:     var textarea_height = textarea.offsetHeight;
                   1699:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1700:     var bottom_top      = getY(bottom);
1.565     albertel 1701:     var bottom_height   = bottom.offsetHeight;
                   1702:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1703:     var fudge           = 23;
1.565     albertel 1704:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1705:     if (new_height < 300) {
                   1706: 	new_height = 300;
                   1707:     }
                   1708:     textarea.style.height=new_height+'px';
                   1709: }
1.824     bisitz   1710: // ]]>
1.565     albertel 1711: </script>
                   1712: RESIZE
                   1713: 
                   1714: }
                   1715: 
                   1716: =pod
                   1717: 
1.256     matthew  1718: =head1 Excel and CSV file utility routines
                   1719: 
                   1720: =over 4
                   1721: 
                   1722: =cut
                   1723: 
                   1724: ###############################################################
                   1725: ###############################################################
                   1726: 
                   1727: =pod
                   1728: 
1.648     raeburn  1729: =item * &csv_translate($text) 
1.37      matthew  1730: 
1.185     www      1731: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  1732: format.
                   1733: 
                   1734: =cut
                   1735: 
1.180     matthew  1736: ###############################################################
                   1737: ###############################################################
1.37      matthew  1738: sub csv_translate {
                   1739:     my $text = shift;
                   1740:     $text =~ s/\"/\"\"/g;
1.209     albertel 1741:     $text =~ s/\n/ /g;
1.37      matthew  1742:     return $text;
                   1743: }
1.180     matthew  1744: 
                   1745: ###############################################################
                   1746: ###############################################################
                   1747: 
                   1748: =pod
                   1749: 
1.648     raeburn  1750: =item * &define_excel_formats()
1.180     matthew  1751: 
                   1752: Define some commonly used Excel cell formats.
                   1753: 
                   1754: Currently supported formats:
                   1755: 
                   1756: =over 4
                   1757: 
                   1758: =item header
                   1759: 
                   1760: =item bold
                   1761: 
                   1762: =item h1
                   1763: 
                   1764: =item h2
                   1765: 
                   1766: =item h3
                   1767: 
1.256     matthew  1768: =item h4
                   1769: 
                   1770: =item i
                   1771: 
1.180     matthew  1772: =item date
                   1773: 
                   1774: =back
                   1775: 
                   1776: Inputs: $workbook
                   1777: 
                   1778: Returns: $format, a hash reference.
                   1779: 
1.1057    foxr     1780: 
1.180     matthew  1781: =cut
                   1782: 
                   1783: ###############################################################
                   1784: ###############################################################
                   1785: sub define_excel_formats {
                   1786:     my ($workbook) = @_;
                   1787:     my $format;
                   1788:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   1789:                                                 bottom    => 1,
                   1790:                                                 align     => 'center');
                   1791:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   1792:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   1793:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   1794:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  1795:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  1796:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  1797:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  1798:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  1799:     return $format;
                   1800: }
                   1801: 
                   1802: ###############################################################
                   1803: ###############################################################
1.113     bowersj2 1804: 
                   1805: =pod
                   1806: 
1.648     raeburn  1807: =item * &create_workbook()
1.255     matthew  1808: 
                   1809: Create an Excel worksheet.  If it fails, output message on the
                   1810: request object and return undefs.
                   1811: 
                   1812: Inputs: Apache request object
                   1813: 
                   1814: Returns (undef) on failure, 
                   1815:     Excel worksheet object, scalar with filename, and formats 
                   1816:     from &Apache::loncommon::define_excel_formats on success
                   1817: 
                   1818: =cut
                   1819: 
                   1820: ###############################################################
                   1821: ###############################################################
                   1822: sub create_workbook {
                   1823:     my ($r) = @_;
                   1824:         #
                   1825:     # Create the excel spreadsheet
                   1826:     my $filename = '/prtspool/'.
1.258     albertel 1827:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  1828:         time.'_'.rand(1000000000).'.xls';
                   1829:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   1830:     if (! defined($workbook)) {
                   1831:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   1832:         $r->print(
                   1833:             '<p class="LC_error">'
                   1834:            .&mt('Problems occurred in creating the new Excel file.')
                   1835:            .' '.&mt('This error has been logged.')
                   1836:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   1837:            .'</p>'
                   1838:         );
1.255     matthew  1839:         return (undef);
                   1840:     }
                   1841:     #
1.1014    foxr     1842:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  1843:     #
                   1844:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   1845:     return ($workbook,$filename,$format);
                   1846: }
                   1847: 
                   1848: ###############################################################
                   1849: ###############################################################
                   1850: 
                   1851: =pod
                   1852: 
1.648     raeburn  1853: =item * &create_text_file()
1.113     bowersj2 1854: 
1.542     raeburn  1855: Create a file to write to and eventually make available to the user.
1.256     matthew  1856: If file creation fails, outputs an error message on the request object and 
                   1857: return undefs.
1.113     bowersj2 1858: 
1.256     matthew  1859: Inputs: Apache request object, and file suffix
1.113     bowersj2 1860: 
1.256     matthew  1861: Returns (undef) on failure, 
                   1862:     Filehandle and filename on success.
1.113     bowersj2 1863: 
                   1864: =cut
                   1865: 
1.256     matthew  1866: ###############################################################
                   1867: ###############################################################
                   1868: sub create_text_file {
                   1869:     my ($r,$suffix) = @_;
                   1870:     if (! defined($suffix)) { $suffix = 'txt'; };
                   1871:     my $fh;
                   1872:     my $filename = '/prtspool/'.
1.258     albertel 1873:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  1874:         time.'_'.rand(1000000000).'.'.$suffix;
                   1875:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   1876:     if (! defined($fh)) {
                   1877:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   1878:         $r->print(
                   1879:             '<p class="LC_error">'
                   1880:            .&mt('Problems occurred in creating the output file.')
                   1881:            .' '.&mt('This error has been logged.')
                   1882:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   1883:            .'</p>'
                   1884:         );
1.113     bowersj2 1885:     }
1.256     matthew  1886:     return ($fh,$filename)
1.113     bowersj2 1887: }
                   1888: 
                   1889: 
1.256     matthew  1890: =pod 
1.113     bowersj2 1891: 
                   1892: =back
                   1893: 
                   1894: =cut
1.37      matthew  1895: 
                   1896: ###############################################################
1.33      matthew  1897: ##        Home server <option> list generating code          ##
                   1898: ###############################################################
1.35      matthew  1899: 
1.169     www      1900: # ------------------------------------------
                   1901: 
                   1902: sub domain_select {
                   1903:     my ($name,$value,$multiple)=@_;
                   1904:     my %domains=map { 
1.514     albertel 1905: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 1906:     } &Apache::lonnet::all_domains();
1.169     www      1907:     if ($multiple) {
                   1908: 	$domains{''}=&mt('Any domain');
1.550     albertel 1909: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 1910: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      1911:     } else {
1.550     albertel 1912: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  1913: 	return &select_form($name,$value,\%domains);
1.169     www      1914:     }
                   1915: }
                   1916: 
1.282     albertel 1917: #-------------------------------------------
                   1918: 
                   1919: =pod
                   1920: 
1.519     raeburn  1921: =head1 Routines for form select boxes
                   1922: 
                   1923: =over 4
                   1924: 
1.648     raeburn  1925: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 1926: 
                   1927: Returns a string containing a <select> element int multiple mode
                   1928: 
                   1929: 
                   1930: Args:
                   1931:   $name - name of the <select> element
1.506     raeburn  1932:   $value - scalar or array ref of values that should already be selected
1.282     albertel 1933:   $size - number of rows long the select element is
1.283     albertel 1934:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 1935:           (shown text should already have been &mt())
1.506     raeburn  1936:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 1937: 
1.282     albertel 1938: =cut
                   1939: 
                   1940: #-------------------------------------------
1.169     www      1941: sub multiple_select_form {
1.284     albertel 1942:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      1943:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   1944:     my $output='';
1.191     matthew  1945:     if (! defined($size)) {
                   1946:         $size = 4;
1.283     albertel 1947:         if (scalar(keys(%$hash))<4) {
                   1948:             $size = scalar(keys(%$hash));
1.191     matthew  1949:         }
                   1950:     }
1.734     bisitz   1951:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 1952:     my @order;
1.506     raeburn  1953:     if (ref($order) eq 'ARRAY')  {
                   1954:         @order = @{$order};
                   1955:     } else {
                   1956:         @order = sort(keys(%$hash));
1.501     banghart 1957:     }
                   1958:     if (exists($$hash{'select_form_order'})) {
                   1959:         @order = @{$$hash{'select_form_order'}};
                   1960:     }
                   1961:         
1.284     albertel 1962:     foreach my $key (@order) {
1.356     albertel 1963:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 1964:         $output.='selected="selected" ' if ($selected{$key});
                   1965:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      1966:     }
                   1967:     $output.="</select>\n";
                   1968:     return $output;
                   1969: }
                   1970: 
1.88      www      1971: #-------------------------------------------
                   1972: 
                   1973: =pod
                   1974: 
1.970     raeburn  1975: =item * &select_form($defdom,$name,$hashref,$onchange)
1.88      www      1976: 
                   1977: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  1978: allow a user to select options from a ref to a hash containing:
                   1979: option_name => displayed text. An optional $onchange can include
                   1980: a javascript onchange item, e.g., onchange="this.form.submit();"  
                   1981: 
1.88      www      1982: See lonrights.pm for an example invocation and use.
                   1983: 
                   1984: =cut
                   1985: 
                   1986: #-------------------------------------------
                   1987: sub select_form {
1.970     raeburn  1988:     my ($def,$name,$hashref,$onchange) = @_;
                   1989:     return unless (ref($hashref) eq 'HASH');
                   1990:     if ($onchange) {
                   1991:         $onchange = ' onchange="'.$onchange.'"';
                   1992:     }
                   1993:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.128     albertel 1994:     my @keys;
1.970     raeburn  1995:     if (exists($hashref->{'select_form_order'})) {
                   1996: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 1997:     } else {
1.970     raeburn  1998: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 1999:     }
1.356     albertel 2000:     foreach my $key (@keys) {
                   2001:         $selectform.=
                   2002: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2003:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2004:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2005:     }
                   2006:     $selectform.="</select>";
                   2007:     return $selectform;
                   2008: }
                   2009: 
1.475     www      2010: # For display filters
                   2011: 
                   2012: sub display_filter {
1.1074    raeburn  2013:     my ($context) = @_;
1.475     www      2014:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2015:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2016:     my $phraseinput = 'hidden';
                   2017:     my $includeinput = 'hidden';
                   2018:     my ($checked,$includetypestext);
                   2019:     if ($env{'form.displayfilter'} eq 'containing') {
                   2020:         $phraseinput = 'text'; 
                   2021:         if ($context eq 'parmslog') {
                   2022:             $includeinput = 'checkbox';
                   2023:             if ($env{'form.includetypes'}) {
                   2024:                 $checked = ' checked="checked"';
                   2025:             }
                   2026:             $includetypestext = &mt('Include parameter types');
                   2027:         }
                   2028:     } else {
                   2029:         $includetypestext = '&nbsp;';
                   2030:     }
                   2031:     my ($additional,$secondid,$thirdid);
                   2032:     if ($context eq 'parmslog') {
                   2033:         $additional = 
                   2034:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2035:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2036:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2037:             '</label>';
                   2038:         $secondid = 'includetypes';
                   2039:         $thirdid = 'includetypestext';
                   2040:     }
                   2041:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2042:                                                     '$secondid','$thirdid')";
                   2043:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2044: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2045: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2046: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2047:            &mt('Filter: [_1]',
1.477     www      2048: 	   &select_form($env{'form.displayfilter'},
                   2049: 			'displayfilter',
1.970     raeburn  2050: 			{'currentfolder' => 'Current folder/page',
1.477     www      2051: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2052: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2053: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2054:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2055:                          '" />'.$additional;
                   2056: }
                   2057: 
                   2058: sub display_filter_js {
                   2059:     my $includetext = &mt('Include parameter types');
                   2060:     return <<"ENDJS";
                   2061:   
                   2062: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2063:     var firstType = 'hidden';
                   2064:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2065:         firstType = 'text';
                   2066:     }
                   2067:     firstObject = document.getElementById(firstid);
                   2068:     if (typeof(firstObject) == 'object') {
                   2069:         if (firstObject.type != firstType) {
                   2070:             changeInputType(firstObject,firstType);
                   2071:         }
                   2072:     }
                   2073:     if (context == 'parmslog') {
                   2074:         var secondType = 'hidden';
                   2075:         if (firstType == 'text') {
                   2076:             secondType = 'checkbox';
                   2077:         }
                   2078:         secondObject = document.getElementById(secondid);  
                   2079:         if (typeof(secondObject) == 'object') {
                   2080:             if (secondObject.type != secondType) {
                   2081:                 changeInputType(secondObject,secondType);
                   2082:             }
                   2083:         }
                   2084:         var textItem = document.getElementById(thirdid);
                   2085:         var currtext = textItem.innerHTML;
                   2086:         var newtext;
                   2087:         if (firstType == 'text') {
                   2088:             newtext = '$includetext';
                   2089:         } else {
                   2090:             newtext = '&nbsp;';
                   2091:         }
                   2092:         if (currtext != newtext) {
                   2093:             textItem.innerHTML = newtext;
                   2094:         }
                   2095:     }
                   2096:     return;
                   2097: }
                   2098: 
                   2099: function changeInputType(oldObject,newType) {
                   2100:     var newObject = document.createElement('input');
                   2101:     newObject.type = newType;
                   2102:     if (oldObject.size) {
                   2103:         newObject.size = oldObject.size;
                   2104:     }
                   2105:     if (oldObject.value) {
                   2106:         newObject.value = oldObject.value;
                   2107:     }
                   2108:     if (oldObject.name) {
                   2109:         newObject.name = oldObject.name;
                   2110:     }
                   2111:     if (oldObject.id) {
                   2112:         newObject.id = oldObject.id;
                   2113:     }
                   2114:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2115:     return;
                   2116: }
                   2117: 
                   2118: ENDJS
1.475     www      2119: }
                   2120: 
1.167     www      2121: sub gradeleveldescription {
                   2122:     my $gradelevel=shift;
                   2123:     my %gradelevels=(0 => 'Not specified',
                   2124: 		     1 => 'Grade 1',
                   2125: 		     2 => 'Grade 2',
                   2126: 		     3 => 'Grade 3',
                   2127: 		     4 => 'Grade 4',
                   2128: 		     5 => 'Grade 5',
                   2129: 		     6 => 'Grade 6',
                   2130: 		     7 => 'Grade 7',
                   2131: 		     8 => 'Grade 8',
                   2132: 		     9 => 'Grade 9',
                   2133: 		     10 => 'Grade 10',
                   2134: 		     11 => 'Grade 11',
                   2135: 		     12 => 'Grade 12',
                   2136: 		     13 => 'Grade 13',
                   2137: 		     14 => '100 Level',
                   2138: 		     15 => '200 Level',
                   2139: 		     16 => '300 Level',
                   2140: 		     17 => '400 Level',
                   2141: 		     18 => 'Graduate Level');
                   2142:     return &mt($gradelevels{$gradelevel});
                   2143: }
                   2144: 
1.163     www      2145: sub select_level_form {
                   2146:     my ($deflevel,$name)=@_;
                   2147:     unless ($deflevel) { $deflevel=0; }
1.167     www      2148:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2149:     for (my $i=0; $i<=18; $i++) {
                   2150:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2151:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2152:                 ">".&gradeleveldescription($i)."</option>\n";
                   2153:     }
                   2154:     $selectform.="</select>";
                   2155:     return $selectform;
1.163     www      2156: }
1.167     www      2157: 
1.35      matthew  2158: #-------------------------------------------
                   2159: 
1.45      matthew  2160: =pod
                   2161: 
1.910     raeburn  2162: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms)
1.35      matthew  2163: 
                   2164: Returns a string containing a <select name='$name' size='1'> form to 
                   2165: allow a user to select the domain to preform an operation in.  
                   2166: See loncreateuser.pm for an example invocation and use.
                   2167: 
1.90      www      2168: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2169: selected");
                   2170: 
1.743     raeburn  2171: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2172: 
1.910     raeburn  2173: The optional $onchange argument specifies what should occur if the domain selector is changed, e.g., 'this.form.submit()' if the form is to be automatically submitted.
                   2174: 
                   2175: The optional $incdoms is a reference to an array of domains which will be the only available options. 
1.563     raeburn  2176: 
1.35      matthew  2177: =cut
                   2178: 
                   2179: #-------------------------------------------
1.34      matthew  2180: sub select_dom_form {
1.910     raeburn  2181:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms) = @_;
1.872     raeburn  2182:     if ($onchange) {
1.874     raeburn  2183:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2184:     }
1.910     raeburn  2185:     my @domains;
                   2186:     if (ref($incdoms) eq 'ARRAY') {
                   2187:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2188:     } else {
                   2189:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2190:     }
1.90      www      2191:     if ($includeempty) { @domains=('',@domains); }
1.743     raeburn  2192:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.356     albertel 2193:     foreach my $dom (@domains) {
                   2194:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2195:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2196:         if ($showdomdesc) {
                   2197:             if ($dom ne '') {
                   2198:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2199:                 if ($domdesc ne '') {
                   2200:                     $selectdomain .= ' ('.$domdesc.')';
                   2201:                 }
                   2202:             } 
                   2203:         }
                   2204:         $selectdomain .= "</option>\n";
1.34      matthew  2205:     }
                   2206:     $selectdomain.="</select>";
                   2207:     return $selectdomain;
                   2208: }
                   2209: 
1.35      matthew  2210: #-------------------------------------------
                   2211: 
1.45      matthew  2212: =pod
                   2213: 
1.648     raeburn  2214: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2215: 
1.586     raeburn  2216: input: 4 arguments (two required, two optional) - 
                   2217:     $domain - domain of new user
                   2218:     $name - name of form element
                   2219:     $default - Value of 'default' causes a default item to be first 
                   2220:                             option, and selected by default. 
                   2221:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2222:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2223: output: returns 2 items: 
1.586     raeburn  2224: (a) form element which contains either:
                   2225:    (i) <select name="$name">
                   2226:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2227:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2228:        </select>
                   2229:        form item if there are multiple library servers in $domain, or
                   2230:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2231:        if there is only one library server in $domain.
                   2232: 
                   2233: (b) number of library servers found.
                   2234: 
                   2235: See loncreateuser.pm for example of use.
1.35      matthew  2236: 
                   2237: =cut
                   2238: 
                   2239: #-------------------------------------------
1.586     raeburn  2240: sub home_server_form_item {
                   2241:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2242:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2243:     my $result;
                   2244:     my $numlib = keys(%servers);
                   2245:     if ($numlib > 1) {
                   2246:         $result .= '<select name="'.$name.'" />'."\n";
                   2247:         if ($default) {
1.804     bisitz   2248:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2249:                        '</option>'."\n";
                   2250:         }
                   2251:         foreach my $hostid (sort(keys(%servers))) {
                   2252:             $result.= '<option value="'.$hostid.'">'.
                   2253: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2254:         }
                   2255:         $result .= '</select>'."\n";
                   2256:     } elsif ($numlib == 1) {
                   2257:         my $hostid;
                   2258:         foreach my $item (keys(%servers)) {
                   2259:             $hostid = $item;
                   2260:         }
                   2261:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2262:                    $hostid.'" />';
                   2263:                    if (!$hide) {
                   2264:                        $result .= $hostid.' '.$servers{$hostid};
                   2265:                    }
                   2266:                    $result .= "\n";
                   2267:     } elsif ($default) {
                   2268:         $result .= '<input type="hidden" name="'.$name.
                   2269:                    '" value="default" />';
                   2270:                    if (!$hide) {
                   2271:                        $result .= &mt('default');
                   2272:                    }
                   2273:                    $result .= "\n";
1.33      matthew  2274:     }
1.586     raeburn  2275:     return ($result,$numlib);
1.33      matthew  2276: }
1.112     bowersj2 2277: 
                   2278: =pod
                   2279: 
1.534     albertel 2280: =back 
                   2281: 
1.112     bowersj2 2282: =cut
1.87      matthew  2283: 
                   2284: ###############################################################
1.112     bowersj2 2285: ##                  Decoding User Agent                      ##
1.87      matthew  2286: ###############################################################
                   2287: 
                   2288: =pod
                   2289: 
1.112     bowersj2 2290: =head1 Decoding the User Agent
                   2291: 
                   2292: =over 4
                   2293: 
                   2294: =item * &decode_user_agent()
1.87      matthew  2295: 
                   2296: Inputs: $r
                   2297: 
                   2298: Outputs:
                   2299: 
                   2300: =over 4
                   2301: 
1.112     bowersj2 2302: =item * $httpbrowser
1.87      matthew  2303: 
1.112     bowersj2 2304: =item * $clientbrowser
1.87      matthew  2305: 
1.112     bowersj2 2306: =item * $clientversion
1.87      matthew  2307: 
1.112     bowersj2 2308: =item * $clientmathml
1.87      matthew  2309: 
1.112     bowersj2 2310: =item * $clientunicode
1.87      matthew  2311: 
1.112     bowersj2 2312: =item * $clientos
1.87      matthew  2313: 
                   2314: =back
                   2315: 
1.157     matthew  2316: =back 
                   2317: 
1.87      matthew  2318: =cut
                   2319: 
                   2320: ###############################################################
                   2321: ###############################################################
                   2322: sub decode_user_agent {
1.247     albertel 2323:     my ($r)=@_;
1.87      matthew  2324:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2325:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2326:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2327:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2328:     my $clientbrowser='unknown';
                   2329:     my $clientversion='0';
                   2330:     my $clientmathml='';
                   2331:     my $clientunicode='0';
                   2332:     for (my $i=0;$i<=$#browsertype;$i++) {
                   2333:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
                   2334: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2335: 	    $clientbrowser=$bname;
                   2336:             $httpbrowser=~/$vreg/i;
                   2337: 	    $clientversion=$1;
                   2338:             $clientmathml=($clientversion>=$minv);
                   2339:             $clientunicode=($clientversion>=$univ);
                   2340: 	}
                   2341:     }
                   2342:     my $clientos='unknown';
                   2343:     if (($httpbrowser=~/linux/i) ||
                   2344:         ($httpbrowser=~/unix/i) ||
                   2345:         ($httpbrowser=~/ux/i) ||
                   2346:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2347:     if (($httpbrowser=~/vax/i) ||
                   2348:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2349:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2350:     if (($httpbrowser=~/mac/i) ||
                   2351:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
                   2352:     if ($httpbrowser=~/win/i) { $clientos='win'; }
                   2353:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
                   2354:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
                   2355:             $clientunicode,$clientos,);
                   2356: }
                   2357: 
1.32      matthew  2358: ###############################################################
                   2359: ##    Authentication changing form generation subroutines    ##
                   2360: ###############################################################
                   2361: ##
                   2362: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2363: ## hash, and have reasonable default values.
                   2364: ##
                   2365: ##    formname = the name given in the <form> tag.
1.35      matthew  2366: #-------------------------------------------
                   2367: 
1.45      matthew  2368: =pod
                   2369: 
1.112     bowersj2 2370: =head1 Authentication Routines
                   2371: 
                   2372: =over 4
                   2373: 
1.648     raeburn  2374: =item * &authform_xxxxxx()
1.35      matthew  2375: 
                   2376: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2377: handle some of the conveniences required for authentication forms.  
                   2378: This is not an optimal method, but it works.  
                   2379: 
                   2380: =over 4
                   2381: 
1.112     bowersj2 2382: =item * authform_header
1.35      matthew  2383: 
1.112     bowersj2 2384: =item * authform_authorwarning
1.35      matthew  2385: 
1.112     bowersj2 2386: =item * authform_nochange
1.35      matthew  2387: 
1.112     bowersj2 2388: =item * authform_kerberos
1.35      matthew  2389: 
1.112     bowersj2 2390: =item * authform_internal
1.35      matthew  2391: 
1.112     bowersj2 2392: =item * authform_filesystem
1.35      matthew  2393: 
                   2394: =back
                   2395: 
1.648     raeburn  2396: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2397: 
1.35      matthew  2398: =cut
                   2399: 
                   2400: #-------------------------------------------
1.32      matthew  2401: sub authform_header{  
                   2402:     my %in = (
                   2403:         formname => 'cu',
1.80      albertel 2404:         kerb_def_dom => '',
1.32      matthew  2405:         @_,
                   2406:     );
                   2407:     $in{'formname'} = 'document.' . $in{'formname'};
                   2408:     my $result='';
1.80      albertel 2409: 
                   2410: #---------------------------------------------- Code for upper case translation
                   2411:     my $Javascript_toUpperCase;
                   2412:     unless ($in{kerb_def_dom}) {
                   2413:         $Javascript_toUpperCase =<<"END";
                   2414:         switch (choice) {
                   2415:            case 'krb': currentform.elements[choicearg].value =
                   2416:                currentform.elements[choicearg].value.toUpperCase();
                   2417:                break;
                   2418:            default:
                   2419:         }
                   2420: END
                   2421:     } else {
                   2422:         $Javascript_toUpperCase = "";
                   2423:     }
                   2424: 
1.165     raeburn  2425:     my $radioval = "'nochange'";
1.591     raeburn  2426:     if (defined($in{'curr_authtype'})) {
                   2427:         if ($in{'curr_authtype'} ne '') {
                   2428:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2429:         }
1.174     matthew  2430:     }
1.165     raeburn  2431:     my $argfield = 'null';
1.591     raeburn  2432:     if (defined($in{'mode'})) {
1.165     raeburn  2433:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2434:             if (defined($in{'curr_autharg'})) {
                   2435:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2436:                     $argfield = "'$in{'curr_autharg'}'";
                   2437:                 }
                   2438:             }
                   2439:         }
                   2440:     }
                   2441: 
1.32      matthew  2442:     $result.=<<"END";
                   2443: var current = new Object();
1.165     raeburn  2444: current.radiovalue = $radioval;
                   2445: current.argfield = $argfield;
1.32      matthew  2446: 
                   2447: function changed_radio(choice,currentform) {
                   2448:     var choicearg = choice + 'arg';
                   2449:     // If a radio button in changed, we need to change the argfield
                   2450:     if (current.radiovalue != choice) {
                   2451:         current.radiovalue = choice;
                   2452:         if (current.argfield != null) {
                   2453:             currentform.elements[current.argfield].value = '';
                   2454:         }
                   2455:         if (choice == 'nochange') {
                   2456:             current.argfield = null;
                   2457:         } else {
                   2458:             current.argfield = choicearg;
                   2459:             switch(choice) {
                   2460:                 case 'krb': 
                   2461:                     currentform.elements[current.argfield].value = 
                   2462:                         "$in{'kerb_def_dom'}";
                   2463:                 break;
                   2464:               default:
                   2465:                 break;
                   2466:             }
                   2467:         }
                   2468:     }
                   2469:     return;
                   2470: }
1.22      www      2471: 
1.32      matthew  2472: function changed_text(choice,currentform) {
                   2473:     var choicearg = choice + 'arg';
                   2474:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2475:         $Javascript_toUpperCase
1.32      matthew  2476:         // clear old field
                   2477:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2478:             currentform.elements[current.argfield].value = '';
                   2479:         }
                   2480:         current.argfield = choicearg;
                   2481:     }
                   2482:     set_auth_radio_buttons(choice,currentform);
                   2483:     return;
1.20      www      2484: }
1.32      matthew  2485: 
                   2486: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2487:     var numauthchoices = currentform.login.length;
                   2488:     if (typeof numauthchoices  == "undefined") {
                   2489:         return;
                   2490:     } 
1.32      matthew  2491:     var i=0;
1.986     raeburn  2492:     while (i < numauthchoices) {
1.32      matthew  2493:         if (currentform.login[i].value == newvalue) { break; }
                   2494:         i++;
                   2495:     }
1.986     raeburn  2496:     if (i == numauthchoices) {
1.32      matthew  2497:         return;
                   2498:     }
                   2499:     current.radiovalue = newvalue;
                   2500:     currentform.login[i].checked = true;
                   2501:     return;
                   2502: }
                   2503: END
                   2504:     return $result;
                   2505: }
                   2506: 
                   2507: sub authform_authorwarning{
                   2508:     my $result='';
1.144     matthew  2509:     $result='<i>'.
                   2510:         &mt('As a general rule, only authors or co-authors should be '.
                   2511:             'filesystem authenticated '.
                   2512:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2513:     return $result;
                   2514: }
                   2515: 
                   2516: sub authform_nochange{  
                   2517:     my %in = (
                   2518:               formname => 'document.cu',
                   2519:               kerb_def_dom => 'MSU.EDU',
                   2520:               @_,
                   2521:           );
1.586     raeburn  2522:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
                   2523:     my $result;
                   2524:     if (keys(%can_assign) == 0) {
                   2525:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
                   2526:     } else {
                   2527:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2528:                   '<input type="radio" name="login" value="nochange" '.
                   2529:                   'checked="checked" onclick="'.
1.281     albertel 2530:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2531: 	    '</label>';
1.586     raeburn  2532:     }
1.32      matthew  2533:     return $result;
                   2534: }
                   2535: 
1.591     raeburn  2536: sub authform_kerberos {
1.32      matthew  2537:     my %in = (
                   2538:               formname => 'document.cu',
                   2539:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2540:               kerb_def_auth => 'krb4',
1.32      matthew  2541:               @_,
                   2542:               );
1.586     raeburn  2543:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
                   2544:         $autharg,$jscall);
                   2545:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
1.80      albertel 2546:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2547:        $check5 = ' checked="checked"';
1.80      albertel 2548:     } else {
1.772     bisitz   2549:        $check4 = ' checked="checked"';
1.80      albertel 2550:     }
1.165     raeburn  2551:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2552:     if (defined($in{'curr_authtype'})) {
                   2553:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2554:             $krbcheck = ' checked="checked"';
1.623     raeburn  2555:             if (defined($in{'mode'})) {
                   2556:                 if ($in{'mode'} eq 'modifyuser') {
                   2557:                     $krbcheck = '';
                   2558:                 }
                   2559:             }
1.591     raeburn  2560:             if (defined($in{'curr_kerb_ver'})) {
                   2561:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2562:                     $check5 = ' checked="checked"';
1.591     raeburn  2563:                     $check4 = '';
                   2564:                 } else {
1.772     bisitz   2565:                     $check4 = ' checked="checked"';
1.591     raeburn  2566:                     $check5 = '';
                   2567:                 }
1.586     raeburn  2568:             }
1.591     raeburn  2569:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2570:                 $krbarg = $in{'curr_autharg'};
                   2571:             }
1.586     raeburn  2572:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2573:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2574:                     $result = 
                   2575:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2576:         $in{'curr_autharg'},$krbver);
                   2577:                 } else {
                   2578:                     $result =
                   2579:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2580:                 }
                   2581:                 return $result; 
                   2582:             }
                   2583:         }
                   2584:     } else {
                   2585:         if ($authnum == 1) {
1.784     bisitz   2586:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2587:         }
                   2588:     }
1.586     raeburn  2589:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2590:         return;
1.587     raeburn  2591:     } elsif ($authtype eq '') {
1.591     raeburn  2592:         if (defined($in{'mode'})) {
1.587     raeburn  2593:             if ($in{'mode'} eq 'modifycourse') {
                   2594:                 if ($authnum == 1) {
1.784     bisitz   2595:                     $authtype = '<input type="hidden" name="login" value="krb" />';
1.587     raeburn  2596:                 }
                   2597:             }
                   2598:         }
1.586     raeburn  2599:     }
                   2600:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2601:     if ($authtype eq '') {
                   2602:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2603:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
                   2604:                     $krbcheck.' />';
                   2605:     }
                   2606:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
                   2607:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
                   2608:          $in{'curr_authtype'} eq 'krb5') ||
                   2609:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
                   2610:          $in{'curr_authtype'} eq 'krb4')) {
                   2611:         $result .= &mt
1.144     matthew  2612:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2613:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2614:          '<label>'.$authtype,
1.281     albertel 2615:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2616:              'value="'.$krbarg.'" '.
1.144     matthew  2617:              'onchange="'.$jscall.'" />',
1.281     albertel 2618:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
                   2619:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
                   2620: 	 '</label>');
1.586     raeburn  2621:     } elsif ($can_assign{'krb4'}) {
                   2622:         $result .= &mt
                   2623:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2624:          '[_3] Version 4 [_4]',
                   2625:          '<label>'.$authtype,
                   2626:          '</label><input type="text" size="10" name="krbarg" '.
                   2627:              'value="'.$krbarg.'" '.
                   2628:              'onchange="'.$jscall.'" />',
                   2629:          '<label><input type="hidden" name="krbver" value="4" />',
                   2630:          '</label>');
                   2631:     } elsif ($can_assign{'krb5'}) {
                   2632:         $result .= &mt
                   2633:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2634:          '[_3] Version 5 [_4]',
                   2635:          '<label>'.$authtype,
                   2636:          '</label><input type="text" size="10" name="krbarg" '.
                   2637:              'value="'.$krbarg.'" '.
                   2638:              'onchange="'.$jscall.'" />',
                   2639:          '<label><input type="hidden" name="krbver" value="5" />',
                   2640:          '</label>');
                   2641:     }
1.32      matthew  2642:     return $result;
                   2643: }
                   2644: 
                   2645: sub authform_internal{  
1.586     raeburn  2646:     my %in = (
1.32      matthew  2647:                 formname => 'document.cu',
                   2648:                 kerb_def_dom => 'MSU.EDU',
                   2649:                 @_,
                   2650:                 );
1.586     raeburn  2651:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
                   2652:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
1.591     raeburn  2653:     if (defined($in{'curr_authtype'})) {
                   2654:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2655:             if ($can_assign{'int'}) {
1.772     bisitz   2656:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2657:                 if (defined($in{'mode'})) {
                   2658:                     if ($in{'mode'} eq 'modifyuser') {
                   2659:                         $intcheck = '';
                   2660:                     }
                   2661:                 }
1.591     raeburn  2662:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2663:                     $intarg = $in{'curr_autharg'};
                   2664:                 }
                   2665:             } else {
                   2666:                 $result = &mt('Currently internally authenticated.');
                   2667:                 return $result;
1.165     raeburn  2668:             }
                   2669:         }
1.586     raeburn  2670:     } else {
                   2671:         if ($authnum == 1) {
1.784     bisitz   2672:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  2673:         }
                   2674:     }
                   2675:     if (!$can_assign{'int'}) {
                   2676:         return;
1.587     raeburn  2677:     } elsif ($authtype eq '') {
1.591     raeburn  2678:         if (defined($in{'mode'})) {
1.587     raeburn  2679:             if ($in{'mode'} eq 'modifycourse') {
                   2680:                 if ($authnum == 1) {
1.784     bisitz   2681:                     $authtype = '<input type="hidden" name="login" value="int" />';
1.587     raeburn  2682:                 }
                   2683:             }
                   2684:         }
1.165     raeburn  2685:     }
1.586     raeburn  2686:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   2687:     if ($authtype eq '') {
                   2688:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
                   2689:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
                   2690:     }
1.605     bisitz   2691:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.586     raeburn  2692:                $intarg.'" onchange="'.$jscall.'" />';
                   2693:     $result = &mt
1.144     matthew  2694:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  2695:          '<label>'.$authtype,'</label>'.$autharg);
1.824     bisitz   2696:     $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  2697:     return $result;
                   2698: }
                   2699: 
                   2700: sub authform_local{  
                   2701:     my %in = (
                   2702:               formname => 'document.cu',
                   2703:               kerb_def_dom => 'MSU.EDU',
                   2704:               @_,
                   2705:               );
1.586     raeburn  2706:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
                   2707:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
1.591     raeburn  2708:     if (defined($in{'curr_authtype'})) {
                   2709:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  2710:             if ($can_assign{'loc'}) {
1.772     bisitz   2711:                 $loccheck = 'checked="checked" ';
1.623     raeburn  2712:                 if (defined($in{'mode'})) {
                   2713:                     if ($in{'mode'} eq 'modifyuser') {
                   2714:                         $loccheck = '';
                   2715:                     }
                   2716:                 }
1.591     raeburn  2717:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2718:                     $locarg = $in{'curr_autharg'};
                   2719:                 }
                   2720:             } else {
                   2721:                 $result = &mt('Currently using local (institutional) authentication.');
                   2722:                 return $result;
1.165     raeburn  2723:             }
                   2724:         }
1.586     raeburn  2725:     } else {
                   2726:         if ($authnum == 1) {
1.784     bisitz   2727:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  2728:         }
                   2729:     }
                   2730:     if (!$can_assign{'loc'}) {
                   2731:         return;
1.587     raeburn  2732:     } elsif ($authtype eq '') {
1.591     raeburn  2733:         if (defined($in{'mode'})) {
1.587     raeburn  2734:             if ($in{'mode'} eq 'modifycourse') {
                   2735:                 if ($authnum == 1) {
1.784     bisitz   2736:                     $authtype = '<input type="hidden" name="login" value="loc" />';
1.587     raeburn  2737:                 }
                   2738:             }
                   2739:         }
1.165     raeburn  2740:     }
1.586     raeburn  2741:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   2742:     if ($authtype eq '') {
                   2743:         $authtype = '<input type="radio" name="login" value="loc" '.
                   2744:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
                   2745:                     $jscall.'" />';
                   2746:     }
                   2747:     $autharg = '<input type="text" size="10" name="locarg" value="'.
                   2748:                $locarg.'" onchange="'.$jscall.'" />';
                   2749:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   2750:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  2751:     return $result;
                   2752: }
                   2753: 
                   2754: sub authform_filesystem{  
                   2755:     my %in = (
                   2756:               formname => 'document.cu',
                   2757:               kerb_def_dom => 'MSU.EDU',
                   2758:               @_,
                   2759:               );
1.586     raeburn  2760:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
                   2761:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
1.591     raeburn  2762:     if (defined($in{'curr_authtype'})) {
                   2763:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  2764:             if ($can_assign{'fsys'}) {
1.772     bisitz   2765:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  2766:                 if (defined($in{'mode'})) {
                   2767:                     if ($in{'mode'} eq 'modifyuser') {
                   2768:                         $fsyscheck = '';
                   2769:                     }
                   2770:                 }
1.586     raeburn  2771:             } else {
                   2772:                 $result = &mt('Currently Filesystem Authenticated.');
                   2773:                 return $result;
                   2774:             }           
                   2775:         }
                   2776:     } else {
                   2777:         if ($authnum == 1) {
1.784     bisitz   2778:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  2779:         }
                   2780:     }
                   2781:     if (!$can_assign{'fsys'}) {
                   2782:         return;
1.587     raeburn  2783:     } elsif ($authtype eq '') {
1.591     raeburn  2784:         if (defined($in{'mode'})) {
1.587     raeburn  2785:             if ($in{'mode'} eq 'modifycourse') {
                   2786:                 if ($authnum == 1) {
1.784     bisitz   2787:                     $authtype = '<input type="hidden" name="login" value="fsys" />';
1.587     raeburn  2788:                 }
                   2789:             }
                   2790:         }
1.586     raeburn  2791:     }
                   2792:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   2793:     if ($authtype eq '') {
                   2794:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   2795:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
                   2796:                     $jscall.'" />';
                   2797:     }
                   2798:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
                   2799:                ' onchange="'.$jscall.'" />';
                   2800:     $result = &mt
1.144     matthew  2801:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 2802:          '<label><input type="radio" name="login" value="fsys" '.
1.586     raeburn  2803:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1.605     bisitz   2804:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.144     matthew  2805:                   'onchange="'.$jscall.'" />');
1.32      matthew  2806:     return $result;
                   2807: }
                   2808: 
1.586     raeburn  2809: sub get_assignable_auth {
                   2810:     my ($dom) = @_;
                   2811:     if ($dom eq '') {
                   2812:         $dom = $env{'request.role.domain'};
                   2813:     }
                   2814:     my %can_assign = (
                   2815:                           krb4 => 1,
                   2816:                           krb5 => 1,
                   2817:                           int  => 1,
                   2818:                           loc  => 1,
                   2819:                      );
                   2820:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   2821:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   2822:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   2823:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   2824:             my $context;
                   2825:             if ($env{'request.role'} =~ /^au/) {
                   2826:                 $context = 'author';
                   2827:             } elsif ($env{'request.role'} =~ /^dc/) {
                   2828:                 $context = 'domain';
                   2829:             } elsif ($env{'request.course.id'}) {
                   2830:                 $context = 'course';
                   2831:             }
                   2832:             if ($context) {
                   2833:                 if (ref($authhash->{$context}) eq 'HASH') {
                   2834:                    %can_assign = %{$authhash->{$context}}; 
                   2835:                 }
                   2836:             }
                   2837:         }
                   2838:     }
                   2839:     my $authnum = 0;
                   2840:     foreach my $key (keys(%can_assign)) {
                   2841:         if ($can_assign{$key}) {
                   2842:             $authnum ++;
                   2843:         }
                   2844:     }
                   2845:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   2846:         $authnum --;
                   2847:     }
                   2848:     return ($authnum,%can_assign);
                   2849: }
                   2850: 
1.80      albertel 2851: ###############################################################
                   2852: ##    Get Kerberos Defaults for Domain                 ##
                   2853: ###############################################################
                   2854: ##
                   2855: ## Returns default kerberos version and an associated argument
                   2856: ## as listed in file domain.tab. If not listed, provides
                   2857: ## appropriate default domain and kerberos version.
                   2858: ##
                   2859: #-------------------------------------------
                   2860: 
                   2861: =pod
                   2862: 
1.648     raeburn  2863: =item * &get_kerberos_defaults()
1.80      albertel 2864: 
                   2865: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  2866: version and domain. If not found, it defaults to version 4 and the 
                   2867: domain of the server.
1.80      albertel 2868: 
1.648     raeburn  2869: =over 4
                   2870: 
1.80      albertel 2871: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   2872: 
1.648     raeburn  2873: =back
                   2874: 
                   2875: =back
                   2876: 
1.80      albertel 2877: =cut
                   2878: 
                   2879: #-------------------------------------------
                   2880: sub get_kerberos_defaults {
                   2881:     my $domain=shift;
1.641     raeburn  2882:     my ($krbdef,$krbdefdom);
                   2883:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2884:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   2885:         $krbdef = $domdefaults{'auth_def'};
                   2886:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   2887:     } else {
1.80      albertel 2888:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   2889:         my $krbdefdom=$1;
                   2890:         $krbdefdom=~tr/a-z/A-Z/;
                   2891:         $krbdef = "krb4";
                   2892:     }
                   2893:     return ($krbdef,$krbdefdom);
                   2894: }
1.112     bowersj2 2895: 
1.32      matthew  2896: 
1.46      matthew  2897: ###############################################################
                   2898: ##                Thesaurus Functions                        ##
                   2899: ###############################################################
1.20      www      2900: 
1.46      matthew  2901: =pod
1.20      www      2902: 
1.112     bowersj2 2903: =head1 Thesaurus Functions
                   2904: 
                   2905: =over 4
                   2906: 
1.648     raeburn  2907: =item * &initialize_keywords()
1.46      matthew  2908: 
                   2909: Initializes the package variable %Keywords if it is empty.  Uses the
                   2910: package variable $thesaurus_db_file.
                   2911: 
                   2912: =cut
                   2913: 
                   2914: ###################################################
                   2915: 
                   2916: sub initialize_keywords {
                   2917:     return 1 if (scalar keys(%Keywords));
                   2918:     # If we are here, %Keywords is empty, so fill it up
                   2919:     #   Make sure the file we need exists...
                   2920:     if (! -e $thesaurus_db_file) {
                   2921:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   2922:                                  " failed because it does not exist");
                   2923:         return 0;
                   2924:     }
                   2925:     #   Set up the hash as a database
                   2926:     my %thesaurus_db;
                   2927:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 2928:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  2929:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   2930:                                  $thesaurus_db_file);
                   2931:         return 0;
                   2932:     } 
                   2933:     #  Get the average number of appearances of a word.
                   2934:     my $avecount = $thesaurus_db{'average.count'};
                   2935:     #  Put keywords (those that appear > average) into %Keywords
                   2936:     while (my ($word,$data)=each (%thesaurus_db)) {
                   2937:         my ($count,undef) = split /:/,$data;
                   2938:         $Keywords{$word}++ if ($count > $avecount);
                   2939:     }
                   2940:     untie %thesaurus_db;
                   2941:     # Remove special values from %Keywords.
1.356     albertel 2942:     foreach my $value ('total.count','average.count') {
                   2943:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  2944:   }
1.46      matthew  2945:     return 1;
                   2946: }
                   2947: 
                   2948: ###################################################
                   2949: 
                   2950: =pod
                   2951: 
1.648     raeburn  2952: =item * &keyword($word)
1.46      matthew  2953: 
                   2954: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   2955: than the average number of times in the thesaurus database.  Calls 
                   2956: &initialize_keywords
                   2957: 
                   2958: =cut
                   2959: 
                   2960: ###################################################
1.20      www      2961: 
                   2962: sub keyword {
1.46      matthew  2963:     return if (!&initialize_keywords());
                   2964:     my $word=lc(shift());
                   2965:     $word=~s/\W//g;
                   2966:     return exists($Keywords{$word});
1.20      www      2967: }
1.46      matthew  2968: 
                   2969: ###############################################################
                   2970: 
                   2971: =pod 
1.20      www      2972: 
1.648     raeburn  2973: =item * &get_related_words()
1.46      matthew  2974: 
1.160     matthew  2975: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  2976: an array of words.  If the keyword is not in the thesaurus, an empty array
                   2977: will be returned.  The order of the words returned is determined by the
                   2978: database which holds them.
                   2979: 
                   2980: Uses global $thesaurus_db_file.
                   2981: 
1.1057    foxr     2982: 
1.46      matthew  2983: =cut
                   2984: 
                   2985: ###############################################################
                   2986: sub get_related_words {
                   2987:     my $keyword = shift;
                   2988:     my %thesaurus_db;
                   2989:     if (! -e $thesaurus_db_file) {
                   2990:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   2991:                                  "failed because the file does not exist");
                   2992:         return ();
                   2993:     }
                   2994:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 2995:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  2996:         return ();
                   2997:     } 
                   2998:     my @Words=();
1.429     www      2999:     my $count=0;
1.46      matthew  3000:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3001: 	# The first element is the number of times
                   3002: 	# the word appears.  We do not need it now.
1.429     www      3003: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3004: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3005: 	my $threshold=$mostfrequentcount/10;
                   3006:         foreach my $possibleword (@RelatedWords) {
                   3007:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3008:             if ($wordcount>$threshold) {
                   3009: 		push(@Words,$word);
                   3010:                 $count++;
                   3011:                 if ($count>10) { last; }
                   3012: 	    }
1.20      www      3013:         }
                   3014:     }
1.46      matthew  3015:     untie %thesaurus_db;
                   3016:     return @Words;
1.14      harris41 3017: }
1.46      matthew  3018: 
1.112     bowersj2 3019: =pod
                   3020: 
                   3021: =back
                   3022: 
                   3023: =cut
1.61      www      3024: 
                   3025: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3026: =pod
                   3027: 
1.112     bowersj2 3028: =head1 User Name Functions
                   3029: 
                   3030: =over 4
                   3031: 
1.648     raeburn  3032: =item * &plainname($uname,$udom,$first)
1.81      albertel 3033: 
1.112     bowersj2 3034: Takes a users logon name and returns it as a string in
1.226     albertel 3035: "first middle last generation" form 
                   3036: if $first is set to 'lastname' then it returns it as
                   3037: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3038: 
                   3039: =cut
1.61      www      3040: 
1.295     www      3041: 
1.81      albertel 3042: ###############################################################
1.61      www      3043: sub plainname {
1.226     albertel 3044:     my ($uname,$udom,$first)=@_;
1.537     albertel 3045:     return if (!defined($uname) || !defined($udom));
1.295     www      3046:     my %names=&getnames($uname,$udom);
1.226     albertel 3047:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3048: 					  $names{'middlename'},
                   3049: 					  $names{'lastname'},
                   3050: 					  $names{'generation'},$first);
                   3051:     $name=~s/^\s+//;
1.62      www      3052:     $name=~s/\s+$//;
                   3053:     $name=~s/\s+/ /g;
1.353     albertel 3054:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3055:     return $name;
1.61      www      3056: }
1.66      www      3057: 
                   3058: # -------------------------------------------------------------------- Nickname
1.81      albertel 3059: =pod
                   3060: 
1.648     raeburn  3061: =item * &nickname($uname,$udom)
1.81      albertel 3062: 
                   3063: Gets a users name and returns it as a string as
                   3064: 
                   3065: "&quot;nickname&quot;"
1.66      www      3066: 
1.81      albertel 3067: if the user has a nickname or
                   3068: 
                   3069: "first middle last generation"
                   3070: 
                   3071: if the user does not
                   3072: 
                   3073: =cut
1.66      www      3074: 
                   3075: sub nickname {
                   3076:     my ($uname,$udom)=@_;
1.537     albertel 3077:     return if (!defined($uname) || !defined($udom));
1.295     www      3078:     my %names=&getnames($uname,$udom);
1.68      albertel 3079:     my $name=$names{'nickname'};
1.66      www      3080:     if ($name) {
                   3081:        $name='&quot;'.$name.'&quot;'; 
                   3082:     } else {
                   3083:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3084: 	     $names{'lastname'}.' '.$names{'generation'};
                   3085:        $name=~s/\s+$//;
                   3086:        $name=~s/\s+/ /g;
                   3087:     }
                   3088:     return $name;
                   3089: }
                   3090: 
1.295     www      3091: sub getnames {
                   3092:     my ($uname,$udom)=@_;
1.537     albertel 3093:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3094:     if ($udom eq 'public' && $uname eq 'public') {
                   3095: 	return ('lastname' => &mt('Public'));
                   3096:     }
1.295     www      3097:     my $id=$uname.':'.$udom;
                   3098:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3099:     if ($cached) {
                   3100: 	return %{$names};
                   3101:     } else {
                   3102: 	my %loadnames=&Apache::lonnet::get('environment',
                   3103:                     ['firstname','middlename','lastname','generation','nickname'],
                   3104: 					 $udom,$uname);
                   3105: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3106: 	return %loadnames;
                   3107:     }
                   3108: }
1.61      www      3109: 
1.542     raeburn  3110: # -------------------------------------------------------------------- getemails
1.648     raeburn  3111: 
1.542     raeburn  3112: =pod
                   3113: 
1.648     raeburn  3114: =item * &getemails($uname,$udom)
1.542     raeburn  3115: 
                   3116: Gets a user's email information and returns it as a hash with keys:
                   3117: notification, critnotification, permanentemail
                   3118: 
                   3119: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3120: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3121:  
1.648     raeburn  3122: 
1.542     raeburn  3123: =cut
                   3124: 
1.648     raeburn  3125: 
1.466     albertel 3126: sub getemails {
                   3127:     my ($uname,$udom)=@_;
                   3128:     if ($udom eq 'public' && $uname eq 'public') {
                   3129: 	return;
                   3130:     }
1.467     www      3131:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3132:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3133:     my $id=$uname.':'.$udom;
                   3134:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3135:     if ($cached) {
                   3136: 	return %{$names};
                   3137:     } else {
                   3138: 	my %loadnames=&Apache::lonnet::get('environment',
                   3139:                     			   ['notification','critnotification',
                   3140: 					    'permanentemail'],
                   3141: 					   $udom,$uname);
                   3142: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3143: 	return %loadnames;
                   3144:     }
                   3145: }
                   3146: 
1.551     albertel 3147: sub flush_email_cache {
                   3148:     my ($uname,$udom)=@_;
                   3149:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3150:     if (!$uname) { $uname=$env{'user.name'};   }
                   3151:     return if ($udom eq 'public' && $uname eq 'public');
                   3152:     my $id=$uname.':'.$udom;
                   3153:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3154: }
                   3155: 
1.728     raeburn  3156: # -------------------------------------------------------------------- getlangs
                   3157: 
                   3158: =pod
                   3159: 
                   3160: =item * &getlangs($uname,$udom)
                   3161: 
                   3162: Gets a user's language preference and returns it as a hash with key:
                   3163: language.
                   3164: 
                   3165: =cut
                   3166: 
                   3167: 
                   3168: sub getlangs {
                   3169:     my ($uname,$udom) = @_;
                   3170:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3171:     if (!$uname) { $uname=$env{'user.name'};   }
                   3172:     my $id=$uname.':'.$udom;
                   3173:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3174:     if ($cached) {
                   3175:         return %{$langs};
                   3176:     } else {
                   3177:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3178:                                            $udom,$uname);
                   3179:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3180:         return %loadlangs;
                   3181:     }
                   3182: }
                   3183: 
                   3184: sub flush_langs_cache {
                   3185:     my ($uname,$udom)=@_;
                   3186:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3187:     if (!$uname) { $uname=$env{'user.name'};   }
                   3188:     return if ($udom eq 'public' && $uname eq 'public');
                   3189:     my $id=$uname.':'.$udom;
                   3190:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3191: }
                   3192: 
1.61      www      3193: # ------------------------------------------------------------------ Screenname
1.81      albertel 3194: 
                   3195: =pod
                   3196: 
1.648     raeburn  3197: =item * &screenname($uname,$udom)
1.81      albertel 3198: 
                   3199: Gets a users screenname and returns it as a string
                   3200: 
                   3201: =cut
1.61      www      3202: 
                   3203: sub screenname {
                   3204:     my ($uname,$udom)=@_;
1.258     albertel 3205:     if ($uname eq $env{'user.name'} &&
                   3206: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3207:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3208:     return $names{'screenname'};
1.62      www      3209: }
                   3210: 
1.212     albertel 3211: 
1.802     bisitz   3212: # ------------------------------------------------------------- Confirm Wrapper
                   3213: =pod
                   3214: 
                   3215: =item confirmwrapper
                   3216: 
                   3217: Wrap messages about completion of operation in box
                   3218: 
                   3219: =cut
                   3220: 
                   3221: sub confirmwrapper {
                   3222:     my ($message)=@_;
                   3223:     if ($message) {
                   3224:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3225:                .$message."\n"
                   3226:                .'</div>'."\n";
                   3227:     } else {
                   3228:         return $message;
                   3229:     }
                   3230: }
                   3231: 
1.62      www      3232: # ------------------------------------------------------------- Message Wrapper
                   3233: 
                   3234: sub messagewrapper {
1.369     www      3235:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3236:     return 
1.441     albertel 3237:         '<a href="/adm/email?compose=individual&amp;'.
                   3238:         'recname='.$username.'&amp;recdom='.$domain.
                   3239: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3240:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3241: }
1.802     bisitz   3242: 
1.74      www      3243: # --------------------------------------------------------------- Notes Wrapper
                   3244: 
                   3245: sub noteswrapper {
                   3246:     my ($link,$un,$do)=@_;
                   3247:     return 
1.896     amueller 3248: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3249: }
1.802     bisitz   3250: 
1.62      www      3251: # ------------------------------------------------------------- Aboutme Wrapper
                   3252: 
                   3253: sub aboutmewrapper {
1.1070    raeburn  3254:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3255:     if (!defined($username)  && !defined($domain)) {
                   3256:         return;
                   3257:     }
1.892     amueller 3258:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme?forcestudent=1"'.
1.1070    raeburn  3259: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3260: }
                   3261: 
                   3262: # ------------------------------------------------------------ Syllabus Wrapper
                   3263: 
                   3264: sub syllabuswrapper {
1.707     bisitz   3265:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3266:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3267: }
1.14      harris41 3268: 
1.802     bisitz   3269: # -----------------------------------------------------------------------------
                   3270: 
1.208     matthew  3271: sub track_student_link {
1.887     raeburn  3272:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3273:     my $link ="/adm/trackstudent?";
1.208     matthew  3274:     my $title = 'View recent activity';
                   3275:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3276:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3277:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3278:         $title .= ' of this student';
1.268     albertel 3279:     } 
1.208     matthew  3280:     if (defined($target) && $target !~ /^\s*$/) {
                   3281:         $target = qq{target="$target"};
                   3282:     } else {
                   3283:         $target = '';
                   3284:     }
1.268     albertel 3285:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3286:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3287:     $title = &mt($title);
                   3288:     $linktext = &mt($linktext);
1.448     albertel 3289:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3290: 	&help_open_topic('View_recent_activity');
1.208     matthew  3291: }
                   3292: 
1.781     raeburn  3293: sub slot_reservations_link {
                   3294:     my ($linktext,$sname,$sdom,$target) = @_;
                   3295:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3296:     my $title = 'View slot reservation history';
                   3297:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3298:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3299:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3300:         $title .= ' of this student';
                   3301:     }
                   3302:     if (defined($target) && $target !~ /^\s*$/) {
                   3303:         $target = qq{target="$target"};
                   3304:     } else {
                   3305:         $target = '';
                   3306:     }
                   3307:     $title = &mt($title);
                   3308:     $linktext = &mt($linktext);
                   3309:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3310: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3311: 
                   3312: }
                   3313: 
1.508     www      3314: # ===================================================== Display a student photo
                   3315: 
                   3316: 
1.509     albertel 3317: sub student_image_tag {
1.508     www      3318:     my ($domain,$user)=@_;
                   3319:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3320:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3321: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3322:     } else {
                   3323: 	return '';
                   3324:     }
                   3325: }
                   3326: 
1.112     bowersj2 3327: =pod
                   3328: 
                   3329: =back
                   3330: 
                   3331: =head1 Access .tab File Data
                   3332: 
                   3333: =over 4
                   3334: 
1.648     raeburn  3335: =item * &languageids() 
1.112     bowersj2 3336: 
                   3337: returns list of all language ids
                   3338: 
                   3339: =cut
                   3340: 
1.14      harris41 3341: sub languageids {
1.16      harris41 3342:     return sort(keys(%language));
1.14      harris41 3343: }
                   3344: 
1.112     bowersj2 3345: =pod
                   3346: 
1.648     raeburn  3347: =item * &languagedescription() 
1.112     bowersj2 3348: 
                   3349: returns description of a specified language id
                   3350: 
                   3351: =cut
                   3352: 
1.14      harris41 3353: sub languagedescription {
1.125     www      3354:     my $code=shift;
                   3355:     return  ($supported_language{$code}?'* ':'').
                   3356:             $language{$code}.
1.126     www      3357: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3358: }
                   3359: 
1.1048    foxr     3360: =pod
                   3361: 
                   3362: =item * &plainlanguagedescription
                   3363: 
                   3364: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3365: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3366: 
                   3367: =cut
                   3368: 
1.145     www      3369: sub plainlanguagedescription {
                   3370:     my $code=shift;
                   3371:     return $language{$code};
                   3372: }
                   3373: 
1.1048    foxr     3374: =pod
                   3375: 
                   3376: =item * &supportedlanguagecode
                   3377: 
                   3378: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3379: code.
                   3380: 
                   3381: =cut
                   3382: 
1.145     www      3383: sub supportedlanguagecode {
                   3384:     my $code=shift;
                   3385:     return $supported_language{$code};
1.97      www      3386: }
                   3387: 
1.112     bowersj2 3388: =pod
                   3389: 
1.1048    foxr     3390: =item * &latexlanguage()
                   3391: 
                   3392: Given a language key code returns the correspondnig language to use
                   3393: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3394: is no supported hyphenation for the language code.
                   3395: 
                   3396: =cut
                   3397: 
                   3398: sub latexlanguage {
                   3399:     my $code = shift;
                   3400:     return $latex_language{$code};
                   3401: }
                   3402: 
                   3403: =pod
                   3404: 
                   3405: =item * &latexhyphenation()
                   3406: 
                   3407: Same as above but what's supplied is the language as it might be stored
                   3408: in the metadata.
                   3409: 
                   3410: =cut
                   3411: 
                   3412: sub latexhyphenation {
                   3413:     my $key = shift;
                   3414:     return $latex_language_bykey{$key};
                   3415: }
                   3416: 
                   3417: =pod
                   3418: 
1.648     raeburn  3419: =item * &copyrightids() 
1.112     bowersj2 3420: 
                   3421: returns list of all copyrights
                   3422: 
                   3423: =cut
                   3424: 
                   3425: sub copyrightids {
                   3426:     return sort(keys(%cprtag));
                   3427: }
                   3428: 
                   3429: =pod
                   3430: 
1.648     raeburn  3431: =item * &copyrightdescription() 
1.112     bowersj2 3432: 
                   3433: returns description of a specified copyright id
                   3434: 
                   3435: =cut
                   3436: 
                   3437: sub copyrightdescription {
1.166     www      3438:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3439: }
1.197     matthew  3440: 
                   3441: =pod
                   3442: 
1.648     raeburn  3443: =item * &source_copyrightids() 
1.192     taceyjo1 3444: 
                   3445: returns list of all source copyrights
                   3446: 
                   3447: =cut
                   3448: 
                   3449: sub source_copyrightids {
                   3450:     return sort(keys(%scprtag));
                   3451: }
                   3452: 
                   3453: =pod
                   3454: 
1.648     raeburn  3455: =item * &source_copyrightdescription() 
1.192     taceyjo1 3456: 
                   3457: returns description of a specified source copyright id
                   3458: 
                   3459: =cut
                   3460: 
                   3461: sub source_copyrightdescription {
                   3462:     return &mt($scprtag{shift(@_)});
                   3463: }
1.112     bowersj2 3464: 
                   3465: =pod
                   3466: 
1.648     raeburn  3467: =item * &filecategories() 
1.112     bowersj2 3468: 
                   3469: returns list of all file categories
                   3470: 
                   3471: =cut
                   3472: 
                   3473: sub filecategories {
                   3474:     return sort(keys(%category_extensions));
                   3475: }
                   3476: 
                   3477: =pod
                   3478: 
1.648     raeburn  3479: =item * &filecategorytypes() 
1.112     bowersj2 3480: 
                   3481: returns list of file types belonging to a given file
                   3482: category
                   3483: 
                   3484: =cut
                   3485: 
                   3486: sub filecategorytypes {
1.356     albertel 3487:     my ($cat) = @_;
                   3488:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3489: }
                   3490: 
                   3491: =pod
                   3492: 
1.648     raeburn  3493: =item * &fileembstyle() 
1.112     bowersj2 3494: 
                   3495: returns embedding style for a specified file type
                   3496: 
                   3497: =cut
                   3498: 
                   3499: sub fileembstyle {
                   3500:     return $fe{lc(shift(@_))};
1.169     www      3501: }
                   3502: 
1.351     www      3503: sub filemimetype {
                   3504:     return $fm{lc(shift(@_))};
                   3505: }
                   3506: 
1.169     www      3507: 
                   3508: sub filecategoryselect {
                   3509:     my ($name,$value)=@_;
1.189     matthew  3510:     return &select_form($value,$name,
1.970     raeburn  3511:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 3512: }
                   3513: 
                   3514: =pod
                   3515: 
1.648     raeburn  3516: =item * &filedescription() 
1.112     bowersj2 3517: 
                   3518: returns description for a specified file type
                   3519: 
                   3520: =cut
                   3521: 
                   3522: sub filedescription {
1.188     matthew  3523:     my $file_description = $fd{lc(shift())};
                   3524:     $file_description =~ s:([\[\]]):~$1:g;
                   3525:     return &mt($file_description);
1.112     bowersj2 3526: }
                   3527: 
                   3528: =pod
                   3529: 
1.648     raeburn  3530: =item * &filedescriptionex() 
1.112     bowersj2 3531: 
                   3532: returns description for a specified file type with
                   3533: extra formatting
                   3534: 
                   3535: =cut
                   3536: 
                   3537: sub filedescriptionex {
                   3538:     my $ex=shift;
1.188     matthew  3539:     my $file_description = $fd{lc($ex)};
                   3540:     $file_description =~ s:([\[\]]):~$1:g;
                   3541:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3542: }
                   3543: 
                   3544: # End of .tab access
                   3545: =pod
                   3546: 
                   3547: =back
                   3548: 
                   3549: =cut
                   3550: 
                   3551: # ------------------------------------------------------------------ File Types
                   3552: sub fileextensions {
                   3553:     return sort(keys(%fe));
                   3554: }
                   3555: 
1.97      www      3556: # ----------------------------------------------------------- Display Languages
                   3557: # returns a hash with all desired display languages
                   3558: #
                   3559: 
                   3560: sub display_languages {
                   3561:     my %languages=();
1.695     raeburn  3562:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3563: 	$languages{$lang}=1;
1.97      www      3564:     }
                   3565:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3566:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3567: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3568: 	    $languages{$lang}=1;
1.97      www      3569:         }
                   3570:     }
                   3571:     return %languages;
1.14      harris41 3572: }
                   3573: 
1.582     albertel 3574: sub languages {
                   3575:     my ($possible_langs) = @_;
1.695     raeburn  3576:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3577:     if (!ref($possible_langs)) {
                   3578: 	if( wantarray ) {
                   3579: 	    return @preferred_langs;
                   3580: 	} else {
                   3581: 	    return $preferred_langs[0];
                   3582: 	}
                   3583:     }
                   3584:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3585:     my @preferred_possibilities;
                   3586:     foreach my $preferred_lang (@preferred_langs) {
                   3587: 	if (exists($possibilities{$preferred_lang})) {
                   3588: 	    push(@preferred_possibilities, $preferred_lang);
                   3589: 	}
                   3590:     }
                   3591:     if( wantarray ) {
                   3592: 	return @preferred_possibilities;
                   3593:     }
                   3594:     return $preferred_possibilities[0];
                   3595: }
                   3596: 
1.742     raeburn  3597: sub user_lang {
                   3598:     my ($touname,$toudom,$fromcid) = @_;
                   3599:     my @userlangs;
                   3600:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   3601:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   3602:                     $env{'course.'.$fromcid.'.languages'}));
                   3603:     } else {
                   3604:         my %langhash = &getlangs($touname,$toudom);
                   3605:         if ($langhash{'languages'} ne '') {
                   3606:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   3607:         } else {
                   3608:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   3609:             if ($domdefs{'lang_def'} ne '') {
                   3610:                 @userlangs = ($domdefs{'lang_def'});
                   3611:             }
                   3612:         }
                   3613:     }
                   3614:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   3615:     my $user_lh = Apache::localize->get_handle(@languages);
                   3616:     return $user_lh;
                   3617: }
                   3618: 
                   3619: 
1.112     bowersj2 3620: ###############################################################
                   3621: ##               Student Answer Attempts                     ##
                   3622: ###############################################################
                   3623: 
                   3624: =pod
                   3625: 
                   3626: =head1 Alternate Problem Views
                   3627: 
                   3628: =over 4
                   3629: 
1.648     raeburn  3630: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.112     bowersj2 3631:     $getattempt, $regexp, $gradesub)
                   3632: 
                   3633: Return string with previous attempt on problem. Arguments:
                   3634: 
                   3635: =over 4
                   3636: 
                   3637: =item * $symb: Problem, including path
                   3638: 
                   3639: =item * $username: username of the desired student
                   3640: 
                   3641: =item * $domain: domain of the desired student
1.14      harris41 3642: 
1.112     bowersj2 3643: =item * $course: Course ID
1.14      harris41 3644: 
1.112     bowersj2 3645: =item * $getattempt: Leave blank for all attempts, otherwise put
                   3646:     something
1.14      harris41 3647: 
1.112     bowersj2 3648: =item * $regexp: if string matches this regexp, the string will be
                   3649:     sent to $gradesub
1.14      harris41 3650: 
1.112     bowersj2 3651: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 3652: 
1.112     bowersj2 3653: =back
1.14      harris41 3654: 
1.112     bowersj2 3655: The output string is a table containing all desired attempts, if any.
1.16      harris41 3656: 
1.112     bowersj2 3657: =cut
1.1       albertel 3658: 
                   3659: sub get_previous_attempt {
1.43      ng       3660:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
1.1       albertel 3661:   my $prevattempts='';
1.43      ng       3662:   no strict 'refs';
1.1       albertel 3663:   if ($symb) {
1.3       albertel 3664:     my (%returnhash)=
                   3665:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 3666:     if ($returnhash{'version'}) {
                   3667:       my %lasthash=();
                   3668:       my $version;
                   3669:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.356     albertel 3670:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   3671: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
1.19      harris41 3672:         }
1.1       albertel 3673:       }
1.596     albertel 3674:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   3675:       $prevattempts.='<th>'.&mt('History').'</th>';
1.978     raeburn  3676:       my (%typeparts,%lasthidden);
1.945     raeburn  3677:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 3678:       foreach my $key (sort(keys(%lasthash))) {
                   3679: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       3680: 	if ($#parts > 0) {
1.31      albertel 3681: 	  my $data=$parts[-1];
1.989     raeburn  3682:           next if ($data eq 'foilorder');
1.31      albertel 3683: 	  pop(@parts);
1.1010    www      3684:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  3685:           if ($data eq 'type') {
                   3686:               unless ($showsurv) {
                   3687:                   my $id = join(',',@parts);
                   3688:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  3689:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   3690:                       $lasthidden{$ign.'.'.$id} = 1;
                   3691:                   }
1.945     raeburn  3692:               }
1.1010    www      3693:           } 
1.31      albertel 3694: 	} else {
1.41      ng       3695: 	  if ($#parts == 0) {
                   3696: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   3697: 	  } else {
                   3698: 	    $prevattempts.='<th>'.$ign.'</th>';
                   3699: 	  }
1.31      albertel 3700: 	}
1.16      harris41 3701:       }
1.596     albertel 3702:       $prevattempts.=&end_data_table_header_row();
1.40      ng       3703:       if ($getattempt eq '') {
                   3704: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.945     raeburn  3705:             my @hidden;
                   3706:             if (%typeparts) {
                   3707:                 foreach my $id (keys(%typeparts)) {
                   3708:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
                   3709:                         push(@hidden,$id);
                   3710:                     }
                   3711:                 }
                   3712:             }
                   3713:             $prevattempts.=&start_data_table_row().
                   3714:                            '<td>'.&mt('Transaction [_1]',$version).'</td>';
                   3715:             if (@hidden) {
                   3716:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3717:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  3718:                     my $hide;
                   3719:                     foreach my $id (@hidden) {
                   3720:                         if ($key =~ /^\Q$id\E/) {
                   3721:                             $hide = 1;
                   3722:                             last;
                   3723:                         }
                   3724:                     }
                   3725:                     if ($hide) {
                   3726:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   3727:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   3728:                             my $value = &format_previous_attempt_value($key,
                   3729:                                              $returnhash{$version.':'.$key});
                   3730:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3731:                         } else {
                   3732:                             $prevattempts.='<td>&nbsp;</td>';
                   3733:                         }
                   3734:                     } else {
                   3735:                         if ($key =~ /\./) {
                   3736:                             my $value = &format_previous_attempt_value($key,
                   3737:                                               $returnhash{$version.':'.$key});
                   3738:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3739:                         } else {
                   3740:                             $prevattempts.='<td>&nbsp;</td>';
                   3741:                         }
                   3742:                     }
                   3743:                 }
                   3744:             } else {
                   3745: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3746:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  3747: 		    my $value = &format_previous_attempt_value($key,
                   3748: 			            $returnhash{$version.':'.$key});
                   3749: 		    $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3750: 	        }
                   3751:             }
                   3752: 	    $prevattempts.=&end_data_table_row();
1.40      ng       3753: 	 }
1.1       albertel 3754:       }
1.945     raeburn  3755:       my @currhidden = keys(%lasthidden);
1.596     albertel 3756:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 3757:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3758:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  3759:           if (%typeparts) {
                   3760:               my $hidden;
                   3761:               foreach my $id (@currhidden) {
                   3762:                   if ($key =~ /^\Q$id\E/) {
                   3763:                       $hidden = 1;
                   3764:                       last;
                   3765:                   }
                   3766:               }
                   3767:               if ($hidden) {
                   3768:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   3769:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   3770:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3771:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3772:                           $value = &$gradesub($value);
                   3773:                       }
                   3774:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3775:                   } else {
                   3776:                       $prevattempts.='<td>&nbsp;</td>';
                   3777:                   }
                   3778:               } else {
                   3779:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3780:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3781:                       $value = &$gradesub($value);
                   3782:                   }
                   3783:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3784:               }
                   3785:           } else {
                   3786: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3787: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3788:                   $value = &$gradesub($value);
                   3789:               }
                   3790: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3791:           }
1.16      harris41 3792:       }
1.596     albertel 3793:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 3794:     } else {
1.596     albertel 3795:       $prevattempts=
                   3796: 	  &start_data_table().&start_data_table_row().
                   3797: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   3798: 	  &end_data_table_row().&end_data_table();
1.1       albertel 3799:     }
                   3800:   } else {
1.596     albertel 3801:     $prevattempts=
                   3802: 	  &start_data_table().&start_data_table_row().
                   3803: 	  '<td>'.&mt('No data.').'</td>'.
                   3804: 	  &end_data_table_row().&end_data_table();
1.1       albertel 3805:   }
1.10      albertel 3806: }
                   3807: 
1.581     albertel 3808: sub format_previous_attempt_value {
                   3809:     my ($key,$value) = @_;
1.1011    www      3810:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 3811: 	$value = &Apache::lonlocal::locallocaltime($value);
                   3812:     } elsif (ref($value) eq 'ARRAY') {
                   3813: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  3814:     } elsif ($key =~ /answerstring$/) {
                   3815:         my %answers = &Apache::lonnet::str2hash($value);
                   3816:         my @anskeys = sort(keys(%answers));
                   3817:         if (@anskeys == 1) {
                   3818:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  3819:             if ($answer =~ m{\0}) {
                   3820:                 $answer =~ s{\0}{,}g;
1.988     raeburn  3821:             }
                   3822:             my $tag_internal_answer_name = 'INTERNAL';
                   3823:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   3824:                 $value = $answer; 
                   3825:             } else {
                   3826:                 $value = $anskeys[0].'='.$answer;
                   3827:             }
                   3828:         } else {
                   3829:             foreach my $ans (@anskeys) {
                   3830:                 my $answer = $answers{$ans};
1.1001    raeburn  3831:                 if ($answer =~ m{\0}) {
                   3832:                     $answer =~ s{\0}{,}g;
1.988     raeburn  3833:                 }
                   3834:                 $value .=  $ans.'='.$answer.'<br />';;
                   3835:             } 
                   3836:         }
1.581     albertel 3837:     } else {
                   3838: 	$value = &unescape($value);
                   3839:     }
                   3840:     return $value;
                   3841: }
                   3842: 
                   3843: 
1.107     albertel 3844: sub relative_to_absolute {
                   3845:     my ($url,$output)=@_;
                   3846:     my $parser=HTML::TokeParser->new(\$output);
                   3847:     my $token;
                   3848:     my $thisdir=$url;
                   3849:     my @rlinks=();
                   3850:     while ($token=$parser->get_token) {
                   3851: 	if ($token->[0] eq 'S') {
                   3852: 	    if ($token->[1] eq 'a') {
                   3853: 		if ($token->[2]->{'href'}) {
                   3854: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   3855: 		}
                   3856: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   3857: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   3858: 	    } elsif ($token->[1] eq 'base') {
                   3859: 		$thisdir=$token->[2]->{'href'};
                   3860: 	    }
                   3861: 	}
                   3862:     }
                   3863:     $thisdir=~s-/[^/]*$--;
1.356     albertel 3864:     foreach my $link (@rlinks) {
1.726     raeburn  3865: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 3866: 		($link=~/^\//) ||
                   3867: 		($link=~/^javascript:/i) ||
                   3868: 		($link=~/^mailto:/i) ||
                   3869: 		($link=~/^\#/)) {
                   3870: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   3871: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 3872: 	}
                   3873:     }
                   3874: # -------------------------------------------------- Deal with Applet codebases
                   3875:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   3876:     return $output;
                   3877: }
                   3878: 
1.112     bowersj2 3879: =pod
                   3880: 
1.648     raeburn  3881: =item * &get_student_view()
1.112     bowersj2 3882: 
                   3883: show a snapshot of what student was looking at
                   3884: 
                   3885: =cut
                   3886: 
1.10      albertel 3887: sub get_student_view {
1.186     albertel 3888:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      3889:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 3890:   my (%form);
1.10      albertel 3891:   my @elements=('symb','courseid','domain','username');
                   3892:   foreach my $element (@elements) {
1.186     albertel 3893:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 3894:   }
1.186     albertel 3895:   if (defined($moreenv)) {
                   3896:       %form=(%form,%{$moreenv});
                   3897:   }
1.236     albertel 3898:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 3899:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      3900:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 3901:   $userview=~s/\<body[^\>]*\>//gi;
                   3902:   $userview=~s/\<\/body\>//gi;
                   3903:   $userview=~s/\<html\>//gi;
                   3904:   $userview=~s/\<\/html\>//gi;
                   3905:   $userview=~s/\<head\>//gi;
                   3906:   $userview=~s/\<\/head\>//gi;
                   3907:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 3908:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      3909:   if (wantarray) {
                   3910:      return ($userview,$response);
                   3911:   } else {
                   3912:      return $userview;
                   3913:   }
                   3914: }
                   3915: 
                   3916: sub get_student_view_with_retries {
                   3917:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   3918: 
                   3919:     my $ok = 0;                 # True if we got a good response.
                   3920:     my $content;
                   3921:     my $response;
                   3922: 
                   3923:     # Try to get the student_view done. within the retries count:
                   3924:     
                   3925:     do {
                   3926:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   3927:          $ok      = $response->is_success;
                   3928:          if (!$ok) {
                   3929:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   3930:          }
                   3931:          $retries--;
                   3932:     } while (!$ok && ($retries > 0));
                   3933:     
                   3934:     if (!$ok) {
                   3935:        $content = '';          # On error return an empty content.
                   3936:     }
1.651     www      3937:     if (wantarray) {
                   3938:        return ($content, $response);
                   3939:     } else {
                   3940:        return $content;
                   3941:     }
1.11      albertel 3942: }
                   3943: 
1.112     bowersj2 3944: =pod
                   3945: 
1.648     raeburn  3946: =item * &get_student_answers() 
1.112     bowersj2 3947: 
                   3948: show a snapshot of how student was answering problem
                   3949: 
                   3950: =cut
                   3951: 
1.11      albertel 3952: sub get_student_answers {
1.100     sakharuk 3953:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      3954:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 3955:   my (%moreenv);
1.11      albertel 3956:   my @elements=('symb','courseid','domain','username');
                   3957:   foreach my $element (@elements) {
1.186     albertel 3958:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 3959:   }
1.186     albertel 3960:   $moreenv{'grade_target'}='answer';
                   3961:   %moreenv=(%form,%moreenv);
1.497     raeburn  3962:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   3963:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 3964:   return $userview;
1.1       albertel 3965: }
1.116     albertel 3966: 
                   3967: =pod
                   3968: 
                   3969: =item * &submlink()
                   3970: 
1.242     albertel 3971: Inputs: $text $uname $udom $symb $target
1.116     albertel 3972: 
                   3973: Returns: A link to grades.pm such as to see the SUBM view of a student
                   3974: 
                   3975: =cut
                   3976: 
                   3977: ###############################################
                   3978: sub submlink {
1.242     albertel 3979:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 3980:     if (!($uname && $udom)) {
                   3981: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 3982: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 3983: 	if (!$symb) { $symb=$cursymb; }
                   3984:     }
1.254     matthew  3985:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      3986:     $symb=&escape($symb);
1.960     bisitz   3987:     if ($target) { $target=" target=\"$target\""; }
                   3988:     return
                   3989:         '<a href="/adm/grades?command=submission'.
                   3990:         '&amp;symb='.$symb.
                   3991:         '&amp;student='.$uname.
                   3992:         '&amp;userdom='.$udom.'"'.
                   3993:         $target.'>'.$text.'</a>';
1.242     albertel 3994: }
                   3995: ##############################################
                   3996: 
                   3997: =pod
                   3998: 
                   3999: =item * &pgrdlink()
                   4000: 
                   4001: Inputs: $text $uname $udom $symb $target
                   4002: 
                   4003: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4004: 
                   4005: =cut
                   4006: 
                   4007: ###############################################
                   4008: sub pgrdlink {
                   4009:     my $link=&submlink(@_);
                   4010:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4011:     return $link;
                   4012: }
                   4013: ##############################################
                   4014: 
                   4015: =pod
                   4016: 
                   4017: =item * &pprmlink()
                   4018: 
                   4019: Inputs: $text $uname $udom $symb $target
                   4020: 
                   4021: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4022: student and a specific resource
1.242     albertel 4023: 
                   4024: =cut
                   4025: 
                   4026: ###############################################
                   4027: sub pprmlink {
                   4028:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4029:     if (!($uname && $udom)) {
                   4030: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4031: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4032: 	if (!$symb) { $symb=$cursymb; }
                   4033:     }
1.254     matthew  4034:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4035:     $symb=&escape($symb);
1.242     albertel 4036:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4037:     return '<a href="/adm/parmset?command=set&amp;'.
                   4038: 	'symb='.$symb.'&amp;uname='.$uname.
                   4039: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4040: }
                   4041: ##############################################
1.37      matthew  4042: 
1.112     bowersj2 4043: =pod
                   4044: 
                   4045: =back
                   4046: 
                   4047: =cut
                   4048: 
1.37      matthew  4049: ###############################################
1.51      www      4050: 
                   4051: 
                   4052: sub timehash {
1.687     raeburn  4053:     my ($thistime) = @_;
                   4054:     my $timezone = &Apache::lonlocal::gettimezone();
                   4055:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4056:                      ->set_time_zone($timezone);
                   4057:     my $wday = $dt->day_of_week();
                   4058:     if ($wday == 7) { $wday = 0; }
                   4059:     return ( 'second' => $dt->second(),
                   4060:              'minute' => $dt->minute(),
                   4061:              'hour'   => $dt->hour(),
                   4062:              'day'     => $dt->day_of_month(),
                   4063:              'month'   => $dt->month(),
                   4064:              'year'    => $dt->year(),
                   4065:              'weekday' => $wday,
                   4066:              'dayyear' => $dt->day_of_year(),
                   4067:              'dlsav'   => $dt->is_dst() );
1.51      www      4068: }
                   4069: 
1.370     www      4070: sub utc_string {
                   4071:     my ($date)=@_;
1.371     www      4072:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4073: }
                   4074: 
1.51      www      4075: sub maketime {
                   4076:     my %th=@_;
1.687     raeburn  4077:     my ($epoch_time,$timezone,$dt);
                   4078:     $timezone = &Apache::lonlocal::gettimezone();
                   4079:     eval {
                   4080:         $dt = DateTime->new( year   => $th{'year'},
                   4081:                              month  => $th{'month'},
                   4082:                              day    => $th{'day'},
                   4083:                              hour   => $th{'hour'},
                   4084:                              minute => $th{'minute'},
                   4085:                              second => $th{'second'},
                   4086:                              time_zone => $timezone,
                   4087:                          );
                   4088:     };
                   4089:     if (!$@) {
                   4090:         $epoch_time = $dt->epoch;
                   4091:         if ($epoch_time) {
                   4092:             return $epoch_time;
                   4093:         }
                   4094:     }
1.51      www      4095:     return POSIX::mktime(
                   4096:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4097:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4098: }
                   4099: 
                   4100: #########################################
1.51      www      4101: 
                   4102: sub findallcourses {
1.482     raeburn  4103:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4104:     my %roles;
                   4105:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4106:     my %courses;
1.51      www      4107:     my $now=time;
1.482     raeburn  4108:     if (!defined($uname)) {
                   4109:         $uname = $env{'user.name'};
                   4110:     }
                   4111:     if (!defined($udom)) {
                   4112:         $udom = $env{'user.domain'};
                   4113:     }
                   4114:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4115:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4116:         if (!%roles) {
                   4117:             %roles = (
                   4118:                        cc => 1,
1.907     raeburn  4119:                        co => 1,
1.482     raeburn  4120:                        in => 1,
                   4121:                        ep => 1,
                   4122:                        ta => 1,
                   4123:                        cr => 1,
                   4124:                        st => 1,
                   4125:              );
                   4126:         }
                   4127:         foreach my $entry (keys(%roleshash)) {
                   4128:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4129:             if ($trole =~ /^cr/) { 
                   4130:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4131:             } else {
                   4132:                 next if (!exists($roles{$trole}));
                   4133:             }
                   4134:             if ($tend) {
                   4135:                 next if ($tend < $now);
                   4136:             }
                   4137:             if ($tstart) {
                   4138:                 next if ($tstart > $now);
                   4139:             }
1.1058    raeburn  4140:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4141:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4142:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4143:             if ($secpart eq '') {
                   4144:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4145:                 $sec = 'none';
1.1058    raeburn  4146:                 $value .= $cnum.'/';
1.482     raeburn  4147:             } else {
                   4148:                 $cnum = $cnumpart;
                   4149:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4150:                 $value .= $cnum.'/'.$sec;
                   4151:             }
                   4152:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4153:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4154:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4155:                 }
                   4156:             } else {
                   4157:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4158:             }
1.482     raeburn  4159:         }
                   4160:     } else {
                   4161:         foreach my $key (keys(%env)) {
1.483     albertel 4162: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4163:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4164: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4165: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4166: 	        next if (%roles && !exists($roles{$role}));
                   4167: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4168:                 my $active=1;
                   4169:                 if ($starttime) {
                   4170: 		    if ($now<$starttime) { $active=0; }
                   4171:                 }
                   4172:                 if ($endtime) {
                   4173:                     if ($now>$endtime) { $active=0; }
                   4174:                 }
                   4175:                 if ($active) {
1.1058    raeburn  4176:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4177:                     if ($sec eq '') {
                   4178:                         $sec = 'none';
1.1058    raeburn  4179:                     } else {
                   4180:                         $value .= $sec;
                   4181:                     }
                   4182:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4183:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4184:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4185:                         }
                   4186:                     } else {
                   4187:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4188:                     }
1.474     raeburn  4189:                 }
                   4190:             }
1.51      www      4191:         }
                   4192:     }
1.474     raeburn  4193:     return %courses;
1.51      www      4194: }
1.37      matthew  4195: 
1.54      www      4196: ###############################################
1.474     raeburn  4197: 
                   4198: sub blockcheck {
1.1062    raeburn  4199:     my ($setters,$activity,$uname,$udom,$url) = @_;
1.490     raeburn  4200: 
                   4201:     if (!defined($udom)) {
                   4202:         $udom = $env{'user.domain'};
                   4203:     }
                   4204:     if (!defined($uname)) {
                   4205:         $uname = $env{'user.name'};
                   4206:     }
                   4207: 
                   4208:     # If uname and udom are for a course, check for blocks in the course.
                   4209: 
                   4210:     if (&Apache::lonnet::is_course($udom,$uname)) {
1.1062    raeburn  4211:         my ($startblock,$endblock,$triggerblock) = 
                   4212:             &get_blocks($setters,$activity,$udom,$uname,$url);
                   4213:         return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4214:     }
1.474     raeburn  4215: 
1.502     raeburn  4216:     my $startblock = 0;
                   4217:     my $endblock = 0;
1.1062    raeburn  4218:     my $triggerblock = '';
1.482     raeburn  4219:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4220: 
1.490     raeburn  4221:     # If uname is for a user, and activity is course-specific, i.e.,
                   4222:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4223: 
1.490     raeburn  4224:     if (($activity eq 'boards' || $activity eq 'chat' ||
                   4225:          $activity eq 'groups') && ($env{'request.course.id'})) {
                   4226:         foreach my $key (keys(%live_courses)) {
                   4227:             if ($key ne $env{'request.course.id'}) {
                   4228:                 delete($live_courses{$key});
                   4229:             }
                   4230:         }
                   4231:     }
                   4232: 
                   4233:     my $otheruser = 0;
                   4234:     my %own_courses;
                   4235:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4236:         # Resource belongs to user other than current user.
                   4237:         $otheruser = 1;
                   4238:         # Gather courses for current user
                   4239:         %own_courses = 
                   4240:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4241:     }
                   4242: 
                   4243:     # Gather active course roles - course coordinator, instructor, 
                   4244:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4245: 
                   4246:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4247:         my ($cdom,$cnum);
                   4248:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4249:             $cdom = $env{'course.'.$course.'.domain'};
                   4250:             $cnum = $env{'course.'.$course.'.num'};
                   4251:         } else {
1.490     raeburn  4252:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4253:         }
                   4254:         my $no_ownblock = 0;
                   4255:         my $no_userblock = 0;
1.533     raeburn  4256:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4257:             # Check if current user has 'evb' priv for this
                   4258:             if (defined($own_courses{$course})) {
                   4259:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4260:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4261:                     if ($sec ne 'none') {
                   4262:                         $checkrole .= '/'.$sec;
                   4263:                     }
                   4264:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4265:                         $no_ownblock = 1;
                   4266:                         last;
                   4267:                     }
                   4268:                 }
                   4269:             }
                   4270:             # if they have 'evb' priv and are currently not playing student
                   4271:             next if (($no_ownblock) &&
                   4272:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4273:         }
1.474     raeburn  4274:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4275:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4276:             if ($sec ne 'none') {
1.482     raeburn  4277:                 $checkrole .= '/'.$sec;
1.474     raeburn  4278:             }
1.490     raeburn  4279:             if ($otheruser) {
                   4280:                 # Resource belongs to user other than current user.
                   4281:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4282:                 my (%allroles,%userroles);
                   4283:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4284:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4285:                         my ($trole,$tdom,$tnum,$tsec);
                   4286:                         if ($entry =~ /^cr/) {
                   4287:                             ($trole,$tdom,$tnum,$tsec) = 
                   4288:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4289:                         } else {
                   4290:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4291:                         }
                   4292:                         my ($spec,$area,$trest);
                   4293:                         $area = '/'.$tdom.'/'.$tnum;
                   4294:                         $trest = $tnum;
                   4295:                         if ($tsec ne '') {
                   4296:                             $area .= '/'.$tsec;
                   4297:                             $trest .= '/'.$tsec;
                   4298:                         }
                   4299:                         $spec = $trole.'.'.$area;
                   4300:                         if ($trole =~ /^cr/) {
                   4301:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4302:                                                               $tdom,$spec,$trest,$area);
                   4303:                         } else {
                   4304:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4305:                                                                 $tdom,$spec,$trest,$area);
                   4306:                         }
                   4307:                     }
                   4308:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
                   4309:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   4310:                         if ($1) {
                   4311:                             $no_userblock = 1;
                   4312:                             last;
                   4313:                         }
1.486     raeburn  4314:                     }
                   4315:                 }
1.490     raeburn  4316:             } else {
                   4317:                 # Resource belongs to current user
                   4318:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  4319:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4320:                     $no_ownblock = 1;
                   4321:                     last;
                   4322:                 }
1.474     raeburn  4323:             }
                   4324:         }
                   4325:         # if they have the evb priv and are currently not playing student
1.482     raeburn  4326:         next if (($no_ownblock) &&
1.491     albertel 4327:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  4328:         next if ($no_userblock);
1.474     raeburn  4329: 
1.866     kalberla 4330:         # Retrieve blocking times and identity of locker for course
1.490     raeburn  4331:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  4332:         
1.1062    raeburn  4333:         my ($start,$end,$trigger) = 
                   4334:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  4335:         if (($start != 0) && 
                   4336:             (($startblock == 0) || ($startblock > $start))) {
                   4337:             $startblock = $start;
1.1062    raeburn  4338:             if ($trigger ne '') {
                   4339:                 $triggerblock = $trigger;
                   4340:             }
1.502     raeburn  4341:         }
                   4342:         if (($end != 0)  &&
                   4343:             (($endblock == 0) || ($endblock < $end))) {
                   4344:             $endblock = $end;
1.1062    raeburn  4345:             if ($trigger ne '') {
                   4346:                 $triggerblock = $trigger;
                   4347:             }
1.502     raeburn  4348:         }
1.490     raeburn  4349:     }
1.1062    raeburn  4350:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4351: }
                   4352: 
                   4353: sub get_blocks {
1.1062    raeburn  4354:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  4355:     my $startblock = 0;
                   4356:     my $endblock = 0;
1.1062    raeburn  4357:     my $triggerblock = '';
1.490     raeburn  4358:     my $course = $cdom.'_'.$cnum;
                   4359:     $setters->{$course} = {};
                   4360:     $setters->{$course}{'staff'} = [];
                   4361:     $setters->{$course}{'times'} = [];
1.1062    raeburn  4362:     $setters->{$course}{'triggers'} = [];
                   4363:     my (@blockers,%triggered);
                   4364:     my $now = time;
                   4365:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   4366:     if ($activity eq 'docs') {
                   4367:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   4368:         foreach my $block (@blockers) {
                   4369:             if ($block =~ /^firstaccess____(.+)$/) {
                   4370:                 my $item = $1;
                   4371:                 my $type = 'map';
                   4372:                 my $timersymb = $item;
                   4373:                 if ($item eq 'course') {
                   4374:                     $type = 'course';
                   4375:                 } elsif ($item =~ /___\d+___/) {
                   4376:                     $type = 'resource';
                   4377:                 } else {
                   4378:                     $timersymb = &Apache::lonnet::symbread($item);
                   4379:                 }
                   4380:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4381:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   4382:                 $triggered{$block} = {
                   4383:                                        start => $start,
                   4384:                                        end   => $end,
                   4385:                                        type  => $type,
                   4386:                                      };
                   4387:             }
                   4388:         }
                   4389:     } else {
                   4390:         foreach my $block (keys(%commblocks)) {
                   4391:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   4392:                 my ($start,$end) = ($1,$2);
                   4393:                 if ($start <= time && $end >= time) {
                   4394:                     if (ref($commblocks{$block}) eq 'HASH') {
                   4395:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   4396:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   4397:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   4398:                                     push(@blockers,$block);
                   4399:                                 }
                   4400:                             }
                   4401:                         }
                   4402:                     }
                   4403:                 }
                   4404:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   4405:                 my $item = $1;
                   4406:                 my $timersymb = $item; 
                   4407:                 my $type = 'map';
                   4408:                 if ($item eq 'course') {
                   4409:                     $type = 'course';
                   4410:                 } elsif ($item =~ /___\d+___/) {
                   4411:                     $type = 'resource';
                   4412:                 } else {
                   4413:                     $timersymb = &Apache::lonnet::symbread($item);
                   4414:                 }
                   4415:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4416:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   4417:                 if ($start && $end) {
                   4418:                     if (($start <= time) && ($end >= time)) {
                   4419:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   4420:                             push(@blockers,$block);
                   4421:                             $triggered{$block} = {
                   4422:                                                    start => $start,
                   4423:                                                    end   => $end,
                   4424:                                                    type  => $type,
                   4425:                                                  };
                   4426:                         }
                   4427:                     }
1.490     raeburn  4428:                 }
1.1062    raeburn  4429:             }
                   4430:         }
                   4431:     }
                   4432:     foreach my $blocker (@blockers) {
                   4433:         my ($staff_name,$staff_dom,$title,$blocks) =
                   4434:             &parse_block_record($commblocks{$blocker});
                   4435:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   4436:         my ($start,$end,$triggertype);
                   4437:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   4438:             ($start,$end) = ($1,$2);
                   4439:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   4440:             $start = $triggered{$blocker}{'start'};
                   4441:             $end = $triggered{$blocker}{'end'};
                   4442:             $triggertype = $triggered{$blocker}{'type'};
                   4443:         }
                   4444:         if ($start) {
                   4445:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   4446:             if ($triggertype) {
                   4447:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   4448:             } else {
                   4449:                 push(@{$$setters{$course}{'triggers'}},0);
                   4450:             }
                   4451:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   4452:                 $startblock = $start;
                   4453:                 if ($triggertype) {
                   4454:                     $triggerblock = $blocker;
1.474     raeburn  4455:                 }
                   4456:             }
1.1062    raeburn  4457:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   4458:                $endblock = $end;
                   4459:                if ($triggertype) {
                   4460:                    $triggerblock = $blocker;
                   4461:                }
                   4462:             }
1.474     raeburn  4463:         }
                   4464:     }
1.1062    raeburn  4465:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  4466: }
                   4467: 
                   4468: sub parse_block_record {
                   4469:     my ($record) = @_;
                   4470:     my ($setuname,$setudom,$title,$blocks);
                   4471:     if (ref($record) eq 'HASH') {
                   4472:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   4473:         $title = &unescape($record->{'event'});
                   4474:         $blocks = $record->{'blocks'};
                   4475:     } else {
                   4476:         my @data = split(/:/,$record,3);
                   4477:         if (scalar(@data) eq 2) {
                   4478:             $title = $data[1];
                   4479:             ($setuname,$setudom) = split(/@/,$data[0]);
                   4480:         } else {
                   4481:             ($setuname,$setudom,$title) = @data;
                   4482:         }
                   4483:         $blocks = { 'com' => 'on' };
                   4484:     }
                   4485:     return ($setuname,$setudom,$title,$blocks);
                   4486: }
                   4487: 
1.854     kalberla 4488: sub blocking_status {
1.1062    raeburn  4489:     my ($activity,$uname,$udom,$url) = @_;
1.1061    raeburn  4490:     my %setters;
1.890     droeschl 4491: 
1.1061    raeburn  4492: # check for active blocking
1.1062    raeburn  4493:     my ($startblock,$endblock,$triggerblock) = 
                   4494:         &blockcheck(\%setters,$activity,$uname,$udom,$url);
                   4495:     my $blocked = 0;
                   4496:     if ($startblock && $endblock) {
                   4497:         $blocked = 1;
                   4498:     }
1.890     droeschl 4499: 
1.1061    raeburn  4500: # caller just wants to know whether a block is active
                   4501:     if (!wantarray) { return $blocked; }
                   4502: 
                   4503: # build a link to a popup window containing the details
                   4504:     my $querystring  = "?activity=$activity";
                   4505: # $uname and $udom decide whose portfolio the user is trying to look at
1.1062    raeburn  4506:     if ($activity eq 'port') {
                   4507:         $querystring .= "&amp;udom=$udom"      if $udom;
                   4508:         $querystring .= "&amp;uname=$uname"    if $uname;
                   4509:     } elsif ($activity eq 'docs') {
                   4510:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   4511:     }
1.1061    raeburn  4512: 
                   4513:     my $output .= <<'END_MYBLOCK';
                   4514: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   4515:     var options = "width=" + w + ",height=" + h + ",";
                   4516:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   4517:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   4518:     var newWin = window.open(url, wdwName, options);
                   4519:     newWin.focus();
                   4520: }
1.890     droeschl 4521: END_MYBLOCK
1.854     kalberla 4522: 
1.1061    raeburn  4523:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 4524:   
1.1061    raeburn  4525:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  4526:     my $text = &mt('Communication Blocked');
                   4527:     if ($activity eq 'docs') {
                   4528:         $text = &mt('Content Access Blocked');
1.1063    raeburn  4529:     } elsif ($activity eq 'printout') {
                   4530:         $text = &mt('Printing Blocked');
1.1062    raeburn  4531:     }
1.1061    raeburn  4532:     $output .= <<"END_BLOCK";
1.867     kalberla 4533: <div class='LC_comblock'>
1.869     kalberla 4534:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 4535:   title='$text'>
                   4536:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 4537:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 4538:   title='$text'>$text</a>
1.867     kalberla 4539: </div>
                   4540: 
                   4541: END_BLOCK
1.474     raeburn  4542: 
1.1061    raeburn  4543:     return ($blocked, $output);
1.854     kalberla 4544: }
1.490     raeburn  4545: 
1.60      matthew  4546: ###############################################
                   4547: 
1.682     raeburn  4548: sub check_ip_acc {
                   4549:     my ($acc)=@_;
                   4550:     &Apache::lonxml::debug("acc is $acc");
                   4551:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   4552:         return 1;
                   4553:     }
                   4554:     my $allowed=0;
                   4555:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
                   4556: 
                   4557:     my $name;
                   4558:     foreach my $pattern (split(',',$acc)) {
                   4559:         $pattern =~ s/^\s*//;
                   4560:         $pattern =~ s/\s*$//;
                   4561:         if ($pattern =~ /\*$/) {
                   4562:             #35.8.*
                   4563:             $pattern=~s/\*//;
                   4564:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4565:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   4566:             #35.8.3.[34-56]
                   4567:             my $low=$2;
                   4568:             my $high=$3;
                   4569:             $pattern=$1;
                   4570:             if ($ip =~ /^\Q$pattern\E/) {
                   4571:                 my $last=(split(/\./,$ip))[3];
                   4572:                 if ($last <=$high && $last >=$low) { $allowed=1; }
                   4573:             }
                   4574:         } elsif ($pattern =~ /^\*/) {
                   4575:             #*.msu.edu
                   4576:             $pattern=~s/\*//;
                   4577:             if (!defined($name)) {
                   4578:                 use Socket;
                   4579:                 my $netaddr=inet_aton($ip);
                   4580:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4581:             }
                   4582:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4583:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   4584:             #127.0.0.1
                   4585:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4586:         } else {
                   4587:             #some.name.com
                   4588:             if (!defined($name)) {
                   4589:                 use Socket;
                   4590:                 my $netaddr=inet_aton($ip);
                   4591:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4592:             }
                   4593:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4594:         }
                   4595:         if ($allowed) { last; }
                   4596:     }
                   4597:     return $allowed;
                   4598: }
                   4599: 
                   4600: ###############################################
                   4601: 
1.60      matthew  4602: =pod
                   4603: 
1.112     bowersj2 4604: =head1 Domain Template Functions
                   4605: 
                   4606: =over 4
                   4607: 
                   4608: =item * &determinedomain()
1.60      matthew  4609: 
                   4610: Inputs: $domain (usually will be undef)
                   4611: 
1.63      www      4612: Returns: Determines which domain should be used for designs
1.60      matthew  4613: 
                   4614: =cut
1.54      www      4615: 
1.60      matthew  4616: ###############################################
1.63      www      4617: sub determinedomain {
                   4618:     my $domain=shift;
1.531     albertel 4619:     if (! $domain) {
1.60      matthew  4620:         # Determine domain if we have not been given one
1.893     raeburn  4621:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 4622:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   4623:         if ($env{'request.role.domain'}) { 
                   4624:             $domain=$env{'request.role.domain'}; 
1.60      matthew  4625:         }
                   4626:     }
1.63      www      4627:     return $domain;
                   4628: }
                   4629: ###############################################
1.517     raeburn  4630: 
1.518     albertel 4631: sub devalidate_domconfig_cache {
                   4632:     my ($udom)=@_;
                   4633:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   4634: }
                   4635: 
                   4636: # ---------------------- Get domain configuration for a domain
                   4637: sub get_domainconf {
                   4638:     my ($udom) = @_;
                   4639:     my $cachetime=1800;
                   4640:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   4641:     if (defined($cached)) { return %{$result}; }
                   4642: 
                   4643:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  4644: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  4645:     my (%designhash,%legacy);
1.518     albertel 4646:     if (keys(%domconfig) > 0) {
                   4647:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  4648:             if (keys(%{$domconfig{'login'}})) {
                   4649:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  4650:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.946     raeburn  4651:                         if ($key eq 'loginvia') {
                   4652:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
1.1013    raeburn  4653:                                 foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
1.948     raeburn  4654:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
                   4655:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   4656:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   4657:                                             $designhash{$udom.'.login.loginvia'} = $server;
                   4658:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   4659: 
                   4660:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   4661:                                             } else {
1.1013    raeburn  4662:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
1.948     raeburn  4663:                                             }
                   4664:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
                   4665:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
                   4666:                                             }
1.946     raeburn  4667:                                         }
                   4668:                                     }
                   4669:                                 }
                   4670:                             }
                   4671:                         } else {
                   4672:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   4673:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   4674:                                     $domconfig{'login'}{$key}{$img};
                   4675:                             }
1.699     raeburn  4676:                         }
                   4677:                     } else {
                   4678:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   4679:                     }
1.632     raeburn  4680:                 }
                   4681:             } else {
                   4682:                 $legacy{'login'} = 1;
1.518     albertel 4683:             }
1.632     raeburn  4684:         } else {
                   4685:             $legacy{'login'} = 1;
1.518     albertel 4686:         }
                   4687:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  4688:             if (keys(%{$domconfig{'rolecolors'}})) {
                   4689:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   4690:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   4691:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   4692:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   4693:                         }
1.518     albertel 4694:                     }
                   4695:                 }
1.632     raeburn  4696:             } else {
                   4697:                 $legacy{'rolecolors'} = 1;
1.518     albertel 4698:             }
1.632     raeburn  4699:         } else {
                   4700:             $legacy{'rolecolors'} = 1;
1.518     albertel 4701:         }
1.948     raeburn  4702:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4703:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   4704:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   4705:             }
                   4706:         }
1.632     raeburn  4707:         if (keys(%legacy) > 0) {
                   4708:             my %legacyhash = &get_legacy_domconf($udom);
                   4709:             foreach my $item (keys(%legacyhash)) {
                   4710:                 if ($item =~ /^\Q$udom\E\.login/) {
                   4711:                     if ($legacy{'login'}) { 
                   4712:                         $designhash{$item} = $legacyhash{$item};
                   4713:                     }
                   4714:                 } else {
                   4715:                     if ($legacy{'rolecolors'}) {
                   4716:                         $designhash{$item} = $legacyhash{$item};
                   4717:                     }
1.518     albertel 4718:                 }
                   4719:             }
                   4720:         }
1.632     raeburn  4721:     } else {
                   4722:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 4723:     }
                   4724:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   4725: 				  $cachetime);
                   4726:     return %designhash;
                   4727: }
                   4728: 
1.632     raeburn  4729: sub get_legacy_domconf {
                   4730:     my ($udom) = @_;
                   4731:     my %legacyhash;
                   4732:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   4733:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   4734:     if (-e $designfile) {
                   4735:         if ( open (my $fh,"<$designfile") ) {
                   4736:             while (my $line = <$fh>) {
                   4737:                 next if ($line =~ /^\#/);
                   4738:                 chomp($line);
                   4739:                 my ($key,$val)=(split(/\=/,$line));
                   4740:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   4741:             }
                   4742:             close($fh);
                   4743:         }
                   4744:     }
1.1026    raeburn  4745:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  4746:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   4747:     }
                   4748:     return %legacyhash;
                   4749: }
                   4750: 
1.63      www      4751: =pod
                   4752: 
1.112     bowersj2 4753: =item * &domainlogo()
1.63      www      4754: 
                   4755: Inputs: $domain (usually will be undef)
                   4756: 
                   4757: Returns: A link to a domain logo, if the domain logo exists.
                   4758: If the domain logo does not exist, a description of the domain.
                   4759: 
                   4760: =cut
1.112     bowersj2 4761: 
1.63      www      4762: ###############################################
                   4763: sub domainlogo {
1.517     raeburn  4764:     my $domain = &determinedomain(shift);
1.518     albertel 4765:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  4766:     # See if there is a logo
                   4767:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  4768:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 4769:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   4770: 	    if ($imgsrc =~ m{^/res/}) {
                   4771: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   4772: 		&Apache::lonnet::repcopy($local_name);
                   4773: 	    }
                   4774: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  4775:         } 
                   4776:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 4777:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   4778:         return &Apache::lonnet::domain($domain,'description');
1.59      www      4779:     } else {
1.60      matthew  4780:         return '';
1.59      www      4781:     }
                   4782: }
1.63      www      4783: ##############################################
                   4784: 
                   4785: =pod
                   4786: 
1.112     bowersj2 4787: =item * &designparm()
1.63      www      4788: 
                   4789: Inputs: $which parameter; $domain (usually will be undef)
                   4790: 
                   4791: Returns: value of designparamter $which
                   4792: 
                   4793: =cut
1.112     bowersj2 4794: 
1.397     albertel 4795: 
1.400     albertel 4796: ##############################################
1.397     albertel 4797: sub designparm {
                   4798:     my ($which,$domain)=@_;
                   4799:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   4800:         return $env{'environment.color.'.$which};
1.96      www      4801:     }
1.63      www      4802:     $domain=&determinedomain($domain);
1.1016    raeburn  4803:     my %domdesign;
                   4804:     unless ($domain eq 'public') {
                   4805:         %domdesign = &get_domainconf($domain);
                   4806:     }
1.520     raeburn  4807:     my $output;
1.517     raeburn  4808:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   4809:         $output = $domdesign{$domain.'.'.$which};
1.63      www      4810:     } else {
1.520     raeburn  4811:         $output = $defaultdesign{$which};
                   4812:     }
                   4813:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  4814:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 4815:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   4816:             if ($output =~ m{^/res/}) {
                   4817:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   4818:                 &Apache::lonnet::repcopy($local_name);
                   4819:             }
1.520     raeburn  4820:             $output = &lonhttpdurl($output);
                   4821:         }
1.63      www      4822:     }
1.520     raeburn  4823:     return $output;
1.63      www      4824: }
1.59      www      4825: 
1.822     bisitz   4826: ##############################################
                   4827: =pod
                   4828: 
1.832     bisitz   4829: =item * &authorspace()
                   4830: 
1.1028    raeburn  4831: Inputs: $url (usually will be undef).
1.832     bisitz   4832: 
1.1028    raeburn  4833: Returns: Path to Construction Space containing the resource or 
                   4834:          directory being viewed (or for which action is being taken). 
                   4835:          If $url is provided, and begins /priv/<domain>/<uname>
                   4836:          the path will be that portion of the $context argument.
                   4837:          Otherwise the path will be for the author space of the current
                   4838:          user when the current role is author, or for that of the 
                   4839:          co-author/assistant co-author space when the current role 
                   4840:          is co-author or assistant co-author.
1.832     bisitz   4841: 
                   4842: =cut
                   4843: 
                   4844: sub authorspace {
1.1028    raeburn  4845:     my ($url) = @_;
                   4846:     if ($url ne '') {
                   4847:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   4848:            return $1;
                   4849:         }
                   4850:     }
1.832     bisitz   4851:     my $caname = '';
1.1024    www      4852:     my $cadom = '';
1.1028    raeburn  4853:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      4854:         ($cadom,$caname) =
1.832     bisitz   4855:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  4856:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   4857:         $caname = $env{'user.name'};
1.1024    www      4858:         $cadom = $env{'user.domain'};
1.832     bisitz   4859:     }
1.1028    raeburn  4860:     if (($caname ne '') && ($cadom ne '')) {
                   4861:         return "/priv/$cadom/$caname/";
                   4862:     }
                   4863:     return;
1.832     bisitz   4864: }
                   4865: 
                   4866: ##############################################
                   4867: =pod
                   4868: 
1.822     bisitz   4869: =item * &head_subbox()
                   4870: 
                   4871: Inputs: $content (contains HTML code with page functions, etc.)
                   4872: 
                   4873: Returns: HTML div with $content
                   4874:          To be included in page header
                   4875: 
                   4876: =cut
                   4877: 
                   4878: sub head_subbox {
                   4879:     my ($content)=@_;
                   4880:     my $output =
1.993     raeburn  4881:         '<div class="LC_head_subbox">'
1.822     bisitz   4882:        .$content
                   4883:        .'</div>'
                   4884: }
                   4885: 
                   4886: ##############################################
                   4887: =pod
                   4888: 
                   4889: =item * &CSTR_pageheader()
                   4890: 
1.1026    raeburn  4891: Input: (optional) filename from which breadcrumb trail is built.
                   4892:        In most cases no input as needed, as $env{'request.filename'}
                   4893:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   4894: 
                   4895: Returns: HTML div with CSTR path and recent box
                   4896:          To be included on Construction Space pages
                   4897: 
                   4898: =cut
                   4899: 
                   4900: sub CSTR_pageheader {
1.1026    raeburn  4901:     my ($trailfile) = @_;
                   4902:     if ($trailfile eq '') {
                   4903:         $trailfile = $env{'request.filename'};
                   4904:     }
                   4905: 
                   4906: # this is for resources; directories have customtitle, and crumbs
                   4907: # and select recent are created in lonpubdir.pm
                   4908: 
                   4909:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      4910:     my ($udom,$uname,$thisdisfn)=
1.1026    raeburn  4911:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)/(.*)$});
                   4912:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   4913:     $formaction =~ s{/+}{/}g;
1.822     bisitz   4914: 
                   4915:     my $parentpath = '';
                   4916:     my $lastitem = '';
                   4917:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   4918:         $parentpath = $1;
                   4919:         $lastitem = $2;
                   4920:     } else {
                   4921:         $lastitem = $thisdisfn;
                   4922:     }
1.921     bisitz   4923: 
                   4924:     my $output =
1.822     bisitz   4925:          '<div>'
                   4926:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
                   4927:         .'<b>'.&mt('Construction Space:').'</b> '
                   4928:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   4929:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      4930:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   4931: 
                   4932:     if ($lastitem) {
                   4933:         $output .=
                   4934:              '<span class="LC_filename">'
                   4935:             .$lastitem
                   4936:             .'</span>';
                   4937:     }
                   4938:     $output .=
                   4939:          '<br />'
1.822     bisitz   4940:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   4941:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   4942:         .'</form>'
                   4943:         .&Apache::lonmenu::constspaceform()
                   4944:         .'</div>';
1.921     bisitz   4945: 
                   4946:     return $output;
1.822     bisitz   4947: }
                   4948: 
1.60      matthew  4949: ###############################################
                   4950: ###############################################
                   4951: 
                   4952: =pod
                   4953: 
1.112     bowersj2 4954: =back
                   4955: 
1.549     albertel 4956: =head1 HTML Helpers
1.112     bowersj2 4957: 
                   4958: =over 4
                   4959: 
                   4960: =item * &bodytag()
1.60      matthew  4961: 
                   4962: Returns a uniform header for LON-CAPA web pages.
                   4963: 
                   4964: Inputs: 
                   4965: 
1.112     bowersj2 4966: =over 4
                   4967: 
                   4968: =item * $title, A title to be displayed on the page.
                   4969: 
                   4970: =item * $function, the current role (can be undef).
                   4971: 
                   4972: =item * $addentries, extra parameters for the <body> tag.
                   4973: 
                   4974: =item * $bodyonly, if defined, only return the <body> tag.
                   4975: 
                   4976: =item * $domain, if defined, force a given domain.
                   4977: 
                   4978: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      4979:             text interface only)
1.60      matthew  4980: 
1.814     bisitz   4981: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   4982:                      navigational links
1.317     albertel 4983: 
1.338     albertel 4984: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   4985: 
1.460     albertel 4986: =item * $args, optional argument valid values are
                   4987:             no_auto_mt_title -> prevents &mt()ing the title arg
1.562     albertel 4988:             inherit_jsmath -> when creating popup window in a page,
                   4989:                               should it have jsmath forced on by the
                   4990:                               current page
1.460     albertel 4991: 
1.112     bowersj2 4992: =back
                   4993: 
1.60      matthew  4994: Returns: A uniform header for LON-CAPA web pages.  
                   4995: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   4996: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   4997: other decorations will be returned.
                   4998: 
                   4999: =cut
                   5000: 
1.54      www      5001: sub bodytag {
1.831     bisitz   5002:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.962     droeschl 5003:         $no_nav_bar,$bgcolor,$args)=@_;
1.339     albertel 5004: 
1.954     raeburn  5005:     my $public;
                   5006:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5007:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5008:         $public = 1;
                   5009:     }
1.460     albertel 5010:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.339     albertel 5011: 
1.183     matthew  5012:     $function = &get_users_function() if (!$function);
1.339     albertel 5013:     my $img =    &designparm($function.'.img',$domain);
                   5014:     my $font =   &designparm($function.'.font',$domain);
                   5015:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5016: 
1.803     bisitz   5017:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5018: 		   'bgcolor' => $pgbg,
1.339     albertel 5019: 		   'text'    => $font,
                   5020:                    'alink'   => &designparm($function.'.alink',$domain),
                   5021: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5022: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5023:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5024: 
1.63      www      5025:  # role and realm
1.378     raeburn  5026:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
                   5027:     if ($role  eq 'ca') {
1.479     albertel 5028:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5029:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5030:     } 
1.55      www      5031: # realm
1.258     albertel 5032:     if ($env{'request.course.id'}) {
1.378     raeburn  5033:         if ($env{'request.role'} !~ /^cr/) {
                   5034:             $role = &Apache::lonnet::plaintext($role,&course_type());
                   5035:         }
1.898     raeburn  5036:         if ($env{'request.course.sec'}) {
                   5037:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5038:         }   
1.359     albertel 5039: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5040:     } else {
                   5041:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5042:     }
1.433     albertel 5043: 
1.359     albertel 5044:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5045: 
1.438     albertel 5046:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5047: 
1.101     www      5048: # construct main body tag
1.359     albertel 5049:     my $bodytag = "<body $extra_body_attr>".
1.562     albertel 5050: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
1.252     albertel 5051: 
1.530     albertel 5052:     if ($bodyonly) {
1.60      matthew  5053:         return $bodytag;
1.798     tempelho 5054:     } 
1.359     albertel 5055: 
1.410     albertel 5056:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
1.954     raeburn  5057:     if ($public) {
1.433     albertel 5058: 	undef($role);
1.434     albertel 5059:     } else {
1.1070    raeburn  5060: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   5061:                                 undef,'LC_menubuttons_link');
1.433     albertel 5062:     }
1.359     albertel 5063:     
1.762     bisitz   5064:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5065:     #
                   5066:     # Extra info if you are the DC
                   5067:     my $dc_info = '';
                   5068:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5069:                         $env{'course.'.$env{'request.course.id'}.
                   5070:                                  '.domain'}.'/'})) {
                   5071:         my $cid = $env{'request.course.id'};
1.917     raeburn  5072:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5073:         $dc_info =~ s/\s+$//;
1.359     albertel 5074:     }
                   5075: 
1.898     raeburn  5076:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
1.853     droeschl 5077:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5078: 
1.916     droeschl 5079:         if ($no_nav_bar || $env{'form.inhibitmenu'} eq 'yes') { 
                   5080:             return $bodytag; 
                   5081:         } 
1.903     droeschl 5082: 
                   5083:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5084: 
                   5085:         #    if ($env{'request.state'} eq 'construct') {
                   5086:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5087:         #    }
                   5088: 
1.359     albertel 5089: 
                   5090: 
1.916     droeschl 5091:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.917     raeburn  5092:              if ($dc_info) {
                   5093:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   5094:              }
1.916     droeschl 5095:              $bodytag .= qq|<div id="LC_nav_bar">$name $role<br />
                   5096:                 <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5097:             return $bodytag;
                   5098:         }
1.894     droeschl 5099: 
1.927     raeburn  5100:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   5101:             $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>|;
                   5102:         }
1.916     droeschl 5103: 
1.903     droeschl 5104:         $bodytag .= Apache::lonhtmlcommon::scripttag(
                   5105:             Apache::lonmenu::utilityfunctions(), 'start');
1.816     bisitz   5106: 
1.903     droeschl 5107:         $bodytag .= Apache::lonmenu::primary_menu();
1.852     droeschl 5108: 
1.917     raeburn  5109:         if ($dc_info) {
                   5110:             $dc_info = &dc_courseid_toggle($dc_info);
                   5111:         }
                   5112:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5113: 
1.903     droeschl 5114:         #don't show menus for public users
1.954     raeburn  5115:         if (!$public){
1.903     droeschl 5116:             $bodytag .= Apache::lonmenu::secondary_menu();
                   5117:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5118:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5119:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5120:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.920     raeburn  5121:                                 $args->{'bread_crumbs'});
                   5122:             } elsif ($forcereg) { 
                   5123:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg);
                   5124:             }
1.903     droeschl 5125:         }else{
                   5126:             # this is to seperate menu from content when there's no secondary
                   5127:             # menu. Especially needed for public accessible ressources.
                   5128:             $bodytag .= '<hr style="clear:both" />';
                   5129:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5130:         }
1.903     droeschl 5131: 
1.235     raeburn  5132:         return $bodytag;
1.182     matthew  5133: }
                   5134: 
1.917     raeburn  5135: sub dc_courseid_toggle {
                   5136:     my ($dc_info) = @_;
1.980     raeburn  5137:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5138:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5139:            &mt('(More ...)').'</a></span>'.
                   5140:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5141: }
                   5142: 
1.330     albertel 5143: sub make_attr_string {
                   5144:     my ($register,$attr_ref) = @_;
                   5145: 
                   5146:     if ($attr_ref && !ref($attr_ref)) {
                   5147: 	die("addentries Must be a hash ref ".
                   5148: 	    join(':',caller(1))." ".
                   5149: 	    join(':',caller(0))." ");
                   5150:     }
                   5151: 
                   5152:     if ($register) {
1.339     albertel 5153: 	my ($on_load,$on_unload);
                   5154: 	foreach my $key (keys(%{$attr_ref})) {
                   5155: 	    if      (lc($key) eq 'onload') {
                   5156: 		$on_load.=$attr_ref->{$key}.';';
                   5157: 		delete($attr_ref->{$key});
                   5158: 
                   5159: 	    } elsif (lc($key) eq 'onunload') {
                   5160: 		$on_unload.=$attr_ref->{$key}.';';
                   5161: 		delete($attr_ref->{$key});
                   5162: 	    }
                   5163: 	}
1.953     droeschl 5164: 	$attr_ref->{'onload'}  = $on_load;
                   5165: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 5166:     }
1.339     albertel 5167: 
1.330     albertel 5168:     my $attr_string;
                   5169:     foreach my $attr (keys(%$attr_ref)) {
                   5170: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5171:     }
                   5172:     return $attr_string;
                   5173: }
                   5174: 
                   5175: 
1.182     matthew  5176: ###############################################
1.251     albertel 5177: ###############################################
                   5178: 
                   5179: =pod
                   5180: 
                   5181: =item * &endbodytag()
                   5182: 
                   5183: Returns a uniform footer for LON-CAPA web pages.
                   5184: 
1.635     raeburn  5185: Inputs: 1 - optional reference to an args hash
                   5186: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5187: a 'Continue' link is not displayed if the page contains an
                   5188: internal redirect in the <head></head> section,
                   5189: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5190: 
                   5191: =cut
                   5192: 
                   5193: sub endbodytag {
1.635     raeburn  5194:     my ($args) = @_;
1.1080    raeburn  5195:     my $endbodytag;
                   5196:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5197:         $endbodytag='</body>';
                   5198:     }
1.269     albertel 5199:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
1.315     albertel 5200:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5201:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5202: 	    $endbodytag=
                   5203: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5204: 	        &mt('Continue').'</a>'.
                   5205: 	        $endbodytag;
                   5206:         }
1.315     albertel 5207:     }
1.251     albertel 5208:     return $endbodytag;
                   5209: }
                   5210: 
1.352     albertel 5211: =pod
                   5212: 
                   5213: =item * &standard_css()
                   5214: 
                   5215: Returns a style sheet
                   5216: 
                   5217: Inputs: (all optional)
                   5218:             domain         -> force to color decorate a page for a specific
                   5219:                                domain
                   5220:             function       -> force usage of a specific rolish color scheme
                   5221:             bgcolor        -> override the default page bgcolor
                   5222: 
                   5223: =cut
                   5224: 
1.343     albertel 5225: sub standard_css {
1.345     albertel 5226:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5227:     $function  = &get_users_function() if (!$function);
                   5228:     my $img    = &designparm($function.'.img',   $domain);
                   5229:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5230:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5231:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5232: #second colour for later usage
1.345     albertel 5233:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5234:     my $pgbg_or_bgcolor =
                   5235: 	         $bgcolor ||
1.352     albertel 5236: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5237:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5238:     my $alink  = &designparm($function.'.alink', $domain);
                   5239:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5240:     my $link   = &designparm($function.'.link',  $domain);
                   5241: 
1.602     albertel 5242:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5243:     my $mono                 = 'monospace';
1.850     bisitz   5244:     my $data_table_head      = $sidebg;
                   5245:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5246:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5247:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5248:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5249:     my $mail_new             = '#FFBB77';
                   5250:     my $mail_new_hover       = '#DD9955';
                   5251:     my $mail_read            = '#BBBB77';
                   5252:     my $mail_read_hover      = '#999944';
                   5253:     my $mail_replied         = '#AAAA88';
                   5254:     my $mail_replied_hover   = '#888855';
                   5255:     my $mail_other           = '#99BBBB';
                   5256:     my $mail_other_hover     = '#669999';
1.391     albertel 5257:     my $table_header         = '#DDDDDD';
1.489     raeburn  5258:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5259:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5260:     my $button_hover         = '#BF2317';
1.392     albertel 5261: 
1.608     albertel 5262:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5263:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5264:                                              : '0 3px 0 4px';
1.448     albertel 5265: 
1.523     albertel 5266: 
1.343     albertel 5267:     return <<END;
1.947     droeschl 5268: 
                   5269: /* needed for iframe to allow 100% height in FF */
                   5270: body, html { 
                   5271:     margin: 0;
                   5272:     padding: 0 0.5%;
                   5273:     height: 99%; /* to avoid scrollbars */
                   5274: }
                   5275: 
1.795     www      5276: body {
1.911     bisitz   5277:   font-family: $sans;
                   5278:   line-height:130%;
                   5279:   font-size:0.83em;
                   5280:   color:$font;
1.795     www      5281: }
                   5282: 
1.959     onken    5283: a:focus,
                   5284: a:focus img {
1.795     www      5285:   color: red;
                   5286: }
1.698     harmsja  5287: 
1.911     bisitz   5288: form, .inline {
                   5289:   display: inline;
1.795     www      5290: }
1.721     harmsja  5291: 
1.795     www      5292: .LC_right {
1.911     bisitz   5293:   text-align:right;
1.795     www      5294: }
                   5295: 
                   5296: .LC_middle {
1.911     bisitz   5297:   vertical-align:middle;
1.795     www      5298: }
1.721     harmsja  5299: 
1.911     bisitz   5300: .LC_400Box {
                   5301:   width:400px;
                   5302: }
1.721     harmsja  5303: 
1.947     droeschl 5304: .LC_iframecontainer {
                   5305:     width: 98%;
                   5306:     margin: 0;
                   5307:     position: fixed;
                   5308:     top: 8.5em;
                   5309:     bottom: 0;
                   5310: }
                   5311: 
                   5312: .LC_iframecontainer iframe{
                   5313:     border: none;
                   5314:     width: 100%;
                   5315:     height: 100%;
                   5316: }
                   5317: 
1.778     bisitz   5318: .LC_filename {
                   5319:   font-family: $mono;
                   5320:   white-space:pre;
1.921     bisitz   5321:   font-size: 120%;
1.778     bisitz   5322: }
                   5323: 
                   5324: .LC_fileicon {
                   5325:   border: none;
                   5326:   height: 1.3em;
                   5327:   vertical-align: text-bottom;
                   5328:   margin-right: 0.3em;
                   5329:   text-decoration:none;
                   5330: }
                   5331: 
1.1008    www      5332: .LC_setting {
                   5333:   text-decoration:underline;
                   5334: }
                   5335: 
1.350     albertel 5336: .LC_error {
                   5337:   color: red;
                   5338:   font-size: larger;
                   5339: }
1.795     www      5340: 
1.457     albertel 5341: .LC_warning,
                   5342: .LC_diff_removed {
1.733     bisitz   5343:   color: red;
1.394     albertel 5344: }
1.532     albertel 5345: 
                   5346: .LC_info,
1.457     albertel 5347: .LC_success,
                   5348: .LC_diff_added {
1.350     albertel 5349:   color: green;
                   5350: }
1.795     www      5351: 
1.802     bisitz   5352: div.LC_confirm_box {
                   5353:   background-color: #FAFAFA;
                   5354:   border: 1px solid $lg_border_color;
                   5355:   margin-right: 0;
                   5356:   padding: 5px;
                   5357: }
                   5358: 
                   5359: div.LC_confirm_box .LC_error img,
                   5360: div.LC_confirm_box .LC_success img {
                   5361:   vertical-align: middle;
                   5362: }
                   5363: 
1.440     albertel 5364: .LC_icon {
1.771     droeschl 5365:   border: none;
1.790     droeschl 5366:   vertical-align: middle;
1.771     droeschl 5367: }
                   5368: 
1.543     albertel 5369: .LC_docs_spacer {
                   5370:   width: 25px;
                   5371:   height: 1px;
1.771     droeschl 5372:   border: none;
1.543     albertel 5373: }
1.346     albertel 5374: 
1.532     albertel 5375: .LC_internal_info {
1.735     bisitz   5376:   color: #999999;
1.532     albertel 5377: }
                   5378: 
1.794     www      5379: .LC_discussion {
1.1050    www      5380:   background: $data_table_dark;
1.911     bisitz   5381:   border: 1px solid black;
                   5382:   margin: 2px;
1.794     www      5383: }
                   5384: 
                   5385: .LC_disc_action_left {
1.1050    www      5386:   background: $sidebg;
1.911     bisitz   5387:   text-align: left;
1.1050    www      5388:   padding: 4px;
                   5389:   margin: 2px;
1.794     www      5390: }
                   5391: 
                   5392: .LC_disc_action_right {
1.1050    www      5393:   background: $sidebg;
1.911     bisitz   5394:   text-align: right;
1.1050    www      5395:   padding: 4px;
                   5396:   margin: 2px;
1.794     www      5397: }
                   5398: 
                   5399: .LC_disc_new_item {
1.911     bisitz   5400:   background: white;
                   5401:   border: 2px solid red;
1.1050    www      5402:   margin: 4px;
                   5403:   padding: 4px;
1.794     www      5404: }
                   5405: 
                   5406: .LC_disc_old_item {
1.911     bisitz   5407:   background: white;
1.1050    www      5408:   margin: 4px;
                   5409:   padding: 4px;
1.794     www      5410: }
                   5411: 
1.458     albertel 5412: table.LC_pastsubmission {
                   5413:   border: 1px solid black;
                   5414:   margin: 2px;
                   5415: }
                   5416: 
1.924     bisitz   5417: table#LC_menubuttons {
1.345     albertel 5418:   width: 100%;
                   5419:   background: $pgbg;
1.392     albertel 5420:   border: 2px;
1.402     albertel 5421:   border-collapse: separate;
1.803     bisitz   5422:   padding: 0;
1.345     albertel 5423: }
1.392     albertel 5424: 
1.801     tempelho 5425: table#LC_title_bar a {
                   5426:   color: $fontmenu;
                   5427: }
1.836     bisitz   5428: 
1.807     droeschl 5429: table#LC_title_bar {
1.819     tempelho 5430:   clear: both;
1.836     bisitz   5431:   display: none;
1.807     droeschl 5432: }
                   5433: 
1.795     www      5434: table#LC_title_bar,
1.933     droeschl 5435: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 5436: table#LC_title_bar.LC_with_remote {
1.359     albertel 5437:   width: 100%;
1.392     albertel 5438:   border-color: $pgbg;
                   5439:   border-style: solid;
                   5440:   border-width: $border;
1.379     albertel 5441:   background: $pgbg;
1.801     tempelho 5442:   color: $fontmenu;
1.392     albertel 5443:   border-collapse: collapse;
1.803     bisitz   5444:   padding: 0;
1.819     tempelho 5445:   margin: 0;
1.359     albertel 5446: }
1.795     www      5447: 
1.933     droeschl 5448: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 5449:     margin: 0;
                   5450:     padding: 0;
1.933     droeschl 5451:     position: relative;
                   5452:     list-style: none;
1.913     droeschl 5453: }
1.933     droeschl 5454: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 5455:     display: inline;
                   5456: }
1.933     droeschl 5457: 
                   5458: .LC_breadcrumb_tools_navigation {
1.913     droeschl 5459:     padding: 0;
1.933     droeschl 5460:     margin: 0;
                   5461:     float: left;
1.913     droeschl 5462: }
1.933     droeschl 5463: .LC_breadcrumb_tools_tools {
                   5464:     padding: 0;
                   5465:     margin: 0;
1.913     droeschl 5466:     float: right;
                   5467: }
                   5468: 
1.359     albertel 5469: table#LC_title_bar td {
                   5470:   background: $tabbg;
                   5471: }
1.795     www      5472: 
1.911     bisitz   5473: table#LC_menubuttons img {
1.803     bisitz   5474:   border: none;
1.346     albertel 5475: }
1.795     www      5476: 
1.842     droeschl 5477: .LC_breadcrumbs_component {
1.911     bisitz   5478:   float: right;
                   5479:   margin: 0 1em;
1.357     albertel 5480: }
1.842     droeschl 5481: .LC_breadcrumbs_component img {
1.911     bisitz   5482:   vertical-align: middle;
1.777     tempelho 5483: }
1.795     www      5484: 
1.383     albertel 5485: td.LC_table_cell_checkbox {
                   5486:   text-align: center;
                   5487: }
1.795     www      5488: 
                   5489: .LC_fontsize_small {
1.911     bisitz   5490:   font-size: 70%;
1.705     tempelho 5491: }
                   5492: 
1.844     bisitz   5493: #LC_breadcrumbs {
1.911     bisitz   5494:   clear:both;
                   5495:   background: $sidebg;
                   5496:   border-bottom: 1px solid $lg_border_color;
                   5497:   line-height: 2.5em;
1.933     droeschl 5498:   overflow: hidden;
1.911     bisitz   5499:   margin: 0;
                   5500:   padding: 0;
1.995     raeburn  5501:   text-align: left;
1.819     tempelho 5502: }
1.862     bisitz   5503: 
1.993     raeburn  5504: .LC_head_subbox {
1.911     bisitz   5505:   clear:both;
                   5506:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 5507:   border: 1px solid $sidebg;
                   5508:   margin: 0 0 10px 0;      
1.966     bisitz   5509:   padding: 3px;
1.995     raeburn  5510:   text-align: left;
1.822     bisitz   5511: }
                   5512: 
1.795     www      5513: .LC_fontsize_medium {
1.911     bisitz   5514:   font-size: 85%;
1.705     tempelho 5515: }
                   5516: 
1.795     www      5517: .LC_fontsize_large {
1.911     bisitz   5518:   font-size: 120%;
1.705     tempelho 5519: }
                   5520: 
1.346     albertel 5521: .LC_menubuttons_inline_text {
                   5522:   color: $font;
1.698     harmsja  5523:   font-size: 90%;
1.701     harmsja  5524:   padding-left:3px;
1.346     albertel 5525: }
                   5526: 
1.934     droeschl 5527: .LC_menubuttons_inline_text img{
                   5528:   vertical-align: middle;
                   5529: }
                   5530: 
1.1051    www      5531: li.LC_menubuttons_inline_text img {
1.951     onken    5532:   cursor:pointer;
1.1002    droeschl 5533:   text-decoration: none;
1.951     onken    5534: }
                   5535: 
1.526     www      5536: .LC_menubuttons_link {
                   5537:   text-decoration: none;
                   5538: }
1.795     www      5539: 
1.522     albertel 5540: .LC_menubuttons_category {
1.521     www      5541:   color: $font;
1.526     www      5542:   background: $pgbg;
1.521     www      5543:   font-size: larger;
                   5544:   font-weight: bold;
                   5545: }
                   5546: 
1.346     albertel 5547: td.LC_menubuttons_text {
1.911     bisitz   5548:   color: $font;
1.346     albertel 5549: }
1.706     harmsja  5550: 
1.346     albertel 5551: .LC_current_location {
                   5552:   background: $tabbg;
                   5553: }
1.795     www      5554: 
1.938     bisitz   5555: table.LC_data_table {
1.347     albertel 5556:   border: 1px solid #000000;
1.402     albertel 5557:   border-collapse: separate;
1.426     albertel 5558:   border-spacing: 1px;
1.610     albertel 5559:   background: $pgbg;
1.347     albertel 5560: }
1.795     www      5561: 
1.422     albertel 5562: .LC_data_table_dense {
                   5563:   font-size: small;
                   5564: }
1.795     www      5565: 
1.507     raeburn  5566: table.LC_nested_outer {
                   5567:   border: 1px solid #000000;
1.589     raeburn  5568:   border-collapse: collapse;
1.803     bisitz   5569:   border-spacing: 0;
1.507     raeburn  5570:   width: 100%;
                   5571: }
1.795     www      5572: 
1.879     raeburn  5573: table.LC_innerpickbox,
1.507     raeburn  5574: table.LC_nested {
1.803     bisitz   5575:   border: none;
1.589     raeburn  5576:   border-collapse: collapse;
1.803     bisitz   5577:   border-spacing: 0;
1.507     raeburn  5578:   width: 100%;
                   5579: }
1.795     www      5580: 
1.911     bisitz   5581: table.LC_data_table tr th,
                   5582: table.LC_calendar tr th,
1.879     raeburn  5583: table.LC_prior_tries tr th,
                   5584: table.LC_innerpickbox tr th {
1.349     albertel 5585:   font-weight: bold;
                   5586:   background-color: $data_table_head;
1.801     tempelho 5587:   color:$fontmenu;
1.701     harmsja  5588:   font-size:90%;
1.347     albertel 5589: }
1.795     www      5590: 
1.879     raeburn  5591: table.LC_innerpickbox tr th,
                   5592: table.LC_innerpickbox tr td {
                   5593:   vertical-align: top;
                   5594: }
                   5595: 
1.711     raeburn  5596: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   5597:   background-color: #CCCCCC;
1.711     raeburn  5598:   font-weight: bold;
                   5599:   text-align: left;
                   5600: }
1.795     www      5601: 
1.912     bisitz   5602: table.LC_data_table tr.LC_odd_row > td {
                   5603:   background-color: $data_table_light;
                   5604:   padding: 2px;
                   5605:   vertical-align: top;
                   5606: }
                   5607: 
1.809     bisitz   5608: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 5609:   background-color: $data_table_light;
1.912     bisitz   5610:   vertical-align: top;
                   5611: }
                   5612: 
                   5613: table.LC_data_table tr.LC_even_row > td {
                   5614:   background-color: $data_table_dark;
1.425     albertel 5615:   padding: 2px;
1.900     bisitz   5616:   vertical-align: top;
1.347     albertel 5617: }
1.795     www      5618: 
1.809     bisitz   5619: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 5620:   background-color: $data_table_dark;
1.900     bisitz   5621:   vertical-align: top;
1.347     albertel 5622: }
1.795     www      5623: 
1.425     albertel 5624: table.LC_data_table tr.LC_data_table_highlight td {
                   5625:   background-color: $data_table_darker;
                   5626: }
1.795     www      5627: 
1.639     raeburn  5628: table.LC_data_table tr td.LC_leftcol_header {
                   5629:   background-color: $data_table_head;
                   5630:   font-weight: bold;
                   5631: }
1.795     www      5632: 
1.451     albertel 5633: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  5634: table.LC_nested tr.LC_empty_row td {
1.421     albertel 5635:   font-weight: bold;
                   5636:   font-style: italic;
                   5637:   text-align: center;
                   5638:   padding: 8px;
1.347     albertel 5639: }
1.795     www      5640: 
1.940     bisitz   5641: table.LC_data_table tr.LC_empty_row td {
                   5642:   background-color: $sidebg;
                   5643: }
                   5644: 
                   5645: table.LC_nested tr.LC_empty_row td {
                   5646:   background-color: #FFFFFF;
                   5647: }
                   5648: 
1.890     droeschl 5649: table.LC_caption {
                   5650: }
                   5651: 
1.507     raeburn  5652: table.LC_nested tr.LC_empty_row td {
1.465     albertel 5653:   padding: 4ex
                   5654: }
1.795     www      5655: 
1.507     raeburn  5656: table.LC_nested_outer tr th {
                   5657:   font-weight: bold;
1.801     tempelho 5658:   color:$fontmenu;
1.507     raeburn  5659:   background-color: $data_table_head;
1.701     harmsja  5660:   font-size: small;
1.507     raeburn  5661:   border-bottom: 1px solid #000000;
                   5662: }
1.795     www      5663: 
1.507     raeburn  5664: table.LC_nested_outer tr td.LC_subheader {
                   5665:   background-color: $data_table_head;
                   5666:   font-weight: bold;
                   5667:   font-size: small;
                   5668:   border-bottom: 1px solid #000000;
                   5669:   text-align: right;
1.451     albertel 5670: }
1.795     www      5671: 
1.507     raeburn  5672: table.LC_nested tr.LC_info_row td {
1.735     bisitz   5673:   background-color: #CCCCCC;
1.451     albertel 5674:   font-weight: bold;
                   5675:   font-size: small;
1.507     raeburn  5676:   text-align: center;
                   5677: }
1.795     www      5678: 
1.589     raeburn  5679: table.LC_nested tr.LC_info_row td.LC_left_item,
                   5680: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  5681:   text-align: left;
1.451     albertel 5682: }
1.795     www      5683: 
1.507     raeburn  5684: table.LC_nested td {
1.735     bisitz   5685:   background-color: #FFFFFF;
1.451     albertel 5686:   font-size: small;
1.507     raeburn  5687: }
1.795     www      5688: 
1.507     raeburn  5689: table.LC_nested_outer tr th.LC_right_item,
                   5690: table.LC_nested tr.LC_info_row td.LC_right_item,
                   5691: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   5692: table.LC_nested tr td.LC_right_item {
1.451     albertel 5693:   text-align: right;
                   5694: }
                   5695: 
1.507     raeburn  5696: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   5697:   background-color: #EEEEEE;
1.451     albertel 5698: }
                   5699: 
1.473     raeburn  5700: table.LC_createuser {
                   5701: }
                   5702: 
                   5703: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  5704:   font-size: small;
1.473     raeburn  5705: }
                   5706: 
                   5707: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   5708:   background-color: #CCCCCC;
1.473     raeburn  5709:   font-weight: bold;
                   5710:   text-align: center;
                   5711: }
                   5712: 
1.349     albertel 5713: table.LC_calendar {
                   5714:   border: 1px solid #000000;
                   5715:   border-collapse: collapse;
1.917     raeburn  5716:   width: 98%;
1.349     albertel 5717: }
1.795     www      5718: 
1.349     albertel 5719: table.LC_calendar_pickdate {
                   5720:   font-size: xx-small;
                   5721: }
1.795     www      5722: 
1.349     albertel 5723: table.LC_calendar tr td {
                   5724:   border: 1px solid #000000;
                   5725:   vertical-align: top;
1.917     raeburn  5726:   width: 14%;
1.349     albertel 5727: }
1.795     www      5728: 
1.349     albertel 5729: table.LC_calendar tr td.LC_calendar_day_empty {
                   5730:   background-color: $data_table_dark;
                   5731: }
1.795     www      5732: 
1.779     bisitz   5733: table.LC_calendar tr td.LC_calendar_day_current {
                   5734:   background-color: $data_table_highlight;
1.777     tempelho 5735: }
1.795     www      5736: 
1.938     bisitz   5737: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 5738:   background-color: $mail_new;
                   5739: }
1.795     www      5740: 
1.938     bisitz   5741: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 5742:   background-color: $mail_new_hover;
                   5743: }
1.795     www      5744: 
1.938     bisitz   5745: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 5746:   background-color: $mail_read;
                   5747: }
1.795     www      5748: 
1.938     bisitz   5749: /*
                   5750: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 5751:   background-color: $mail_read_hover;
                   5752: }
1.938     bisitz   5753: */
1.795     www      5754: 
1.938     bisitz   5755: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 5756:   background-color: $mail_replied;
                   5757: }
1.795     www      5758: 
1.938     bisitz   5759: /*
                   5760: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 5761:   background-color: $mail_replied_hover;
                   5762: }
1.938     bisitz   5763: */
1.795     www      5764: 
1.938     bisitz   5765: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 5766:   background-color: $mail_other;
                   5767: }
1.795     www      5768: 
1.938     bisitz   5769: /*
                   5770: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 5771:   background-color: $mail_other_hover;
                   5772: }
1.938     bisitz   5773: */
1.494     raeburn  5774: 
1.777     tempelho 5775: table.LC_data_table tr > td.LC_browser_file,
                   5776: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   5777:   background: #AAEE77;
1.389     albertel 5778: }
1.795     www      5779: 
1.777     tempelho 5780: table.LC_data_table tr > td.LC_browser_file_locked,
                   5781: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 5782:   background: #FFAA99;
1.387     albertel 5783: }
1.795     www      5784: 
1.777     tempelho 5785: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   5786:   background: #888888;
1.779     bisitz   5787: }
1.795     www      5788: 
1.777     tempelho 5789: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   5790: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   5791:   background: #F8F866;
1.777     tempelho 5792: }
1.795     www      5793: 
1.696     bisitz   5794: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   5795:   background: #E0E8FF;
1.387     albertel 5796: }
1.696     bisitz   5797: 
1.707     bisitz   5798: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   5799:   /* background: #77FF77; */
1.707     bisitz   5800: }
1.795     www      5801: 
1.707     bisitz   5802: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   5803:   border-right: 8px solid #FFFF77;
1.707     bisitz   5804: }
1.795     www      5805: 
1.707     bisitz   5806: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   5807:   border-right: 8px solid #FFAA77;
1.707     bisitz   5808: }
1.795     www      5809: 
1.707     bisitz   5810: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   5811:   border-right: 8px solid #FF7777;
1.707     bisitz   5812: }
1.795     www      5813: 
1.707     bisitz   5814: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   5815:   border-right: 8px solid #AAFF77;
1.707     bisitz   5816: }
1.795     www      5817: 
1.707     bisitz   5818: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   5819:   border-right: 8px solid #11CC55;
1.707     bisitz   5820: }
                   5821: 
1.388     albertel 5822: span.LC_current_location {
1.701     harmsja  5823:   font-size:larger;
1.388     albertel 5824:   background: $pgbg;
                   5825: }
1.387     albertel 5826: 
1.1029    www      5827: span.LC_current_nav_location {
                   5828:   font-weight:bold;
                   5829:   background: $sidebg;
                   5830: }
                   5831: 
1.395     albertel 5832: span.LC_parm_menu_item {
                   5833:   font-size: larger;
                   5834: }
1.795     www      5835: 
1.395     albertel 5836: span.LC_parm_scope_all {
                   5837:   color: red;
                   5838: }
1.795     www      5839: 
1.395     albertel 5840: span.LC_parm_scope_folder {
                   5841:   color: green;
                   5842: }
1.795     www      5843: 
1.395     albertel 5844: span.LC_parm_scope_resource {
                   5845:   color: orange;
                   5846: }
1.795     www      5847: 
1.395     albertel 5848: span.LC_parm_part {
                   5849:   color: blue;
                   5850: }
1.795     www      5851: 
1.911     bisitz   5852: span.LC_parm_folder,
                   5853: span.LC_parm_symb {
1.395     albertel 5854:   font-size: x-small;
                   5855:   font-family: $mono;
                   5856:   color: #AAAAAA;
                   5857: }
                   5858: 
1.977     bisitz   5859: ul.LC_parm_parmlist li {
                   5860:   display: inline-block;
                   5861:   padding: 0.3em 0.8em;
                   5862:   vertical-align: top;
                   5863:   width: 150px;
                   5864:   border-top:1px solid $lg_border_color;
                   5865: }
                   5866: 
1.795     www      5867: td.LC_parm_overview_level_menu,
                   5868: td.LC_parm_overview_map_menu,
                   5869: td.LC_parm_overview_parm_selectors,
                   5870: td.LC_parm_overview_restrictions  {
1.396     albertel 5871:   border: 1px solid black;
                   5872:   border-collapse: collapse;
                   5873: }
1.795     www      5874: 
1.396     albertel 5875: table.LC_parm_overview_restrictions td {
                   5876:   border-width: 1px 4px 1px 4px;
                   5877:   border-style: solid;
                   5878:   border-color: $pgbg;
                   5879:   text-align: center;
                   5880: }
1.795     www      5881: 
1.396     albertel 5882: table.LC_parm_overview_restrictions th {
                   5883:   background: $tabbg;
                   5884:   border-width: 1px 4px 1px 4px;
                   5885:   border-style: solid;
                   5886:   border-color: $pgbg;
                   5887: }
1.795     www      5888: 
1.398     albertel 5889: table#LC_helpmenu {
1.803     bisitz   5890:   border: none;
1.398     albertel 5891:   height: 55px;
1.803     bisitz   5892:   border-spacing: 0;
1.398     albertel 5893: }
                   5894: 
                   5895: table#LC_helpmenu fieldset legend {
                   5896:   font-size: larger;
                   5897: }
1.795     www      5898: 
1.397     albertel 5899: table#LC_helpmenu_links {
                   5900:   width: 100%;
                   5901:   border: 1px solid black;
                   5902:   background: $pgbg;
1.803     bisitz   5903:   padding: 0;
1.397     albertel 5904:   border-spacing: 1px;
                   5905: }
1.795     www      5906: 
1.397     albertel 5907: table#LC_helpmenu_links tr td {
                   5908:   padding: 1px;
                   5909:   background: $tabbg;
1.399     albertel 5910:   text-align: center;
                   5911:   font-weight: bold;
1.397     albertel 5912: }
1.396     albertel 5913: 
1.795     www      5914: table#LC_helpmenu_links a:link,
                   5915: table#LC_helpmenu_links a:visited,
1.397     albertel 5916: table#LC_helpmenu_links a:active {
                   5917:   text-decoration: none;
                   5918:   color: $font;
                   5919: }
1.795     www      5920: 
1.397     albertel 5921: table#LC_helpmenu_links a:hover {
                   5922:   text-decoration: underline;
                   5923:   color: $vlink;
                   5924: }
1.396     albertel 5925: 
1.417     albertel 5926: .LC_chrt_popup_exists {
                   5927:   border: 1px solid #339933;
                   5928:   margin: -1px;
                   5929: }
1.795     www      5930: 
1.417     albertel 5931: .LC_chrt_popup_up {
                   5932:   border: 1px solid yellow;
                   5933:   margin: -1px;
                   5934: }
1.795     www      5935: 
1.417     albertel 5936: .LC_chrt_popup {
                   5937:   border: 1px solid #8888FF;
                   5938:   background: #CCCCFF;
                   5939: }
1.795     www      5940: 
1.421     albertel 5941: table.LC_pick_box {
                   5942:   border-collapse: separate;
                   5943:   background: white;
                   5944:   border: 1px solid black;
                   5945:   border-spacing: 1px;
                   5946: }
1.795     www      5947: 
1.421     albertel 5948: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   5949:   background: $sidebg;
1.421     albertel 5950:   font-weight: bold;
1.900     bisitz   5951:   text-align: left;
1.740     bisitz   5952:   vertical-align: top;
1.421     albertel 5953:   width: 184px;
                   5954:   padding: 8px;
                   5955: }
1.795     www      5956: 
1.579     raeburn  5957: table.LC_pick_box td.LC_pick_box_value {
                   5958:   text-align: left;
                   5959:   padding: 8px;
                   5960: }
1.795     www      5961: 
1.579     raeburn  5962: table.LC_pick_box td.LC_pick_box_select {
                   5963:   text-align: left;
                   5964:   padding: 8px;
                   5965: }
1.795     www      5966: 
1.424     albertel 5967: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   5968:   padding: 0;
1.421     albertel 5969:   height: 1px;
                   5970:   background: black;
                   5971: }
1.795     www      5972: 
1.421     albertel 5973: table.LC_pick_box td.LC_pick_box_submit {
                   5974:   text-align: right;
                   5975: }
1.795     www      5976: 
1.579     raeburn  5977: table.LC_pick_box td.LC_evenrow_value {
                   5978:   text-align: left;
                   5979:   padding: 8px;
                   5980:   background-color: $data_table_light;
                   5981: }
1.795     www      5982: 
1.579     raeburn  5983: table.LC_pick_box td.LC_oddrow_value {
                   5984:   text-align: left;
                   5985:   padding: 8px;
                   5986:   background-color: $data_table_light;
                   5987: }
1.795     www      5988: 
1.579     raeburn  5989: span.LC_helpform_receipt_cat {
                   5990:   font-weight: bold;
                   5991: }
1.795     www      5992: 
1.424     albertel 5993: table.LC_group_priv_box {
                   5994:   background: white;
                   5995:   border: 1px solid black;
                   5996:   border-spacing: 1px;
                   5997: }
1.795     www      5998: 
1.424     albertel 5999: table.LC_group_priv_box td.LC_pick_box_title {
                   6000:   background: $tabbg;
                   6001:   font-weight: bold;
                   6002:   text-align: right;
                   6003:   width: 184px;
                   6004: }
1.795     www      6005: 
1.424     albertel 6006: table.LC_group_priv_box td.LC_groups_fixed {
                   6007:   background: $data_table_light;
                   6008:   text-align: center;
                   6009: }
1.795     www      6010: 
1.424     albertel 6011: table.LC_group_priv_box td.LC_groups_optional {
                   6012:   background: $data_table_dark;
                   6013:   text-align: center;
                   6014: }
1.795     www      6015: 
1.424     albertel 6016: table.LC_group_priv_box td.LC_groups_functionality {
                   6017:   background: $data_table_darker;
                   6018:   text-align: center;
                   6019:   font-weight: bold;
                   6020: }
1.795     www      6021: 
1.424     albertel 6022: table.LC_group_priv td {
                   6023:   text-align: left;
1.803     bisitz   6024:   padding: 0;
1.424     albertel 6025: }
                   6026: 
                   6027: .LC_navbuttons {
                   6028:   margin: 2ex 0ex 2ex 0ex;
                   6029: }
1.795     www      6030: 
1.423     albertel 6031: .LC_topic_bar {
                   6032:   font-weight: bold;
                   6033:   background: $tabbg;
1.918     wenzelju 6034:   margin: 1em 0em 1em 2em;
1.805     bisitz   6035:   padding: 3px;
1.918     wenzelju 6036:   font-size: 1.2em;
1.423     albertel 6037: }
1.795     www      6038: 
1.423     albertel 6039: .LC_topic_bar span {
1.918     wenzelju 6040:   left: 0.5em;
                   6041:   position: absolute;
1.423     albertel 6042:   vertical-align: middle;
1.918     wenzelju 6043:   font-size: 1.2em;
1.423     albertel 6044: }
1.795     www      6045: 
1.423     albertel 6046: table.LC_course_group_status {
                   6047:   margin: 20px;
                   6048: }
1.795     www      6049: 
1.423     albertel 6050: table.LC_status_selector td {
                   6051:   vertical-align: top;
                   6052:   text-align: center;
1.424     albertel 6053:   padding: 4px;
                   6054: }
1.795     www      6055: 
1.599     albertel 6056: div.LC_feedback_link {
1.616     albertel 6057:   clear: both;
1.829     kalberla 6058:   background: $sidebg;
1.779     bisitz   6059:   width: 100%;
1.829     kalberla 6060:   padding-bottom: 10px;
                   6061:   border: 1px $tabbg solid;
1.833     kalberla 6062:   height: 22px;
                   6063:   line-height: 22px;
                   6064:   padding-top: 5px;
                   6065: }
                   6066: 
                   6067: div.LC_feedback_link img {
                   6068:   height: 22px;
1.867     kalberla 6069:   vertical-align:middle;
1.829     kalberla 6070: }
                   6071: 
1.911     bisitz   6072: div.LC_feedback_link a {
1.829     kalberla 6073:   text-decoration: none;
1.489     raeburn  6074: }
1.795     www      6075: 
1.867     kalberla 6076: div.LC_comblock {
1.911     bisitz   6077:   display:inline;
1.867     kalberla 6078:   color:$font;
                   6079:   font-size:90%;
                   6080: }
                   6081: 
                   6082: div.LC_feedback_link div.LC_comblock {
                   6083:   padding-left:5px;
                   6084: }
                   6085: 
                   6086: div.LC_feedback_link div.LC_comblock a {
                   6087:   color:$font;
                   6088: }
                   6089: 
1.489     raeburn  6090: span.LC_feedback_link {
1.858     bisitz   6091:   /* background: $feedback_link_bg; */
1.599     albertel 6092:   font-size: larger;
                   6093: }
1.795     www      6094: 
1.599     albertel 6095: span.LC_message_link {
1.858     bisitz   6096:   /* background: $feedback_link_bg; */
1.599     albertel 6097:   font-size: larger;
                   6098:   position: absolute;
                   6099:   right: 1em;
1.489     raeburn  6100: }
1.421     albertel 6101: 
1.515     albertel 6102: table.LC_prior_tries {
1.524     albertel 6103:   border: 1px solid #000000;
                   6104:   border-collapse: separate;
                   6105:   border-spacing: 1px;
1.515     albertel 6106: }
1.523     albertel 6107: 
1.515     albertel 6108: table.LC_prior_tries td {
1.524     albertel 6109:   padding: 2px;
1.515     albertel 6110: }
1.523     albertel 6111: 
                   6112: .LC_answer_correct {
1.795     www      6113:   background: lightgreen;
                   6114:   color: darkgreen;
                   6115:   padding: 6px;
1.523     albertel 6116: }
1.795     www      6117: 
1.523     albertel 6118: .LC_answer_charged_try {
1.797     www      6119:   background: #FFAAAA;
1.795     www      6120:   color: darkred;
                   6121:   padding: 6px;
1.523     albertel 6122: }
1.795     www      6123: 
1.779     bisitz   6124: .LC_answer_not_charged_try,
1.523     albertel 6125: .LC_answer_no_grade,
                   6126: .LC_answer_late {
1.795     www      6127:   background: lightyellow;
1.523     albertel 6128:   color: black;
1.795     www      6129:   padding: 6px;
1.523     albertel 6130: }
1.795     www      6131: 
1.523     albertel 6132: .LC_answer_previous {
1.795     www      6133:   background: lightblue;
                   6134:   color: darkblue;
                   6135:   padding: 6px;
1.523     albertel 6136: }
1.795     www      6137: 
1.779     bisitz   6138: .LC_answer_no_message {
1.777     tempelho 6139:   background: #FFFFFF;
                   6140:   color: black;
1.795     www      6141:   padding: 6px;
1.779     bisitz   6142: }
1.795     www      6143: 
1.779     bisitz   6144: .LC_answer_unknown {
                   6145:   background: orange;
                   6146:   color: black;
1.795     www      6147:   padding: 6px;
1.777     tempelho 6148: }
1.795     www      6149: 
1.529     albertel 6150: span.LC_prior_numerical,
                   6151: span.LC_prior_string,
                   6152: span.LC_prior_custom,
                   6153: span.LC_prior_reaction,
                   6154: span.LC_prior_math {
1.925     bisitz   6155:   font-family: $mono;
1.523     albertel 6156:   white-space: pre;
                   6157: }
                   6158: 
1.525     albertel 6159: span.LC_prior_string {
1.925     bisitz   6160:   font-family: $mono;
1.525     albertel 6161:   white-space: pre;
                   6162: }
                   6163: 
1.523     albertel 6164: table.LC_prior_option {
                   6165:   width: 100%;
                   6166:   border-collapse: collapse;
                   6167: }
1.795     www      6168: 
1.911     bisitz   6169: table.LC_prior_rank,
1.795     www      6170: table.LC_prior_match {
1.528     albertel 6171:   border-collapse: collapse;
                   6172: }
1.795     www      6173: 
1.528     albertel 6174: table.LC_prior_option tr td,
                   6175: table.LC_prior_rank tr td,
                   6176: table.LC_prior_match tr td {
1.524     albertel 6177:   border: 1px solid #000000;
1.515     albertel 6178: }
                   6179: 
1.855     bisitz   6180: .LC_nobreak {
1.544     albertel 6181:   white-space: nowrap;
1.519     raeburn  6182: }
                   6183: 
1.576     raeburn  6184: span.LC_cusr_emph {
                   6185:   font-style: italic;
                   6186: }
                   6187: 
1.633     raeburn  6188: span.LC_cusr_subheading {
                   6189:   font-weight: normal;
                   6190:   font-size: 85%;
                   6191: }
                   6192: 
1.861     bisitz   6193: div.LC_docs_entry_move {
1.859     bisitz   6194:   border: 1px solid #BBBBBB;
1.545     albertel 6195:   background: #DDDDDD;
1.861     bisitz   6196:   width: 22px;
1.859     bisitz   6197:   padding: 1px;
                   6198:   margin: 0;
1.545     albertel 6199: }
                   6200: 
1.861     bisitz   6201: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6202: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6203:   background: #DDDDDD;
                   6204:   font-size: x-small;
                   6205: }
1.795     www      6206: 
1.861     bisitz   6207: .LC_docs_entry_parameter {
                   6208:   white-space: nowrap;
                   6209: }
                   6210: 
1.544     albertel 6211: .LC_docs_copy {
1.545     albertel 6212:   color: #000099;
1.544     albertel 6213: }
1.795     www      6214: 
1.544     albertel 6215: .LC_docs_cut {
1.545     albertel 6216:   color: #550044;
1.544     albertel 6217: }
1.795     www      6218: 
1.544     albertel 6219: .LC_docs_rename {
1.545     albertel 6220:   color: #009900;
1.544     albertel 6221: }
1.795     www      6222: 
1.544     albertel 6223: .LC_docs_remove {
1.545     albertel 6224:   color: #990000;
                   6225: }
                   6226: 
1.547     albertel 6227: .LC_docs_reinit_warn,
                   6228: .LC_docs_ext_edit {
                   6229:   font-size: x-small;
                   6230: }
                   6231: 
1.545     albertel 6232: table.LC_docs_adddocs td,
                   6233: table.LC_docs_adddocs th {
                   6234:   border: 1px solid #BBBBBB;
                   6235:   padding: 4px;
                   6236:   background: #DDDDDD;
1.543     albertel 6237: }
                   6238: 
1.584     albertel 6239: table.LC_sty_begin {
                   6240:   background: #BBFFBB;
                   6241: }
1.795     www      6242: 
1.584     albertel 6243: table.LC_sty_end {
                   6244:   background: #FFBBBB;
                   6245: }
                   6246: 
1.589     raeburn  6247: table.LC_double_column {
1.803     bisitz   6248:   border-width: 0;
1.589     raeburn  6249:   border-collapse: collapse;
                   6250:   width: 100%;
                   6251:   padding: 2px;
                   6252: }
                   6253: 
                   6254: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6255:   top: 2px;
1.589     raeburn  6256:   left: 2px;
                   6257:   width: 47%;
                   6258:   vertical-align: top;
                   6259: }
                   6260: 
                   6261: table.LC_double_column tr td.LC_right_col {
                   6262:   top: 2px;
1.779     bisitz   6263:   right: 2px;
1.589     raeburn  6264:   width: 47%;
                   6265:   vertical-align: top;
                   6266: }
                   6267: 
1.591     raeburn  6268: div.LC_left_float {
                   6269:   float: left;
                   6270:   padding-right: 5%;
1.597     albertel 6271:   padding-bottom: 4px;
1.591     raeburn  6272: }
                   6273: 
                   6274: div.LC_clear_float_header {
1.597     albertel 6275:   padding-bottom: 2px;
1.591     raeburn  6276: }
                   6277: 
                   6278: div.LC_clear_float_footer {
1.597     albertel 6279:   padding-top: 10px;
1.591     raeburn  6280:   clear: both;
                   6281: }
                   6282: 
1.597     albertel 6283: div.LC_grade_show_user {
1.941     bisitz   6284: /*  border-left: 5px solid $sidebg; */
                   6285:   border-top: 5px solid #000000;
                   6286:   margin: 50px 0 0 0;
1.936     bisitz   6287:   padding: 15px 0 5px 10px;
1.597     albertel 6288: }
1.795     www      6289: 
1.936     bisitz   6290: div.LC_grade_show_user_odd_row {
1.941     bisitz   6291: /*  border-left: 5px solid #000000; */
                   6292: }
                   6293: 
                   6294: div.LC_grade_show_user div.LC_Box {
                   6295:   margin-right: 50px;
1.597     albertel 6296: }
                   6297: 
                   6298: div.LC_grade_submissions,
                   6299: div.LC_grade_message_center,
1.936     bisitz   6300: div.LC_grade_info_links {
1.597     albertel 6301:   margin: 5px;
                   6302:   width: 99%;
                   6303:   background: #FFFFFF;
                   6304: }
1.795     www      6305: 
1.597     albertel 6306: div.LC_grade_submissions_header,
1.936     bisitz   6307: div.LC_grade_message_center_header {
1.705     tempelho 6308:   font-weight: bold;
                   6309:   font-size: large;
1.597     albertel 6310: }
1.795     www      6311: 
1.597     albertel 6312: div.LC_grade_submissions_body,
1.936     bisitz   6313: div.LC_grade_message_center_body {
1.597     albertel 6314:   border: 1px solid black;
                   6315:   width: 99%;
                   6316:   background: #FFFFFF;
                   6317: }
1.795     www      6318: 
1.613     albertel 6319: table.LC_scantron_action {
                   6320:   width: 100%;
                   6321: }
1.795     www      6322: 
1.613     albertel 6323: table.LC_scantron_action tr th {
1.698     harmsja  6324:   font-weight:bold;
                   6325:   font-style:normal;
1.613     albertel 6326: }
1.795     www      6327: 
1.779     bisitz   6328: .LC_edit_problem_header,
1.614     albertel 6329: div.LC_edit_problem_footer {
1.705     tempelho 6330:   font-weight: normal;
                   6331:   font-size:  medium;
1.602     albertel 6332:   margin: 2px;
1.1060    bisitz   6333:   background-color: $sidebg;
1.600     albertel 6334: }
1.795     www      6335: 
1.600     albertel 6336: div.LC_edit_problem_header,
1.602     albertel 6337: div.LC_edit_problem_header div,
1.614     albertel 6338: div.LC_edit_problem_footer,
                   6339: div.LC_edit_problem_footer div,
1.602     albertel 6340: div.LC_edit_problem_editxml_header,
                   6341: div.LC_edit_problem_editxml_header div {
1.600     albertel 6342:   margin-top: 5px;
                   6343: }
1.795     www      6344: 
1.600     albertel 6345: div.LC_edit_problem_header_title {
1.705     tempelho 6346:   font-weight: bold;
                   6347:   font-size: larger;
1.602     albertel 6348:   background: $tabbg;
                   6349:   padding: 3px;
1.1060    bisitz   6350:   margin: 0 0 5px 0;
1.602     albertel 6351: }
1.795     www      6352: 
1.602     albertel 6353: table.LC_edit_problem_header_title {
                   6354:   width: 100%;
1.600     albertel 6355:   background: $tabbg;
1.602     albertel 6356: }
                   6357: 
                   6358: div.LC_edit_problem_discards {
                   6359:   float: left;
                   6360:   padding-bottom: 5px;
                   6361: }
1.795     www      6362: 
1.602     albertel 6363: div.LC_edit_problem_saves {
                   6364:   float: right;
                   6365:   padding-bottom: 5px;
1.600     albertel 6366: }
1.795     www      6367: 
1.911     bisitz   6368: img.stift {
1.803     bisitz   6369:   border-width: 0;
                   6370:   vertical-align: middle;
1.677     riegler  6371: }
1.680     riegler  6372: 
1.923     bisitz   6373: table td.LC_mainmenu_col_fieldset {
1.680     riegler  6374:   vertical-align: top;
1.777     tempelho 6375: }
1.795     www      6376: 
1.716     raeburn  6377: div.LC_createcourse {
1.911     bisitz   6378:   margin: 10px 10px 10px 10px;
1.716     raeburn  6379: }
                   6380: 
1.917     raeburn  6381: .LC_dccid {
                   6382:   margin: 0.2em 0 0 0;
                   6383:   padding: 0;
                   6384:   font-size: 90%;
                   6385:   display:none;
                   6386: }
                   6387: 
1.897     wenzelju 6388: ol.LC_primary_menu a:hover,
1.721     harmsja  6389: ol#LC_MenuBreadcrumbs a:hover,
                   6390: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 6391: ul#LC_secondary_menu a:hover,
1.721     harmsja  6392: .LC_FormSectionClearButton input:hover
1.795     www      6393: ul.LC_TabContent   li:hover a {
1.952     onken    6394:   color:$button_hover;
1.911     bisitz   6395:   text-decoration:none;
1.693     droeschl 6396: }
                   6397: 
1.779     bisitz   6398: h1 {
1.911     bisitz   6399:   padding: 0;
                   6400:   line-height:130%;
1.693     droeschl 6401: }
1.698     harmsja  6402: 
1.911     bisitz   6403: h2,
                   6404: h3,
                   6405: h4,
                   6406: h5,
                   6407: h6 {
                   6408:   margin: 5px 0 5px 0;
                   6409:   padding: 0;
                   6410:   line-height:130%;
1.693     droeschl 6411: }
1.795     www      6412: 
                   6413: .LC_hcell {
1.911     bisitz   6414:   padding:3px 15px 3px 15px;
                   6415:   margin: 0;
                   6416:   background-color:$tabbg;
                   6417:   color:$fontmenu;
                   6418:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 6419: }
1.795     www      6420: 
1.840     bisitz   6421: .LC_Box > .LC_hcell {
1.911     bisitz   6422:   margin: 0 -10px 10px -10px;
1.835     bisitz   6423: }
                   6424: 
1.721     harmsja  6425: .LC_noBorder {
1.911     bisitz   6426:   border: 0;
1.698     harmsja  6427: }
1.693     droeschl 6428: 
1.721     harmsja  6429: .LC_FormSectionClearButton input {
1.911     bisitz   6430:   background-color:transparent;
                   6431:   border: none;
                   6432:   cursor:pointer;
                   6433:   text-decoration:underline;
1.693     droeschl 6434: }
1.763     bisitz   6435: 
                   6436: .LC_help_open_topic {
1.911     bisitz   6437:   color: #FFFFFF;
                   6438:   background-color: #EEEEFF;
                   6439:   margin: 1px;
                   6440:   padding: 4px;
                   6441:   border: 1px solid #000033;
                   6442:   white-space: nowrap;
                   6443:   /* vertical-align: middle; */
1.759     neumanie 6444: }
1.693     droeschl 6445: 
1.911     bisitz   6446: dl,
                   6447: ul,
                   6448: div,
                   6449: fieldset {
                   6450:   margin: 10px 10px 10px 0;
                   6451:   /* overflow: hidden; */
1.693     droeschl 6452: }
1.795     www      6453: 
1.838     bisitz   6454: fieldset > legend {
1.911     bisitz   6455:   font-weight: bold;
                   6456:   padding: 0 5px 0 5px;
1.838     bisitz   6457: }
                   6458: 
1.813     bisitz   6459: #LC_nav_bar {
1.911     bisitz   6460:   float: left;
1.995     raeburn  6461:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   6462:   margin: 0 0 2px 0;
1.807     droeschl 6463: }
                   6464: 
1.916     droeschl 6465: #LC_realm {
                   6466:   margin: 0.2em 0 0 0;
                   6467:   padding: 0;
                   6468:   font-weight: bold;
                   6469:   text-align: center;
1.995     raeburn  6470:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 6471: }
                   6472: 
1.911     bisitz   6473: #LC_nav_bar em {
                   6474:   font-weight: bold;
                   6475:   font-style: normal;
1.807     droeschl 6476: }
                   6477: 
1.897     wenzelju 6478: ol.LC_primary_menu {
1.911     bisitz   6479:   float: right;
1.934     droeschl 6480:   margin: 0;
1.1076    raeburn  6481:   padding: 0;
1.995     raeburn  6482:   background-color: $pgbg_or_bgcolor;
1.807     droeschl 6483: }
                   6484: 
1.852     droeschl 6485: ol#LC_PathBreadcrumbs {
1.911     bisitz   6486:   margin: 0;
1.693     droeschl 6487: }
                   6488: 
1.897     wenzelju 6489: ol.LC_primary_menu li {
1.1076    raeburn  6490:   color: RGB(80, 80, 80);
                   6491:   vertical-align: middle;
                   6492:   text-align: left;
                   6493:   list-style: none;
                   6494:   float: left;
                   6495: }
                   6496: 
                   6497: ol.LC_primary_menu li a {
                   6498:   display: block;
                   6499:   margin: 0;
                   6500:   padding: 0 5px 0 10px;
                   6501:   text-decoration: none;
                   6502: }
                   6503: 
                   6504: ol.LC_primary_menu li ul {
                   6505:   display: none;
                   6506:   width: 10em;
                   6507:   background-color: $data_table_light;
                   6508: }
                   6509: 
                   6510: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
                   6511:   display: block;
                   6512:   position: absolute;
                   6513:   margin: 0;
                   6514:   padding: 0;
1.1078    raeburn  6515:   z-index: 2;
1.1076    raeburn  6516: }
                   6517: 
                   6518: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
                   6519:   font-size: 90%;
1.911     bisitz   6520:   vertical-align: top;
1.1076    raeburn  6521:   float: none;
1.1079    raeburn  6522:   border-left: 1px solid black;
                   6523:   border-right: 1px solid black;
1.1076    raeburn  6524: }
                   6525: 
                   6526: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
1.1078    raeburn  6527:   background-color:$data_table_light;
1.1076    raeburn  6528: }
                   6529: 
                   6530: ol.LC_primary_menu li li a:hover {
                   6531:    color:$button_hover;
                   6532:    background-color:$data_table_dark;
1.693     droeschl 6533: }
                   6534: 
1.897     wenzelju 6535: ol.LC_primary_menu li img {
1.911     bisitz   6536:   vertical-align: bottom;
1.934     droeschl 6537:   height: 1.1em;
1.1077    raeburn  6538:   margin: 0.2em 0 0 0;
1.693     droeschl 6539: }
                   6540: 
1.897     wenzelju 6541: ol.LC_primary_menu a {
1.911     bisitz   6542:   color: RGB(80, 80, 80);
                   6543:   text-decoration: none;
1.693     droeschl 6544: }
1.795     www      6545: 
1.949     droeschl 6546: ol.LC_primary_menu a.LC_new_message {
                   6547:   font-weight:bold;
                   6548:   color: darkred;
                   6549: }
                   6550: 
1.975     raeburn  6551: ol.LC_docs_parameters {
                   6552:   margin-left: 0;
                   6553:   padding: 0;
                   6554:   list-style: none;
                   6555: }
                   6556: 
                   6557: ol.LC_docs_parameters li {
                   6558:   margin: 0;
                   6559:   padding-right: 20px;
                   6560:   display: inline;
                   6561: }
                   6562: 
1.976     raeburn  6563: ol.LC_docs_parameters li:before {
                   6564:   content: "\\002022 \\0020";
                   6565: }
                   6566: 
                   6567: li.LC_docs_parameters_title {
                   6568:   font-weight: bold;
                   6569: }
                   6570: 
                   6571: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   6572:   content: "";
                   6573: }
                   6574: 
1.897     wenzelju 6575: ul#LC_secondary_menu {
1.911     bisitz   6576:   clear: both;
                   6577:   color: $fontmenu;
                   6578:   background: $tabbg;
                   6579:   list-style: none;
                   6580:   padding: 0;
                   6581:   margin: 0;
                   6582:   width: 100%;
1.995     raeburn  6583:   text-align: left;
1.808     droeschl 6584: }
                   6585: 
1.897     wenzelju 6586: ul#LC_secondary_menu li {
1.911     bisitz   6587:   font-weight: bold;
                   6588:   line-height: 1.8em;
                   6589:   padding: 0 0.8em;
                   6590:   border-right: 1px solid black;
                   6591:   display: inline;
                   6592:   vertical-align: middle;
1.807     droeschl 6593: }
                   6594: 
1.847     tempelho 6595: ul.LC_TabContent {
1.911     bisitz   6596:   display:block;
                   6597:   background: $sidebg;
                   6598:   border-bottom: solid 1px $lg_border_color;
                   6599:   list-style:none;
1.1020    raeburn  6600:   margin: -1px -10px 0 -10px;
1.911     bisitz   6601:   padding: 0;
1.693     droeschl 6602: }
                   6603: 
1.795     www      6604: ul.LC_TabContent li,
                   6605: ul.LC_TabContentBigger li {
1.911     bisitz   6606:   float:left;
1.741     harmsja  6607: }
1.795     www      6608: 
1.897     wenzelju 6609: ul#LC_secondary_menu li a {
1.911     bisitz   6610:   color: $fontmenu;
                   6611:   text-decoration: none;
1.693     droeschl 6612: }
1.795     www      6613: 
1.721     harmsja  6614: ul.LC_TabContent {
1.952     onken    6615:   min-height:20px;
1.721     harmsja  6616: }
1.795     www      6617: 
                   6618: ul.LC_TabContent li {
1.911     bisitz   6619:   vertical-align:middle;
1.959     onken    6620:   padding: 0 16px 0 10px;
1.911     bisitz   6621:   background-color:$tabbg;
                   6622:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  6623:   border-left: solid 1px $font;
1.721     harmsja  6624: }
1.795     www      6625: 
1.847     tempelho 6626: ul.LC_TabContent .right {
1.911     bisitz   6627:   float:right;
1.847     tempelho 6628: }
                   6629: 
1.911     bisitz   6630: ul.LC_TabContent li a,
                   6631: ul.LC_TabContent li {
                   6632:   color:rgb(47,47,47);
                   6633:   text-decoration:none;
                   6634:   font-size:95%;
                   6635:   font-weight:bold;
1.952     onken    6636:   min-height:20px;
                   6637: }
                   6638: 
1.959     onken    6639: ul.LC_TabContent li a:hover,
                   6640: ul.LC_TabContent li a:focus {
1.952     onken    6641:   color: $button_hover;
1.959     onken    6642:   background:none;
                   6643:   outline:none;
1.952     onken    6644: }
                   6645: 
                   6646: ul.LC_TabContent li:hover {
                   6647:   color: $button_hover;
                   6648:   cursor:pointer;
1.721     harmsja  6649: }
1.795     www      6650: 
1.911     bisitz   6651: ul.LC_TabContent li.active {
1.952     onken    6652:   color: $font;
1.911     bisitz   6653:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    6654:   border-bottom:solid 1px #FFFFFF;
                   6655:   cursor: default;
1.744     ehlerst  6656: }
1.795     www      6657: 
1.959     onken    6658: ul.LC_TabContent li.active a {
                   6659:   color:$font;
                   6660:   background:#FFFFFF;
                   6661:   outline: none;
                   6662: }
1.1047    raeburn  6663: 
                   6664: ul.LC_TabContent li.goback {
                   6665:   float: left;
                   6666:   border-left: none;
                   6667: }
                   6668: 
1.870     tempelho 6669: #maincoursedoc {
1.911     bisitz   6670:   clear:both;
1.870     tempelho 6671: }
                   6672: 
                   6673: ul.LC_TabContentBigger {
1.911     bisitz   6674:   display:block;
                   6675:   list-style:none;
                   6676:   padding: 0;
1.870     tempelho 6677: }
                   6678: 
1.795     www      6679: ul.LC_TabContentBigger li {
1.911     bisitz   6680:   vertical-align:bottom;
                   6681:   height: 30px;
                   6682:   font-size:110%;
                   6683:   font-weight:bold;
                   6684:   color: #737373;
1.841     tempelho 6685: }
                   6686: 
1.957     onken    6687: ul.LC_TabContentBigger li.active {
                   6688:   position: relative;
                   6689:   top: 1px;
                   6690: }
                   6691: 
1.870     tempelho 6692: ul.LC_TabContentBigger li a {
1.911     bisitz   6693:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   6694:   height: 30px;
                   6695:   line-height: 30px;
                   6696:   text-align: center;
                   6697:   display: block;
                   6698:   text-decoration: none;
1.958     onken    6699:   outline: none;  
1.741     harmsja  6700: }
1.795     www      6701: 
1.870     tempelho 6702: ul.LC_TabContentBigger li.active a {
1.911     bisitz   6703:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   6704:   color:$font;
1.744     ehlerst  6705: }
1.795     www      6706: 
1.870     tempelho 6707: ul.LC_TabContentBigger li b {
1.911     bisitz   6708:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   6709:   display: block;
                   6710:   float: left;
                   6711:   padding: 0 30px;
1.957     onken    6712:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 6713: }
                   6714: 
1.956     onken    6715: ul.LC_TabContentBigger li:hover b {
                   6716:   color:$button_hover;
                   6717: }
                   6718: 
1.870     tempelho 6719: ul.LC_TabContentBigger li.active b {
1.911     bisitz   6720:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   6721:   color:$font;
1.957     onken    6722:   border: 0;
1.741     harmsja  6723: }
1.693     droeschl 6724: 
1.870     tempelho 6725: 
1.862     bisitz   6726: ul.LC_CourseBreadcrumbs {
                   6727:   background: $sidebg;
1.1020    raeburn  6728:   height: 2em;
1.862     bisitz   6729:   padding-left: 10px;
1.1020    raeburn  6730:   margin: 0;
1.862     bisitz   6731:   list-style-position: inside;
                   6732: }
                   6733: 
1.911     bisitz   6734: ol#LC_MenuBreadcrumbs,
1.862     bisitz   6735: ol#LC_PathBreadcrumbs {
1.911     bisitz   6736:   padding-left: 10px;
                   6737:   margin: 0;
1.933     droeschl 6738:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 6739: }
                   6740: 
1.911     bisitz   6741: ol#LC_MenuBreadcrumbs li,
                   6742: ol#LC_PathBreadcrumbs li,
1.862     bisitz   6743: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   6744:   display: inline;
1.933     droeschl 6745:   white-space: normal;  
1.693     droeschl 6746: }
                   6747: 
1.823     bisitz   6748: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   6749: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   6750:   text-decoration: none;
                   6751:   font-size:90%;
1.693     droeschl 6752: }
1.795     www      6753: 
1.969     droeschl 6754: ol#LC_MenuBreadcrumbs h1 {
                   6755:   display: inline;
                   6756:   font-size: 90%;
                   6757:   line-height: 2.5em;
                   6758:   margin: 0;
                   6759:   padding: 0;
                   6760: }
                   6761: 
1.795     www      6762: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   6763:   text-decoration:none;
                   6764:   font-size:100%;
                   6765:   font-weight:bold;
1.693     droeschl 6766: }
1.795     www      6767: 
1.840     bisitz   6768: .LC_Box {
1.911     bisitz   6769:   border: solid 1px $lg_border_color;
                   6770:   padding: 0 10px 10px 10px;
1.746     neumanie 6771: }
1.795     www      6772: 
1.1020    raeburn  6773: .LC_DocsBox {
                   6774:   border: solid 1px $lg_border_color;
                   6775:   padding: 0 0 10px 10px;
                   6776: }
                   6777: 
1.795     www      6778: .LC_AboutMe_Image {
1.911     bisitz   6779:   float:left;
                   6780:   margin-right:10px;
1.747     neumanie 6781: }
1.795     www      6782: 
                   6783: .LC_Clear_AboutMe_Image {
1.911     bisitz   6784:   clear:left;
1.747     neumanie 6785: }
1.795     www      6786: 
1.721     harmsja  6787: dl.LC_ListStyleClean dt {
1.911     bisitz   6788:   padding-right: 5px;
                   6789:   display: table-header-group;
1.693     droeschl 6790: }
                   6791: 
1.721     harmsja  6792: dl.LC_ListStyleClean dd {
1.911     bisitz   6793:   display: table-row;
1.693     droeschl 6794: }
                   6795: 
1.721     harmsja  6796: .LC_ListStyleClean,
                   6797: .LC_ListStyleSimple,
                   6798: .LC_ListStyleNormal,
1.795     www      6799: .LC_ListStyleSpecial {
1.911     bisitz   6800:   /* display:block; */
                   6801:   list-style-position: inside;
                   6802:   list-style-type: none;
                   6803:   overflow: hidden;
                   6804:   padding: 0;
1.693     droeschl 6805: }
                   6806: 
1.721     harmsja  6807: .LC_ListStyleSimple li,
                   6808: .LC_ListStyleSimple dd,
                   6809: .LC_ListStyleNormal li,
                   6810: .LC_ListStyleNormal dd,
                   6811: .LC_ListStyleSpecial li,
1.795     www      6812: .LC_ListStyleSpecial dd {
1.911     bisitz   6813:   margin: 0;
                   6814:   padding: 5px 5px 5px 10px;
                   6815:   clear: both;
1.693     droeschl 6816: }
                   6817: 
1.721     harmsja  6818: .LC_ListStyleClean li,
                   6819: .LC_ListStyleClean dd {
1.911     bisitz   6820:   padding-top: 0;
                   6821:   padding-bottom: 0;
1.693     droeschl 6822: }
                   6823: 
1.721     harmsja  6824: .LC_ListStyleSimple dd,
1.795     www      6825: .LC_ListStyleSimple li {
1.911     bisitz   6826:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 6827: }
                   6828: 
1.721     harmsja  6829: .LC_ListStyleSpecial li,
                   6830: .LC_ListStyleSpecial dd {
1.911     bisitz   6831:   list-style-type: none;
                   6832:   background-color: RGB(220, 220, 220);
                   6833:   margin-bottom: 4px;
1.693     droeschl 6834: }
                   6835: 
1.721     harmsja  6836: table.LC_SimpleTable {
1.911     bisitz   6837:   margin:5px;
                   6838:   border:solid 1px $lg_border_color;
1.795     www      6839: }
1.693     droeschl 6840: 
1.721     harmsja  6841: table.LC_SimpleTable tr {
1.911     bisitz   6842:   padding: 0;
                   6843:   border:solid 1px $lg_border_color;
1.693     droeschl 6844: }
1.795     www      6845: 
                   6846: table.LC_SimpleTable thead {
1.911     bisitz   6847:   background:rgb(220,220,220);
1.693     droeschl 6848: }
                   6849: 
1.721     harmsja  6850: div.LC_columnSection {
1.911     bisitz   6851:   display: block;
                   6852:   clear: both;
                   6853:   overflow: hidden;
                   6854:   margin: 0;
1.693     droeschl 6855: }
                   6856: 
1.721     harmsja  6857: div.LC_columnSection>* {
1.911     bisitz   6858:   float: left;
                   6859:   margin: 10px 20px 10px 0;
                   6860:   overflow:hidden;
1.693     droeschl 6861: }
1.721     harmsja  6862: 
1.795     www      6863: table em {
1.911     bisitz   6864:   font-weight: bold;
                   6865:   font-style: normal;
1.748     schulted 6866: }
1.795     www      6867: 
1.779     bisitz   6868: table.LC_tableBrowseRes,
1.795     www      6869: table.LC_tableOfContent {
1.911     bisitz   6870:   border:none;
                   6871:   border-spacing: 1px;
                   6872:   padding: 3px;
                   6873:   background-color: #FFFFFF;
                   6874:   font-size: 90%;
1.753     droeschl 6875: }
1.789     droeschl 6876: 
1.911     bisitz   6877: table.LC_tableOfContent {
                   6878:   border-collapse: collapse;
1.789     droeschl 6879: }
                   6880: 
1.771     droeschl 6881: table.LC_tableBrowseRes a,
1.768     schulted 6882: table.LC_tableOfContent a {
1.911     bisitz   6883:   background-color: transparent;
                   6884:   text-decoration: none;
1.753     droeschl 6885: }
                   6886: 
1.795     www      6887: table.LC_tableOfContent img {
1.911     bisitz   6888:   border: none;
                   6889:   height: 1.3em;
                   6890:   vertical-align: text-bottom;
                   6891:   margin-right: 0.3em;
1.753     droeschl 6892: }
1.757     schulted 6893: 
1.795     www      6894: a#LC_content_toolbar_firsthomework {
1.911     bisitz   6895:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  6896: }
                   6897: 
1.795     www      6898: a#LC_content_toolbar_everything {
1.911     bisitz   6899:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  6900: }
                   6901: 
1.795     www      6902: a#LC_content_toolbar_uncompleted {
1.911     bisitz   6903:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  6904: }
                   6905: 
1.795     www      6906: #LC_content_toolbar_clearbubbles {
1.911     bisitz   6907:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  6908: }
                   6909: 
1.795     www      6910: a#LC_content_toolbar_changefolder {
1.911     bisitz   6911:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 6912: }
                   6913: 
1.795     www      6914: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   6915:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 6916: }
                   6917: 
1.1043    raeburn  6918: a#LC_content_toolbar_edittoplevel {
                   6919:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   6920: }
                   6921: 
1.795     www      6922: ul#LC_toolbar li a:hover {
1.911     bisitz   6923:   background-position: bottom center;
1.757     schulted 6924: }
                   6925: 
1.795     www      6926: ul#LC_toolbar {
1.911     bisitz   6927:   padding: 0;
                   6928:   margin: 2px;
                   6929:   list-style:none;
                   6930:   position:relative;
                   6931:   background-color:white;
1.1082    raeburn  6932:   overflow: auto;
1.757     schulted 6933: }
                   6934: 
1.795     www      6935: ul#LC_toolbar li {
1.911     bisitz   6936:   border:1px solid white;
                   6937:   padding: 0;
                   6938:   margin: 0;
                   6939:   float: left;
                   6940:   display:inline;
                   6941:   vertical-align:middle;
1.1082    raeburn  6942:   white-space: nowrap;
1.911     bisitz   6943: }
1.757     schulted 6944: 
1.783     amueller 6945: 
1.795     www      6946: a.LC_toolbarItem {
1.911     bisitz   6947:   display:block;
                   6948:   padding: 0;
                   6949:   margin: 0;
                   6950:   height: 32px;
                   6951:   width: 32px;
                   6952:   color:white;
                   6953:   border: none;
                   6954:   background-repeat:no-repeat;
                   6955:   background-color:transparent;
1.757     schulted 6956: }
                   6957: 
1.915     droeschl 6958: ul.LC_funclist {
                   6959:     margin: 0;
                   6960:     padding: 0.5em 1em 0.5em 0;
                   6961: }
                   6962: 
1.933     droeschl 6963: ul.LC_funclist > li:first-child {
                   6964:     font-weight:bold; 
                   6965:     margin-left:0.8em;
                   6966: }
                   6967: 
1.915     droeschl 6968: ul.LC_funclist + ul.LC_funclist {
                   6969:     /* 
                   6970:        left border as a seperator if we have more than
                   6971:        one list 
                   6972:     */
                   6973:     border-left: 1px solid $sidebg;
                   6974:     /* 
                   6975:        this hides the left border behind the border of the 
                   6976:        outer box if element is wrapped to the next 'line' 
                   6977:     */
                   6978:     margin-left: -1px;
                   6979: }
                   6980: 
1.843     bisitz   6981: ul.LC_funclist li {
1.915     droeschl 6982:   display: inline;
1.782     bisitz   6983:   white-space: nowrap;
1.915     droeschl 6984:   margin: 0 0 0 25px;
                   6985:   line-height: 150%;
1.782     bisitz   6986: }
                   6987: 
1.974     wenzelju 6988: .LC_hidden {
                   6989:   display: none;
                   6990: }
                   6991: 
1.1030    www      6992: .LCmodal-overlay {
                   6993: 		position:fixed;
                   6994: 		top:0;
                   6995: 		right:0;
                   6996: 		bottom:0;
                   6997: 		left:0;
                   6998: 		height:100%;
                   6999: 		width:100%;
                   7000: 		margin:0;
                   7001: 		padding:0;
                   7002: 		background:#999;
                   7003: 		opacity:.75;
                   7004: 		filter: alpha(opacity=75);
                   7005: 		-moz-opacity: 0.75;
                   7006: 		z-index:101;
                   7007: }
                   7008: 
                   7009: * html .LCmodal-overlay {   
                   7010: 		position: absolute;
                   7011: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7012: }
                   7013: 
                   7014: .LCmodal-window {
                   7015: 		position:fixed;
                   7016: 		top:50%;
                   7017: 		left:50%;
                   7018: 		margin:0;
                   7019: 		padding:0;
                   7020: 		z-index:102;
                   7021: 	}
                   7022: 
                   7023: * html .LCmodal-window {
                   7024: 		position:absolute;
                   7025: }
                   7026: 
                   7027: .LCclose-window {
                   7028: 		position:absolute;
                   7029: 		width:32px;
                   7030: 		height:32px;
                   7031: 		right:8px;
                   7032: 		top:8px;
                   7033: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7034: 		text-indent:-99999px;
                   7035: 		overflow:hidden;
                   7036: 		cursor:pointer;
                   7037: }
                   7038: 
1.343     albertel 7039: END
                   7040: }
                   7041: 
1.306     albertel 7042: =pod
                   7043: 
                   7044: =item * &headtag()
                   7045: 
                   7046: Returns a uniform footer for LON-CAPA web pages.
                   7047: 
1.307     albertel 7048: Inputs: $title - optional title for the head
                   7049:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7050:         $args - optional arguments
1.319     albertel 7051:             force_register - if is true call registerurl so the remote is 
                   7052:                              informed
1.415     albertel 7053:             redirect       -> array ref of
                   7054:                                    1- seconds before redirect occurs
                   7055:                                    2- url to redirect to
                   7056:                                    3- whether the side effect should occur
1.315     albertel 7057:                            (side effect of setting 
                   7058:                                $env{'internal.head.redirect'} to the url 
                   7059:                                redirected too)
1.352     albertel 7060:             domain         -> force to color decorate a page for a specific
                   7061:                                domain
                   7062:             function       -> force usage of a specific rolish color scheme
                   7063:             bgcolor        -> override the default page bgcolor
1.460     albertel 7064:             no_auto_mt_title
                   7065:                            -> prevent &mt()ing the title arg
1.464     albertel 7066: 
1.306     albertel 7067: =cut
                   7068: 
                   7069: sub headtag {
1.313     albertel 7070:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7071:     
1.363     albertel 7072:     my $function = $args->{'function'} || &get_users_function();
                   7073:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7074:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.418     albertel 7075:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7076: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7077: 		   #time(),
1.418     albertel 7078: 		   $env{'environment.color.timestamp'},
1.363     albertel 7079: 		   $function,$domain,$bgcolor);
                   7080: 
1.369     www      7081:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7082: 
1.308     albertel 7083:     my $result =
                   7084: 	'<head>'.
1.461     albertel 7085: 	&font_settings();
1.319     albertel 7086: 
1.1064    raeburn  7087:     my $inhibitprint = &print_suppression();
                   7088: 
1.461     albertel 7089:     if (!$args->{'frameset'}) {
                   7090: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7091:     }
1.962     droeschl 7092:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   7093:         $result .= Apache::lonxml::display_title();
1.319     albertel 7094:     }
1.436     albertel 7095:     if (!$args->{'no_nav_bar'} 
                   7096: 	&& !$args->{'only_body'}
                   7097: 	&& !$args->{'frameset'}) {
                   7098: 	$result .= &help_menu_js();
1.1032    www      7099:         $result.=&modal_window();
1.1038    www      7100:         $result.=&togglebox_script();
1.1034    www      7101:         $result.=&wishlist_window();
1.1041    www      7102:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7103:     } else {
                   7104:         if ($args->{'add_modal'}) {
                   7105:            $result.=&modal_window();
                   7106:         }
                   7107:         if ($args->{'add_wishlist'}) {
                   7108:            $result.=&wishlist_window();
                   7109:         }
1.1038    www      7110:         if ($args->{'add_togglebox'}) {
                   7111:            $result.=&togglebox_script();
                   7112:         }
1.1041    www      7113:         if ($args->{'add_progressbar'}) {
                   7114:            $result.=&LCprogressbarUpdate_script();
                   7115:         }
1.436     albertel 7116:     }
1.314     albertel 7117:     if (ref($args->{'redirect'})) {
1.414     albertel 7118: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7119: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7120: 	if (!$inhibit_continue) {
                   7121: 	    $env{'internal.head.redirect'} = $url;
                   7122: 	}
1.313     albertel 7123: 	$result.=<<ADDMETA
                   7124: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7125: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7126: ADDMETA
                   7127:     }
1.306     albertel 7128:     if (!defined($title)) {
                   7129: 	$title = 'The LearningOnline Network with CAPA';
                   7130:     }
1.460     albertel 7131:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   7132:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.414     albertel 7133: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
1.1064    raeburn  7134:         .$inhibitprint
1.414     albertel 7135: 	.$head_extra;
1.962     droeschl 7136:     return $result.'</head>';
1.306     albertel 7137: }
                   7138: 
                   7139: =pod
                   7140: 
1.340     albertel 7141: =item * &font_settings()
                   7142: 
                   7143: Returns neccessary <meta> to set the proper encoding
                   7144: 
                   7145: Inputs: none
                   7146: 
                   7147: =cut
                   7148: 
                   7149: sub font_settings {
                   7150:     my $headerstring='';
1.647     www      7151:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
1.340     albertel 7152: 	$headerstring.=
                   7153: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
                   7154:     }
                   7155:     return $headerstring;
                   7156: }
                   7157: 
1.341     albertel 7158: =pod
                   7159: 
1.1064    raeburn  7160: =item * &print_suppression()
                   7161: 
                   7162: In course context returns css which causes the body to be blank when media="print",
                   7163: if printout generation is unavailable for the current resource.
                   7164: 
                   7165: This could be because:
                   7166: 
                   7167: (a) printstartdate is in the future
                   7168: 
                   7169: (b) printenddate is in the past
                   7170: 
                   7171: (c) there is an active exam block with "printout"
                   7172: functionality blocked
                   7173: 
                   7174: Users with pav, pfo or evb privileges are exempt.
                   7175: 
                   7176: Inputs: none
                   7177: 
                   7178: =cut
                   7179: 
                   7180: 
                   7181: sub print_suppression {
                   7182:     my $noprint;
                   7183:     if ($env{'request.course.id'}) {
                   7184:         my $scope = $env{'request.course.id'};
                   7185:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7186:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   7187:             return;
                   7188:         }
                   7189:         if ($env{'request.course.sec'} ne '') {
                   7190:             $scope .= "/$env{'request.course.sec'}";
                   7191:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7192:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  7193:                 return;
1.1064    raeburn  7194:             }
                   7195:         }
                   7196:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7197:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1065    raeburn  7198:         my $blocked = &blocking_status('printout',$cnum,$cdom);
1.1064    raeburn  7199:         if ($blocked) {
                   7200:             my $checkrole = "cm./$cdom/$cnum";
                   7201:             if ($env{'request.course.sec'} ne '') {
                   7202:                 $checkrole .= "/$env{'request.course.sec'}";
                   7203:             }
                   7204:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   7205:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   7206:                 $noprint = 1;
                   7207:             }
                   7208:         }
                   7209:         unless ($noprint) {
                   7210:             my $symb = &Apache::lonnet::symbread();
                   7211:             if ($symb ne '') {
                   7212:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   7213:                 if (ref($navmap)) {
                   7214:                     my $res = $navmap->getBySymb($symb);
                   7215:                     if (ref($res)) {
                   7216:                         if (!$res->resprintable()) {
                   7217:                             $noprint = 1;
                   7218:                         }
                   7219:                     }
                   7220:                 }
                   7221:             }
                   7222:         }
                   7223:         if ($noprint) {
                   7224:             return <<"ENDSTYLE";
                   7225: <style type="text/css" media="print">
                   7226:     body { display:none }
                   7227: </style>
                   7228: ENDSTYLE
                   7229:         }
                   7230:     }
                   7231:     return;
                   7232: }
                   7233: 
                   7234: =pod
                   7235: 
1.341     albertel 7236: =item * &xml_begin()
                   7237: 
                   7238: Returns the needed doctype and <html>
                   7239: 
                   7240: Inputs: none
                   7241: 
                   7242: =cut
                   7243: 
                   7244: sub xml_begin {
                   7245:     my $output='';
                   7246: 
                   7247:     if ($env{'browser.mathml'}) {
                   7248: 	$output='<?xml version="1.0"?>'
                   7249:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   7250: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   7251:             
                   7252: #	    .'<!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">] >'
                   7253: 	    .'<!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">'
                   7254:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   7255: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
                   7256:     } else {
1.849     bisitz   7257: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
                   7258:            .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
1.341     albertel 7259:     }
                   7260:     return $output;
                   7261: }
1.340     albertel 7262: 
                   7263: =pod
                   7264: 
1.306     albertel 7265: =item * &start_page()
                   7266: 
                   7267: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   7268: 
1.648     raeburn  7269: Inputs:
                   7270: 
                   7271: =over 4
                   7272: 
                   7273: $title - optional title for the page
                   7274: 
                   7275: $head_extra - optional extra HTML to incude inside the <head>
                   7276: 
                   7277: $args - additional optional args supported are:
                   7278: 
                   7279: =over 8
                   7280: 
                   7281:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 7282:                                     arg on
1.814     bisitz   7283:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  7284:              add_entries    -> additional attributes to add to the  <body>
                   7285:              domain         -> force to color decorate a page for a 
1.317     albertel 7286:                                     specific domain
1.648     raeburn  7287:              function       -> force usage of a specific rolish color
1.317     albertel 7288:                                     scheme
1.648     raeburn  7289:              redirect       -> see &headtag()
                   7290:              bgcolor        -> override the default page bg color
                   7291:              js_ready       -> return a string ready for being used in 
1.317     albertel 7292:                                     a javascript writeln
1.648     raeburn  7293:              html_encode    -> return a string ready for being used in 
1.320     albertel 7294:                                     a html attribute
1.648     raeburn  7295:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 7296:                                     $forcereg arg
1.648     raeburn  7297:              frameset       -> if true will start with a <frameset>
1.330     albertel 7298:                                     rather than <body>
1.648     raeburn  7299:              skip_phases    -> hash ref of 
1.338     albertel 7300:                                     head -> skip the <html><head> generation
                   7301:                                     body -> skip all <body> generation
1.648     raeburn  7302:              no_auto_mt_title -> prevent &mt()ing the title arg
                   7303:              inherit_jsmath -> when creating popup window in a page,
                   7304:                                     should it have jsmath forced on by the
                   7305:                                     current page
1.867     kalberla 7306:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  7307:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.361     albertel 7308: 
1.648     raeburn  7309: =back
1.460     albertel 7310: 
1.648     raeburn  7311: =back
1.562     albertel 7312: 
1.306     albertel 7313: =cut
                   7314: 
                   7315: sub start_page {
1.309     albertel 7316:     my ($title,$head_extra,$args) = @_;
1.318     albertel 7317:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 7318: 
1.315     albertel 7319:     $env{'internal.start_page'}++;
1.338     albertel 7320:     my $result;
1.964     droeschl 7321: 
1.338     albertel 7322:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1030    www      7323:         $result .= &xml_begin() . &headtag($title, $head_extra, $args);
1.338     albertel 7324:     }
                   7325:     
                   7326:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   7327: 	if ($args->{'frameset'}) {
                   7328: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   7329: 						$args->{'add_entries'});
                   7330: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   7331:         } else {
                   7332:             $result .=
                   7333:                 &bodytag($title, 
                   7334:                          $args->{'function'},       $args->{'add_entries'},
                   7335:                          $args->{'only_body'},      $args->{'domain'},
                   7336:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.962     droeschl 7337:                          $args->{'bgcolor'},        $args);
1.831     bisitz   7338:         }
1.330     albertel 7339:     }
1.338     albertel 7340: 
1.315     albertel 7341:     if ($args->{'js_ready'}) {
1.713     kaisler  7342: 		$result = &js_ready($result);
1.315     albertel 7343:     }
1.320     albertel 7344:     if ($args->{'html_encode'}) {
1.713     kaisler  7345: 		$result = &html_encode($result);
                   7346:     }
                   7347: 
1.813     bisitz   7348:     # Preparation for new and consistent functionlist at top of screen
                   7349:     # if ($args->{'functionlist'}) {
                   7350:     #            $result .= &build_functionlist();
                   7351:     #}
                   7352: 
1.964     droeschl 7353:     # Don't add anything more if only_body wanted or in const space
                   7354:     return $result if    $args->{'only_body'} 
                   7355:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   7356: 
                   7357:     #Breadcrumbs
1.758     kaisler  7358:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   7359: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   7360: 		#if any br links exists, add them to the breadcrumbs
                   7361: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   7362: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   7363: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   7364: 			}
                   7365: 		}
                   7366: 
                   7367: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   7368: 		if(exists($args->{'bread_crumbs_component'})){
                   7369: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
                   7370: 		}else{
                   7371: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
                   7372: 		}
1.320     albertel 7373:     }
1.315     albertel 7374:     return $result;
1.306     albertel 7375: }
                   7376: 
                   7377: sub end_page {
1.315     albertel 7378:     my ($args) = @_;
                   7379:     $env{'internal.end_page'}++;
1.330     albertel 7380:     my $result;
1.335     albertel 7381:     if ($args->{'discussion'}) {
                   7382: 	my ($target,$parser);
                   7383: 	if (ref($args->{'discussion'})) {
                   7384: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   7385: 				$args->{'discussion'}{'parser'});
                   7386: 	}
                   7387: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   7388:     }
1.330     albertel 7389:     if ($args->{'frameset'}) {
                   7390: 	$result .= '</frameset>';
                   7391:     } else {
1.635     raeburn  7392: 	$result .= &endbodytag($args);
1.330     albertel 7393:     }
1.1080    raeburn  7394:     unless ($args->{'notbody'}) {
                   7395:         $result .= "\n</html>";
                   7396:     }
1.330     albertel 7397: 
1.315     albertel 7398:     if ($args->{'js_ready'}) {
1.317     albertel 7399: 	$result = &js_ready($result);
1.315     albertel 7400:     }
1.335     albertel 7401: 
1.320     albertel 7402:     if ($args->{'html_encode'}) {
                   7403: 	$result = &html_encode($result);
                   7404:     }
1.335     albertel 7405: 
1.315     albertel 7406:     return $result;
                   7407: }
                   7408: 
1.1034    www      7409: sub wishlist_window {
                   7410:     return(<<'ENDWISHLIST');
1.1046    raeburn  7411: <script type="text/javascript">
1.1034    www      7412: // <![CDATA[
                   7413: // <!-- BEGIN LON-CAPA Internal
                   7414: function set_wishlistlink(title, path) {
                   7415:     if (!title) {
                   7416:         title = document.title;
                   7417:         title = title.replace(/^LON-CAPA /,'');
                   7418:     }
                   7419:     if (!path) {
                   7420:         path = location.pathname;
                   7421:     }
                   7422:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   7423:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   7424: }
                   7425: // END LON-CAPA Internal -->
                   7426: // ]]>
                   7427: </script>
                   7428: ENDWISHLIST
                   7429: }
                   7430: 
1.1030    www      7431: sub modal_window {
                   7432:     return(<<'ENDMODAL');
1.1046    raeburn  7433: <script type="text/javascript">
1.1030    www      7434: // <![CDATA[
                   7435: // <!-- BEGIN LON-CAPA Internal
                   7436: var modalWindow = {
                   7437: 	parent:"body",
                   7438: 	windowId:null,
                   7439: 	content:null,
                   7440: 	width:null,
                   7441: 	height:null,
                   7442: 	close:function()
                   7443: 	{
                   7444: 	        $(".LCmodal-window").remove();
                   7445: 	        $(".LCmodal-overlay").remove();
                   7446: 	},
                   7447: 	open:function()
                   7448: 	{
                   7449: 		var modal = "";
                   7450: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   7451: 		modal += "<div id=\"" + this.windowId + "\" class=\"LCmodal-window\" style=\"width:" + this.width + "px; height:" + this.height + "px; margin-top:-" + (this.height / 2) + "px; margin-left:-" + (this.width / 2) + "px;\">";
                   7452: 		modal += this.content;
                   7453: 		modal += "</div>";	
                   7454: 
                   7455: 		$(this.parent).append(modal);
                   7456: 
                   7457: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   7458: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   7459: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   7460: 	}
                   7461: };
1.1031    www      7462: 	var openMyModal = function(source,width,height,scrolling)
1.1030    www      7463: 	{
                   7464: 		modalWindow.windowId = "myModal";
                   7465: 		modalWindow.width = width;
                   7466: 		modalWindow.height = height;
1.1031    www      7467: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='true' src='" + source + "'>&lt/iframe>";
1.1030    www      7468: 		modalWindow.open();
                   7469: 	};	
                   7470: // END LON-CAPA Internal -->
                   7471: // ]]>
                   7472: </script>
                   7473: ENDMODAL
                   7474: }
                   7475: 
                   7476: sub modal_link {
1.1052    www      7477:     my ($link,$linktext,$width,$height,$target,$scrolling,$title)=@_;
1.1030    www      7478:     unless ($width) { $width=480; }
                   7479:     unless ($height) { $height=400; }
1.1031    www      7480:     unless ($scrolling) { $scrolling='yes'; }
1.1074    raeburn  7481:     my $target_attr;
                   7482:     if (defined($target)) {
                   7483:         $target_attr = 'target="'.$target.'"';
                   7484:     }
                   7485:     return <<"ENDLINK";
                   7486: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling'); return false;">
                   7487:            $linktext</a>
                   7488: ENDLINK
1.1030    www      7489: }
                   7490: 
1.1032    www      7491: sub modal_adhoc_script {
                   7492:     my ($funcname,$width,$height,$content)=@_;
                   7493:     return (<<ENDADHOC);
1.1046    raeburn  7494: <script type="text/javascript">
1.1032    www      7495: // <![CDATA[
                   7496:         var $funcname = function()
                   7497:         {
                   7498:                 modalWindow.windowId = "myModal";
                   7499:                 modalWindow.width = $width;
                   7500:                 modalWindow.height = $height;
                   7501:                 modalWindow.content = '$content';
                   7502:                 modalWindow.open();
                   7503:         };  
                   7504: // ]]>
                   7505: </script>
                   7506: ENDADHOC
                   7507: }
                   7508: 
1.1041    www      7509: sub modal_adhoc_inner {
                   7510:     my ($funcname,$width,$height,$content)=@_;
                   7511:     my $innerwidth=$width-20;
                   7512:     $content=&js_ready(
1.1042    www      7513:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1041    www      7514:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px').
                   7515:                     $content.
                   7516:                  &end_scrollbox().
                   7517:                &end_page()
                   7518:              );
                   7519:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   7520: }
                   7521: 
                   7522: sub modal_adhoc_window {
                   7523:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   7524:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   7525:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   7526: }
                   7527: 
                   7528: sub modal_adhoc_launch {
                   7529:     my ($funcname,$width,$height,$content)=@_;
                   7530:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   7531: <script type="text/javascript">
                   7532: // <![CDATA[
                   7533: $funcname();
                   7534: // ]]>
                   7535: </script>
                   7536: ENDLAUNCH
                   7537: }
                   7538: 
                   7539: sub modal_adhoc_close {
                   7540:     return (<<ENDCLOSE);
                   7541: <script type="text/javascript">
                   7542: // <![CDATA[
                   7543: modalWindow.close();
                   7544: // ]]>
                   7545: </script>
                   7546: ENDCLOSE
                   7547: }
                   7548: 
1.1038    www      7549: sub togglebox_script {
                   7550:    return(<<ENDTOGGLE);
                   7551: <script type="text/javascript"> 
                   7552: // <![CDATA[
                   7553: function LCtoggleDisplay(id,hidetext,showtext) {
                   7554:    link = document.getElementById(id + "link").childNodes[0];
                   7555:    with (document.getElementById(id).style) {
                   7556:       if (display == "none" ) {
                   7557:           display = "inline";
                   7558:           link.nodeValue = hidetext;
                   7559:         } else {
                   7560:           display = "none";
                   7561:           link.nodeValue = showtext;
                   7562:        }
                   7563:    }
                   7564: }
                   7565: // ]]>
                   7566: </script>
                   7567: ENDTOGGLE
                   7568: }
                   7569: 
1.1039    www      7570: sub start_togglebox {
                   7571:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   7572:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   7573:     unless ($showtext) { $showtext=&mt('show'); }
                   7574:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   7575:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   7576:     return &start_data_table().
                   7577:            &start_data_table_header_row().
                   7578:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   7579:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   7580:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   7581:            &end_data_table_header_row().
                   7582:            '<tr id="'.$id.'" style="display:none""><td>';
                   7583: }
                   7584: 
                   7585: sub end_togglebox {
                   7586:     return '</td></tr>'.&end_data_table();
                   7587: }
                   7588: 
1.1041    www      7589: sub LCprogressbar_script {
1.1045    www      7590:    my ($id)=@_;
1.1041    www      7591:    return(<<ENDPROGRESS);
                   7592: <script type="text/javascript">
                   7593: // <![CDATA[
1.1045    www      7594: \$('#progressbar$id').progressbar({
1.1041    www      7595:   value: 0,
                   7596:   change: function(event, ui) {
                   7597:     var newVal = \$(this).progressbar('option', 'value');
                   7598:     \$('.pblabel', this).text(LCprogressTxt);
                   7599:   }
                   7600: });
                   7601: // ]]>
                   7602: </script>
                   7603: ENDPROGRESS
                   7604: }
                   7605: 
                   7606: sub LCprogressbarUpdate_script {
                   7607:    return(<<ENDPROGRESSUPDATE);
                   7608: <style type="text/css">
                   7609: .ui-progressbar { position:relative; }
                   7610: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   7611: </style>
                   7612: <script type="text/javascript">
                   7613: // <![CDATA[
1.1045    www      7614: var LCprogressTxt='---';
                   7615: 
                   7616: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      7617:    LCprogressTxt=progresstext;
1.1045    www      7618:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      7619: }
                   7620: // ]]>
                   7621: </script>
                   7622: ENDPROGRESSUPDATE
                   7623: }
                   7624: 
1.1042    www      7625: my $LClastpercent;
1.1045    www      7626: my $LCidcnt;
                   7627: my $LCcurrentid;
1.1042    www      7628: 
1.1041    www      7629: sub LCprogressbar {
1.1042    www      7630:     my ($r)=(@_);
                   7631:     $LClastpercent=0;
1.1045    www      7632:     $LCidcnt++;
                   7633:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      7634:     my $starting=&mt('Starting');
                   7635:     my $content=(<<ENDPROGBAR);
                   7636: <p>
1.1045    www      7637:   <div id="progressbar$LCcurrentid">
1.1041    www      7638:     <span class="pblabel">$starting</span>
                   7639:   </div>
                   7640: </p>
                   7641: ENDPROGBAR
1.1045    www      7642:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      7643: }
                   7644: 
                   7645: sub LCprogressbarUpdate {
1.1042    www      7646:     my ($r,$val,$text)=@_;
                   7647:     unless ($val) { 
                   7648:        if ($LClastpercent) {
                   7649:            $val=$LClastpercent;
                   7650:        } else {
                   7651:            $val=0;
                   7652:        }
                   7653:     }
1.1041    www      7654:     if ($val<0) { $val=0; }
                   7655:     if ($val>100) { $val=0; }
1.1042    www      7656:     $LClastpercent=$val;
1.1041    www      7657:     unless ($text) { $text=$val.'%'; }
                   7658:     $text=&js_ready($text);
1.1044    www      7659:     &r_print($r,<<ENDUPDATE);
1.1041    www      7660: <script type="text/javascript">
                   7661: // <![CDATA[
1.1045    www      7662: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      7663: // ]]>
                   7664: </script>
                   7665: ENDUPDATE
1.1035    www      7666: }
                   7667: 
1.1042    www      7668: sub LCprogressbarClose {
                   7669:     my ($r)=@_;
                   7670:     $LClastpercent=0;
1.1044    www      7671:     &r_print($r,<<ENDCLOSE);
1.1042    www      7672: <script type="text/javascript">
                   7673: // <![CDATA[
1.1045    www      7674: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      7675: // ]]>
                   7676: </script>
                   7677: ENDCLOSE
1.1044    www      7678: }
                   7679: 
                   7680: sub r_print {
                   7681:     my ($r,$to_print)=@_;
                   7682:     if ($r) {
                   7683:       $r->print($to_print);
                   7684:       $r->rflush();
                   7685:     } else {
                   7686:       print($to_print);
                   7687:     }
1.1042    www      7688: }
                   7689: 
1.320     albertel 7690: sub html_encode {
                   7691:     my ($result) = @_;
                   7692: 
1.322     albertel 7693:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 7694:     
                   7695:     return $result;
                   7696: }
1.1044    www      7697: 
1.317     albertel 7698: sub js_ready {
                   7699:     my ($result) = @_;
                   7700: 
1.323     albertel 7701:     $result =~ s/[\n\r]/ /xmsg;
                   7702:     $result =~ s/\\/\\\\/xmsg;
                   7703:     $result =~ s/'/\\'/xmsg;
1.372     albertel 7704:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 7705:     
                   7706:     return $result;
                   7707: }
                   7708: 
1.315     albertel 7709: sub validate_page {
                   7710:     if (  exists($env{'internal.start_page'})
1.316     albertel 7711: 	  &&     $env{'internal.start_page'} > 1) {
                   7712: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 7713: 				 $env{'internal.start_page'}.' '.
1.316     albertel 7714: 				 $ENV{'request.filename'});
1.315     albertel 7715:     }
                   7716:     if (  exists($env{'internal.end_page'})
1.316     albertel 7717: 	  &&     $env{'internal.end_page'} > 1) {
                   7718: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 7719: 				 $env{'internal.end_page'}.' '.
1.316     albertel 7720: 				 $env{'request.filename'});
1.315     albertel 7721:     }
                   7722:     if (     exists($env{'internal.start_page'})
                   7723: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 7724: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   7725: 				 $env{'request.filename'});
1.315     albertel 7726:     }
                   7727:     if (   ! exists($env{'internal.start_page'})
                   7728: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 7729: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   7730: 				 $env{'request.filename'});
1.315     albertel 7731:     }
1.306     albertel 7732: }
1.315     albertel 7733: 
1.996     www      7734: 
                   7735: sub start_scrollbox {
1.1075    raeburn  7736:     my ($outerwidth,$width,$height,$id,$bgcolor)=@_;
1.998     raeburn  7737:     unless ($outerwidth) { $outerwidth='520px'; }
                   7738:     unless ($width) { $width='500px'; }
                   7739:     unless ($height) { $height='200px'; }
1.1075    raeburn  7740:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  7741:     if ($id ne '') {
1.1020    raeburn  7742:         $table_id = " id='table_$id'";
                   7743:         $div_id = " id='div_$id'";
1.1018    raeburn  7744:     }
1.1075    raeburn  7745:     if ($bgcolor ne '') {
                   7746:         $tdcol = "background-color: $bgcolor;";
                   7747:     }
                   7748:     return <<"END";
                   7749: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol"><div style="overflow:auto; width:$width; height: $height;"$div_id>
                   7750: END
1.996     www      7751: }
                   7752: 
                   7753: sub end_scrollbox {
1.1036    www      7754:     return '</div></td></tr></table>';
1.996     www      7755: }
                   7756: 
1.318     albertel 7757: sub simple_error_page {
                   7758:     my ($r,$title,$msg) = @_;
                   7759:     my $page =
                   7760: 	&Apache::loncommon::start_page($title).
                   7761: 	&mt($msg).
                   7762: 	&Apache::loncommon::end_page();
                   7763:     if (ref($r)) {
                   7764: 	$r->print($page);
1.327     albertel 7765: 	return;
1.318     albertel 7766:     }
                   7767:     return $page;
                   7768: }
1.347     albertel 7769: 
                   7770: {
1.610     albertel 7771:     my @row_count;
1.961     onken    7772: 
                   7773:     sub start_data_table_count {
                   7774:         unshift(@row_count, 0);
                   7775:         return;
                   7776:     }
                   7777: 
                   7778:     sub end_data_table_count {
                   7779:         shift(@row_count);
                   7780:         return;
                   7781:     }
                   7782: 
1.347     albertel 7783:     sub start_data_table {
1.1018    raeburn  7784: 	my ($add_class,$id) = @_;
1.422     albertel 7785: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  7786:         my $table_id;
                   7787:         if (defined($id)) {
                   7788:             $table_id = ' id="'.$id.'"';
                   7789:         }
1.961     onken    7790: 	&start_data_table_count();
1.1018    raeburn  7791: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 7792:     }
                   7793: 
                   7794:     sub end_data_table {
1.961     onken    7795: 	&end_data_table_count();
1.389     albertel 7796: 	return '</table>'."\n";;
1.347     albertel 7797:     }
                   7798: 
                   7799:     sub start_data_table_row {
1.974     wenzelju 7800: 	my ($add_class, $id) = @_;
1.610     albertel 7801: 	$row_count[0]++;
                   7802: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   7803: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 7804:         $id = (' id="'.$id.'"') unless ($id eq '');
                   7805:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 7806:     }
1.471     banghart 7807:     
                   7808:     sub continue_data_table_row {
1.974     wenzelju 7809: 	my ($add_class, $id) = @_;
1.610     albertel 7810: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 7811: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   7812:         $id = (' id="'.$id.'"') unless ($id eq '');
                   7813:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 7814:     }
1.347     albertel 7815: 
                   7816:     sub end_data_table_row {
1.389     albertel 7817: 	return '</tr>'."\n";;
1.347     albertel 7818:     }
1.367     www      7819: 
1.421     albertel 7820:     sub start_data_table_empty_row {
1.707     bisitz   7821: #	$row_count[0]++;
1.421     albertel 7822: 	return  '<tr class="LC_empty_row" >'."\n";;
                   7823:     }
                   7824: 
                   7825:     sub end_data_table_empty_row {
                   7826: 	return '</tr>'."\n";;
                   7827:     }
                   7828: 
1.367     www      7829:     sub start_data_table_header_row {
1.389     albertel 7830: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      7831:     }
                   7832: 
                   7833:     sub end_data_table_header_row {
1.389     albertel 7834: 	return '</tr>'."\n";;
1.367     www      7835:     }
1.890     droeschl 7836: 
                   7837:     sub data_table_caption {
                   7838:         my $caption = shift;
                   7839:         return "<caption class=\"LC_caption\">$caption</caption>";
                   7840:     }
1.347     albertel 7841: }
                   7842: 
1.548     albertel 7843: =pod
                   7844: 
                   7845: =item * &inhibit_menu_check($arg)
                   7846: 
                   7847: Checks for a inhibitmenu state and generates output to preserve it
                   7848: 
                   7849: Inputs:         $arg - can be any of
                   7850:                      - undef - in which case the return value is a string 
                   7851:                                to add  into arguments list of a uri
                   7852:                      - 'input' - in which case the return value is a HTML
                   7853:                                  <form> <input> field of type hidden to
                   7854:                                  preserve the value
                   7855:                      - a url - in which case the return value is the url with
                   7856:                                the neccesary cgi args added to preserve the
                   7857:                                inhibitmenu state
                   7858:                      - a ref to a url - no return value, but the string is
                   7859:                                         updated to include the neccessary cgi
                   7860:                                         args to preserve the inhibitmenu state
                   7861: 
                   7862: =cut
                   7863: 
                   7864: sub inhibit_menu_check {
                   7865:     my ($arg) = @_;
                   7866:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   7867:     if ($arg eq 'input') {
                   7868: 	if ($env{'form.inhibitmenu'}) {
                   7869: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   7870: 	} else {
                   7871: 	    return
                   7872: 	}
                   7873:     }
                   7874:     if ($env{'form.inhibitmenu'}) {
                   7875: 	if (ref($arg)) {
                   7876: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   7877: 	} elsif ($arg eq '') {
                   7878: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   7879: 	} else {
                   7880: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   7881: 	}
                   7882:     }
                   7883:     if (!ref($arg)) {
                   7884: 	return $arg;
                   7885:     }
                   7886: }
                   7887: 
1.251     albertel 7888: ###############################################
1.182     matthew  7889: 
                   7890: =pod
                   7891: 
1.549     albertel 7892: =back
                   7893: 
                   7894: =head1 User Information Routines
                   7895: 
                   7896: =over 4
                   7897: 
1.405     albertel 7898: =item * &get_users_function()
1.182     matthew  7899: 
                   7900: Used by &bodytag to determine the current users primary role.
                   7901: Returns either 'student','coordinator','admin', or 'author'.
                   7902: 
                   7903: =cut
                   7904: 
                   7905: ###############################################
                   7906: sub get_users_function {
1.815     tempelho 7907:     my $function = 'norole';
1.818     tempelho 7908:     if ($env{'request.role'}=~/^(st)/) {
                   7909:         $function='student';
                   7910:     }
1.907     raeburn  7911:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  7912:         $function='coordinator';
                   7913:     }
1.258     albertel 7914:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  7915:         $function='admin';
                   7916:     }
1.826     bisitz   7917:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  7918:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  7919:         $function='author';
                   7920:     }
                   7921:     return $function;
1.54      www      7922: }
1.99      www      7923: 
                   7924: ###############################################
                   7925: 
1.233     raeburn  7926: =pod
                   7927: 
1.821     raeburn  7928: =item * &show_course()
                   7929: 
                   7930: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   7931: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   7932: 
                   7933: Inputs:
                   7934: None
                   7935: 
                   7936: Outputs:
                   7937: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   7938: 
                   7939: =cut
                   7940: 
                   7941: ###############################################
                   7942: sub show_course {
                   7943:     my $course = !$env{'user.adv'};
                   7944:     if (!$env{'user.adv'}) {
                   7945:         foreach my $env (keys(%env)) {
                   7946:             next if ($env !~ m/^user\.priv\./);
                   7947:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   7948:                 $course = 0;
                   7949:                 last;
                   7950:             }
                   7951:         }
                   7952:     }
                   7953:     return $course;
                   7954: }
                   7955: 
                   7956: ###############################################
                   7957: 
                   7958: =pod
                   7959: 
1.542     raeburn  7960: =item * &check_user_status()
1.274     raeburn  7961: 
                   7962: Determines current status of supplied role for a
                   7963: specific user. Roles can be active, previous or future.
                   7964: 
                   7965: Inputs: 
                   7966: user's domain, user's username, course's domain,
1.375     raeburn  7967: course's number, optional section ID.
1.274     raeburn  7968: 
                   7969: Outputs:
                   7970: role status: active, previous or future. 
                   7971: 
                   7972: =cut
                   7973: 
                   7974: sub check_user_status {
1.412     raeburn  7975:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  7976:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.274     raeburn  7977:     my @uroles = keys %userinfo;
                   7978:     my $srchstr;
                   7979:     my $active_chk = 'none';
1.412     raeburn  7980:     my $now = time;
1.274     raeburn  7981:     if (@uroles > 0) {
1.908     raeburn  7982:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  7983:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   7984:         } else {
1.412     raeburn  7985:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   7986:         }
                   7987:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  7988:             my $role_end = 0;
                   7989:             my $role_start = 0;
                   7990:             $active_chk = 'active';
1.412     raeburn  7991:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   7992:                 $role_end = $1;
                   7993:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   7994:                     $role_start = $1;
1.274     raeburn  7995:                 }
                   7996:             }
                   7997:             if ($role_start > 0) {
1.412     raeburn  7998:                 if ($now < $role_start) {
1.274     raeburn  7999:                     $active_chk = 'future';
                   8000:                 }
                   8001:             }
                   8002:             if ($role_end > 0) {
1.412     raeburn  8003:                 if ($now > $role_end) {
1.274     raeburn  8004:                     $active_chk = 'previous';
                   8005:                 }
                   8006:             }
                   8007:         }
                   8008:     }
                   8009:     return $active_chk;
                   8010: }
                   8011: 
                   8012: ###############################################
                   8013: 
                   8014: =pod
                   8015: 
1.405     albertel 8016: =item * &get_sections()
1.233     raeburn  8017: 
                   8018: Determines all the sections for a course including
                   8019: sections with students and sections containing other roles.
1.419     raeburn  8020: Incoming parameters: 
                   8021: 
                   8022: 1. domain
                   8023: 2. course number 
                   8024: 3. reference to array containing roles for which sections should 
                   8025: be gathered (optional).
                   8026: 4. reference to array containing status types for which sections 
                   8027: should be gathered (optional).
                   8028: 
                   8029: If the third argument is undefined, sections are gathered for any role. 
                   8030: If the fourth argument is undefined, sections are gathered for any status.
                   8031: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  8032:  
1.374     raeburn  8033: Returns section hash (keys are section IDs, values are
                   8034: number of users in each section), subject to the
1.419     raeburn  8035: optional roles filter, optional status filter 
1.233     raeburn  8036: 
                   8037: =cut
                   8038: 
                   8039: ###############################################
                   8040: sub get_sections {
1.419     raeburn  8041:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 8042:     if (!defined($cdom) || !defined($cnum)) {
                   8043:         my $cid =  $env{'request.course.id'};
                   8044: 
                   8045: 	return if (!defined($cid));
                   8046: 
                   8047:         $cdom = $env{'course.'.$cid.'.domain'};
                   8048:         $cnum = $env{'course.'.$cid.'.num'};
                   8049:     }
                   8050: 
                   8051:     my %sectioncount;
1.419     raeburn  8052:     my $now = time;
1.240     albertel 8053: 
1.366     albertel 8054:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
1.276     albertel 8055: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 8056: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   8057: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  8058:         my $start_index = &Apache::loncoursedata::CL_START();
                   8059:         my $end_index = &Apache::loncoursedata::CL_END();
                   8060:         my $status;
1.366     albertel 8061: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  8062: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   8063: 				                     $data->[$status_index],
                   8064:                                                      $data->[$start_index],
                   8065:                                                      $data->[$end_index]);
                   8066:             if ($stu_status eq 'Active') {
                   8067:                 $status = 'active';
                   8068:             } elsif ($end < $now) {
                   8069:                 $status = 'previous';
                   8070:             } elsif ($start > $now) {
                   8071:                 $status = 'future';
                   8072:             } 
                   8073: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   8074:                 if ((!defined($possible_status)) || (($status ne '') && 
                   8075:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   8076: 		    $sectioncount{$section}++;
                   8077:                 }
1.240     albertel 8078: 	    }
                   8079: 	}
                   8080:     }
                   8081:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8082:     foreach my $user (sort(keys(%courseroles))) {
                   8083: 	if ($user !~ /^(\w{2})/) { next; }
                   8084: 	my ($role) = ($user =~ /^(\w{2})/);
                   8085: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  8086: 	my ($section,$status);
1.240     albertel 8087: 	if ($role eq 'cr' &&
                   8088: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   8089: 	    $section=$1;
                   8090: 	}
                   8091: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   8092: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  8093:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   8094:         if ($end == -1 && $start == -1) {
                   8095:             next; #deleted role
                   8096:         }
                   8097:         if (!defined($possible_status)) { 
                   8098:             $sectioncount{$section}++;
                   8099:         } else {
                   8100:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   8101:                 $status = 'active';
                   8102:             } elsif ($end < $now) {
                   8103:                 $status = 'future';
                   8104:             } elsif ($start > $now) {
                   8105:                 $status = 'previous';
                   8106:             }
                   8107:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   8108:                 $sectioncount{$section}++;
                   8109:             }
                   8110:         }
1.233     raeburn  8111:     }
1.366     albertel 8112:     return %sectioncount;
1.233     raeburn  8113: }
                   8114: 
1.274     raeburn  8115: ###############################################
1.294     raeburn  8116: 
                   8117: =pod
1.405     albertel 8118: 
                   8119: =item * &get_course_users()
                   8120: 
1.275     raeburn  8121: Retrieves usernames:domains for users in the specified course
                   8122: with specific role(s), and access status. 
                   8123: 
                   8124: Incoming parameters:
1.277     albertel 8125: 1. course domain
                   8126: 2. course number
                   8127: 3. access status: users must have - either active, 
1.275     raeburn  8128: previous, future, or all.
1.277     albertel 8129: 4. reference to array of permissible roles
1.288     raeburn  8130: 5. reference to array of section restrictions (optional)
                   8131: 6. reference to results object (hash of hashes).
                   8132: 7. reference to optional userdata hash
1.609     raeburn  8133: 8. reference to optional statushash
1.630     raeburn  8134: 9. flag if privileged users (except those set to unhide in
                   8135:    course settings) should be excluded    
1.609     raeburn  8136: Keys of top level results hash are roles.
1.275     raeburn  8137: Keys of inner hashes are username:domain, with 
                   8138: values set to access type.
1.288     raeburn  8139: Optional userdata hash returns an array with arguments in the 
                   8140: same order as loncoursedata::get_classlist() for student data.
                   8141: 
1.609     raeburn  8142: Optional statushash returns
                   8143: 
1.288     raeburn  8144: Entries for end, start, section and status are blank because
                   8145: of the possibility of multiple values for non-student roles.
                   8146: 
1.275     raeburn  8147: =cut
1.405     albertel 8148: 
1.275     raeburn  8149: ###############################################
1.405     albertel 8150: 
1.275     raeburn  8151: sub get_course_users {
1.630     raeburn  8152:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  8153:     my %idx = ();
1.419     raeburn  8154:     my %seclists;
1.288     raeburn  8155: 
                   8156:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   8157:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   8158:     $idx{end} = &Apache::loncoursedata::CL_END();
                   8159:     $idx{start} = &Apache::loncoursedata::CL_START();
                   8160:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   8161:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   8162:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   8163:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   8164: 
1.290     albertel 8165:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 8166:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  8167:         my $now = time;
1.277     albertel 8168:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  8169:             my $match = 0;
1.412     raeburn  8170:             my $secmatch = 0;
1.419     raeburn  8171:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  8172:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  8173:             if ($section eq '') {
                   8174:                 $section = 'none';
                   8175:             }
1.291     albertel 8176:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8177:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8178:                     $secmatch = 1;
                   8179:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 8180:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8181:                         $secmatch = 1;
                   8182:                     }
                   8183:                 } else {  
1.419     raeburn  8184: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  8185: 		        $secmatch = 1;
                   8186:                     }
1.290     albertel 8187: 		}
1.412     raeburn  8188:                 if (!$secmatch) {
                   8189:                     next;
                   8190:                 }
1.419     raeburn  8191:             }
1.275     raeburn  8192:             if (defined($$types{'active'})) {
1.288     raeburn  8193:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  8194:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  8195:                     $match = 1;
1.275     raeburn  8196:                 }
                   8197:             }
                   8198:             if (defined($$types{'previous'})) {
1.609     raeburn  8199:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  8200:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  8201:                     $match = 1;
1.275     raeburn  8202:                 }
                   8203:             }
                   8204:             if (defined($$types{'future'})) {
1.609     raeburn  8205:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  8206:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  8207:                     $match = 1;
1.275     raeburn  8208:                 }
                   8209:             }
1.609     raeburn  8210:             if ($match) {
                   8211:                 push(@{$seclists{$student}},$section);
                   8212:                 if (ref($userdata) eq 'HASH') {
                   8213:                     $$userdata{$student} = $$classlist{$student};
                   8214:                 }
                   8215:                 if (ref($statushash) eq 'HASH') {
                   8216:                     $statushash->{$student}{'st'}{$section} = $status;
                   8217:                 }
1.288     raeburn  8218:             }
1.275     raeburn  8219:         }
                   8220:     }
1.412     raeburn  8221:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  8222:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8223:         my $now = time;
1.609     raeburn  8224:         my %displaystatus = ( previous => 'Expired',
                   8225:                               active   => 'Active',
                   8226:                               future   => 'Future',
                   8227:                             );
1.630     raeburn  8228:         my %nothide;
                   8229:         if ($hidepriv) {
                   8230:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   8231:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   8232:                 if ($user !~ /:/) {
                   8233:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   8234:                 } else {
                   8235:                     $nothide{$user} = 1;
                   8236:                 }
                   8237:             }
                   8238:         }
1.439     raeburn  8239:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  8240:             my $match = 0;
1.412     raeburn  8241:             my $secmatch = 0;
1.439     raeburn  8242:             my $status;
1.412     raeburn  8243:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  8244:             $user =~ s/:$//;
1.439     raeburn  8245:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   8246:             if ($end == -1 || $start == -1) {
                   8247:                 next;
                   8248:             }
                   8249:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   8250:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  8251:                 my ($uname,$udom) = split(/:/,$user);
                   8252:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8253:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8254:                         $secmatch = 1;
                   8255:                     } elsif ($usec eq '') {
1.420     albertel 8256:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8257:                             $secmatch = 1;
                   8258:                         }
                   8259:                     } else {
                   8260:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   8261:                             $secmatch = 1;
                   8262:                         }
                   8263:                     }
                   8264:                     if (!$secmatch) {
                   8265:                         next;
                   8266:                     }
1.288     raeburn  8267:                 }
1.419     raeburn  8268:                 if ($usec eq '') {
                   8269:                     $usec = 'none';
                   8270:                 }
1.275     raeburn  8271:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  8272:                     if ($hidepriv) {
                   8273:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
                   8274:                             (!$nothide{$uname.':'.$udom})) {
                   8275:                             next;
                   8276:                         }
                   8277:                     }
1.503     raeburn  8278:                     if ($end > 0 && $end < $now) {
1.439     raeburn  8279:                         $status = 'previous';
                   8280:                     } elsif ($start > $now) {
                   8281:                         $status = 'future';
                   8282:                     } else {
                   8283:                         $status = 'active';
                   8284:                     }
1.277     albertel 8285:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  8286:                         if ($status eq $type) {
1.420     albertel 8287:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  8288:                                 push(@{$$users{$role}{$user}},$type);
                   8289:                             }
1.288     raeburn  8290:                             $match = 1;
                   8291:                         }
                   8292:                     }
1.419     raeburn  8293:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   8294:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   8295: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   8296:                         }
1.420     albertel 8297:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  8298:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   8299:                         }
1.609     raeburn  8300:                         if (ref($statushash) eq 'HASH') {
                   8301:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   8302:                         }
1.275     raeburn  8303:                     }
                   8304:                 }
                   8305:             }
                   8306:         }
1.290     albertel 8307:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  8308:             if ((defined($cdom)) && (defined($cnum))) {
                   8309:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   8310:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   8311:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  8312:                     next if ($owner eq '');
                   8313:                     my ($ownername,$ownerdom);
                   8314:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   8315:                         $ownername = $1;
                   8316:                         $ownerdom = $2;
                   8317:                     } else {
                   8318:                         $ownername = $owner;
                   8319:                         $ownerdom = $cdom;
                   8320:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  8321:                     }
                   8322:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 8323:                     if (defined($userdata) && 
1.609     raeburn  8324: 			!exists($$userdata{$owner})) {
                   8325: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   8326:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   8327:                             push(@{$seclists{$owner}},'none');
                   8328:                         }
                   8329:                         if (ref($statushash) eq 'HASH') {
                   8330:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  8331:                         }
1.290     albertel 8332: 		    }
1.279     raeburn  8333:                 }
                   8334:             }
                   8335:         }
1.419     raeburn  8336:         foreach my $user (keys(%seclists)) {
                   8337:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   8338:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   8339:         }
1.275     raeburn  8340:     }
                   8341:     return;
                   8342: }
                   8343: 
1.288     raeburn  8344: sub get_user_info {
                   8345:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 8346:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   8347: 	&plainname($uname,$udom,'lastname');
1.291     albertel 8348:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  8349:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  8350:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   8351:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  8352:     return;
                   8353: }
1.275     raeburn  8354: 
1.472     raeburn  8355: ###############################################
                   8356: 
                   8357: =pod
                   8358: 
                   8359: =item * &get_user_quota()
                   8360: 
                   8361: Retrieves quota assigned for storage of portfolio files for a user  
                   8362: 
                   8363: Incoming parameters:
                   8364: 1. user's username
                   8365: 2. user's domain
                   8366: 
                   8367: Returns:
1.536     raeburn  8368: 1. Disk quota (in Mb) assigned to student.
                   8369: 2. (Optional) Type of setting: custom or default
                   8370:    (individually assigned or default for user's 
                   8371:    institutional status).
                   8372: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   8373:    or student - types as defined in localenroll::inst_usertypes 
                   8374:    for user's domain, which determines default quota for user.
                   8375: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  8376: 
                   8377: If a value has been stored in the user's environment, 
1.536     raeburn  8378: it will return that, otherwise it returns the maximal default
                   8379: defined for the user's instituional status(es) in the domain.
1.472     raeburn  8380: 
                   8381: =cut
                   8382: 
                   8383: ###############################################
                   8384: 
                   8385: 
                   8386: sub get_user_quota {
                   8387:     my ($uname,$udom) = @_;
1.536     raeburn  8388:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  8389:     if (!defined($udom)) {
                   8390:         $udom = $env{'user.domain'};
                   8391:     }
                   8392:     if (!defined($uname)) {
                   8393:         $uname = $env{'user.name'};
                   8394:     }
                   8395:     if (($udom eq '' || $uname eq '') ||
                   8396:         ($udom eq 'public') && ($uname eq 'public')) {
                   8397:         $quota = 0;
1.536     raeburn  8398:         $quotatype = 'default';
                   8399:         $defquota = 0; 
1.472     raeburn  8400:     } else {
1.536     raeburn  8401:         my $inststatus;
1.472     raeburn  8402:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   8403:             $quota = $env{'environment.portfolioquota'};
1.536     raeburn  8404:             $inststatus = $env{'environment.inststatus'};
1.472     raeburn  8405:         } else {
1.536     raeburn  8406:             my %userenv = 
                   8407:                 &Apache::lonnet::get('environment',['portfolioquota',
                   8408:                                      'inststatus'],$udom,$uname);
1.472     raeburn  8409:             my ($tmp) = keys(%userenv);
                   8410:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   8411:                 $quota = $userenv{'portfolioquota'};
1.536     raeburn  8412:                 $inststatus = $userenv{'inststatus'};
1.472     raeburn  8413:             } else {
                   8414:                 undef(%userenv);
                   8415:             }
                   8416:         }
1.536     raeburn  8417:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
1.472     raeburn  8418:         if ($quota eq '') {
1.536     raeburn  8419:             $quota = $defquota;
                   8420:             $quotatype = 'default';
                   8421:         } else {
                   8422:             $quotatype = 'custom';
1.472     raeburn  8423:         }
                   8424:     }
1.536     raeburn  8425:     if (wantarray) {
                   8426:         return ($quota,$quotatype,$settingstatus,$defquota);
                   8427:     } else {
                   8428:         return $quota;
                   8429:     }
1.472     raeburn  8430: }
                   8431: 
                   8432: ###############################################
                   8433: 
                   8434: =pod
                   8435: 
                   8436: =item * &default_quota()
                   8437: 
1.536     raeburn  8438: Retrieves default quota assigned for storage of user portfolio files,
                   8439: given an (optional) user's institutional status.
1.472     raeburn  8440: 
                   8441: Incoming parameters:
                   8442: 1. domain
1.536     raeburn  8443: 2. (Optional) institutional status(es).  This is a : separated list of 
                   8444:    status types (e.g., faculty, staff, student etc.)
                   8445:    which apply to the user for whom the default is being retrieved.
                   8446:    If the institutional status string in undefined, the domain
                   8447:    default quota will be returned. 
1.472     raeburn  8448: 
                   8449: Returns:
                   8450: 1. Default disk quota (in Mb) for user portfolios in the domain.
1.536     raeburn  8451: 2. (Optional) institutional type which determined the value of the
                   8452:    default quota.
1.472     raeburn  8453: 
                   8454: If a value has been stored in the domain's configuration db,
                   8455: it will return that, otherwise it returns 20 (for backwards 
                   8456: compatibility with domains which have not set up a configuration
                   8457: db file; the original statically defined portfolio quota was 20 Mb). 
                   8458: 
1.536     raeburn  8459: If the user's status includes multiple types (e.g., staff and student),
                   8460: the largest default quota which applies to the user determines the
                   8461: default quota returned.
                   8462: 
1.780     raeburn  8463: =back
                   8464: 
1.472     raeburn  8465: =cut
                   8466: 
                   8467: ###############################################
                   8468: 
                   8469: 
                   8470: sub default_quota {
1.536     raeburn  8471:     my ($udom,$inststatus) = @_;
                   8472:     my ($defquota,$settingstatus);
                   8473:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  8474:                                             ['quotas'],$udom);
                   8475:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  8476:         if ($inststatus ne '') {
1.765     raeburn  8477:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  8478:             foreach my $item (@statuses) {
1.711     raeburn  8479:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
                   8480:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
                   8481:                         if ($defquota eq '') {
                   8482:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
                   8483:                             $settingstatus = $item;
                   8484:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
                   8485:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
                   8486:                             $settingstatus = $item;
                   8487:                         }
                   8488:                     }
                   8489:                 } else {
                   8490:                     if ($quotahash{'quotas'}{$item} ne '') {
                   8491:                         if ($defquota eq '') {
                   8492:                             $defquota = $quotahash{'quotas'}{$item};
                   8493:                             $settingstatus = $item;
                   8494:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   8495:                             $defquota = $quotahash{'quotas'}{$item};
                   8496:                             $settingstatus = $item;
                   8497:                         }
1.536     raeburn  8498:                     }
                   8499:                 }
                   8500:             }
                   8501:         }
                   8502:         if ($defquota eq '') {
1.711     raeburn  8503:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
                   8504:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
                   8505:             } else {
                   8506:                 $defquota = $quotahash{'quotas'}{'default'};
                   8507:             }
1.536     raeburn  8508:             $settingstatus = 'default';
                   8509:         }
                   8510:     } else {
                   8511:         $settingstatus = 'default';
                   8512:         $defquota = 20;
                   8513:     }
                   8514:     if (wantarray) {
                   8515:         return ($defquota,$settingstatus);
1.472     raeburn  8516:     } else {
1.536     raeburn  8517:         return $defquota;
1.472     raeburn  8518:     }
                   8519: }
                   8520: 
1.384     raeburn  8521: sub get_secgrprole_info {
                   8522:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   8523:     my %sections_count = &get_sections($cdom,$cnum);
                   8524:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   8525:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   8526:     my @groups = sort(keys(%curr_groups));
                   8527:     my $allroles = [];
                   8528:     my $rolehash;
                   8529:     my $accesshash = {
                   8530:                      active => 'Currently has access',
                   8531:                      future => 'Will have future access',
                   8532:                      previous => 'Previously had access',
                   8533:                   };
                   8534:     if ($needroles) {
                   8535:         $rolehash = {'all' => 'all'};
1.385     albertel 8536:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8537: 	if (&Apache::lonnet::error(%user_roles)) {
                   8538: 	    undef(%user_roles);
                   8539: 	}
                   8540:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  8541:             my ($role)=split(/\:/,$item,2);
                   8542:             if ($role eq 'cr') { next; }
                   8543:             if ($role =~ /^cr/) {
                   8544:                 $$rolehash{$role} = (split('/',$role))[3];
                   8545:             } else {
                   8546:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   8547:             }
                   8548:         }
                   8549:         foreach my $key (sort(keys(%{$rolehash}))) {
                   8550:             push(@{$allroles},$key);
                   8551:         }
                   8552:         push (@{$allroles},'st');
                   8553:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   8554:     }
                   8555:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   8556: }
                   8557: 
1.555     raeburn  8558: sub user_picker {
1.994     raeburn  8559:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
1.555     raeburn  8560:     my $currdom = $dom;
                   8561:     my %curr_selected = (
                   8562:                         srchin => 'dom',
1.580     raeburn  8563:                         srchby => 'lastname',
1.555     raeburn  8564:                       );
                   8565:     my $srchterm;
1.625     raeburn  8566:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  8567:         if ($srch->{'srchby'} ne '') {
                   8568:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   8569:         }
                   8570:         if ($srch->{'srchin'} ne '') {
                   8571:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   8572:         }
                   8573:         if ($srch->{'srchtype'} ne '') {
                   8574:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   8575:         }
                   8576:         if ($srch->{'srchdomain'} ne '') {
                   8577:             $currdom = $srch->{'srchdomain'};
                   8578:         }
                   8579:         $srchterm = $srch->{'srchterm'};
                   8580:     }
                   8581:     my %lt=&Apache::lonlocal::texthash(
1.573     raeburn  8582:                     'usr'       => 'Search criteria',
1.563     raeburn  8583:                     'doma'      => 'Domain/institution to search',
1.558     albertel 8584:                     'uname'     => 'username',
                   8585:                     'lastname'  => 'last name',
1.555     raeburn  8586:                     'lastfirst' => 'last name, first name',
1.558     albertel 8587:                     'crs'       => 'in this course',
1.576     raeburn  8588:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 8589:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  8590:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 8591:                     'exact'     => 'is',
                   8592:                     'contains'  => 'contains',
1.569     raeburn  8593:                     'begins'    => 'begins with',
1.571     raeburn  8594:                     'youm'      => "You must include some text to search for.",
                   8595:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   8596:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   8597:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   8598:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   8599:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   8600:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   8601:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  8602:                                        );
1.563     raeburn  8603:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   8604:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  8605: 
                   8606:     my @srchins = ('crs','dom','alc','instd');
                   8607: 
                   8608:     foreach my $option (@srchins) {
                   8609:         # FIXME 'alc' option unavailable until 
                   8610:         #       loncreateuser::print_user_query_page()
                   8611:         #       has been completed.
                   8612:         next if ($option eq 'alc');
1.880     raeburn  8613:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  8614:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  8615:         if ($curr_selected{'srchin'} eq $option) {
                   8616:             $srchinsel .= ' 
                   8617:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   8618:         } else {
                   8619:             $srchinsel .= '
                   8620:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   8621:         }
1.555     raeburn  8622:     }
1.563     raeburn  8623:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  8624: 
                   8625:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  8626:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  8627:         if ($curr_selected{'srchby'} eq $option) {
                   8628:             $srchbysel .= '
                   8629:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   8630:         } else {
                   8631:             $srchbysel .= '
                   8632:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   8633:          }
                   8634:     }
                   8635:     $srchbysel .= "\n  </select>\n";
                   8636: 
                   8637:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  8638:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  8639:         if ($curr_selected{'srchtype'} eq $option) {
                   8640:             $srchtypesel .= '
                   8641:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   8642:         } else {
                   8643:             $srchtypesel .= '
                   8644:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   8645:         }
                   8646:     }
                   8647:     $srchtypesel .= "\n  </select>\n";
                   8648: 
1.558     albertel 8649:     my ($newuserscript,$new_user_create);
1.994     raeburn  8650:     my $context_dom = $env{'request.role.domain'};
                   8651:     if ($context eq 'requestcrs') {
                   8652:         if ($env{'form.coursedom'} ne '') { 
                   8653:             $context_dom = $env{'form.coursedom'};
                   8654:         }
                   8655:     }
1.556     raeburn  8656:     if ($forcenewuser) {
1.576     raeburn  8657:         if (ref($srch) eq 'HASH') {
1.994     raeburn  8658:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  8659:                 if ($cancreate) {
                   8660:                     $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>';
                   8661:                 } else {
1.799     bisitz   8662:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  8663:                     my %usertypetext = (
                   8664:                         official   => 'institutional',
                   8665:                         unofficial => 'non-institutional',
                   8666:                     );
1.799     bisitz   8667:                     $new_user_create = '<p class="LC_warning">'
                   8668:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   8669:                                       .' '
                   8670:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   8671:                                           ,'<a href="'.$helplink.'">','</a>')
                   8672:                                       .'</p><br />';
1.627     raeburn  8673:                 }
1.576     raeburn  8674:             }
                   8675:         }
                   8676: 
1.556     raeburn  8677:         $newuserscript = <<"ENDSCRIPT";
                   8678: 
1.570     raeburn  8679: function setSearch(createnew,callingForm) {
1.556     raeburn  8680:     if (createnew == 1) {
1.570     raeburn  8681:         for (var i=0; i<callingForm.srchby.length; i++) {
                   8682:             if (callingForm.srchby.options[i].value == 'uname') {
                   8683:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  8684:             }
                   8685:         }
1.570     raeburn  8686:         for (var i=0; i<callingForm.srchin.length; i++) {
                   8687:             if ( callingForm.srchin.options[i].value == 'dom') {
                   8688: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  8689:             }
                   8690:         }
1.570     raeburn  8691:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   8692:             if (callingForm.srchtype.options[i].value == 'exact') {
                   8693:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  8694:             }
                   8695:         }
1.570     raeburn  8696:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  8697:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  8698:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  8699:             }
                   8700:         }
                   8701:     }
                   8702: }
                   8703: ENDSCRIPT
1.558     albertel 8704: 
1.556     raeburn  8705:     }
                   8706: 
1.555     raeburn  8707:     my $output = <<"END_BLOCK";
1.556     raeburn  8708: <script type="text/javascript">
1.824     bisitz   8709: // <![CDATA[
1.570     raeburn  8710: function validateEntry(callingForm) {
1.558     albertel 8711: 
1.556     raeburn  8712:     var checkok = 1;
1.558     albertel 8713:     var srchin;
1.570     raeburn  8714:     for (var i=0; i<callingForm.srchin.length; i++) {
                   8715: 	if ( callingForm.srchin[i].checked ) {
                   8716: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 8717: 	}
                   8718:     }
                   8719: 
1.570     raeburn  8720:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   8721:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   8722:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   8723:     var srchterm =  callingForm.srchterm.value;
                   8724:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  8725:     var msg = "";
                   8726: 
                   8727:     if (srchterm == "") {
                   8728:         checkok = 0;
1.571     raeburn  8729:         msg += "$lt{'youm'}\\n";
1.556     raeburn  8730:     }
                   8731: 
1.569     raeburn  8732:     if (srchtype== 'begins') {
                   8733:         if (srchterm.length < 2) {
                   8734:             checkok = 0;
1.571     raeburn  8735:             msg += "$lt{'thte'}\\n";
1.569     raeburn  8736:         }
                   8737:     }
                   8738: 
1.556     raeburn  8739:     if (srchtype== 'contains') {
                   8740:         if (srchterm.length < 3) {
                   8741:             checkok = 0;
1.571     raeburn  8742:             msg += "$lt{'thet'}\\n";
1.556     raeburn  8743:         }
                   8744:     }
                   8745:     if (srchin == 'instd') {
                   8746:         if (srchdomain == '') {
                   8747:             checkok = 0;
1.571     raeburn  8748:             msg += "$lt{'yomc'}\\n";
1.556     raeburn  8749:         }
                   8750:     }
                   8751:     if (srchin == 'dom') {
                   8752:         if (srchdomain == '') {
                   8753:             checkok = 0;
1.571     raeburn  8754:             msg += "$lt{'ymcd'}\\n";
1.556     raeburn  8755:         }
                   8756:     }
                   8757:     if (srchby == 'lastfirst') {
                   8758:         if (srchterm.indexOf(",") == -1) {
                   8759:             checkok = 0;
1.571     raeburn  8760:             msg += "$lt{'whus'}\\n";
1.556     raeburn  8761:         }
                   8762:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   8763:             checkok = 0;
1.571     raeburn  8764:             msg += "$lt{'whse'}\\n";
1.556     raeburn  8765:         }
                   8766:     }
                   8767:     if (checkok == 0) {
1.571     raeburn  8768:         alert("$lt{'thfo'}\\n"+msg);
1.556     raeburn  8769:         return;
                   8770:     }
                   8771:     if (checkok == 1) {
1.570     raeburn  8772:         callingForm.submit();
1.556     raeburn  8773:     }
                   8774: }
                   8775: 
                   8776: $newuserscript
                   8777: 
1.824     bisitz   8778: // ]]>
1.556     raeburn  8779: </script>
1.558     albertel 8780: 
                   8781: $new_user_create
                   8782: 
1.555     raeburn  8783: END_BLOCK
1.558     albertel 8784: 
1.876     raeburn  8785:     $output .= &Apache::lonhtmlcommon::start_pick_box().
                   8786:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
                   8787:                $domform.
                   8788:                &Apache::lonhtmlcommon::row_closure().
                   8789:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
                   8790:                $srchbysel.
                   8791:                $srchtypesel. 
                   8792:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   8793:                $srchinsel.
                   8794:                &Apache::lonhtmlcommon::row_closure(1). 
                   8795:                &Apache::lonhtmlcommon::end_pick_box().
                   8796:                '<br />';
1.555     raeburn  8797:     return $output;
                   8798: }
                   8799: 
1.612     raeburn  8800: sub user_rule_check {
1.615     raeburn  8801:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.612     raeburn  8802:     my $response;
                   8803:     if (ref($usershash) eq 'HASH') {
                   8804:         foreach my $user (keys(%{$usershash})) {
                   8805:             my ($uname,$udom) = split(/:/,$user);
                   8806:             next if ($udom eq '' || $uname eq '');
1.615     raeburn  8807:             my ($id,$newuser);
1.612     raeburn  8808:             if (ref($usershash->{$user}) eq 'HASH') {
1.615     raeburn  8809:                 $newuser = $usershash->{$user}->{'newuser'};
1.612     raeburn  8810:                 $id = $usershash->{$user}->{'id'};
                   8811:             }
                   8812:             my $inst_response;
                   8813:             if (ref($checks) eq 'HASH') {
                   8814:                 if (defined($checks->{'username'})) {
1.615     raeburn  8815:                     ($inst_response,%{$inst_results->{$user}}) = 
1.612     raeburn  8816:                         &Apache::lonnet::get_instuser($udom,$uname);
                   8817:                 } elsif (defined($checks->{'id'})) {
1.615     raeburn  8818:                     ($inst_response,%{$inst_results->{$user}}) =
1.612     raeburn  8819:                         &Apache::lonnet::get_instuser($udom,undef,$id);
                   8820:                 }
1.615     raeburn  8821:             } else {
                   8822:                 ($inst_response,%{$inst_results->{$user}}) =
                   8823:                     &Apache::lonnet::get_instuser($udom,$uname);
                   8824:                 return;
1.612     raeburn  8825:             }
1.615     raeburn  8826:             if (!$got_rules->{$udom}) {
1.612     raeburn  8827:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
                   8828:                                                   ['usercreation'],$udom);
                   8829:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
1.615     raeburn  8830:                     foreach my $item ('username','id') {
1.612     raeburn  8831:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   8832:                             $$curr_rules{$udom}{$item} = 
                   8833:                                 $domconfig{'usercreation'}{$item.'_rule'};
1.585     raeburn  8834:                         }
                   8835:                     }
                   8836:                 }
1.615     raeburn  8837:                 $got_rules->{$udom} = 1;  
1.585     raeburn  8838:             }
1.612     raeburn  8839:             foreach my $item (keys(%{$checks})) {
                   8840:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   8841:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   8842:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
                   8843:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
                   8844:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   8845:                                 if ($rule_check{$rule}) {
                   8846:                                     $$rulematch{$user}{$item} = $rule;
                   8847:                                     if ($inst_response eq 'ok') {
1.615     raeburn  8848:                                         if (ref($inst_results) eq 'HASH') {
                   8849:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   8850:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   8851:                                                     $$alerts{$item}{$udom}{$uname} = 1;
                   8852:                                                 }
1.612     raeburn  8853:                                             }
                   8854:                                         }
1.615     raeburn  8855:                                     }
                   8856:                                     last;
1.585     raeburn  8857:                                 }
                   8858:                             }
                   8859:                         }
                   8860:                     }
                   8861:                 }
                   8862:             }
                   8863:         }
                   8864:     }
1.612     raeburn  8865:     return;
                   8866: }
                   8867: 
                   8868: sub user_rule_formats {
                   8869:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   8870:     my %text = ( 
                   8871:                  'username' => 'Usernames',
                   8872:                  'id'       => 'IDs',
                   8873:                );
                   8874:     my $output;
                   8875:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   8876:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   8877:         if (@{$ruleorder} > 0) {
                   8878:             $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>';
                   8879:             foreach my $rule (@{$ruleorder}) {
                   8880:                 if (ref($curr_rules) eq 'ARRAY') {
                   8881:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   8882:                         if (ref($rules->{$rule}) eq 'HASH') {
                   8883:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   8884:                                         $rules->{$rule}{'desc'}.'</li>';
                   8885:                         }
                   8886:                     }
                   8887:                 }
                   8888:             }
                   8889:             $output .= '</ul>';
                   8890:         }
                   8891:     }
                   8892:     return $output;
                   8893: }
                   8894: 
                   8895: sub instrule_disallow_msg {
1.615     raeburn  8896:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  8897:     my $response;
                   8898:     my %text = (
                   8899:                   item   => 'username',
                   8900:                   items  => 'usernames',
                   8901:                   match  => 'matches',
                   8902:                   do     => 'does',
                   8903:                   action => 'a username',
                   8904:                   one    => 'one',
                   8905:                );
                   8906:     if ($count > 1) {
                   8907:         $text{'item'} = 'usernames';
                   8908:         $text{'match'} ='match';
                   8909:         $text{'do'} = 'do';
                   8910:         $text{'action'} = 'usernames',
                   8911:         $text{'one'} = 'ones';
                   8912:     }
                   8913:     if ($checkitem eq 'id') {
                   8914:         $text{'items'} = 'IDs';
                   8915:         $text{'item'} = 'ID';
                   8916:         $text{'action'} = 'an ID';
1.615     raeburn  8917:         if ($count > 1) {
                   8918:             $text{'item'} = 'IDs';
                   8919:             $text{'action'} = 'IDs';
                   8920:         }
1.612     raeburn  8921:     }
1.674     bisitz   8922:     $response = &mt("The $text{'item'} you chose $text{'match'} the format of $text{'items'} defined for [_1], but the $text{'item'} $text{'do'} not exist in the institutional directory.",'<span class="LC_cusr_emph">'.$domdesc.'</span>').'<br />';
1.615     raeburn  8923:     if ($mode eq 'upload') {
                   8924:         if ($checkitem eq 'username') {
                   8925:             $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'}.");
                   8926:         } elsif ($checkitem eq 'id') {
1.674     bisitz   8927:             $response .= &mt("Either upload a file which includes $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or when associating fields with data columns, omit an association for the Student/Employee ID field.");
1.615     raeburn  8928:         }
1.669     raeburn  8929:     } elsif ($mode eq 'selfcreate') {
                   8930:         if ($checkitem eq 'id') {
                   8931:             $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.");
                   8932:         }
1.615     raeburn  8933:     } else {
                   8934:         if ($checkitem eq 'username') {
                   8935:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   8936:         } elsif ($checkitem eq 'id') {
                   8937:             $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.");
                   8938:         }
1.612     raeburn  8939:     }
                   8940:     return $response;
1.585     raeburn  8941: }
                   8942: 
1.624     raeburn  8943: sub personal_data_fieldtitles {
                   8944:     my %fieldtitles = &Apache::lonlocal::texthash (
                   8945:                         id => 'Student/Employee ID',
                   8946:                         permanentemail => 'E-mail address',
                   8947:                         lastname => 'Last Name',
                   8948:                         firstname => 'First Name',
                   8949:                         middlename => 'Middle Name',
                   8950:                         generation => 'Generation',
                   8951:                         gen => 'Generation',
1.765     raeburn  8952:                         inststatus => 'Affiliation',
1.624     raeburn  8953:                    );
                   8954:     return %fieldtitles;
                   8955: }
                   8956: 
1.642     raeburn  8957: sub sorted_inst_types {
                   8958:     my ($dom) = @_;
                   8959:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   8960:     my $othertitle = &mt('All users');
                   8961:     if ($env{'request.course.id'}) {
1.668     raeburn  8962:         $othertitle  = &mt('Any users');
1.642     raeburn  8963:     }
                   8964:     my @types;
                   8965:     if (ref($order) eq 'ARRAY') {
                   8966:         @types = @{$order};
                   8967:     }
                   8968:     if (@types == 0) {
                   8969:         if (ref($usertypes) eq 'HASH') {
                   8970:             @types = sort(keys(%{$usertypes}));
                   8971:         }
                   8972:     }
                   8973:     if (keys(%{$usertypes}) > 0) {
                   8974:         $othertitle = &mt('Other users');
                   8975:     }
                   8976:     return ($othertitle,$usertypes,\@types);
                   8977: }
                   8978: 
1.645     raeburn  8979: sub get_institutional_codes {
                   8980:     my ($settings,$allcourses,$LC_code) = @_;
                   8981: # Get complete list of course sections to update
                   8982:     my @currsections = ();
                   8983:     my @currxlists = ();
                   8984:     my $coursecode = $$settings{'internal.coursecode'};
                   8985: 
                   8986:     if ($$settings{'internal.sectionnums'} ne '') {
                   8987:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   8988:     }
                   8989: 
                   8990:     if ($$settings{'internal.crosslistings'} ne '') {
                   8991:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   8992:     }
                   8993: 
                   8994:     if (@currxlists > 0) {
                   8995:         foreach (@currxlists) {
                   8996:             if (m/^([^:]+):(\w*)$/) {
                   8997:                 unless (grep/^$1$/,@{$allcourses}) {
                   8998:                     push @{$allcourses},$1;
                   8999:                     $$LC_code{$1} = $2;
                   9000:                 }
                   9001:             }
                   9002:         }
                   9003:     }
                   9004:  
                   9005:     if (@currsections > 0) {
                   9006:         foreach (@currsections) {
                   9007:             if (m/^(\w+):(\w*)$/) {
                   9008:                 my $sec = $coursecode.$1;
                   9009:                 my $lc_sec = $2;
                   9010:                 unless (grep/^$sec$/,@{$allcourses}) {
                   9011:                     push @{$allcourses},$sec;
                   9012:                     $$LC_code{$sec} = $lc_sec;
                   9013:                 }
                   9014:             }
                   9015:         }
                   9016:     }
                   9017:     return;
                   9018: }
                   9019: 
1.971     raeburn  9020: sub get_standard_codeitems {
                   9021:     return ('Year','Semester','Department','Number','Section');
                   9022: }
                   9023: 
1.112     bowersj2 9024: =pod
                   9025: 
1.780     raeburn  9026: =head1 Slot Helpers
                   9027: 
                   9028: =over 4
                   9029: 
                   9030: =item * sorted_slots()
                   9031: 
1.1040    raeburn  9032: Sorts an array of slot names in order of an optional sort key,
                   9033: default sort is by slot start time (earliest first). 
1.780     raeburn  9034: 
                   9035: Inputs:
                   9036: 
                   9037: =over 4
                   9038: 
                   9039: slotsarr  - Reference to array of unsorted slot names.
                   9040: 
                   9041: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   9042: 
1.1040    raeburn  9043: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   9044: 
1.549     albertel 9045: =back
                   9046: 
1.780     raeburn  9047: Returns:
                   9048: 
                   9049: =over 4
                   9050: 
1.1040    raeburn  9051: sorted   - An array of slot names sorted by a specified sort key 
                   9052:            (default sort key is start time of the slot).
1.780     raeburn  9053: 
                   9054: =back
                   9055: 
                   9056: =cut
                   9057: 
                   9058: 
                   9059: sub sorted_slots {
1.1040    raeburn  9060:     my ($slotsarr,$slots,$sortkey) = @_;
                   9061:     if ($sortkey eq '') {
                   9062:         $sortkey = 'starttime';
                   9063:     }
1.780     raeburn  9064:     my @sorted;
                   9065:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   9066:         @sorted =
                   9067:             sort {
                   9068:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  9069:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  9070:                      }
                   9071:                      if (ref($slots->{$a})) { return -1;}
                   9072:                      if (ref($slots->{$b})) { return 1;}
                   9073:                      return 0;
                   9074:                  } @{$slotsarr};
                   9075:     }
                   9076:     return @sorted;
                   9077: }
                   9078: 
1.1040    raeburn  9079: =pod
                   9080: 
                   9081: =item * get_future_slots()
                   9082: 
                   9083: Inputs:
                   9084: 
                   9085: =over 4
                   9086: 
                   9087: cnum - course number
                   9088: 
                   9089: cdom - course domain
                   9090: 
                   9091: now - current UNIX time
                   9092: 
                   9093: symb - optional symb
                   9094: 
                   9095: =back
                   9096: 
                   9097: Returns:
                   9098: 
                   9099: =over 4
                   9100: 
                   9101: sorted_reservable - ref to array of student_schedulable slots currently 
                   9102:                     reservable, ordered by end date of reservation period.
                   9103: 
                   9104: reservable_now - ref to hash of student_schedulable slots currently
                   9105:                  reservable.
                   9106: 
                   9107:     Keys in inner hash are:
                   9108:     (a) symb: either blank or symb to which slot use is restricted.
                   9109:     (b) endreserve: end date of reservation period. 
                   9110: 
                   9111: sorted_future - ref to array of student_schedulable slots reservable in
                   9112:                 the future, ordered by start date of reservation period.
                   9113: 
                   9114: future_reservable - ref to hash of student_schedulable slots reservable
                   9115:                     in the future.
                   9116: 
                   9117:     Keys in inner hash are:
                   9118:     (a) symb: either blank or symb to which slot use is restricted.
                   9119:     (b) startreserve:  start date of reservation period.
                   9120: 
                   9121: =back
                   9122: 
                   9123: =cut
                   9124: 
                   9125: sub get_future_slots {
                   9126:     my ($cnum,$cdom,$now,$symb) = @_;
                   9127:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   9128:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   9129:     foreach my $slot (keys(%slots)) {
                   9130:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   9131:         if ($symb) {
                   9132:             next if (($slots{$slot}->{'symb'} ne '') && 
                   9133:                      ($slots{$slot}->{'symb'} ne $symb));
                   9134:         }
                   9135:         if (($slots{$slot}->{'starttime'} > $now) &&
                   9136:             ($slots{$slot}->{'endtime'} > $now)) {
                   9137:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   9138:                 my $userallowed = 0;
                   9139:                 if ($slots{$slot}->{'allowedsections'}) {
                   9140:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   9141:                     if (!defined($env{'request.role.sec'})
                   9142:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   9143:                         $userallowed=1;
                   9144:                     } else {
                   9145:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   9146:                             $userallowed=1;
                   9147:                         }
                   9148:                     }
                   9149:                     unless ($userallowed) {
                   9150:                         if (defined($env{'request.course.groups'})) {
                   9151:                             my @groups = split(/:/,$env{'request.course.groups'});
                   9152:                             foreach my $group (@groups) {
                   9153:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   9154:                                     $userallowed=1;
                   9155:                                     last;
                   9156:                                 }
                   9157:                             }
                   9158:                         }
                   9159:                     }
                   9160:                 }
                   9161:                 if ($slots{$slot}->{'allowedusers'}) {
                   9162:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   9163:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   9164:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   9165:                         $userallowed = 1;
                   9166:                     }
                   9167:                 }
                   9168:                 next unless($userallowed);
                   9169:             }
                   9170:             my $startreserve = $slots{$slot}->{'startreserve'};
                   9171:             my $endreserve = $slots{$slot}->{'endreserve'};
                   9172:             my $symb = $slots{$slot}->{'symb'};
                   9173:             if (($startreserve < $now) &&
                   9174:                 (!$endreserve || $endreserve > $now)) {
                   9175:                 my $lastres = $endreserve;
                   9176:                 if (!$lastres) {
                   9177:                     $lastres = $slots{$slot}->{'starttime'};
                   9178:                 }
                   9179:                 $reservable_now{$slot} = {
                   9180:                                            symb       => $symb,
                   9181:                                            endreserve => $lastres
                   9182:                                          };
                   9183:             } elsif (($startreserve > $now) &&
                   9184:                      (!$endreserve || $endreserve > $startreserve)) {
                   9185:                 $future_reservable{$slot} = {
                   9186:                                               symb         => $symb,
                   9187:                                               startreserve => $startreserve
                   9188:                                             };
                   9189:             }
                   9190:         }
                   9191:     }
                   9192:     my @unsorted_reservable = keys(%reservable_now);
                   9193:     if (@unsorted_reservable > 0) {
                   9194:         @sorted_reservable = 
                   9195:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   9196:     }
                   9197:     my @unsorted_future = keys(%future_reservable);
                   9198:     if (@unsorted_future > 0) {
                   9199:         @sorted_future =
                   9200:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   9201:     }
                   9202:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   9203: }
1.780     raeburn  9204: 
                   9205: =pod
                   9206: 
1.1057    foxr     9207: =back
                   9208: 
1.549     albertel 9209: =head1 HTTP Helpers
                   9210: 
                   9211: =over 4
                   9212: 
1.648     raeburn  9213: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 9214: 
1.258     albertel 9215: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 9216: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 9217: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 9218: 
                   9219: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   9220: $possible_names is an ref to an array of form element names.  As an example:
                   9221: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 9222: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 9223: 
                   9224: =cut
1.1       albertel 9225: 
1.6       albertel 9226: sub get_unprocessed_cgi {
1.25      albertel 9227:   my ($query,$possible_names)= @_;
1.26      matthew  9228:   # $Apache::lonxml::debug=1;
1.356     albertel 9229:   foreach my $pair (split(/&/,$query)) {
                   9230:     my ($name, $value) = split(/=/,$pair);
1.369     www      9231:     $name = &unescape($name);
1.25      albertel 9232:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   9233:       $value =~ tr/+/ /;
                   9234:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 9235:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 9236:     }
1.16      harris41 9237:   }
1.6       albertel 9238: }
                   9239: 
1.112     bowersj2 9240: =pod
                   9241: 
1.648     raeburn  9242: =item * &cacheheader() 
1.112     bowersj2 9243: 
                   9244: returns cache-controlling header code
                   9245: 
                   9246: =cut
                   9247: 
1.7       albertel 9248: sub cacheheader {
1.258     albertel 9249:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 9250:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   9251:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 9252:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   9253:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 9254:     return $output;
1.7       albertel 9255: }
                   9256: 
1.112     bowersj2 9257: =pod
                   9258: 
1.648     raeburn  9259: =item * &no_cache($r) 
1.112     bowersj2 9260: 
                   9261: specifies header code to not have cache
                   9262: 
                   9263: =cut
                   9264: 
1.9       albertel 9265: sub no_cache {
1.216     albertel 9266:     my ($r) = @_;
                   9267:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 9268: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 9269:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   9270:     $r->no_cache(1);
                   9271:     $r->header_out("Expires" => $date);
                   9272:     $r->header_out("Pragma" => "no-cache");
1.123     www      9273: }
                   9274: 
                   9275: sub content_type {
1.181     albertel 9276:     my ($r,$type,$charset) = @_;
1.299     foxr     9277:     if ($r) {
                   9278: 	#  Note that printout.pl calls this with undef for $r.
                   9279: 	&no_cache($r);
                   9280:     }
1.258     albertel 9281:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 9282:     unless ($charset) {
                   9283: 	$charset=&Apache::lonlocal::current_encoding;
                   9284:     }
                   9285:     if ($charset) { $type.='; charset='.$charset; }
                   9286:     if ($r) {
                   9287: 	$r->content_type($type);
                   9288:     } else {
                   9289: 	print("Content-type: $type\n\n");
                   9290:     }
1.9       albertel 9291: }
1.25      albertel 9292: 
1.112     bowersj2 9293: =pod
                   9294: 
1.648     raeburn  9295: =item * &add_to_env($name,$value) 
1.112     bowersj2 9296: 
1.258     albertel 9297: adds $name to the %env hash with value
1.112     bowersj2 9298: $value, if $name already exists, the entry is converted to an array
                   9299: reference and $value is added to the array.
                   9300: 
                   9301: =cut
                   9302: 
1.25      albertel 9303: sub add_to_env {
                   9304:   my ($name,$value)=@_;
1.258     albertel 9305:   if (defined($env{$name})) {
                   9306:     if (ref($env{$name})) {
1.25      albertel 9307:       #already have multiple values
1.258     albertel 9308:       push(@{ $env{$name} },$value);
1.25      albertel 9309:     } else {
                   9310:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 9311:       my $first=$env{$name};
                   9312:       undef($env{$name});
                   9313:       push(@{ $env{$name} },$first,$value);
1.25      albertel 9314:     }
                   9315:   } else {
1.258     albertel 9316:     $env{$name}=$value;
1.25      albertel 9317:   }
1.31      albertel 9318: }
1.149     albertel 9319: 
                   9320: =pod
                   9321: 
1.648     raeburn  9322: =item * &get_env_multiple($name) 
1.149     albertel 9323: 
1.258     albertel 9324: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 9325: values may be defined and end up as an array ref.
                   9326: 
                   9327: returns an array of values
                   9328: 
                   9329: =cut
                   9330: 
                   9331: sub get_env_multiple {
                   9332:     my ($name) = @_;
                   9333:     my @values;
1.258     albertel 9334:     if (defined($env{$name})) {
1.149     albertel 9335:         # exists is it an array
1.258     albertel 9336:         if (ref($env{$name})) {
                   9337:             @values=@{ $env{$name} };
1.149     albertel 9338:         } else {
1.258     albertel 9339:             $values[0]=$env{$name};
1.149     albertel 9340:         }
                   9341:     }
                   9342:     return(@values);
                   9343: }
                   9344: 
1.660     raeburn  9345: sub ask_for_embedded_content {
                   9346:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  9347:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  9348:         %currsubfile,%unused,$rem);
1.1071    raeburn  9349:     my $counter = 0;
                   9350:     my $numnew = 0;
1.987     raeburn  9351:     my $numremref = 0;
                   9352:     my $numinvalid = 0;
                   9353:     my $numpathchg = 0;
                   9354:     my $numexisting = 0;
1.1071    raeburn  9355:     my $numunused = 0;
                   9356:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
                   9357:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path);
                   9358:     my $heading = &mt('Upload embedded files');
                   9359:     my $buttontext = &mt('Upload');
                   9360: 
1.1085    raeburn  9361:     my $navmap;
                   9362:     if ($env{'request.course.id'}) {
                   9363:         $navmap = Apache::lonnavmaps::navmap->new();
                   9364:     }
1.984     raeburn  9365:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   9366:         my $current_path='/';
                   9367:         if ($env{'form.currentpath'}) {
                   9368:             $current_path = $env{'form.currentpath'};
                   9369:         }
                   9370:         if ($actionurl eq '/adm/coursegrp_portfolio') {
                   9371:             $udom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9372:             $uname = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9373:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   9374:         } else {
                   9375:             $udom = $env{'user.domain'};
                   9376:             $uname = $env{'user.name'};
                   9377:             $url = '/userfiles/portfolio';
                   9378:         }
1.987     raeburn  9379:         $toplevel = $url.'/';
1.984     raeburn  9380:         $url .= $current_path;
                   9381:         $getpropath = 1;
1.987     raeburn  9382:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   9383:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      9384:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  9385:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  9386:         $toplevel = $url;
1.984     raeburn  9387:         if ($rest ne '') {
1.987     raeburn  9388:             $url .= $rest;
                   9389:         }
                   9390:     } elsif ($actionurl eq '/adm/coursedocs') {
                   9391:         if (ref($args) eq 'HASH') {
1.1071    raeburn  9392:             $url = $args->{'docs_url'};
                   9393:             $toplevel = $url;
1.1084    raeburn  9394:             if ($args->{'context'} eq 'paste') {
                   9395:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   9396:                 ($path) = 
                   9397:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   9398:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   9399:                 $fileloc =~ s{^/}{};
                   9400:             }
1.1071    raeburn  9401:         }
1.1084    raeburn  9402:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  9403:         if ($env{'request.course.id'} ne '') {
                   9404:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9405:             $cnum =  $env{'course.'.$env{'request.course.id'}.'.num'};
                   9406:             if (ref($args) eq 'HASH') {
                   9407:                 $url = $args->{'docs_url'};
                   9408:                 $title = $args->{'docs_title'};
                   9409:                 $toplevel = "/$url";
1.1085    raeburn  9410:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1071    raeburn  9411:                 ($path) =  
                   9412:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   9413:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   9414:                 $fileloc =~ s{^/}{};
                   9415:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   9416:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   9417:             }
1.987     raeburn  9418:         }
                   9419:     }
                   9420:     my $now = time();
                   9421:     foreach my $embed_file (keys(%{$allfiles})) {
                   9422:         my $absolutepath;
                   9423:         if ($embed_file =~ m{^\w+://}) {
                   9424:             $newfiles{$embed_file} = 1;
                   9425:             $mapping{$embed_file} = $embed_file;
                   9426:         } else {
                   9427:             if ($embed_file =~ m{^/}) {
                   9428:                 $absolutepath = $embed_file;
                   9429:                 $embed_file =~ s{^(/+)}{};
                   9430:             }
                   9431:             if ($embed_file =~ m{/}) {
                   9432:                 my ($path,$fname) = ($embed_file =~ m{^(.+)/([^/]*)$});
                   9433:                 $path = &check_for_traversal($path,$url,$toplevel);
                   9434:                 my $item = $fname;
                   9435:                 if ($path ne '') {
                   9436:                     $item = $path.'/'.$fname;
                   9437:                     $subdependencies{$path}{$fname} = 1;
                   9438:                 } else {
                   9439:                     $dependencies{$item} = 1;
                   9440:                 }
                   9441:                 if ($absolutepath) {
                   9442:                     $mapping{$item} = $absolutepath;
                   9443:                 } else {
                   9444:                     $mapping{$item} = $embed_file;
                   9445:                 }
                   9446:             } else {
                   9447:                 $dependencies{$embed_file} = 1;
                   9448:                 if ($absolutepath) {
                   9449:                     $mapping{$embed_file} = $absolutepath;
                   9450:                 } else {
                   9451:                     $mapping{$embed_file} = $embed_file;
                   9452:                 }
                   9453:             }
1.984     raeburn  9454:         }
                   9455:     }
1.1071    raeburn  9456:     my $dirptr = 16384;
1.984     raeburn  9457:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  9458:         $currsubfile{$path} = {};
1.984     raeburn  9459:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  9460:             my ($sublistref,$listerror) =
                   9461:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   9462:             if (ref($sublistref) eq 'ARRAY') {
                   9463:                 foreach my $line (@{$sublistref}) {
                   9464:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  9465:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  9466:                 }
1.984     raeburn  9467:             }
1.987     raeburn  9468:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  9469:             if (opendir(my $dir,$url.'/'.$path)) {
                   9470:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  9471:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   9472:             }
1.1084    raeburn  9473:         } elsif (($actionurl eq '/adm/dependencies') ||
                   9474:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   9475:                   ($args->{'context'} eq 'paste'))) {
1.1071    raeburn  9476:             if ($env{'request.course.id'} ne '') {
                   9477:                 my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   9478:                 if ($dir ne '') {
                   9479:                     my ($sublistref,$listerror) =
                   9480:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   9481:                     if (ref($sublistref) eq 'ARRAY') {
                   9482:                         foreach my $line (@{$sublistref}) {
                   9483:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   9484:                                 undef,$mtime)=split(/\&/,$line,12);
                   9485:                             unless (($testdir&$dirptr) ||
                   9486:                                     ($file_name =~ /^\.\.?$/)) {
                   9487:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   9488:                             }
                   9489:                         }
                   9490:                     }
                   9491:                 }
1.984     raeburn  9492:             }
                   9493:         }
                   9494:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  9495:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  9496:                 my $item = $path.'/'.$file;
                   9497:                 unless ($mapping{$item} eq $item) {
                   9498:                     $pathchanges{$item} = 1;
                   9499:                 }
                   9500:                 $existing{$item} = 1;
                   9501:                 $numexisting ++;
                   9502:             } else {
                   9503:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  9504:             }
                   9505:         }
1.1071    raeburn  9506:         if ($actionurl eq '/adm/dependencies') {
                   9507:             foreach my $path (keys(%currsubfile)) {
                   9508:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   9509:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   9510:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  9511:                              next if (($rem ne '') &&
                   9512:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   9513:                                        (ref($navmap) &&
                   9514:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   9515:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   9516:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  9517:                              $unused{$path.'/'.$file} = 1; 
                   9518:                          }
                   9519:                     }
                   9520:                 }
                   9521:             }
                   9522:         }
1.984     raeburn  9523:     }
1.987     raeburn  9524:     my %currfile;
1.984     raeburn  9525:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  9526:         my ($dirlistref,$listerror) =
                   9527:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   9528:         if (ref($dirlistref) eq 'ARRAY') {
                   9529:             foreach my $line (@{$dirlistref}) {
                   9530:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   9531:                 $currfile{$file_name} = 1;
                   9532:             }
1.984     raeburn  9533:         }
1.987     raeburn  9534:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  9535:         if (opendir(my $dir,$url)) {
1.987     raeburn  9536:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  9537:             map {$currfile{$_} = 1;} @dir_list;
                   9538:         }
1.1084    raeburn  9539:     } elsif (($actionurl eq '/adm/dependencies') ||
                   9540:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   9541:               ($args->{'context'} eq 'paste'))) {
1.1071    raeburn  9542:         if ($env{'request.course.id'} ne '') {
                   9543:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   9544:             if ($dir ne '') {
                   9545:                 my ($dirlistref,$listerror) =
                   9546:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   9547:                 if (ref($dirlistref) eq 'ARRAY') {
                   9548:                     foreach my $line (@{$dirlistref}) {
                   9549:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   9550:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   9551:                         unless (($testdir&$dirptr) ||
                   9552:                                 ($file_name =~ /^\.\.?$/)) {
                   9553:                             $currfile{$file_name} = [$size,$mtime];
                   9554:                         }
                   9555:                     }
                   9556:                 }
                   9557:             }
                   9558:         }
1.984     raeburn  9559:     }
                   9560:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  9561:         if (exists($currfile{$file})) {
1.987     raeburn  9562:             unless ($mapping{$file} eq $file) {
                   9563:                 $pathchanges{$file} = 1;
                   9564:             }
                   9565:             $existing{$file} = 1;
                   9566:             $numexisting ++;
                   9567:         } else {
1.984     raeburn  9568:             $newfiles{$file} = 1;
                   9569:         }
                   9570:     }
1.1071    raeburn  9571:     foreach my $file (keys(%currfile)) {
                   9572:         unless (($file eq $filename) ||
                   9573:                 ($file eq $filename.'.bak') ||
                   9574:                 ($dependencies{$file})) {
1.1085    raeburn  9575:             if ($actionurl eq '/adm/dependencies') {
                   9576:                 next if (($rem ne '') &&
                   9577:                          (($env{"httpref.$rem".$file} ne '') ||
                   9578:                           (ref($navmap) &&
                   9579:                           (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   9580:                            (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   9581:                             ($navmap->getResourceByUrl($rem.$1)))))));
                   9582:             }
1.1071    raeburn  9583:             $unused{$file} = 1;
                   9584:         }
                   9585:     }
1.1084    raeburn  9586:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   9587:         ($args->{'context'} eq 'paste')) {
                   9588:         $counter = scalar(keys(%existing));
                   9589:         $numpathchg = scalar(keys(%pathchanges));
                   9590:         return ($output,$counter,$numpathchg,\%existing); 
                   9591:     }
1.984     raeburn  9592:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  9593:         if ($actionurl eq '/adm/dependencies') {
                   9594:             next if ($embed_file =~ m{^\w+://});
                   9595:         }
1.660     raeburn  9596:         $upload_output .= &start_data_table_row().
1.1071    raeburn  9597:                           '<td><img src="'.&icon($embed_file).'" />&nbsp;'.
                   9598:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  9599:         unless ($mapping{$embed_file} eq $embed_file) {
                   9600:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.&mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
                   9601:         }
                   9602:         $upload_output .= '</td><td>';
1.1071    raeburn  9603:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.660     raeburn  9604:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
1.987     raeburn  9605:             $numremref++;
1.660     raeburn  9606:         } elsif ($args->{'error_on_invalid_names'}
                   9607:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.987     raeburn  9608:             $upload_output.='<span class="LC_warning">'.&mt('Invalid characters').'</span>';
                   9609:             $numinvalid++;
1.660     raeburn  9610:         } else {
1.1071    raeburn  9611:             $upload_output .= &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  9612:                                                      $embed_file,\%mapping,
1.1071    raeburn  9613:                                                      $allfiles,$codebase,'upload');
                   9614:             $counter ++;
                   9615:             $numnew ++;
1.987     raeburn  9616:         }
                   9617:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   9618:     }
                   9619:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  9620:         if ($actionurl eq '/adm/dependencies') {
                   9621:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   9622:             $modify_output .= &start_data_table_row().
                   9623:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   9624:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   9625:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   9626:                               '<td>'.$size.'</td>'.
                   9627:                               '<td>'.$mtime.'</td>'.
                   9628:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   9629:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   9630:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   9631:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   9632:                               &embedded_file_element('upload_embedded',$counter,
                   9633:                                                      $embed_file,\%mapping,
                   9634:                                                      $allfiles,$codebase,'modify').
                   9635:                               '</div></td>'.
                   9636:                               &end_data_table_row()."\n";
                   9637:             $counter ++;
                   9638:         } else {
                   9639:             $upload_output .= &start_data_table_row().
                   9640:                               '<td><span class="LC_filename">'.$embed_file.'</span></td>';
                   9641:                               '<td><span class="LC_warning">'.&mt('Already exists').'</span></td>'.
                   9642:                               &Apache::loncommon::end_data_table_row()."\n";
                   9643:         }
                   9644:     }
                   9645:     my $delidx = $counter;
                   9646:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   9647:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   9648:         $delete_output .= &start_data_table_row().
                   9649:                           '<td><img src="'.&icon($oldfile).'" />'.
                   9650:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   9651:                           '<td>'.$size.'</td>'.
                   9652:                           '<td>'.$mtime.'</td>'.
                   9653:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   9654:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   9655:                           &embedded_file_element('upload_embedded',$delidx,
                   9656:                                                  $oldfile,\%mapping,$allfiles,
                   9657:                                                  $codebase,'delete').'</td>'.
                   9658:                           &end_data_table_row()."\n"; 
                   9659:         $numunused ++;
                   9660:         $delidx ++;
1.987     raeburn  9661:     }
                   9662:     if ($upload_output) {
                   9663:         $upload_output = &start_data_table().
                   9664:                          $upload_output.
                   9665:                          &end_data_table()."\n";
                   9666:     }
1.1071    raeburn  9667:     if ($modify_output) {
                   9668:         $modify_output = &start_data_table().
                   9669:                          &start_data_table_header_row().
                   9670:                          '<th>'.&mt('File').'</th>'.
                   9671:                          '<th>'.&mt('Size (KB)').'</th>'.
                   9672:                          '<th>'.&mt('Modified').'</th>'.
                   9673:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   9674:                          &end_data_table_header_row().
                   9675:                          $modify_output.
                   9676:                          &end_data_table()."\n";
                   9677:     }
                   9678:     if ($delete_output) {
                   9679:         $delete_output = &start_data_table().
                   9680:                          &start_data_table_header_row().
                   9681:                          '<th>'.&mt('File').'</th>'.
                   9682:                          '<th>'.&mt('Size (KB)').'</th>'.
                   9683:                          '<th>'.&mt('Modified').'</th>'.
                   9684:                          '<th>'.&mt('Delete?').'</th>'.
                   9685:                          &end_data_table_header_row().
                   9686:                          $delete_output.
                   9687:                          &end_data_table()."\n";
                   9688:     }
1.987     raeburn  9689:     my $applies = 0;
                   9690:     if ($numremref) {
                   9691:         $applies ++;
                   9692:     }
                   9693:     if ($numinvalid) {
                   9694:         $applies ++;
                   9695:     }
                   9696:     if ($numexisting) {
                   9697:         $applies ++;
                   9698:     }
1.1071    raeburn  9699:     if ($counter || $numunused) {
1.987     raeburn  9700:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   9701:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  9702:                   $state.'<h3>'.$heading.'</h3>'; 
                   9703:         if ($actionurl eq '/adm/dependencies') {
                   9704:             if ($numnew) {
                   9705:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   9706:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   9707:                            $upload_output.'<br />'."\n";
                   9708:             }
                   9709:             if ($numexisting) {
                   9710:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   9711:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   9712:                            $modify_output.'<br />'."\n";
                   9713:                            $buttontext = &mt('Save changes');
                   9714:             }
                   9715:             if ($numunused) {
                   9716:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   9717:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   9718:                            $delete_output.'<br />'."\n";
                   9719:                            $buttontext = &mt('Save changes');
                   9720:             }
                   9721:         } else {
                   9722:             $output .= $upload_output.'<br />'."\n";
                   9723:         }
                   9724:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   9725:                    $counter.'" />'."\n";
                   9726:         if ($actionurl eq '/adm/dependencies') { 
                   9727:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   9728:                        $numnew.'" />'."\n";
                   9729:         } elsif ($actionurl eq '') {
1.987     raeburn  9730:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   9731:         }
                   9732:     } elsif ($applies) {
                   9733:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   9734:         if ($applies > 1) {
                   9735:             $output .=  
                   9736:                 &mt('No files need to be uploaded, as one of the following applies to each reference:').'<ul>';
                   9737:             if ($numremref) {
                   9738:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   9739:             }
                   9740:             if ($numinvalid) {
                   9741:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   9742:             }
                   9743:             if ($numexisting) {
                   9744:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   9745:             }
                   9746:             $output .= '</ul><br />';
                   9747:         } elsif ($numremref) {
                   9748:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   9749:         } elsif ($numinvalid) {
                   9750:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   9751:         } elsif ($numexisting) {
                   9752:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   9753:         }
                   9754:         $output .= $upload_output.'<br />';
                   9755:     }
                   9756:     my ($pathchange_output,$chgcount);
1.1071    raeburn  9757:     $chgcount = $counter;
1.987     raeburn  9758:     if (keys(%pathchanges) > 0) {
                   9759:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  9760:             if ($counter) {
1.987     raeburn  9761:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   9762:                                                   $embed_file,\%mapping,
1.1071    raeburn  9763:                                                   $allfiles,$codebase,'change');
1.987     raeburn  9764:             } else {
                   9765:                 $pathchange_output .= 
                   9766:                     &start_data_table_row().
                   9767:                     '<td><input type ="checkbox" name="namechange" value="'.
                   9768:                     $chgcount.'" checked="checked" /></td>'.
                   9769:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   9770:                     '<td>'.$embed_file.
                   9771:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  9772:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  9773:                     '</td>'.&end_data_table_row();
1.660     raeburn  9774:             }
1.987     raeburn  9775:             $numpathchg ++;
                   9776:             $chgcount ++;
1.660     raeburn  9777:         }
                   9778:     }
1.1071    raeburn  9779:     if ($counter) {
1.987     raeburn  9780:         if ($numpathchg) {
                   9781:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   9782:                        $numpathchg.'" />'."\n";
                   9783:         }
                   9784:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   9785:             ($actionurl eq '/adm/imsimport')) {
                   9786:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   9787:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   9788:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  9789:         } elsif ($actionurl eq '/adm/dependencies') {
                   9790:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  9791:         }
1.1071    raeburn  9792:         $output .=  '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  9793:     } elsif ($numpathchg) {
                   9794:         my %pathchange = ();
                   9795:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   9796:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   9797:             $output .= '<p>'.&mt('or').'</p>'; 
                   9798:         } 
                   9799:     }
1.1071    raeburn  9800:     return ($output,$counter,$numpathchg);
1.987     raeburn  9801: }
                   9802: 
                   9803: sub embedded_file_element {
1.1071    raeburn  9804:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  9805:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   9806:                    (ref($codebase) eq 'HASH'));
                   9807:     my $output;
1.1071    raeburn  9808:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  9809:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   9810:     }
                   9811:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   9812:                &escape($embed_file).'" />';
                   9813:     unless (($context eq 'upload_embedded') && 
                   9814:             ($mapping->{$embed_file} eq $embed_file)) {
                   9815:         $output .='
                   9816:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   9817:     }
                   9818:     my $attrib;
                   9819:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   9820:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   9821:     }
                   9822:     $output .=
                   9823:         "\n\t\t".
                   9824:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   9825:         $attrib.'" />';
                   9826:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   9827:         $output .=
                   9828:             "\n\t\t".
                   9829:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   9830:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  9831:     }
1.987     raeburn  9832:     return $output;
1.660     raeburn  9833: }
                   9834: 
1.1071    raeburn  9835: sub get_dependency_details {
                   9836:     my ($currfile,$currsubfile,$embed_file) = @_;
                   9837:     my ($size,$mtime,$showsize,$showmtime);
                   9838:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   9839:         if ($embed_file =~ m{/}) {
                   9840:             my ($path,$fname) = split(/\//,$embed_file);
                   9841:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   9842:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   9843:             }
                   9844:         } else {
                   9845:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   9846:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   9847:             }
                   9848:         }
                   9849:         $showsize = $size/1024.0;
                   9850:         $showsize = sprintf("%.1f",$showsize);
                   9851:         if ($mtime > 0) {
                   9852:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   9853:         }
                   9854:     }
                   9855:     return ($showsize,$showmtime);
                   9856: }
                   9857: 
                   9858: sub ask_embedded_js {
                   9859:     return <<"END";
                   9860: <script type="text/javascript"">
                   9861: // <![CDATA[
                   9862: function toggleBrowse(counter) {
                   9863:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   9864:     var fileid = document.getElementById('embedded_item_'+counter);
                   9865:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   9866:     if (chkboxid.checked == true) {
                   9867:         uploaddivid.style.display='block';
                   9868:     } else {
                   9869:         uploaddivid.style.display='none';
                   9870:         fileid.value = '';
                   9871:     }
                   9872: }
                   9873: // ]]>
                   9874: </script>
                   9875: 
                   9876: END
                   9877: }
                   9878: 
1.661     raeburn  9879: sub upload_embedded {
                   9880:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  9881:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   9882:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  9883:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   9884:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   9885:         my $orig_uploaded_filename =
                   9886:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  9887:         foreach my $type ('orig','ref','attrib','codebase') {
                   9888:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   9889:                 $env{'form.embedded_'.$type.'_'.$i} =
                   9890:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   9891:             }
                   9892:         }
1.661     raeburn  9893:         my ($path,$fname) =
                   9894:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   9895:         # no path, whole string is fname
                   9896:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   9897:         $fname = &Apache::lonnet::clean_filename($fname);
                   9898:         # See if there is anything left
                   9899:         next if ($fname eq '');
                   9900: 
                   9901:         # Check if file already exists as a file or directory.
                   9902:         my ($state,$msg);
                   9903:         if ($context eq 'portfolio') {
                   9904:             my $port_path = $dirpath;
                   9905:             if ($group ne '') {
                   9906:                 $port_path = "groups/$group/$port_path";
                   9907:             }
1.987     raeburn  9908:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   9909:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  9910:                                               $dir_root,$port_path,$disk_quota,
                   9911:                                               $current_disk_usage,$uname,$udom);
                   9912:             if ($state eq 'will_exceed_quota'
1.984     raeburn  9913:                 || $state eq 'file_locked') {
1.661     raeburn  9914:                 $output .= $msg;
                   9915:                 next;
                   9916:             }
                   9917:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   9918:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   9919:             if ($state eq 'exists') {
                   9920:                 $output .= $msg;
                   9921:                 next;
                   9922:             }
                   9923:         }
                   9924:         # Check if extension is valid
                   9925:         if (($fname =~ /\.(\w+)$/) &&
                   9926:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.987     raeburn  9927:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1).'<br />';
1.661     raeburn  9928:             next;
                   9929:         } elsif (($fname =~ /\.(\w+)$/) &&
                   9930:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  9931:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  9932:             next;
                   9933:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.987     raeburn  9934:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
1.661     raeburn  9935:             next;
                   9936:         }
                   9937:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
                   9938:         if ($context eq 'portfolio') {
1.984     raeburn  9939:             my $result;
                   9940:             if ($state eq 'existingfile') {
                   9941:                 $result=
                   9942:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.987     raeburn  9943:                                                     $dirpath.$env{'form.currentpath'}.$path);
1.661     raeburn  9944:             } else {
1.984     raeburn  9945:                 $result=
                   9946:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  9947:                                                     $dirpath.
                   9948:                                                     $env{'form.currentpath'}.$path);
1.984     raeburn  9949:                 if ($result !~ m|^/uploaded/|) {
                   9950:                     $output .= '<span class="LC_error">'
                   9951:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   9952:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   9953:                                .'</span><br />';
                   9954:                     next;
                   9955:                 } else {
1.987     raeburn  9956:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   9957:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  9958:                 }
1.661     raeburn  9959:             }
1.987     raeburn  9960:         } elsif ($context eq 'coursedoc') {
                   9961:             my $result =
                   9962:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'coursedoc',
                   9963:                                                 $dirpath.'/'.$path);
                   9964:             if ($result !~ m|^/uploaded/|) {
                   9965:                 $output .= '<span class="LC_error">'
                   9966:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   9967:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   9968:                            .'</span><br />';
                   9969:                     next;
                   9970:             } else {
                   9971:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   9972:                            $path.$fname.'</span>').'<br />';
                   9973:             }
1.661     raeburn  9974:         } else {
                   9975: # Save the file
                   9976:             my $target = $env{'form.embedded_item_'.$i};
                   9977:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   9978:             my $dest = $fullpath.$fname;
                   9979:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  9980:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  9981:             my $count;
                   9982:             my $filepath = $dir_root;
1.1027    raeburn  9983:             foreach my $subdir (@parts) {
                   9984:                 $filepath .= "/$subdir";
                   9985:                 if (!-e $filepath) {
1.661     raeburn  9986:                     mkdir($filepath,0770);
                   9987:                 }
                   9988:             }
                   9989:             my $fh;
                   9990:             if (!open($fh,'>'.$dest)) {
                   9991:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   9992:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  9993:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   9994:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  9995:                            '</span><br />';
                   9996:             } else {
                   9997:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   9998:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   9999:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  10000:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   10001:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  10002:                               '</span><br />';
                   10003:                 } else {
1.987     raeburn  10004:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10005:                                $url.'</span>').'<br />';
                   10006:                     unless ($context eq 'testbank') {
                   10007:                         $footer .= &mt('View embedded file: [_1]',
                   10008:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   10009:                     }
                   10010:                 }
                   10011:                 close($fh);
                   10012:             }
                   10013:         }
                   10014:         if ($env{'form.embedded_ref_'.$i}) {
                   10015:             $pathchange{$i} = 1;
                   10016:         }
                   10017:     }
                   10018:     if ($output) {
                   10019:         $output = '<p>'.$output.'</p>';
                   10020:     }
                   10021:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   10022:     $returnflag = 'ok';
1.1071    raeburn  10023:     my $numpathchgs = scalar(keys(%pathchange));
                   10024:     if ($numpathchgs > 0) {
1.987     raeburn  10025:         if ($context eq 'portfolio') {
                   10026:             $output .= '<p>'.&mt('or').'</p>';
                   10027:         } elsif ($context eq 'testbank') {
1.1071    raeburn  10028:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   10029:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  10030:             $returnflag = 'modify_orightml';
                   10031:         }
                   10032:     }
1.1071    raeburn  10033:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  10034: }
                   10035: 
                   10036: sub modify_html_form {
                   10037:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   10038:     my $end = 0;
                   10039:     my $modifyform;
                   10040:     if ($context eq 'upload_embedded') {
                   10041:         return unless (ref($pathchange) eq 'HASH');
                   10042:         if ($env{'form.number_embedded_items'}) {
                   10043:             $end += $env{'form.number_embedded_items'};
                   10044:         }
                   10045:         if ($env{'form.number_pathchange_items'}) {
                   10046:             $end += $env{'form.number_pathchange_items'};
                   10047:         }
                   10048:         if ($end) {
                   10049:             for (my $i=0; $i<$end; $i++) {
                   10050:                 if ($i < $env{'form.number_embedded_items'}) {
                   10051:                     next unless($pathchange->{$i});
                   10052:                 }
                   10053:                 $modifyform .=
                   10054:                     &start_data_table_row().
                   10055:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   10056:                     'checked="checked" /></td>'.
                   10057:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   10058:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   10059:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   10060:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   10061:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   10062:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   10063:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   10064:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   10065:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   10066:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   10067:                     &end_data_table_row();
1.1071    raeburn  10068:             }
1.987     raeburn  10069:         }
                   10070:     } else {
                   10071:         $modifyform = $pathchgtable;
                   10072:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   10073:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   10074:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   10075:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   10076:         }
                   10077:     }
                   10078:     if ($modifyform) {
1.1071    raeburn  10079:         if ($actionurl eq '/adm/dependencies') {
                   10080:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   10081:         }
1.987     raeburn  10082:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   10083:                '<p>'.&mt('Changes need to be made to the reference(s) used for one or more of the dependencies, if your HTML file is to work correctly:').'<ol>'."\n".
                   10084:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   10085:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   10086:                '</ol></p>'."\n".'<p>'.
                   10087:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   10088:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   10089:                &start_data_table()."\n".
                   10090:                &start_data_table_header_row().
                   10091:                '<th>'.&mt('Change?').'</th>'.
                   10092:                '<th>'.&mt('Current reference').'</th>'.
                   10093:                '<th>'.&mt('Required reference').'</th>'.
                   10094:                &end_data_table_header_row()."\n".
                   10095:                $modifyform.
                   10096:                &end_data_table().'<br />'."\n".$hiddenstate.
                   10097:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   10098:                '</form>'."\n";
                   10099:     }
                   10100:     return;
                   10101: }
                   10102: 
                   10103: sub modify_html_refs {
                   10104:     my ($context,$dirpath,$uname,$udom,$dir_root) = @_;
                   10105:     my $container;
                   10106:     if ($context eq 'portfolio') {
                   10107:         $container = $env{'form.container'};
                   10108:     } elsif ($context eq 'coursedoc') {
                   10109:         $container = $env{'form.primaryurl'};
1.1071    raeburn  10110:     } elsif ($context eq 'manage_dependencies') {
                   10111:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   10112:         $container = "/$container";
1.987     raeburn  10113:     } else {
1.1027    raeburn  10114:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  10115:     }
                   10116:     my (%allfiles,%codebase,$output,$content);
                   10117:     my @changes = &get_env_multiple('form.namechange');
1.1071    raeburn  10118:     unless (@changes > 0) {
                   10119:         if (wantarray) {
                   10120:             return ('',0,0); 
                   10121:         } else {
                   10122:             return;
                   10123:         }
                   10124:     }
                   10125:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
                   10126:         ($context eq 'manage_dependencies')) {
                   10127:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   10128:             if (wantarray) {
                   10129:                 return ('',0,0);
                   10130:             } else {
                   10131:                 return;
                   10132:             }
                   10133:         } 
1.987     raeburn  10134:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  10135:         if ($content eq '-1') {
                   10136:             if (wantarray) {
                   10137:                 return ('',0,0);
                   10138:             } else {
                   10139:                 return;
                   10140:             }
                   10141:         }
1.987     raeburn  10142:     } else {
1.1071    raeburn  10143:         unless ($container =~ /^\Q$dir_root\E/) {
                   10144:             if (wantarray) {
                   10145:                 return ('',0,0);
                   10146:             } else {
                   10147:                 return;
                   10148:             }
                   10149:         } 
1.987     raeburn  10150:         if (open(my $fh,"<$container")) {
                   10151:             $content = join('', <$fh>);
                   10152:             close($fh);
                   10153:         } else {
1.1071    raeburn  10154:             if (wantarray) {
                   10155:                 return ('',0,0);
                   10156:             } else {
                   10157:                 return;
                   10158:             }
1.987     raeburn  10159:         }
                   10160:     }
                   10161:     my ($count,$codebasecount) = (0,0);
                   10162:     my $mm = new File::MMagic;
                   10163:     my $mime_type = $mm->checktype_contents($content);
                   10164:     if ($mime_type eq 'text/html') {
                   10165:         my $parse_result = 
                   10166:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   10167:                                                     \%codebase,\$content);
                   10168:         if ($parse_result eq 'ok') {
                   10169:             foreach my $i (@changes) {
                   10170:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   10171:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   10172:                 if ($allfiles{$ref}) {
                   10173:                     my $newname =  $orig;
                   10174:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  10175:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  10176:                     if ($attrib_regexp =~ /:/) {
                   10177:                         $attrib_regexp =~ s/\:/|/g;
                   10178:                     }
                   10179:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   10180:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   10181:                         $count += $numchg;
                   10182:                     }
                   10183:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  10184:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  10185:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   10186:                         $codebasecount ++;
                   10187:                     }
                   10188:                 }
                   10189:             }
                   10190:             if ($count || $codebasecount) {
                   10191:                 my $saveresult;
1.1071    raeburn  10192:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
                   10193:                     ($context eq 'manage_dependencies')) {
1.987     raeburn  10194:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   10195:                     if ($url eq $container) {
                   10196:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   10197:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   10198:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  10199:                                             $fname.'</span>').'</p>';
1.987     raeburn  10200:                     } else {
                   10201:                          $output = '<p class="LC_error">'.
                   10202:                                    &mt('Error: update failed for: [_1].',
                   10203:                                    '<span class="LC_filename">'.
                   10204:                                    $container.'</span>').'</p>';
                   10205:                     }
                   10206:                 } else {
                   10207:                     if (open(my $fh,">$container")) {
                   10208:                         print $fh $content;
                   10209:                         close($fh);
                   10210:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   10211:                                   $count,'<span class="LC_filename">'.
                   10212:                                   $container.'</span>').'</p>';
1.661     raeburn  10213:                     } else {
1.987     raeburn  10214:                          $output = '<p class="LC_error">'.
                   10215:                                    &mt('Error: could not update [_1].',
                   10216:                                    '<span class="LC_filename">'.
                   10217:                                    $container.'</span>').'</p>';
1.661     raeburn  10218:                     }
                   10219:                 }
                   10220:             }
1.987     raeburn  10221:         } else {
                   10222:             &logthis('Failed to parse '.$container.
                   10223:                      ' to modify references: '.$parse_result);
1.661     raeburn  10224:         }
                   10225:     }
1.1071    raeburn  10226:     if (wantarray) {
                   10227:         return ($output,$count,$codebasecount);
                   10228:     } else {
                   10229:         return $output;
                   10230:     }
1.661     raeburn  10231: }
                   10232: 
                   10233: sub check_for_existing {
                   10234:     my ($path,$fname,$element) = @_;
                   10235:     my ($state,$msg);
                   10236:     if (-d $path.'/'.$fname) {
                   10237:         $state = 'exists';
                   10238:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   10239:     } elsif (-e $path.'/'.$fname) {
                   10240:         $state = 'exists';
                   10241:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   10242:     }
                   10243:     if ($state eq 'exists') {
                   10244:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   10245:     }
                   10246:     return ($state,$msg);
                   10247: }
                   10248: 
                   10249: sub check_for_upload {
                   10250:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   10251:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  10252:     my $filesize = length($env{'form.'.$element});
                   10253:     if (!$filesize) {
                   10254:         my $msg = '<span class="LC_error">'.
                   10255:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   10256:                       '<span class="LC_filename">'.$fname.'</span>',
                   10257:                       $filesize).'<br />'.
1.1007    raeburn  10258:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  10259:                   '</span>';
                   10260:         return ('zero_bytes',$msg);
                   10261:     }
                   10262:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  10263:     my $getpropath = 1;
1.1021    raeburn  10264:     my ($dirlistref,$listerror) =
                   10265:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  10266:     my $found_file = 0;
                   10267:     my $locked_file = 0;
1.991     raeburn  10268:     my @lockers;
                   10269:     my $navmap;
                   10270:     if ($env{'request.course.id'}) {
                   10271:         $navmap = Apache::lonnavmaps::navmap->new();
                   10272:     }
1.1021    raeburn  10273:     if (ref($dirlistref) eq 'ARRAY') {
                   10274:         foreach my $line (@{$dirlistref}) {
                   10275:             my ($file_name,$rest)=split(/\&/,$line,2);
                   10276:             if ($file_name eq $fname){
                   10277:                 $file_name = $path.$file_name;
                   10278:                 if ($group ne '') {
                   10279:                     $file_name = $group.$file_name;
                   10280:                 }
                   10281:                 $found_file = 1;
                   10282:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   10283:                     foreach my $lock (@lockers) {
                   10284:                         if (ref($lock) eq 'ARRAY') {
                   10285:                             my ($symb,$crsid) = @{$lock};
                   10286:                             if ($crsid eq $env{'request.course.id'}) {
                   10287:                                 if (ref($navmap)) {
                   10288:                                     my $res = $navmap->getBySymb($symb);
                   10289:                                     foreach my $part (@{$res->parts()}) { 
                   10290:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   10291:                                         unless (($slot_status == $res->RESERVED) ||
                   10292:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   10293:                                             $locked_file = 1;
                   10294:                                         }
1.991     raeburn  10295:                                     }
1.1021    raeburn  10296:                                 } else {
                   10297:                                     $locked_file = 1;
1.991     raeburn  10298:                                 }
                   10299:                             } else {
                   10300:                                 $locked_file = 1;
                   10301:                             }
                   10302:                         }
1.1021    raeburn  10303:                    }
                   10304:                 } else {
                   10305:                     my @info = split(/\&/,$rest);
                   10306:                     my $currsize = $info[6]/1000;
                   10307:                     if ($currsize < $filesize) {
                   10308:                         my $extra = $filesize - $currsize;
                   10309:                         if (($current_disk_usage + $extra) > $disk_quota) {
                   10310:                             my $msg = '<span class="LC_error">'.
                   10311:                                       &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded if existing (smaller) file with same name (size = [_3] kilobytes) is replaced.',
                   10312:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
                   10313:                                       '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   10314:                                                    $disk_quota,$current_disk_usage);
                   10315:                             return ('will_exceed_quota',$msg);
                   10316:                         }
1.984     raeburn  10317:                     }
                   10318:                 }
1.661     raeburn  10319:             }
                   10320:         }
                   10321:     }
                   10322:     if (($current_disk_usage + $filesize) > $disk_quota){
                   10323:         my $msg = '<span class="LC_error">'.
                   10324:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
                   10325:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
                   10326:         return ('will_exceed_quota',$msg);
                   10327:     } elsif ($found_file) {
                   10328:         if ($locked_file) {
                   10329:             my $msg = '<span class="LC_error">';
                   10330:             $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>');
                   10331:             $msg .= '</span><br />';
                   10332:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   10333:             return ('file_locked',$msg);
                   10334:         } else {
                   10335:             my $msg = '<span class="LC_error">';
1.984     raeburn  10336:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
1.661     raeburn  10337:             $msg .= '</span>';
1.984     raeburn  10338:             return ('existingfile',$msg);
1.661     raeburn  10339:         }
                   10340:     }
                   10341: }
                   10342: 
1.987     raeburn  10343: sub check_for_traversal {
                   10344:     my ($path,$url,$toplevel) = @_;
                   10345:     my @parts=split(/\//,$path);
                   10346:     my $cleanpath;
                   10347:     my $fullpath = $url;
                   10348:     for (my $i=0;$i<@parts;$i++) {
                   10349:         next if ($parts[$i] eq '.');
                   10350:         if ($parts[$i] eq '..') {
                   10351:             $fullpath =~ s{([^/]+/)$}{};
                   10352:         } else {
                   10353:             $fullpath .= $parts[$i].'/';
                   10354:         }
                   10355:     }
                   10356:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   10357:         $cleanpath = $1;
                   10358:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   10359:         my $curr_toprel = $1;
                   10360:         my @parts = split(/\//,$curr_toprel);
                   10361:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   10362:         my @urlparts = split(/\//,$url_toprel);
                   10363:         my $doubledots;
                   10364:         my $startdiff = -1;
                   10365:         for (my $i=0; $i<@urlparts; $i++) {
                   10366:             if ($startdiff == -1) {
                   10367:                 unless ($urlparts[$i] eq $parts[$i]) {
                   10368:                     $startdiff = $i;
                   10369:                     $doubledots .= '../';
                   10370:                 }
                   10371:             } else {
                   10372:                 $doubledots .= '../';
                   10373:             }
                   10374:         }
                   10375:         if ($startdiff > -1) {
                   10376:             $cleanpath = $doubledots;
                   10377:             for (my $i=$startdiff; $i<@parts; $i++) {
                   10378:                 $cleanpath .= $parts[$i].'/';
                   10379:             }
                   10380:         }
                   10381:     }
                   10382:     $cleanpath =~ s{(/)$}{};
                   10383:     return $cleanpath;
                   10384: }
1.31      albertel 10385: 
1.1053    raeburn  10386: sub is_archive_file {
                   10387:     my ($mimetype) = @_;
                   10388:     if (($mimetype eq 'application/octet-stream') ||
                   10389:         ($mimetype eq 'application/x-stuffit') ||
                   10390:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   10391:         return 1;
                   10392:     }
                   10393:     return;
                   10394: }
                   10395: 
                   10396: sub decompress_form {
1.1065    raeburn  10397:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  10398:     my %lt = &Apache::lonlocal::texthash (
                   10399:         this => 'This file is an archive file.',
1.1067    raeburn  10400:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  10401:         itsc => 'Its contents are as follows:',
1.1053    raeburn  10402:         youm => 'You may wish to extract its contents.',
                   10403:         extr => 'Extract contents',
1.1067    raeburn  10404:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   10405:         proa => 'Process automatically?',
1.1053    raeburn  10406:         yes  => 'Yes',
                   10407:         no   => 'No',
1.1067    raeburn  10408:         fold => 'Title for folder containing movie',
                   10409:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  10410:     );
1.1065    raeburn  10411:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  10412:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  10413:     my $info = &list_archive_contents($fileloc,\@paths);
                   10414:     if (@paths) {
                   10415:         foreach my $path (@paths) {
                   10416:             $path =~ s{^/}{};
1.1067    raeburn  10417:             if ($path =~ m{^([^/]+)/$}) {
                   10418:                 $topdir = $1;
                   10419:             }
1.1065    raeburn  10420:             if ($path =~ m{^([^/]+)/}) {
                   10421:                 $toplevel{$1} = $path;
                   10422:             } else {
                   10423:                 $toplevel{$path} = $path;
                   10424:             }
                   10425:         }
                   10426:     }
1.1067    raeburn  10427:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
                   10428:         my @camtasia = ("$topdir/","$topdir/index.html",
                   10429:                         "$topdir/media/",
                   10430:                         "$topdir/media/$topdir.mp4",
                   10431:                         "$topdir/media/FirstFrame.png",
                   10432:                         "$topdir/media/player.swf",
                   10433:                         "$topdir/media/swfobject.js",
                   10434:                         "$topdir/media/expressInstall.swf");
                   10435:         my @diffs = &compare_arrays(\@paths,\@camtasia);
                   10436:         if (@diffs == 0) {
                   10437:             $is_camtasia = 1;
                   10438:         }
                   10439:     }
                   10440:     my $output;
                   10441:     if ($is_camtasia) {
                   10442:         $output = <<"ENDCAM";
                   10443: <script type="text/javascript" language="Javascript">
                   10444: // <![CDATA[
                   10445: 
                   10446: function camtasiaToggle() {
                   10447:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   10448:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
                   10449:             if (document.uploaded_decompress.autoextract_camtasia[i].value == 1) {
                   10450: 
                   10451:                 document.getElementById('camtasia_titles').style.display='block';
                   10452:             } else {
                   10453:                 document.getElementById('camtasia_titles').style.display='none';
                   10454:             }
                   10455:         }
                   10456:     }
                   10457:     return;
                   10458: }
                   10459: 
                   10460: // ]]>
                   10461: </script>
                   10462: <p>$lt{'camt'}</p>
                   10463: ENDCAM
1.1065    raeburn  10464:     } else {
1.1067    raeburn  10465:         $output = '<p>'.$lt{'this'};
                   10466:         if ($info eq '') {
                   10467:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   10468:         } else {
                   10469:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   10470:                        '<div><pre>'.$info.'</pre></div>';
                   10471:         }
1.1065    raeburn  10472:     }
1.1067    raeburn  10473:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  10474:     my $duplicates;
                   10475:     my $num = 0;
                   10476:     if (ref($dirlist) eq 'ARRAY') {
                   10477:         foreach my $item (@{$dirlist}) {
                   10478:             if (ref($item) eq 'ARRAY') {
                   10479:                 if (exists($toplevel{$item->[0]})) {
                   10480:                     $duplicates .= 
                   10481:                         &start_data_table_row().
                   10482:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   10483:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   10484:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   10485:                         'value="1" />'.&mt('Yes').'</label>'.
                   10486:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   10487:                         '<td>'.$item->[0].'</td>';
                   10488:                     if ($item->[2]) {
                   10489:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   10490:                     } else {
                   10491:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   10492:                     }
                   10493:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   10494:                                    '<td>'.
                   10495:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   10496:                                    '</td>'.
                   10497:                                    &end_data_table_row();
                   10498:                     $num ++;
                   10499:                 }
                   10500:             }
                   10501:         }
                   10502:     }
                   10503:     my $itemcount;
                   10504:     if (@paths > 0) {
                   10505:         $itemcount = scalar(@paths);
                   10506:     } else {
                   10507:         $itemcount = 1;
                   10508:     }
1.1067    raeburn  10509:     if ($is_camtasia) {
                   10510:         $output .= $lt{'auto'}.'<br />'.
                   10511:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
                   10512:                    '<input type="radio" name="autoextract_camtasia" value="1" onclick="javascript:camtasiaToggle();" checked="checked" />'.
                   10513:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   10514:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   10515:                    $lt{'no'}.'</label></span><br />'.
                   10516:                    '<div id="camtasia_titles" style="display:block">'.
                   10517:                    &Apache::lonhtmlcommon::start_pick_box().
                   10518:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   10519:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   10520:                    &Apache::lonhtmlcommon::row_closure().
                   10521:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   10522:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   10523:                    &Apache::lonhtmlcommon::row_closure(1).
                   10524:                    &Apache::lonhtmlcommon::end_pick_box().
                   10525:                    '</div>';
                   10526:     }
1.1065    raeburn  10527:     $output .= 
                   10528:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  10529:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   10530:         "\n";
1.1065    raeburn  10531:     if ($duplicates ne '') {
                   10532:         $output .= '<p><span class="LC_warning">'.
                   10533:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   10534:                    &start_data_table().
                   10535:                    &start_data_table_header_row().
                   10536:                    '<th>'.&mt('Overwrite?').'</th>'.
                   10537:                    '<th>'.&mt('Name').'</th>'.
                   10538:                    '<th>'.&mt('Type').'</th>'.
                   10539:                    '<th>'.&mt('Size').'</th>'.
                   10540:                    '<th>'.&mt('Last modified').'</th>'.
                   10541:                    &end_data_table_header_row().
                   10542:                    $duplicates.
                   10543:                    &end_data_table().
                   10544:                    '</p>';
                   10545:     }
1.1067    raeburn  10546:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  10547:     if (ref($hiddenelements) eq 'HASH') {
                   10548:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   10549:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   10550:         }
                   10551:     }
                   10552:     $output .= <<"END";
1.1067    raeburn  10553: <br />
1.1053    raeburn  10554: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   10555: </form>
                   10556: $noextract
                   10557: END
                   10558:     return $output;
                   10559: }
                   10560: 
1.1065    raeburn  10561: sub decompression_utility {
                   10562:     my ($program) = @_;
                   10563:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   10564:     my $location;
                   10565:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   10566:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   10567:                          '/usr/sbin/') {
                   10568:             if (-x $dir.$program) {
                   10569:                 $location = $dir.$program;
                   10570:                 last;
                   10571:             }
                   10572:         }
                   10573:     }
                   10574:     return $location;
                   10575: }
                   10576: 
                   10577: sub list_archive_contents {
                   10578:     my ($file,$pathsref) = @_;
                   10579:     my (@cmd,$output);
                   10580:     my $needsregexp;
                   10581:     if ($file =~ /\.zip$/) {
                   10582:         @cmd = (&decompression_utility('unzip'),"-l");
                   10583:         $needsregexp = 1;
                   10584:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   10585:              ($file =~ /\.tgz$/)) {
                   10586:         @cmd = (&decompression_utility('tar'),"-ztf");
                   10587:     } elsif ($file =~ /\.tar\.bz2$/) {
                   10588:         @cmd = (&decompression_utility('tar'),"-jtf");
                   10589:     } elsif ($file =~ m|\.tar$|) {
                   10590:         @cmd = (&decompression_utility('tar'),"-tf");
                   10591:     }
                   10592:     if (@cmd) {
                   10593:         undef($!);
                   10594:         undef($@);
                   10595:         if (open(my $fh,"-|", @cmd, $file)) {
                   10596:             while (my $line = <$fh>) {
                   10597:                 $output .= $line;
                   10598:                 chomp($line);
                   10599:                 my $item;
                   10600:                 if ($needsregexp) {
                   10601:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   10602:                 } else {
                   10603:                     $item = $line;
                   10604:                 }
                   10605:                 if ($item ne '') {
                   10606:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   10607:                         push(@{$pathsref},$item);
                   10608:                     } 
                   10609:                 }
                   10610:             }
                   10611:             close($fh);
                   10612:         }
                   10613:     }
                   10614:     return $output;
                   10615: }
                   10616: 
1.1053    raeburn  10617: sub decompress_uploaded_file {
                   10618:     my ($file,$dir) = @_;
                   10619:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   10620:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   10621:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   10622:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   10623:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   10624:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   10625:     my $decompressed = $env{'cgi.decompressed'};
                   10626:     &Apache::lonnet::delenv('cgi.file');
                   10627:     &Apache::lonnet::delenv('cgi.dir');
                   10628:     &Apache::lonnet::delenv('cgi.decompressed');
                   10629:     return ($decompressed,$result);
                   10630: }
                   10631: 
1.1055    raeburn  10632: sub process_decompression {
                   10633:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   10634:     my ($dir,$error,$warning,$output);
                   10635:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
                   10636:         $error = &mt('File name not a supported archive file type.').
                   10637:                  '<br />'.&mt('File name should end with one of: [_1].',
                   10638:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   10639:     } else {
                   10640:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   10641:         if ($docuhome eq 'no_host') {
                   10642:             $error = &mt('Could not determine home server for course.');
                   10643:         } else {
                   10644:             my @ids=&Apache::lonnet::current_machine_ids();
                   10645:             my $currdir = "$dir_root/$destination";
                   10646:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   10647:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   10648:                        "$dir_root/$destination";
                   10649:             } else {
                   10650:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   10651:                        "$dir_root/$docudom/$docuname/$destination";
                   10652:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   10653:                     $error = &mt('Archive file not found.');
                   10654:                 }
                   10655:             }
1.1065    raeburn  10656:             my (@to_overwrite,@to_skip);
                   10657:             if ($env{'form.archive_overwrite_total'} > 0) {
                   10658:                 my $total = $env{'form.archive_overwrite_total'};
                   10659:                 for (my $i=0; $i<$total; $i++) {
                   10660:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   10661:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   10662:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   10663:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   10664:                     }
                   10665:                 }
                   10666:             }
                   10667:             my $numskip = scalar(@to_skip);
                   10668:             if (($numskip > 0) && 
                   10669:                 ($numskip == $env{'form.archive_itemcount'})) {
                   10670:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   10671:             } elsif ($dir eq '') {
1.1055    raeburn  10672:                 $error = &mt('Directory containing archive file unavailable.');
                   10673:             } elsif (!$error) {
1.1065    raeburn  10674:                 my ($decompressed,$display);
                   10675:                 if ($numskip > 0) {
                   10676:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   10677:                     mkdir("$dir/$tempdir",0755);
                   10678:                     system("mv $dir/$file $dir/$tempdir/$file");
                   10679:                     ($decompressed,$display) = 
                   10680:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   10681:                     foreach my $item (@to_skip) {
                   10682:                         if (($item ne '') && ($item !~ /\.\./)) {
                   10683:                             if (-f "$dir/$tempdir/$item") { 
                   10684:                                 unlink("$dir/$tempdir/$item");
                   10685:                             } elsif (-d "$dir/$tempdir/$item") {
                   10686:                                 system("rm -rf $dir/$tempdir/$item");
                   10687:                             }
                   10688:                         }
                   10689:                     }
                   10690:                     system("mv $dir/$tempdir/* $dir");
                   10691:                     rmdir("$dir/$tempdir");   
                   10692:                 } else {
                   10693:                     ($decompressed,$display) = 
                   10694:                         &decompress_uploaded_file($file,$dir);
                   10695:                 }
1.1055    raeburn  10696:                 if ($decompressed eq 'ok') {
1.1065    raeburn  10697:                     $output = '<p class="LC_info">'.
                   10698:                               &mt('Files extracted successfully from archive.').
                   10699:                               '</p>'."\n";
1.1055    raeburn  10700:                     my ($warning,$result,@contents);
                   10701:                     my ($newdirlistref,$newlisterror) =
                   10702:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   10703:                                                  $docuname,1);
                   10704:                     my (%is_dir,%changes,@newitems);
                   10705:                     my $dirptr = 16384;
1.1065    raeburn  10706:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  10707:                         foreach my $dir_line (@{$newdirlistref}) {
                   10708:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  10709:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   10710:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  10711:                                 push(@newitems,$item);
                   10712:                                 if ($dirptr&$testdir) {
                   10713:                                     $is_dir{$item} = 1;
                   10714:                                 }
                   10715:                                 $changes{$item} = 1;
                   10716:                             }
                   10717:                         }
                   10718:                     }
                   10719:                     if (keys(%changes) > 0) {
                   10720:                         foreach my $item (sort(@newitems)) {
                   10721:                             if ($changes{$item}) {
                   10722:                                 push(@contents,$item);
                   10723:                             }
                   10724:                         }
                   10725:                     }
                   10726:                     if (@contents > 0) {
1.1067    raeburn  10727:                         my $wantform;
                   10728:                         unless ($env{'form.autoextract_camtasia'}) {
                   10729:                             $wantform = 1;
                   10730:                         }
1.1056    raeburn  10731:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  10732:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   10733:                                                                 $currdir,\%is_dir,
                   10734:                                                                 \%children,\%parent,
1.1056    raeburn  10735:                                                                 \@contents,\%dirorder,
                   10736:                                                                 \%titles,$wantform);
1.1055    raeburn  10737:                         if ($datatable ne '') {
                   10738:                             $output .= &archive_options_form('decompressed',$datatable,
                   10739:                                                              $count,$hiddenelem);
1.1065    raeburn  10740:                             my $startcount = 6;
1.1055    raeburn  10741:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  10742:                                                            \%titles,\%children);
1.1055    raeburn  10743:                         }
1.1067    raeburn  10744:                         if ($env{'form.autoextract_camtasia'}) {
                   10745:                             my %displayed;
                   10746:                             my $total = 1;
                   10747:                             $env{'form.archive_directory'} = [];
                   10748:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   10749:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   10750:                                 $path =~ s{/$}{};
                   10751:                                 my $item;
                   10752:                                 if ($path ne '') {
                   10753:                                     $item = "$path/$titles{$i}";
                   10754:                                 } else {
                   10755:                                     $item = $titles{$i};
                   10756:                                 }
                   10757:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   10758:                                 if ($item eq $contents[0]) {
                   10759:                                     push(@{$env{'form.archive_directory'}},$i);
                   10760:                                     $env{'form.archive_'.$i} = 'display';
                   10761:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   10762:                                     $displayed{'folder'} = $i;
                   10763:                                 } elsif ($item eq "$contents[0]/index.html") {
                   10764:                                     $env{'form.archive_'.$i} = 'display';
                   10765:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   10766:                                     $displayed{'web'} = $i;
                   10767:                                 } else {
                   10768:                                     if ($item eq "$contents[0]/media") {
                   10769:                                         push(@{$env{'form.archive_directory'}},$i);
                   10770:                                     }
                   10771:                                     $env{'form.archive_'.$i} = 'dependency';
                   10772:                                 }
                   10773:                                 $total ++;
                   10774:                             }
                   10775:                             for (my $i=1; $i<$total; $i++) {
                   10776:                                 next if ($i == $displayed{'web'});
                   10777:                                 next if ($i == $displayed{'folder'});
                   10778:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   10779:                             }
                   10780:                             $env{'form.phase'} = 'decompress_cleanup';
                   10781:                             $env{'form.archivedelete'} = 1;
                   10782:                             $env{'form.archive_count'} = $total-1;
                   10783:                             $output .=
                   10784:                                 &process_extracted_files('coursedocs',$docudom,
                   10785:                                                          $docuname,$destination,
                   10786:                                                          $dir_root,$hiddenelem);
                   10787:                         }
1.1055    raeburn  10788:                     } else {
                   10789:                         $warning = &mt('No new items extracted from archive file.');
                   10790:                     }
                   10791:                 } else {
                   10792:                     $output = $display;
                   10793:                     $error = &mt('An error occurred during extraction from the archive file.');
                   10794:                 }
                   10795:             }
                   10796:         }
                   10797:     }
                   10798:     if ($error) {
                   10799:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   10800:                    $error.'</p>'."\n";
                   10801:     }
                   10802:     if ($warning) {
                   10803:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   10804:     }
                   10805:     return $output;
                   10806: }
                   10807: 
                   10808: sub get_extracted {
1.1056    raeburn  10809:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   10810:         $titles,$wantform) = @_;
1.1055    raeburn  10811:     my $count = 0;
                   10812:     my $depth = 0;
                   10813:     my $datatable;
1.1056    raeburn  10814:     my @hierarchy;
1.1055    raeburn  10815:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  10816:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   10817:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  10818:     foreach my $item (@{$contents}) {
                   10819:         $count ++;
1.1056    raeburn  10820:         @{$dirorder->{$count}} = @hierarchy;
                   10821:         $titles->{$count} = $item;
1.1055    raeburn  10822:         &archive_hierarchy($depth,$count,$parent,$children);
                   10823:         if ($wantform) {
                   10824:             $datatable .= &archive_row($is_dir->{$item},$item,
                   10825:                                        $currdir,$depth,$count);
                   10826:         }
                   10827:         if ($is_dir->{$item}) {
                   10828:             $depth ++;
1.1056    raeburn  10829:             push(@hierarchy,$count);
                   10830:             $parent->{$depth} = $count;
1.1055    raeburn  10831:             $datatable .=
                   10832:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  10833:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   10834:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  10835:             $depth --;
1.1056    raeburn  10836:             pop(@hierarchy);
1.1055    raeburn  10837:         }
                   10838:     }
                   10839:     return ($count,$datatable);
                   10840: }
                   10841: 
                   10842: sub recurse_extracted_archive {
1.1056    raeburn  10843:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   10844:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  10845:     my $result='';
1.1056    raeburn  10846:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   10847:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   10848:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  10849:         return $result;
                   10850:     }
                   10851:     my $dirptr = 16384;
                   10852:     my ($newdirlistref,$newlisterror) =
                   10853:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   10854:     if (ref($newdirlistref) eq 'ARRAY') {
                   10855:         foreach my $dir_line (@{$newdirlistref}) {
                   10856:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   10857:             unless ($item =~ /^\.+$/) {
                   10858:                 $$count ++;
1.1056    raeburn  10859:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   10860:                 $titles->{$$count} = $item;
1.1055    raeburn  10861:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  10862: 
1.1055    raeburn  10863:                 my $is_dir;
                   10864:                 if ($dirptr&$testdir) {
                   10865:                     $is_dir = 1;
                   10866:                 }
                   10867:                 if ($wantform) {
                   10868:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   10869:                 }
                   10870:                 if ($is_dir) {
                   10871:                     $$depth ++;
1.1056    raeburn  10872:                     push(@{$hierarchy},$$count);
                   10873:                     $parent->{$$depth} = $$count;
1.1055    raeburn  10874:                     $result .=
                   10875:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   10876:                                                    $docuname,$depth,$count,
1.1056    raeburn  10877:                                                    $hierarchy,$dirorder,$children,
                   10878:                                                    $parent,$titles,$wantform);
1.1055    raeburn  10879:                     $$depth --;
1.1056    raeburn  10880:                     pop(@{$hierarchy});
1.1055    raeburn  10881:                 }
                   10882:             }
                   10883:         }
                   10884:     }
                   10885:     return $result;
                   10886: }
                   10887: 
                   10888: sub archive_hierarchy {
                   10889:     my ($depth,$count,$parent,$children) =@_;
                   10890:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   10891:         if (exists($parent->{$depth})) {
                   10892:              $children->{$parent->{$depth}} .= $count.':';
                   10893:         }
                   10894:     }
                   10895:     return;
                   10896: }
                   10897: 
                   10898: sub archive_row {
                   10899:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   10900:     my ($name) = ($item =~ m{([^/]+)$});
                   10901:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  10902:                                        'display'    => 'Add as file',
1.1055    raeburn  10903:                                        'dependency' => 'Include as dependency',
                   10904:                                        'discard'    => 'Discard',
                   10905:                                       );
                   10906:     if ($is_dir) {
1.1059    raeburn  10907:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  10908:     }
1.1056    raeburn  10909:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   10910:     my $offset = 0;
1.1055    raeburn  10911:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  10912:         $offset ++;
1.1065    raeburn  10913:         if ($action ne 'display') {
                   10914:             $offset ++;
                   10915:         }  
1.1055    raeburn  10916:         $output .= '<td><span class="LC_nobreak">'.
                   10917:                    '<label><input type="radio" name="archive_'.$count.
                   10918:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   10919:         my $text = $choices{$action};
                   10920:         if ($is_dir) {
                   10921:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   10922:             if ($action eq 'display') {
1.1059    raeburn  10923:                 $text = &mt('Add as folder');
1.1055    raeburn  10924:             }
1.1056    raeburn  10925:         } else {
                   10926:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   10927: 
                   10928:         }
                   10929:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   10930:         if ($action eq 'dependency') {
                   10931:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   10932:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   10933:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   10934:                        '<option value=""></option>'."\n".
                   10935:                        '</select>'."\n".
                   10936:                        '</div>';
1.1059    raeburn  10937:         } elsif ($action eq 'display') {
                   10938:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   10939:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   10940:                        '</div>';
1.1055    raeburn  10941:         }
1.1056    raeburn  10942:         $output .= '</td>';
1.1055    raeburn  10943:     }
                   10944:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   10945:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   10946:     for (my $i=0; $i<$depth; $i++) {
                   10947:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   10948:     }
                   10949:     if ($is_dir) {
                   10950:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   10951:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   10952:     } else {
                   10953:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   10954:     }
                   10955:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   10956:                &end_data_table_row();
                   10957:     return $output;
                   10958: }
                   10959: 
                   10960: sub archive_options_form {
1.1065    raeburn  10961:     my ($form,$display,$count,$hiddenelem) = @_;
                   10962:     my %lt = &Apache::lonlocal::texthash(
                   10963:                perm => 'Permanently remove archive file?',
                   10964:                hows => 'How should each extracted item be incorporated in the course?',
                   10965:                cont => 'Content actions for all',
                   10966:                addf => 'Add as folder/file',
                   10967:                incd => 'Include as dependency for a displayed file',
                   10968:                disc => 'Discard',
                   10969:                no   => 'No',
                   10970:                yes  => 'Yes',
                   10971:                save => 'Save',
                   10972:     );
                   10973:     my $output = <<"END";
                   10974: <form name="$form" method="post" action="">
                   10975: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   10976: <label>
                   10977:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   10978: </label>
                   10979: &nbsp;
                   10980: <label>
                   10981:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   10982: </span>
                   10983: </p>
                   10984: <input type="hidden" name="phase" value="decompress_cleanup" />
                   10985: <br />$lt{'hows'}
                   10986: <div class="LC_columnSection">
                   10987:   <fieldset>
                   10988:     <legend>$lt{'cont'}</legend>
                   10989:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   10990:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   10991:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   10992:   </fieldset>
                   10993: </div>
                   10994: END
                   10995:     return $output.
1.1055    raeburn  10996:            &start_data_table()."\n".
1.1065    raeburn  10997:            $display."\n".
1.1055    raeburn  10998:            &end_data_table()."\n".
                   10999:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   11000:            $hiddenelem.
1.1065    raeburn  11001:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  11002:            '</form>';
                   11003: }
                   11004: 
                   11005: sub archive_javascript {
1.1056    raeburn  11006:     my ($startcount,$numitems,$titles,$children) = @_;
                   11007:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  11008:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  11009:     my $scripttag = <<START;
                   11010: <script type="text/javascript">
                   11011: // <![CDATA[
                   11012: 
                   11013: function checkAll(form,prefix) {
                   11014:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   11015:     for (var i=0; i < form.elements.length; i++) {
                   11016:         var id = form.elements[i].id;
                   11017:         if ((id != '') && (id != undefined)) {
                   11018:             if (idstr.test(id)) {
                   11019:                 if (form.elements[i].type == 'radio') {
                   11020:                     form.elements[i].checked = true;
1.1056    raeburn  11021:                     var nostart = i-$startcount;
1.1059    raeburn  11022:                     var offset = nostart%7;
                   11023:                     var count = (nostart-offset)/7;    
1.1056    raeburn  11024:                     dependencyCheck(form,count,offset);
1.1055    raeburn  11025:                 }
                   11026:             }
                   11027:         }
                   11028:     }
                   11029: }
                   11030: 
                   11031: function propagateCheck(form,count) {
                   11032:     if (count > 0) {
1.1059    raeburn  11033:         var startelement = $startcount + ((count-1) * 7);
                   11034:         for (var j=1; j<6; j++) {
                   11035:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  11036:                 var item = startelement + j; 
                   11037:                 if (form.elements[item].type == 'radio') {
                   11038:                     if (form.elements[item].checked) {
                   11039:                         containerCheck(form,count,j);
                   11040:                         break;
                   11041:                     }
1.1055    raeburn  11042:                 }
                   11043:             }
                   11044:         }
                   11045:     }
                   11046: }
                   11047: 
                   11048: numitems = $numitems
1.1056    raeburn  11049: var titles = new Array(numitems);
                   11050: var parents = new Array(numitems);
1.1055    raeburn  11051: for (var i=0; i<numitems; i++) {
1.1056    raeburn  11052:     parents[i] = new Array;
1.1055    raeburn  11053: }
1.1059    raeburn  11054: var maintitle = '$maintitle';
1.1055    raeburn  11055: 
                   11056: START
                   11057: 
1.1056    raeburn  11058:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   11059:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  11060:         for (my $i=0; $i<@contents; $i ++) {
                   11061:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   11062:         }
                   11063:     }
                   11064: 
1.1056    raeburn  11065:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   11066:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   11067:     }
                   11068: 
1.1055    raeburn  11069:     $scripttag .= <<END;
                   11070: 
                   11071: function containerCheck(form,count,offset) {
                   11072:     if (count > 0) {
1.1056    raeburn  11073:         dependencyCheck(form,count,offset);
1.1059    raeburn  11074:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  11075:         form.elements[item].checked = true;
                   11076:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11077:             if (parents[count].length > 0) {
                   11078:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  11079:                     containerCheck(form,parents[count][j],offset);
                   11080:                 }
                   11081:             }
                   11082:         }
                   11083:     }
                   11084: }
                   11085: 
                   11086: function dependencyCheck(form,count,offset) {
                   11087:     if (count > 0) {
1.1059    raeburn  11088:         var chosen = (offset+$startcount)+7*(count-1);
                   11089:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  11090:         var currtype = form.elements[depitem].type;
                   11091:         if (form.elements[chosen].value == 'dependency') {
                   11092:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   11093:             form.elements[depitem].options.length = 0;
                   11094:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  11095:             for (var i=1; i<=numitems; i++) {
                   11096:                 if (i == count) {
                   11097:                     continue;
                   11098:                 }
1.1059    raeburn  11099:                 var startelement = $startcount + (i-1) * 7;
                   11100:                 for (var j=1; j<6; j++) {
                   11101:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  11102:                         var item = startelement + j;
                   11103:                         if (form.elements[item].type == 'radio') {
                   11104:                             if (form.elements[item].checked) {
                   11105:                                 if (form.elements[item].value == 'display') {
                   11106:                                     var n = form.elements[depitem].options.length;
                   11107:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   11108:                                 }
                   11109:                             }
                   11110:                         }
                   11111:                     }
                   11112:                 }
                   11113:             }
                   11114:         } else {
                   11115:             document.getElementById('arc_depon_'+count).style.display='none';
                   11116:             form.elements[depitem].options.length = 0;
                   11117:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   11118:         }
1.1059    raeburn  11119:         titleCheck(form,count,offset);
1.1056    raeburn  11120:     }
                   11121: }
                   11122: 
                   11123: function propagateSelect(form,count,offset) {
                   11124:     if (count > 0) {
1.1065    raeburn  11125:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  11126:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   11127:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11128:             if (parents[count].length > 0) {
                   11129:                 for (var j=0; j<parents[count].length; j++) {
                   11130:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  11131:                 }
                   11132:             }
                   11133:         }
                   11134:     }
                   11135: }
1.1056    raeburn  11136: 
                   11137: function containerSelect(form,count,offset,picked) {
                   11138:     if (count > 0) {
1.1065    raeburn  11139:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  11140:         if (form.elements[item].type == 'radio') {
                   11141:             if (form.elements[item].value == 'dependency') {
                   11142:                 if (form.elements[item+1].type == 'select-one') {
                   11143:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   11144:                         if (form.elements[item+1].options[i].value == picked) {
                   11145:                             form.elements[item+1].selectedIndex = i;
                   11146:                             break;
                   11147:                         }
                   11148:                     }
                   11149:                 }
                   11150:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11151:                     if (parents[count].length > 0) {
                   11152:                         for (var j=0; j<parents[count].length; j++) {
                   11153:                             containerSelect(form,parents[count][j],offset,picked);
                   11154:                         }
                   11155:                     }
                   11156:                 }
                   11157:             }
                   11158:         }
                   11159:     }
                   11160: }
                   11161: 
1.1059    raeburn  11162: function titleCheck(form,count,offset) {
                   11163:     if (count > 0) {
                   11164:         var chosen = (offset+$startcount)+7*(count-1);
                   11165:         var depitem = $startcount + ((count-1) * 7) + 2;
                   11166:         var currtype = form.elements[depitem].type;
                   11167:         if (form.elements[chosen].value == 'display') {
                   11168:             document.getElementById('arc_title_'+count).style.display='block';
                   11169:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   11170:                 document.getElementById('archive_title_'+count).value=maintitle;
                   11171:             }
                   11172:         } else {
                   11173:             document.getElementById('arc_title_'+count).style.display='none';
                   11174:             if (currtype == 'text') { 
                   11175:                 document.getElementById('archive_title_'+count).value='';
                   11176:             }
                   11177:         }
                   11178:     }
                   11179:     return;
                   11180: }
                   11181: 
1.1055    raeburn  11182: // ]]>
                   11183: </script>
                   11184: END
                   11185:     return $scripttag;
                   11186: }
                   11187: 
                   11188: sub process_extracted_files {
1.1067    raeburn  11189:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  11190:     my $numitems = $env{'form.archive_count'};
                   11191:     return unless ($numitems);
                   11192:     my @ids=&Apache::lonnet::current_machine_ids();
                   11193:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  11194:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  11195:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   11196:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   11197:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   11198:         $pathtocheck = "$dir_root/$destination";
                   11199:         $dir = $dir_root;
                   11200:         $ishome = 1;
                   11201:     } else {
                   11202:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   11203:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   11204:         $dir = "$dir_root/$docudom/$docuname";    
                   11205:     }
                   11206:     my $currdir = "$dir_root/$destination";
                   11207:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   11208:     if ($env{'form.folderpath'}) {
                   11209:         my @items = split('&',$env{'form.folderpath'});
                   11210:         $folders{'0'} = $items[-2];
                   11211:         $containers{'0'}='sequence';
                   11212:     } elsif ($env{'form.pagepath'}) {
                   11213:         my @items = split('&',$env{'form.pagepath'});
                   11214:         $folders{'0'} = $items[-2];
                   11215:         $containers{'0'}='page';
                   11216:     }
                   11217:     my @archdirs = &get_env_multiple('form.archive_directory');
                   11218:     if ($numitems) {
                   11219:         for (my $i=1; $i<=$numitems; $i++) {
                   11220:             my $path = $env{'form.archive_content_'.$i};
                   11221:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   11222:                 my $item = $1;
                   11223:                 $toplevelitems{$item} = $i;
                   11224:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   11225:                     $is_dir{$item} = 1;
                   11226:                 }
                   11227:             }
                   11228:         }
                   11229:     }
1.1067    raeburn  11230:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  11231:     if (keys(%toplevelitems) > 0) {
                   11232:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  11233:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   11234:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  11235:     }
1.1066    raeburn  11236:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  11237:     if ($numitems) {
                   11238:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  11239:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  11240:             my $path = $env{'form.archive_content_'.$i};
                   11241:             if ($path =~ /^\Q$pathtocheck\E/) {
                   11242:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   11243:                     if ($prefix ne '' && $path ne '') {
                   11244:                         if (-e $prefix.$path) {
1.1066    raeburn  11245:                             if ((@archdirs > 0) && 
                   11246:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   11247:                                 $todeletedir{$prefix.$path} = 1;
                   11248:                             } else {
                   11249:                                 $todelete{$prefix.$path} = 1;
                   11250:                             }
1.1055    raeburn  11251:                         }
                   11252:                     }
                   11253:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  11254:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  11255:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  11256:                     $docstitle = $env{'form.archive_title_'.$i};
                   11257:                     if ($docstitle eq '') {
                   11258:                         $docstitle = $title;
                   11259:                     }
1.1055    raeburn  11260:                     $outer = 0;
1.1056    raeburn  11261:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   11262:                         if (@{$dirorder{$i}} > 0) {
                   11263:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  11264:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   11265:                                     $outer = $item;
                   11266:                                     last;
                   11267:                                 }
                   11268:                             }
                   11269:                         }
                   11270:                     }
                   11271:                     my ($errtext,$fatal) = 
                   11272:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   11273:                                                '/'.$folders{$outer}.'.'.
                   11274:                                                $containers{$outer});
                   11275:                     next if ($fatal);
                   11276:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   11277:                         if ($context eq 'coursedocs') {
1.1056    raeburn  11278:                             $mapinner{$i} = time;
1.1055    raeburn  11279:                             $folders{$i} = 'default_'.$mapinner{$i};
                   11280:                             $containers{$i} = 'sequence';
                   11281:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   11282:                                       $folders{$i}.'.'.$containers{$i};
                   11283:                             my $newidx = &LONCAPA::map::getresidx();
                   11284:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  11285:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  11286:                             push(@LONCAPA::map::order,$newidx);
                   11287:                             my ($outtext,$errtext) =
                   11288:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   11289:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  11290:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  11291:                             $newseqid{$i} = $newidx;
1.1067    raeburn  11292:                             unless ($errtext) {
                   11293:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   11294:                             }
1.1055    raeburn  11295:                         }
                   11296:                     } else {
                   11297:                         if ($context eq 'coursedocs') {
                   11298:                             my $newidx=&LONCAPA::map::getresidx();
                   11299:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   11300:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   11301:                                       $title;
                   11302:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   11303:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   11304:                             }
                   11305:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   11306:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   11307:                             }
                   11308:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   11309:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  11310:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  11311:                                 unless ($ishome) {
                   11312:                                     my $fetch = "$newdest{$i}/$title";
                   11313:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   11314:                                     $prompttofetch{$fetch} = 1;
                   11315:                                 }
1.1055    raeburn  11316:                             }
                   11317:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  11318:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  11319:                             push(@LONCAPA::map::order, $newidx);
                   11320:                             my ($outtext,$errtext)=
                   11321:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   11322:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  11323:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  11324:                             unless ($errtext) {
                   11325:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   11326:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   11327:                                 }
                   11328:                             }
1.1055    raeburn  11329:                         }
                   11330:                     }
1.1086    raeburn  11331:                 }
                   11332:             } else {
                   11333:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   11334:             }
                   11335:         }
                   11336:         for (my $i=1; $i<=$numitems; $i++) {
                   11337:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   11338:             my $path = $env{'form.archive_content_'.$i};
                   11339:             if ($path =~ /^\Q$pathtocheck\E/) {
                   11340:                 my ($title) = ($path =~ m{/([^/]+)$});
                   11341:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   11342:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   11343:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   11344:                         my ($itemidx,$fullpath,$relpath);
                   11345:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   11346:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  11347:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  11348:                                 if ($dirorder{$i}->[$j] eq $container) {
                   11349:                                     $itemidx = $j;
1.1056    raeburn  11350:                                 }
                   11351:                             }
1.1086    raeburn  11352:                         }
                   11353:                         if ($itemidx eq '') {
                   11354:                             $itemidx =  0;
                   11355:                         } 
                   11356:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   11357:                             if ($mapinner{$referrer{$i}}) {
                   11358:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   11359:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   11360:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   11361:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   11362:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11363:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11364:                                             if (!-e $fullpath) {
                   11365:                                                 mkdir($fullpath,0755);
1.1056    raeburn  11366:                                             }
                   11367:                                         }
1.1086    raeburn  11368:                                     } else {
                   11369:                                         last;
1.1056    raeburn  11370:                                     }
1.1086    raeburn  11371:                                 }
                   11372:                             }
                   11373:                         } elsif ($newdest{$referrer{$i}}) {
                   11374:                             $fullpath = $newdest{$referrer{$i}};
                   11375:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   11376:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   11377:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   11378:                                     last;
                   11379:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   11380:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   11381:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11382:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11383:                                         if (!-e $fullpath) {
                   11384:                                             mkdir($fullpath,0755);
1.1056    raeburn  11385:                                         }
                   11386:                                     }
1.1086    raeburn  11387:                                 } else {
                   11388:                                     last;
1.1056    raeburn  11389:                                 }
1.1055    raeburn  11390:                             }
                   11391:                         }
1.1086    raeburn  11392:                         if ($fullpath ne '') {
                   11393:                             if (-e "$prefix$path") {
                   11394:                                 system("mv $prefix$path $fullpath/$title");
                   11395:                             }
                   11396:                             if (-e "$fullpath/$title") {
                   11397:                                 my $showpath;
                   11398:                                 if ($relpath ne '') {
                   11399:                                     $showpath = "$relpath/$title";
                   11400:                                 } else {
                   11401:                                     $showpath = "/$title";
                   11402:                                 } 
                   11403:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   11404:                             } 
                   11405:                             unless ($ishome) {
                   11406:                                 my $fetch = "$fullpath/$title";
                   11407:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
                   11408:                                 $prompttofetch{$fetch} = 1;
                   11409:                             }
                   11410:                         }
1.1055    raeburn  11411:                     }
1.1086    raeburn  11412:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   11413:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   11414:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  11415:                 }
                   11416:             } else {
                   11417:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   11418:             }
                   11419:         }
                   11420:         if (keys(%todelete)) {
                   11421:             foreach my $key (keys(%todelete)) {
                   11422:                 unlink($key);
1.1066    raeburn  11423:             }
                   11424:         }
                   11425:         if (keys(%todeletedir)) {
                   11426:             foreach my $key (keys(%todeletedir)) {
                   11427:                 rmdir($key);
                   11428:             }
                   11429:         }
                   11430:         foreach my $dir (sort(keys(%is_dir))) {
                   11431:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   11432:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  11433:             }
                   11434:         }
1.1067    raeburn  11435:         if ($result ne '') {
                   11436:             $output .= '<ul>'."\n".
                   11437:                        $result."\n".
                   11438:                        '</ul>';
                   11439:         }
                   11440:         unless ($ishome) {
                   11441:             my $replicationfail;
                   11442:             foreach my $item (keys(%prompttofetch)) {
                   11443:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   11444:                 unless ($fetchresult eq 'ok') {
                   11445:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   11446:                 }
                   11447:             }
                   11448:             if ($replicationfail) {
                   11449:                 $output .= '<p class="LC_error">'.
                   11450:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   11451:                            $replicationfail.
                   11452:                            '</ul></p>';
                   11453:             }
                   11454:         }
1.1055    raeburn  11455:     } else {
                   11456:         $warning = &mt('No items found in archive.');
                   11457:     }
                   11458:     if ($error) {
                   11459:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   11460:                    $error.'</p>'."\n";
                   11461:     }
                   11462:     if ($warning) {
                   11463:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   11464:     }
                   11465:     return $output;
                   11466: }
                   11467: 
1.1066    raeburn  11468: sub cleanup_empty_dirs {
                   11469:     my ($path) = @_;
                   11470:     if (($path ne '') && (-d $path)) {
                   11471:         if (opendir(my $dirh,$path)) {
                   11472:             my @dircontents = grep(!/^\./,readdir($dirh));
                   11473:             my $numitems = 0;
                   11474:             foreach my $item (@dircontents) {
                   11475:                 if (-d "$path/$item") {
                   11476:                     &recurse_dirs("$path/$item");
                   11477:                     if (-e "$path/$item") {
                   11478:                         $numitems ++;
                   11479:                     }
                   11480:                 } else {
                   11481:                     $numitems ++;
                   11482:                 }
                   11483:             }
                   11484:             if ($numitems == 0) {
                   11485:                 rmdir($path);
                   11486:             }
                   11487:             closedir($dirh);
                   11488:         }
                   11489:     }
                   11490:     return;
                   11491: }
                   11492: 
1.41      ng       11493: =pod
1.45      matthew  11494: 
1.1068    raeburn  11495: =item &get_folder_hierarchy()
                   11496: 
                   11497: Provides hierarchy of names of folders/sub-folders containing the current
                   11498: item,
                   11499: 
                   11500: Inputs: 3
                   11501:      - $navmap - navmaps object
                   11502: 
                   11503:      - $map - url for map (either the trigger itself, or map containing
                   11504:                            the resource, which is the trigger).
                   11505: 
                   11506:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   11507: 
                   11508: Outputs: 1 @pathitems - array of folder/subfolder names.
                   11509: 
                   11510: =cut
                   11511: 
                   11512: sub get_folder_hierarchy {
                   11513:     my ($navmap,$map,$showitem) = @_;
                   11514:     my @pathitems;
                   11515:     if (ref($navmap)) {
                   11516:         my $mapres = $navmap->getResourceByUrl($map);
                   11517:         if (ref($mapres)) {
                   11518:             my $pcslist = $mapres->map_hierarchy();
                   11519:             if ($pcslist ne '') {
                   11520:                 my @pcs = split(/,/,$pcslist);
                   11521:                 foreach my $pc (@pcs) {
                   11522:                     if ($pc == 1) {
                   11523:                         push(@pathitems,&mt('Main Course Documents'));
                   11524:                     } else {
                   11525:                         my $res = $navmap->getByMapPc($pc);
                   11526:                         if (ref($res)) {
                   11527:                             my $title = $res->compTitle();
                   11528:                             $title =~ s/\W+/_/g;
                   11529:                             if ($title ne '') {
                   11530:                                 push(@pathitems,$title);
                   11531:                             }
                   11532:                         }
                   11533:                     }
                   11534:                 }
                   11535:             }
1.1071    raeburn  11536:             if ($showitem) {
                   11537:                 if ($mapres->{ID} eq '0.0') {
                   11538:                     push(@pathitems,&mt('Main Course Documents'));
                   11539:                 } else {
                   11540:                     my $maptitle = $mapres->compTitle();
                   11541:                     $maptitle =~ s/\W+/_/g;
                   11542:                     if ($maptitle ne '') {
                   11543:                         push(@pathitems,$maptitle);
                   11544:                     }
1.1068    raeburn  11545:                 }
                   11546:             }
                   11547:         }
                   11548:     }
                   11549:     return @pathitems;
                   11550: }
                   11551: 
                   11552: =pod
                   11553: 
1.1015    raeburn  11554: =item * &get_turnedin_filepath()
                   11555: 
                   11556: Determines path in a user's portfolio file for storage of files uploaded
                   11557: to a specific essayresponse or dropbox item.
                   11558: 
                   11559: Inputs: 3 required + 1 optional.
                   11560: $symb is symb for resource, $uname and $udom are for current user (required).
                   11561: $caller is optional (can be "submission", if routine is called when storing
                   11562: an upoaded file when "Submit Answer" button was pressed).
                   11563: 
                   11564: Returns array containing $path and $multiresp. 
                   11565: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   11566: than one file upload item.  Callers of routine should append partid as a 
                   11567: subdirectory to $path in cases where $multiresp is 1.
                   11568: 
                   11569: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   11570: 
                   11571: =cut
                   11572: 
                   11573: sub get_turnedin_filepath {
                   11574:     my ($symb,$uname,$udom,$caller) = @_;
                   11575:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   11576:     my $turnindir;
                   11577:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   11578:     $turnindir = $userhash{'turnindir'};
                   11579:     my ($path,$multiresp);
                   11580:     if ($turnindir eq '') {
                   11581:         if ($caller eq 'submission') {
                   11582:             $turnindir = &mt('turned in');
                   11583:             $turnindir =~ s/\W+/_/g;
                   11584:             my %newhash = (
                   11585:                             'turnindir' => $turnindir,
                   11586:                           );
                   11587:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   11588:         }
                   11589:     }
                   11590:     if ($turnindir ne '') {
                   11591:         $path = '/'.$turnindir.'/';
                   11592:         my ($multipart,$turnin,@pathitems);
                   11593:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11594:         if (defined($navmap)) {
                   11595:             my $mapres = $navmap->getResourceByUrl($map);
                   11596:             if (ref($mapres)) {
                   11597:                 my $pcslist = $mapres->map_hierarchy();
                   11598:                 if ($pcslist ne '') {
                   11599:                     foreach my $pc (split(/,/,$pcslist)) {
                   11600:                         my $res = $navmap->getByMapPc($pc);
                   11601:                         if (ref($res)) {
                   11602:                             my $title = $res->compTitle();
                   11603:                             $title =~ s/\W+/_/g;
                   11604:                             if ($title ne '') {
                   11605:                                 push(@pathitems,$title);
                   11606:                             }
                   11607:                         }
                   11608:                     }
                   11609:                 }
                   11610:                 my $maptitle = $mapres->compTitle();
                   11611:                 $maptitle =~ s/\W+/_/g;
                   11612:                 if ($maptitle ne '') {
                   11613:                     push(@pathitems,$maptitle);
                   11614:                 }
                   11615:                 unless ($env{'request.state'} eq 'construct') {
                   11616:                     my $res = $navmap->getBySymb($symb);
                   11617:                     if (ref($res)) {
                   11618:                         my $partlist = $res->parts();
                   11619:                         my $totaluploads = 0;
                   11620:                         if (ref($partlist) eq 'ARRAY') {
                   11621:                             foreach my $part (@{$partlist}) {
                   11622:                                 my @types = $res->responseType($part);
                   11623:                                 my @ids = $res->responseIds($part);
                   11624:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   11625:                                     if ($types[$i] eq 'essay') {
                   11626:                                         my $partid = $part.'_'.$ids[$i];
                   11627:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   11628:                                             $totaluploads ++;
                   11629:                                         }
                   11630:                                     }
                   11631:                                 }
                   11632:                             }
                   11633:                             if ($totaluploads > 1) {
                   11634:                                 $multiresp = 1;
                   11635:                             }
                   11636:                         }
                   11637:                     }
                   11638:                 }
                   11639:             } else {
                   11640:                 return;
                   11641:             }
                   11642:         } else {
                   11643:             return;
                   11644:         }
                   11645:         my $restitle=&Apache::lonnet::gettitle($symb);
                   11646:         $restitle =~ s/\W+/_/g;
                   11647:         if ($restitle eq '') {
                   11648:             $restitle = ($resurl =~ m{/[^/]+$});
                   11649:             if ($restitle eq '') {
                   11650:                 $restitle = time;
                   11651:             }
                   11652:         }
                   11653:         push(@pathitems,$restitle);
                   11654:         $path .= join('/',@pathitems);
                   11655:     }
                   11656:     return ($path,$multiresp);
                   11657: }
                   11658: 
                   11659: =pod
                   11660: 
1.464     albertel 11661: =back
1.41      ng       11662: 
1.112     bowersj2 11663: =head1 CSV Upload/Handling functions
1.38      albertel 11664: 
1.41      ng       11665: =over 4
                   11666: 
1.648     raeburn  11667: =item * &upfile_store($r)
1.41      ng       11668: 
                   11669: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 11670: needs $env{'form.upfile'}
1.41      ng       11671: returns $datatoken to be put into hidden field
                   11672: 
                   11673: =cut
1.31      albertel 11674: 
                   11675: sub upfile_store {
                   11676:     my $r=shift;
1.258     albertel 11677:     $env{'form.upfile'}=~s/\r/\n/gs;
                   11678:     $env{'form.upfile'}=~s/\f/\n/gs;
                   11679:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   11680:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 11681: 
1.258     albertel 11682:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   11683: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 11684:     {
1.158     raeburn  11685:         my $datafile = $r->dir_config('lonDaemons').
                   11686:                            '/tmp/'.$datatoken.'.tmp';
                   11687:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 11688:             print $fh $env{'form.upfile'};
1.158     raeburn  11689:             close($fh);
                   11690:         }
1.31      albertel 11691:     }
                   11692:     return $datatoken;
                   11693: }
                   11694: 
1.56      matthew  11695: =pod
                   11696: 
1.648     raeburn  11697: =item * &load_tmp_file($r)
1.41      ng       11698: 
                   11699: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 11700: needs $env{'form.datatoken'},
                   11701: sets $env{'form.upfile'} to the contents of the file
1.41      ng       11702: 
                   11703: =cut
1.31      albertel 11704: 
                   11705: sub load_tmp_file {
                   11706:     my $r=shift;
                   11707:     my @studentdata=();
                   11708:     {
1.158     raeburn  11709:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 11710:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  11711:         if ( open(my $fh,"<$studentfile") ) {
                   11712:             @studentdata=<$fh>;
                   11713:             close($fh);
                   11714:         }
1.31      albertel 11715:     }
1.258     albertel 11716:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 11717: }
                   11718: 
1.56      matthew  11719: =pod
                   11720: 
1.648     raeburn  11721: =item * &upfile_record_sep()
1.41      ng       11722: 
                   11723: Separate uploaded file into records
                   11724: returns array of records,
1.258     albertel 11725: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       11726: 
                   11727: =cut
1.31      albertel 11728: 
                   11729: sub upfile_record_sep {
1.258     albertel 11730:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 11731:     } else {
1.248     albertel 11732: 	my @records;
1.258     albertel 11733: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 11734: 	    if ($line=~/^\s*$/) { next; }
                   11735: 	    push(@records,$line);
                   11736: 	}
                   11737: 	return @records;
1.31      albertel 11738:     }
                   11739: }
                   11740: 
1.56      matthew  11741: =pod
                   11742: 
1.648     raeburn  11743: =item * &record_sep($record)
1.41      ng       11744: 
1.258     albertel 11745: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       11746: 
                   11747: =cut
                   11748: 
1.263     www      11749: sub takeleft {
                   11750:     my $index=shift;
                   11751:     return substr('0000'.$index,-4,4);
                   11752: }
                   11753: 
1.31      albertel 11754: sub record_sep {
                   11755:     my $record=shift;
                   11756:     my %components=();
1.258     albertel 11757:     if ($env{'form.upfiletype'} eq 'xml') {
                   11758:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 11759:         my $i=0;
1.356     albertel 11760:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 11761:             $field=~s/^(\"|\')//;
                   11762:             $field=~s/(\"|\')$//;
1.263     www      11763:             $components{&takeleft($i)}=$field;
1.31      albertel 11764:             $i++;
                   11765:         }
1.258     albertel 11766:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 11767:         my $i=0;
1.356     albertel 11768:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 11769:             $field=~s/^(\"|\')//;
                   11770:             $field=~s/(\"|\')$//;
1.263     www      11771:             $components{&takeleft($i)}=$field;
1.31      albertel 11772:             $i++;
                   11773:         }
                   11774:     } else {
1.561     www      11775:         my $separator=',';
1.480     banghart 11776:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      11777:             $separator=';';
1.480     banghart 11778:         }
1.31      albertel 11779:         my $i=0;
1.561     www      11780: # the character we are looking for to indicate the end of a quote or a record 
                   11781:         my $looking_for=$separator;
                   11782: # do not add the characters to the fields
                   11783:         my $ignore=0;
                   11784: # we just encountered a separator (or the beginning of the record)
                   11785:         my $just_found_separator=1;
                   11786: # store the field we are working on here
                   11787:         my $field='';
                   11788: # work our way through all characters in record
                   11789:         foreach my $character ($record=~/(.)/g) {
                   11790:             if ($character eq $looking_for) {
                   11791:                if ($character ne $separator) {
                   11792: # Found the end of a quote, again looking for separator
                   11793:                   $looking_for=$separator;
                   11794:                   $ignore=1;
                   11795:                } else {
                   11796: # Found a separator, store away what we got
                   11797:                   $components{&takeleft($i)}=$field;
                   11798: 	          $i++;
                   11799:                   $just_found_separator=1;
                   11800:                   $ignore=0;
                   11801:                   $field='';
                   11802:                }
                   11803:                next;
                   11804:             }
                   11805: # single or double quotation marks after a separator indicate beginning of a quote
                   11806: # we are now looking for the end of the quote and need to ignore separators
                   11807:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   11808:                $looking_for=$character;
                   11809:                next;
                   11810:             }
                   11811: # ignore would be true after we reached the end of a quote
                   11812:             if ($ignore) { next; }
                   11813:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   11814:             $field.=$character;
                   11815:             $just_found_separator=0; 
1.31      albertel 11816:         }
1.561     www      11817: # catch the very last entry, since we never encountered the separator
                   11818:         $components{&takeleft($i)}=$field;
1.31      albertel 11819:     }
                   11820:     return %components;
                   11821: }
                   11822: 
1.144     matthew  11823: ######################################################
                   11824: ######################################################
                   11825: 
1.56      matthew  11826: =pod
                   11827: 
1.648     raeburn  11828: =item * &upfile_select_html()
1.41      ng       11829: 
1.144     matthew  11830: Return HTML code to select a file from the users machine and specify 
                   11831: the file type.
1.41      ng       11832: 
                   11833: =cut
                   11834: 
1.144     matthew  11835: ######################################################
                   11836: ######################################################
1.31      albertel 11837: sub upfile_select_html {
1.144     matthew  11838:     my %Types = (
                   11839:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 11840:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  11841:                  space => &mt('Space separated'),
                   11842:                  tab   => &mt('Tabulator separated'),
                   11843: #                 xml   => &mt('HTML/XML'),
                   11844:                  );
                   11845:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  11846:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  11847:     foreach my $type (sort(keys(%Types))) {
                   11848:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   11849:     }
                   11850:     $Str .= "</select>\n";
                   11851:     return $Str;
1.31      albertel 11852: }
                   11853: 
1.301     albertel 11854: sub get_samples {
                   11855:     my ($records,$toget) = @_;
                   11856:     my @samples=({});
                   11857:     my $got=0;
                   11858:     foreach my $rec (@$records) {
                   11859: 	my %temp = &record_sep($rec);
                   11860: 	if (! grep(/\S/, values(%temp))) { next; }
                   11861: 	if (%temp) {
                   11862: 	    $samples[$got]=\%temp;
                   11863: 	    $got++;
                   11864: 	    if ($got == $toget) { last; }
                   11865: 	}
                   11866:     }
                   11867:     return \@samples;
                   11868: }
                   11869: 
1.144     matthew  11870: ######################################################
                   11871: ######################################################
                   11872: 
1.56      matthew  11873: =pod
                   11874: 
1.648     raeburn  11875: =item * &csv_print_samples($r,$records)
1.41      ng       11876: 
                   11877: Prints a table of sample values from each column uploaded $r is an
                   11878: Apache Request ref, $records is an arrayref from
                   11879: &Apache::loncommon::upfile_record_sep
                   11880: 
                   11881: =cut
                   11882: 
1.144     matthew  11883: ######################################################
                   11884: ######################################################
1.31      albertel 11885: sub csv_print_samples {
                   11886:     my ($r,$records) = @_;
1.662     bisitz   11887:     my $samples = &get_samples($records,5);
1.301     albertel 11888: 
1.594     raeburn  11889:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   11890:               &start_data_table_header_row());
1.356     albertel 11891:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   11892:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  11893:     $r->print(&end_data_table_header_row());
1.301     albertel 11894:     foreach my $hash (@$samples) {
1.594     raeburn  11895: 	$r->print(&start_data_table_row());
1.356     albertel 11896: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 11897: 	    $r->print('<td>');
1.356     albertel 11898: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 11899: 	    $r->print('</td>');
                   11900: 	}
1.594     raeburn  11901: 	$r->print(&end_data_table_row());
1.31      albertel 11902:     }
1.594     raeburn  11903:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 11904: }
                   11905: 
1.144     matthew  11906: ######################################################
                   11907: ######################################################
                   11908: 
1.56      matthew  11909: =pod
                   11910: 
1.648     raeburn  11911: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       11912: 
                   11913: Prints a table to create associations between values and table columns.
1.144     matthew  11914: 
1.41      ng       11915: $r is an Apache Request ref,
                   11916: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  11917: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       11918: 
                   11919: =cut
                   11920: 
1.144     matthew  11921: ######################################################
                   11922: ######################################################
1.31      albertel 11923: sub csv_print_select_table {
                   11924:     my ($r,$records,$d) = @_;
1.301     albertel 11925:     my $i=0;
                   11926:     my $samples = &get_samples($records,1);
1.144     matthew  11927:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  11928: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  11929:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  11930:               '<th>'.&mt('Column').'</th>'.
                   11931:               &end_data_table_header_row()."\n");
1.356     albertel 11932:     foreach my $array_ref (@$d) {
                   11933: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  11934: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 11935: 
1.875     bisitz   11936: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  11937: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 11938: 	$r->print('<option value="none"></option>');
1.356     albertel 11939: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   11940: 	    $r->print('<option value="'.$sample.'"'.
                   11941:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   11942:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 11943: 	}
1.594     raeburn  11944: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 11945: 	$i++;
                   11946:     }
1.594     raeburn  11947:     $r->print(&end_data_table());
1.31      albertel 11948:     $i--;
                   11949:     return $i;
                   11950: }
1.56      matthew  11951: 
1.144     matthew  11952: ######################################################
                   11953: ######################################################
                   11954: 
1.56      matthew  11955: =pod
1.31      albertel 11956: 
1.648     raeburn  11957: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       11958: 
                   11959: Prints a table of sample values from the upload and can make associate samples to internal names.
                   11960: 
                   11961: $r is an Apache Request ref,
                   11962: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   11963: $d is an array of 2 element arrays (internal name, displayed name)
                   11964: 
                   11965: =cut
                   11966: 
1.144     matthew  11967: ######################################################
                   11968: ######################################################
1.31      albertel 11969: sub csv_samples_select_table {
                   11970:     my ($r,$records,$d) = @_;
                   11971:     my $i=0;
1.144     matthew  11972:     #
1.662     bisitz   11973:     my $max_samples = 5;
                   11974:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  11975:     $r->print(&start_data_table().
                   11976:               &start_data_table_header_row().'<th>'.
                   11977:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   11978:               &end_data_table_header_row());
1.301     albertel 11979: 
                   11980:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  11981: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  11982: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 11983: 	foreach my $option (@$d) {
                   11984: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  11985: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 11986:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  11987:                       $display.'</option>');
1.31      albertel 11988: 	}
                   11989: 	$r->print('</select></td><td>');
1.662     bisitz   11990: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 11991: 	    if (defined($samples->[$line]{$key})) { 
                   11992: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   11993: 	    }
                   11994: 	}
1.594     raeburn  11995: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 11996: 	$i++;
                   11997:     }
1.594     raeburn  11998:     $r->print(&end_data_table());
1.31      albertel 11999:     $i--;
                   12000:     return($i);
1.115     matthew  12001: }
                   12002: 
1.144     matthew  12003: ######################################################
                   12004: ######################################################
                   12005: 
1.115     matthew  12006: =pod
                   12007: 
1.648     raeburn  12008: =item * &clean_excel_name($name)
1.115     matthew  12009: 
                   12010: Returns a replacement for $name which does not contain any illegal characters.
                   12011: 
                   12012: =cut
                   12013: 
1.144     matthew  12014: ######################################################
                   12015: ######################################################
1.115     matthew  12016: sub clean_excel_name {
                   12017:     my ($name) = @_;
                   12018:     $name =~ s/[:\*\?\/\\]//g;
                   12019:     if (length($name) > 31) {
                   12020:         $name = substr($name,0,31);
                   12021:     }
                   12022:     return $name;
1.25      albertel 12023: }
1.84      albertel 12024: 
1.85      albertel 12025: =pod
                   12026: 
1.648     raeburn  12027: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 12028: 
                   12029: Returns either 1 or undef
                   12030: 
                   12031: 1 if the part is to be hidden, undef if it is to be shown
                   12032: 
                   12033: Arguments are:
                   12034: 
                   12035: $id the id of the part to be checked
                   12036: $symb, optional the symb of the resource to check
                   12037: $udom, optional the domain of the user to check for
                   12038: $uname, optional the username of the user to check for
                   12039: 
                   12040: =cut
1.84      albertel 12041: 
                   12042: sub check_if_partid_hidden {
                   12043:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 12044:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 12045: 					 $symb,$udom,$uname);
1.141     albertel 12046:     my $truth=1;
                   12047:     #if the string starts with !, then the list is the list to show not hide
                   12048:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 12049:     my @hiddenlist=split(/,/,$hiddenparts);
                   12050:     foreach my $checkid (@hiddenlist) {
1.141     albertel 12051: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 12052:     }
1.141     albertel 12053:     return !$truth;
1.84      albertel 12054: }
1.127     matthew  12055: 
1.138     matthew  12056: 
                   12057: ############################################################
                   12058: ############################################################
                   12059: 
                   12060: =pod
                   12061: 
1.157     matthew  12062: =back 
                   12063: 
1.138     matthew  12064: =head1 cgi-bin script and graphing routines
                   12065: 
1.157     matthew  12066: =over 4
                   12067: 
1.648     raeburn  12068: =item * &get_cgi_id()
1.138     matthew  12069: 
                   12070: Inputs: none
                   12071: 
                   12072: Returns an id which can be used to pass environment variables
                   12073: to various cgi-bin scripts.  These environment variables will
                   12074: be removed from the users environment after a given time by
                   12075: the routine &Apache::lonnet::transfer_profile_to_env.
                   12076: 
                   12077: =cut
                   12078: 
                   12079: ############################################################
                   12080: ############################################################
1.152     albertel 12081: my $uniq=0;
1.136     matthew  12082: sub get_cgi_id {
1.154     albertel 12083:     $uniq=($uniq+1)%100000;
1.280     albertel 12084:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  12085: }
                   12086: 
1.127     matthew  12087: ############################################################
                   12088: ############################################################
                   12089: 
                   12090: =pod
                   12091: 
1.648     raeburn  12092: =item * &DrawBarGraph()
1.127     matthew  12093: 
1.138     matthew  12094: Facilitates the plotting of data in a (stacked) bar graph.
                   12095: Puts plot definition data into the users environment in order for 
                   12096: graph.png to plot it.  Returns an <img> tag for the plot.
                   12097: The bars on the plot are labeled '1','2',...,'n'.
                   12098: 
                   12099: Inputs:
                   12100: 
                   12101: =over 4
                   12102: 
                   12103: =item $Title: string, the title of the plot
                   12104: 
                   12105: =item $xlabel: string, text describing the X-axis of the plot
                   12106: 
                   12107: =item $ylabel: string, text describing the Y-axis of the plot
                   12108: 
                   12109: =item $Max: scalar, the maximum Y value to use in the plot
                   12110: If $Max is < any data point, the graph will not be rendered.
                   12111: 
1.140     matthew  12112: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  12113: they are plotted.  If undefined, default values will be used.
                   12114: 
1.178     matthew  12115: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   12116: 
1.138     matthew  12117: =item @Values: An array of array references.  Each array reference holds data
                   12118: to be plotted in a stacked bar chart.
                   12119: 
1.239     matthew  12120: =item If the final element of @Values is a hash reference the key/value
                   12121: pairs will be added to the graph definition.
                   12122: 
1.138     matthew  12123: =back
                   12124: 
                   12125: Returns:
                   12126: 
                   12127: An <img> tag which references graph.png and the appropriate identifying
                   12128: information for the plot.
                   12129: 
1.127     matthew  12130: =cut
                   12131: 
                   12132: ############################################################
                   12133: ############################################################
1.134     matthew  12134: sub DrawBarGraph {
1.178     matthew  12135:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  12136:     #
                   12137:     if (! defined($colors)) {
                   12138:         $colors = ['#33ff00', 
                   12139:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   12140:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   12141:                   ]; 
                   12142:     }
1.228     matthew  12143:     my $extra_settings = {};
                   12144:     if (ref($Values[-1]) eq 'HASH') {
                   12145:         $extra_settings = pop(@Values);
                   12146:     }
1.127     matthew  12147:     #
1.136     matthew  12148:     my $identifier = &get_cgi_id();
                   12149:     my $id = 'cgi.'.$identifier;        
1.129     matthew  12150:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  12151:         return '';
                   12152:     }
1.225     matthew  12153:     #
                   12154:     my @Labels;
                   12155:     if (defined($labels)) {
                   12156:         @Labels = @$labels;
                   12157:     } else {
                   12158:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   12159:             push (@Labels,$i+1);
                   12160:         }
                   12161:     }
                   12162:     #
1.129     matthew  12163:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  12164:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  12165:     my %ValuesHash;
                   12166:     my $NumSets=1;
                   12167:     foreach my $array (@Values) {
                   12168:         next if (! ref($array));
1.136     matthew  12169:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  12170:             join(',',@$array);
1.129     matthew  12171:     }
1.127     matthew  12172:     #
1.136     matthew  12173:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  12174:     if ($NumBars < 3) {
                   12175:         $width = 120+$NumBars*32;
1.220     matthew  12176:         $xskip = 1;
1.225     matthew  12177:         $bar_width = 30;
                   12178:     } elsif ($NumBars < 5) {
                   12179:         $width = 120+$NumBars*20;
                   12180:         $xskip = 1;
                   12181:         $bar_width = 20;
1.220     matthew  12182:     } elsif ($NumBars < 10) {
1.136     matthew  12183:         $width = 120+$NumBars*15;
                   12184:         $xskip = 1;
                   12185:         $bar_width = 15;
                   12186:     } elsif ($NumBars <= 25) {
                   12187:         $width = 120+$NumBars*11;
                   12188:         $xskip = 5;
                   12189:         $bar_width = 8;
                   12190:     } elsif ($NumBars <= 50) {
                   12191:         $width = 120+$NumBars*8;
                   12192:         $xskip = 5;
                   12193:         $bar_width = 4;
                   12194:     } else {
                   12195:         $width = 120+$NumBars*8;
                   12196:         $xskip = 5;
                   12197:         $bar_width = 4;
                   12198:     }
                   12199:     #
1.137     matthew  12200:     $Max = 1 if ($Max < 1);
                   12201:     if ( int($Max) < $Max ) {
                   12202:         $Max++;
                   12203:         $Max = int($Max);
                   12204:     }
1.127     matthew  12205:     $Title  = '' if (! defined($Title));
                   12206:     $xlabel = '' if (! defined($xlabel));
                   12207:     $ylabel = '' if (! defined($ylabel));
1.369     www      12208:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   12209:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   12210:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  12211:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  12212:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   12213:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   12214:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   12215:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   12216:     $ValuesHash{$id.'.height'}   = $height;
                   12217:     $ValuesHash{$id.'.width'}    = $width;
                   12218:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   12219:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   12220:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  12221:     #
1.228     matthew  12222:     # Deal with other parameters
                   12223:     while (my ($key,$value) = each(%$extra_settings)) {
                   12224:         $ValuesHash{$id.'.'.$key} = $value;
                   12225:     }
                   12226:     #
1.646     raeburn  12227:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  12228:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   12229: }
                   12230: 
                   12231: ############################################################
                   12232: ############################################################
                   12233: 
                   12234: =pod
                   12235: 
1.648     raeburn  12236: =item * &DrawXYGraph()
1.137     matthew  12237: 
1.138     matthew  12238: Facilitates the plotting of data in an XY graph.
                   12239: Puts plot definition data into the users environment in order for 
                   12240: graph.png to plot it.  Returns an <img> tag for the plot.
                   12241: 
                   12242: Inputs:
                   12243: 
                   12244: =over 4
                   12245: 
                   12246: =item $Title: string, the title of the plot
                   12247: 
                   12248: =item $xlabel: string, text describing the X-axis of the plot
                   12249: 
                   12250: =item $ylabel: string, text describing the Y-axis of the plot
                   12251: 
                   12252: =item $Max: scalar, the maximum Y value to use in the plot
                   12253: If $Max is < any data point, the graph will not be rendered.
                   12254: 
                   12255: =item $colors: Array ref containing the hex color codes for the data to be 
                   12256: plotted in.  If undefined, default values will be used.
                   12257: 
                   12258: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   12259: 
                   12260: =item $Ydata: Array ref containing Array refs.  
1.185     www      12261: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  12262: 
                   12263: =item %Values: hash indicating or overriding any default values which are 
                   12264: passed to graph.png.  
                   12265: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   12266: 
                   12267: =back
                   12268: 
                   12269: Returns:
                   12270: 
                   12271: An <img> tag which references graph.png and the appropriate identifying
                   12272: information for the plot.
                   12273: 
1.137     matthew  12274: =cut
                   12275: 
                   12276: ############################################################
                   12277: ############################################################
                   12278: sub DrawXYGraph {
                   12279:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   12280:     #
                   12281:     # Create the identifier for the graph
                   12282:     my $identifier = &get_cgi_id();
                   12283:     my $id = 'cgi.'.$identifier;
                   12284:     #
                   12285:     $Title  = '' if (! defined($Title));
                   12286:     $xlabel = '' if (! defined($xlabel));
                   12287:     $ylabel = '' if (! defined($ylabel));
                   12288:     my %ValuesHash = 
                   12289:         (
1.369     www      12290:          $id.'.title'  => &escape($Title),
                   12291:          $id.'.xlabel' => &escape($xlabel),
                   12292:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  12293:          $id.'.y_max_value'=> $Max,
                   12294:          $id.'.labels'     => join(',',@$Xlabels),
                   12295:          $id.'.PlotType'   => 'XY',
                   12296:          );
                   12297:     #
                   12298:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   12299:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   12300:     }
                   12301:     #
                   12302:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   12303:         return '';
                   12304:     }
                   12305:     my $NumSets=1;
1.138     matthew  12306:     foreach my $array (@{$Ydata}){
1.137     matthew  12307:         next if (! ref($array));
                   12308:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   12309:     }
1.138     matthew  12310:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  12311:     #
                   12312:     # Deal with other parameters
                   12313:     while (my ($key,$value) = each(%Values)) {
                   12314:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  12315:     }
                   12316:     #
1.646     raeburn  12317:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  12318:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   12319: }
                   12320: 
                   12321: ############################################################
                   12322: ############################################################
                   12323: 
                   12324: =pod
                   12325: 
1.648     raeburn  12326: =item * &DrawXYYGraph()
1.138     matthew  12327: 
                   12328: Facilitates the plotting of data in an XY graph with two Y axes.
                   12329: Puts plot definition data into the users environment in order for 
                   12330: graph.png to plot it.  Returns an <img> tag for the plot.
                   12331: 
                   12332: Inputs:
                   12333: 
                   12334: =over 4
                   12335: 
                   12336: =item $Title: string, the title of the plot
                   12337: 
                   12338: =item $xlabel: string, text describing the X-axis of the plot
                   12339: 
                   12340: =item $ylabel: string, text describing the Y-axis of the plot
                   12341: 
                   12342: =item $colors: Array ref containing the hex color codes for the data to be 
                   12343: plotted in.  If undefined, default values will be used.
                   12344: 
                   12345: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   12346: 
                   12347: =item $Ydata1: The first data set
                   12348: 
                   12349: =item $Min1: The minimum value of the left Y-axis
                   12350: 
                   12351: =item $Max1: The maximum value of the left Y-axis
                   12352: 
                   12353: =item $Ydata2: The second data set
                   12354: 
                   12355: =item $Min2: The minimum value of the right Y-axis
                   12356: 
                   12357: =item $Max2: The maximum value of the left Y-axis
                   12358: 
                   12359: =item %Values: hash indicating or overriding any default values which are 
                   12360: passed to graph.png.  
                   12361: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   12362: 
                   12363: =back
                   12364: 
                   12365: Returns:
                   12366: 
                   12367: An <img> tag which references graph.png and the appropriate identifying
                   12368: information for the plot.
1.136     matthew  12369: 
                   12370: =cut
                   12371: 
                   12372: ############################################################
                   12373: ############################################################
1.137     matthew  12374: sub DrawXYYGraph {
                   12375:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   12376:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  12377:     #
                   12378:     # Create the identifier for the graph
                   12379:     my $identifier = &get_cgi_id();
                   12380:     my $id = 'cgi.'.$identifier;
                   12381:     #
                   12382:     $Title  = '' if (! defined($Title));
                   12383:     $xlabel = '' if (! defined($xlabel));
                   12384:     $ylabel = '' if (! defined($ylabel));
                   12385:     my %ValuesHash = 
                   12386:         (
1.369     www      12387:          $id.'.title'  => &escape($Title),
                   12388:          $id.'.xlabel' => &escape($xlabel),
                   12389:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  12390:          $id.'.labels' => join(',',@$Xlabels),
                   12391:          $id.'.PlotType' => 'XY',
                   12392:          $id.'.NumSets' => 2,
1.137     matthew  12393:          $id.'.two_axes' => 1,
                   12394:          $id.'.y1_max_value' => $Max1,
                   12395:          $id.'.y1_min_value' => $Min1,
                   12396:          $id.'.y2_max_value' => $Max2,
                   12397:          $id.'.y2_min_value' => $Min2,
1.136     matthew  12398:          );
                   12399:     #
1.137     matthew  12400:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   12401:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   12402:     }
                   12403:     #
                   12404:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   12405:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  12406:         return '';
                   12407:     }
                   12408:     my $NumSets=1;
1.137     matthew  12409:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  12410:         next if (! ref($array));
                   12411:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  12412:     }
                   12413:     #
                   12414:     # Deal with other parameters
                   12415:     while (my ($key,$value) = each(%Values)) {
                   12416:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  12417:     }
                   12418:     #
1.646     raeburn  12419:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 12420:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  12421: }
                   12422: 
                   12423: ############################################################
                   12424: ############################################################
                   12425: 
                   12426: =pod
                   12427: 
1.157     matthew  12428: =back 
                   12429: 
1.139     matthew  12430: =head1 Statistics helper routines?  
                   12431: 
                   12432: Bad place for them but what the hell.
                   12433: 
1.157     matthew  12434: =over 4
                   12435: 
1.648     raeburn  12436: =item * &chartlink()
1.139     matthew  12437: 
                   12438: Returns a link to the chart for a specific student.  
                   12439: 
                   12440: Inputs:
                   12441: 
                   12442: =over 4
                   12443: 
                   12444: =item $linktext: The text of the link
                   12445: 
                   12446: =item $sname: The students username
                   12447: 
                   12448: =item $sdomain: The students domain
                   12449: 
                   12450: =back
                   12451: 
1.157     matthew  12452: =back
                   12453: 
1.139     matthew  12454: =cut
                   12455: 
                   12456: ############################################################
                   12457: ############################################################
                   12458: sub chartlink {
                   12459:     my ($linktext, $sname, $sdomain) = @_;
                   12460:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      12461:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 12462:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  12463:        '">'.$linktext.'</a>';
1.153     matthew  12464: }
                   12465: 
                   12466: #######################################################
                   12467: #######################################################
                   12468: 
                   12469: =pod
                   12470: 
                   12471: =head1 Course Environment Routines
1.157     matthew  12472: 
                   12473: =over 4
1.153     matthew  12474: 
1.648     raeburn  12475: =item * &restore_course_settings()
1.153     matthew  12476: 
1.648     raeburn  12477: =item * &store_course_settings()
1.153     matthew  12478: 
                   12479: Restores/Store indicated form parameters from the course environment.
                   12480: Will not overwrite existing values of the form parameters.
                   12481: 
                   12482: Inputs: 
                   12483: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   12484: 
                   12485: a hash ref describing the data to be stored.  For example:
                   12486:    
                   12487: %Save_Parameters = ('Status' => 'scalar',
                   12488:     'chartoutputmode' => 'scalar',
                   12489:     'chartoutputdata' => 'scalar',
                   12490:     'Section' => 'array',
1.373     raeburn  12491:     'Group' => 'array',
1.153     matthew  12492:     'StudentData' => 'array',
                   12493:     'Maps' => 'array');
                   12494: 
                   12495: Returns: both routines return nothing
                   12496: 
1.631     raeburn  12497: =back
                   12498: 
1.153     matthew  12499: =cut
                   12500: 
                   12501: #######################################################
                   12502: #######################################################
                   12503: sub store_course_settings {
1.496     albertel 12504:     return &store_settings($env{'request.course.id'},@_);
                   12505: }
                   12506: 
                   12507: sub store_settings {
1.153     matthew  12508:     # save to the environment
                   12509:     # appenv the same items, just to be safe
1.300     albertel 12510:     my $udom  = $env{'user.domain'};
                   12511:     my $uname = $env{'user.name'};
1.496     albertel 12512:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  12513:     my %SaveHash;
                   12514:     my %AppHash;
                   12515:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 12516:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 12517:         my $envname = 'environment.'.$basename;
1.258     albertel 12518:         if (exists($env{'form.'.$setting})) {
1.153     matthew  12519:             # Save this value away
                   12520:             if ($type eq 'scalar' &&
1.258     albertel 12521:                 (! exists($env{$envname}) || 
                   12522:                  $env{$envname} ne $env{'form.'.$setting})) {
                   12523:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   12524:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  12525:             } elsif ($type eq 'array') {
                   12526:                 my $stored_form;
1.258     albertel 12527:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  12528:                     $stored_form = join(',',
                   12529:                                         map {
1.369     www      12530:                                             &escape($_);
1.258     albertel 12531:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  12532:                 } else {
                   12533:                     $stored_form = 
1.369     www      12534:                         &escape($env{'form.'.$setting});
1.153     matthew  12535:                 }
                   12536:                 # Determine if the array contents are the same.
1.258     albertel 12537:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  12538:                     $SaveHash{$basename} = $stored_form;
                   12539:                     $AppHash{$envname}   = $stored_form;
                   12540:                 }
                   12541:             }
                   12542:         }
                   12543:     }
                   12544:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 12545:                                           $udom,$uname);
1.153     matthew  12546:     if ($put_result !~ /^(ok|delayed)/) {
                   12547:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   12548:                                  'got error:'.$put_result);
                   12549:     }
                   12550:     # Make sure these settings stick around in this session, too
1.646     raeburn  12551:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  12552:     return;
                   12553: }
                   12554: 
                   12555: sub restore_course_settings {
1.499     albertel 12556:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 12557: }
                   12558: 
                   12559: sub restore_settings {
                   12560:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  12561:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 12562:         next if (exists($env{'form.'.$setting}));
1.496     albertel 12563:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  12564:             '.'.$setting;
1.258     albertel 12565:         if (exists($env{$envname})) {
1.153     matthew  12566:             if ($type eq 'scalar') {
1.258     albertel 12567:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  12568:             } elsif ($type eq 'array') {
1.258     albertel 12569:                 $env{'form.'.$setting} = [ 
1.153     matthew  12570:                                            map { 
1.369     www      12571:                                                &unescape($_); 
1.258     albertel 12572:                                            } split(',',$env{$envname})
1.153     matthew  12573:                                            ];
                   12574:             }
                   12575:         }
                   12576:     }
1.127     matthew  12577: }
                   12578: 
1.618     raeburn  12579: #######################################################
                   12580: #######################################################
                   12581: 
                   12582: =pod
                   12583: 
                   12584: =head1 Domain E-mail Routines  
                   12585: 
                   12586: =over 4
                   12587: 
1.648     raeburn  12588: =item * &build_recipient_list()
1.618     raeburn  12589: 
1.884     raeburn  12590: Build recipient lists for five types of e-mail:
1.766     raeburn  12591: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.884     raeburn  12592: (d) Help requests, (e) Course requests needing approval,  generated by
                   12593: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
                   12594: loncoursequeueadmin.pm respectively.
1.618     raeburn  12595: 
                   12596: Inputs:
1.619     raeburn  12597: defmail (scalar - email address of default recipient), 
1.618     raeburn  12598: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
1.619     raeburn  12599: defdom (domain for which to retrieve configuration settings),
                   12600: origmail (scalar - email address of recipient from loncapa.conf, 
                   12601: i.e., predates configuration by DC via domainprefs.pm 
1.618     raeburn  12602: 
1.655     raeburn  12603: Returns: comma separated list of addresses to which to send e-mail.
                   12604: 
                   12605: =back
1.618     raeburn  12606: 
                   12607: =cut
                   12608: 
                   12609: ############################################################
                   12610: ############################################################
                   12611: sub build_recipient_list {
1.619     raeburn  12612:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  12613:     my @recipients;
                   12614:     my $otheremails;
                   12615:     my %domconfig =
                   12616:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
                   12617:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  12618:         if (exists($domconfig{'contacts'}{$mailing})) {
                   12619:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   12620:                 my @contacts = ('adminemail','supportemail');
                   12621:                 foreach my $item (@contacts) {
                   12622:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   12623:                         my $addr = $domconfig{'contacts'}{$item}; 
                   12624:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   12625:                             push(@recipients,$addr);
                   12626:                         }
1.619     raeburn  12627:                     }
1.766     raeburn  12628:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
1.618     raeburn  12629:                 }
                   12630:             }
1.766     raeburn  12631:         } elsif ($origmail ne '') {
                   12632:             push(@recipients,$origmail);
1.618     raeburn  12633:         }
1.619     raeburn  12634:     } elsif ($origmail ne '') {
                   12635:         push(@recipients,$origmail);
1.618     raeburn  12636:     }
1.688     raeburn  12637:     if (defined($defmail)) {
                   12638:         if ($defmail ne '') {
                   12639:             push(@recipients,$defmail);
                   12640:         }
1.618     raeburn  12641:     }
                   12642:     if ($otheremails) {
1.619     raeburn  12643:         my @others;
                   12644:         if ($otheremails =~ /,/) {
                   12645:             @others = split(/,/,$otheremails);
1.618     raeburn  12646:         } else {
1.619     raeburn  12647:             push(@others,$otheremails);
                   12648:         }
                   12649:         foreach my $addr (@others) {
                   12650:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   12651:                 push(@recipients,$addr);
                   12652:             }
1.618     raeburn  12653:         }
                   12654:     }
1.619     raeburn  12655:     my $recipientlist = join(',',@recipients); 
1.618     raeburn  12656:     return $recipientlist;
                   12657: }
                   12658: 
1.127     matthew  12659: ############################################################
                   12660: ############################################################
1.154     albertel 12661: 
1.655     raeburn  12662: =pod
                   12663: 
                   12664: =head1 Course Catalog Routines
                   12665: 
                   12666: =over 4
                   12667: 
                   12668: =item * &gather_categories()
                   12669: 
                   12670: Converts category definitions - keys of categories hash stored in  
                   12671: coursecategories in configuration.db on the primary library server in a 
                   12672: domain - to an array.  Also generates javascript and idx hash used to 
                   12673: generate Domain Coordinator interface for editing Course Categories.
                   12674: 
                   12675: Inputs:
1.663     raeburn  12676: 
1.655     raeburn  12677: categories (reference to hash of category definitions).
1.663     raeburn  12678: 
1.655     raeburn  12679: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   12680:       categories and subcategories).
1.663     raeburn  12681: 
1.655     raeburn  12682: idx (reference to hash of counters used in Domain Coordinator interface for 
                   12683:       editing Course Categories).
1.663     raeburn  12684: 
1.655     raeburn  12685: jsarray (reference to array of categories used to create Javascript arrays for
                   12686:          Domain Coordinator interface for editing Course Categories).
                   12687: 
                   12688: Returns: nothing
                   12689: 
                   12690: Side effects: populates cats, idx and jsarray. 
                   12691: 
                   12692: =cut
                   12693: 
                   12694: sub gather_categories {
                   12695:     my ($categories,$cats,$idx,$jsarray) = @_;
                   12696:     my %counters;
                   12697:     my $num = 0;
                   12698:     foreach my $item (keys(%{$categories})) {
                   12699:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   12700:         if ($container eq '' && $depth == 0) {
                   12701:             $cats->[$depth][$categories->{$item}] = $cat;
                   12702:         } else {
                   12703:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   12704:         }
                   12705:         my ($escitem,$tail) = split(/:/,$item,2);
                   12706:         if ($counters{$tail} eq '') {
                   12707:             $counters{$tail} = $num;
                   12708:             $num ++;
                   12709:         }
                   12710:         if (ref($idx) eq 'HASH') {
                   12711:             $idx->{$item} = $counters{$tail};
                   12712:         }
                   12713:         if (ref($jsarray) eq 'ARRAY') {
                   12714:             push(@{$jsarray->[$counters{$tail}]},$item);
                   12715:         }
                   12716:     }
                   12717:     return;
                   12718: }
                   12719: 
                   12720: =pod
                   12721: 
                   12722: =item * &extract_categories()
                   12723: 
                   12724: Used to generate breadcrumb trails for course categories.
                   12725: 
                   12726: Inputs:
1.663     raeburn  12727: 
1.655     raeburn  12728: categories (reference to hash of category definitions).
1.663     raeburn  12729: 
1.655     raeburn  12730: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   12731:       categories and subcategories).
1.663     raeburn  12732: 
1.655     raeburn  12733: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  12734: 
1.655     raeburn  12735: allitems (reference to hash - key is category key 
                   12736:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  12737: 
1.655     raeburn  12738: idx (reference to hash of counters used in Domain Coordinator interface for
                   12739:       editing Course Categories).
1.663     raeburn  12740: 
1.655     raeburn  12741: jsarray (reference to array of categories used to create Javascript arrays for
                   12742:          Domain Coordinator interface for editing Course Categories).
                   12743: 
1.665     raeburn  12744: subcats (reference to hash of arrays containing all subcategories within each 
                   12745:          category, -recursive)
                   12746: 
1.655     raeburn  12747: Returns: nothing
                   12748: 
                   12749: Side effects: populates trails and allitems hash references.
                   12750: 
                   12751: =cut
                   12752: 
                   12753: sub extract_categories {
1.665     raeburn  12754:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  12755:     if (ref($categories) eq 'HASH') {
                   12756:         &gather_categories($categories,$cats,$idx,$jsarray);
                   12757:         if (ref($cats->[0]) eq 'ARRAY') {
                   12758:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   12759:                 my $name = $cats->[0][$i];
                   12760:                 my $item = &escape($name).'::0';
                   12761:                 my $trailstr;
                   12762:                 if ($name eq 'instcode') {
                   12763:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  12764:                 } elsif ($name eq 'communities') {
                   12765:                     $trailstr = &mt('Communities');
1.655     raeburn  12766:                 } else {
                   12767:                     $trailstr = $name;
                   12768:                 }
                   12769:                 if ($allitems->{$item} eq '') {
                   12770:                     push(@{$trails},$trailstr);
                   12771:                     $allitems->{$item} = scalar(@{$trails})-1;
                   12772:                 }
                   12773:                 my @parents = ($name);
                   12774:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   12775:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   12776:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  12777:                         if (ref($subcats) eq 'HASH') {
                   12778:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   12779:                         }
                   12780:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   12781:                     }
                   12782:                 } else {
                   12783:                     if (ref($subcats) eq 'HASH') {
                   12784:                         $subcats->{$item} = [];
1.655     raeburn  12785:                     }
                   12786:                 }
                   12787:             }
                   12788:         }
                   12789:     }
                   12790:     return;
                   12791: }
                   12792: 
                   12793: =pod
                   12794: 
                   12795: =item *&recurse_categories()
                   12796: 
                   12797: Recursively used to generate breadcrumb trails for course categories.
                   12798: 
                   12799: Inputs:
1.663     raeburn  12800: 
1.655     raeburn  12801: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   12802:       categories and subcategories).
1.663     raeburn  12803: 
1.655     raeburn  12804: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  12805: 
                   12806: category (current course category, for which breadcrumb trail is being generated).
                   12807: 
                   12808: trails (reference to array of breadcrumb trails for each category).
                   12809: 
1.655     raeburn  12810: allitems (reference to hash - key is category key
                   12811:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  12812: 
1.655     raeburn  12813: parents (array containing containers directories for current category, 
                   12814:          back to top level). 
                   12815: 
                   12816: Returns: nothing
                   12817: 
                   12818: Side effects: populates trails and allitems hash references
                   12819: 
                   12820: =cut
                   12821: 
                   12822: sub recurse_categories {
1.665     raeburn  12823:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  12824:     my $shallower = $depth - 1;
                   12825:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   12826:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   12827:             my $name = $cats->[$depth]{$category}[$k];
                   12828:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   12829:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   12830:             if ($allitems->{$item} eq '') {
                   12831:                 push(@{$trails},$trailstr);
                   12832:                 $allitems->{$item} = scalar(@{$trails})-1;
                   12833:             }
                   12834:             my $deeper = $depth+1;
                   12835:             push(@{$parents},$category);
1.665     raeburn  12836:             if (ref($subcats) eq 'HASH') {
                   12837:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   12838:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   12839:                     my $higher;
                   12840:                     if ($j > 0) {
                   12841:                         $higher = &escape($parents->[$j]).':'.
                   12842:                                   &escape($parents->[$j-1]).':'.$j;
                   12843:                     } else {
                   12844:                         $higher = &escape($parents->[$j]).'::'.$j;
                   12845:                     }
                   12846:                     push(@{$subcats->{$higher}},$subcat);
                   12847:                 }
                   12848:             }
                   12849:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   12850:                                 $subcats);
1.655     raeburn  12851:             pop(@{$parents});
                   12852:         }
                   12853:     } else {
                   12854:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   12855:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   12856:         if ($allitems->{$item} eq '') {
                   12857:             push(@{$trails},$trailstr);
                   12858:             $allitems->{$item} = scalar(@{$trails})-1;
                   12859:         }
                   12860:     }
                   12861:     return;
                   12862: }
                   12863: 
1.663     raeburn  12864: =pod
                   12865: 
                   12866: =item *&assign_categories_table()
                   12867: 
                   12868: Create a datatable for display of hierarchical categories in a domain,
                   12869: with checkboxes to allow a course to be categorized. 
                   12870: 
                   12871: Inputs:
                   12872: 
                   12873: cathash - reference to hash of categories defined for the domain (from
                   12874:           configuration.db)
                   12875: 
                   12876: currcat - scalar with an & separated list of categories assigned to a course. 
                   12877: 
1.919     raeburn  12878: type    - scalar contains course type (Course or Community).
                   12879: 
1.663     raeburn  12880: Returns: $output (markup to be displayed) 
                   12881: 
                   12882: =cut
                   12883: 
                   12884: sub assign_categories_table {
1.919     raeburn  12885:     my ($cathash,$currcat,$type) = @_;
1.663     raeburn  12886:     my $output;
                   12887:     if (ref($cathash) eq 'HASH') {
                   12888:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   12889:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   12890:         $maxdepth = scalar(@cats);
                   12891:         if (@cats > 0) {
                   12892:             my $itemcount = 0;
                   12893:             if (ref($cats[0]) eq 'ARRAY') {
                   12894:                 my @currcategories;
                   12895:                 if ($currcat ne '') {
                   12896:                     @currcategories = split('&',$currcat);
                   12897:                 }
1.919     raeburn  12898:                 my $table;
1.663     raeburn  12899:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   12900:                     my $parent = $cats[0][$i];
1.919     raeburn  12901:                     next if ($parent eq 'instcode');
                   12902:                     if ($type eq 'Community') {
                   12903:                         next unless ($parent eq 'communities');
                   12904:                     } else {
                   12905:                         next if ($parent eq 'communities');
                   12906:                     }
1.663     raeburn  12907:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   12908:                     my $item = &escape($parent).'::0';
                   12909:                     my $checked = '';
                   12910:                     if (@currcategories > 0) {
                   12911:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   12912:                             $checked = ' checked="checked"';
1.663     raeburn  12913:                         }
                   12914:                     }
1.919     raeburn  12915:                     my $parent_title = $parent;
                   12916:                     if ($parent eq 'communities') {
                   12917:                         $parent_title = &mt('Communities');
                   12918:                     }
                   12919:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   12920:                               '<input type="checkbox" name="usecategory" value="'.
                   12921:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
                   12922:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  12923:                     my $depth = 1;
                   12924:                     push(@path,$parent);
1.919     raeburn  12925:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
1.663     raeburn  12926:                     pop(@path);
1.919     raeburn  12927:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  12928:                     $itemcount ++;
                   12929:                 }
1.919     raeburn  12930:                 if ($itemcount) {
                   12931:                     $output = &Apache::loncommon::start_data_table().
                   12932:                               $table.
                   12933:                               &Apache::loncommon::end_data_table();
                   12934:                 }
1.663     raeburn  12935:             }
                   12936:         }
                   12937:     }
                   12938:     return $output;
                   12939: }
                   12940: 
                   12941: =pod
                   12942: 
                   12943: =item *&assign_category_rows()
                   12944: 
                   12945: Create a datatable row for display of nested categories in a domain,
                   12946: with checkboxes to allow a course to be categorized,called recursively.
                   12947: 
                   12948: Inputs:
                   12949: 
                   12950: itemcount - track row number for alternating colors
                   12951: 
                   12952: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   12953:       categories and subcategories.
                   12954: 
                   12955: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   12956: 
                   12957: parent - parent of current category item
                   12958: 
                   12959: path - Array containing all categories back up through the hierarchy from the
                   12960:        current category to the top level.
                   12961: 
                   12962: currcategories - reference to array of current categories assigned to the course
                   12963: 
                   12964: Returns: $output (markup to be displayed).
                   12965: 
                   12966: =cut
                   12967: 
                   12968: sub assign_category_rows {
                   12969:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
                   12970:     my ($text,$name,$item,$chgstr);
                   12971:     if (ref($cats) eq 'ARRAY') {
                   12972:         my $maxdepth = scalar(@{$cats});
                   12973:         if (ref($cats->[$depth]) eq 'HASH') {
                   12974:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   12975:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   12976:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   12977:                 $text .= '<td><table class="LC_datatable">';
                   12978:                 for (my $j=0; $j<$numchildren; $j++) {
                   12979:                     $name = $cats->[$depth]{$parent}[$j];
                   12980:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   12981:                     my $deeper = $depth+1;
                   12982:                     my $checked = '';
                   12983:                     if (ref($currcategories) eq 'ARRAY') {
                   12984:                         if (@{$currcategories} > 0) {
                   12985:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   12986:                                 $checked = ' checked="checked"';
1.663     raeburn  12987:                             }
                   12988:                         }
                   12989:                     }
1.664     raeburn  12990:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   12991:                              '<input type="checkbox" name="usecategory" value="'.
1.675     raeburn  12992:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
                   12993:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   12994:                              '</td><td>';
1.663     raeburn  12995:                     if (ref($path) eq 'ARRAY') {
                   12996:                         push(@{$path},$name);
                   12997:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
                   12998:                         pop(@{$path});
                   12999:                     }
                   13000:                     $text .= '</td></tr>';
                   13001:                 }
                   13002:                 $text .= '</table></td>';
                   13003:             }
                   13004:         }
                   13005:     }
                   13006:     return $text;
                   13007: }
                   13008: 
1.655     raeburn  13009: ############################################################
                   13010: ############################################################
                   13011: 
                   13012: 
1.443     albertel 13013: sub commit_customrole {
1.664     raeburn  13014:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  13015:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 13016:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   13017:                          ($end?', ending '.localtime($end):'').': <b>'.
                   13018:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  13019:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 13020:                  '</b><br />';
                   13021:     return $output;
                   13022: }
                   13023: 
                   13024: sub commit_standardrole {
1.541     raeburn  13025:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
                   13026:     my ($output,$logmsg,$linefeed);
                   13027:     if ($context eq 'auto') {
                   13028:         $linefeed = "\n";
                   13029:     } else {
                   13030:         $linefeed = "<br />\n";
                   13031:     }  
1.443     albertel 13032:     if ($three eq 'st') {
1.541     raeburn  13033:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
                   13034:                                          $one,$two,$sec,$context);
                   13035:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  13036:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   13037:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 13038:         } else {
1.541     raeburn  13039:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 13040:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  13041:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   13042:             if ($context eq 'auto') {
                   13043:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   13044:             } else {
                   13045:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   13046:                &mt('Add to classlist').': <b>ok</b>';
                   13047:             }
                   13048:             $output .= $linefeed;
1.443     albertel 13049:         }
                   13050:     } else {
                   13051:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   13052:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  13053:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  13054:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  13055:         if ($context eq 'auto') {
                   13056:             $output .= $result.$linefeed;
                   13057:         } else {
                   13058:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   13059:         }
1.443     albertel 13060:     }
                   13061:     return $output;
                   13062: }
                   13063: 
                   13064: sub commit_studentrole {
1.541     raeburn  13065:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
1.626     raeburn  13066:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  13067:     if ($context eq 'auto') {
                   13068:         $linefeed = "\n";
                   13069:     } else {
                   13070:         $linefeed = '<br />'."\n";
                   13071:     }
1.443     albertel 13072:     if (defined($one) && defined($two)) {
                   13073:         my $cid=$one.'_'.$two;
                   13074:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   13075:         my $secchange = 0;
                   13076:         my $expire_role_result;
                   13077:         my $modify_section_result;
1.628     raeburn  13078:         if ($oldsec ne '-1') { 
                   13079:             if ($oldsec ne $sec) {
1.443     albertel 13080:                 $secchange = 1;
1.628     raeburn  13081:                 my $now = time;
1.443     albertel 13082:                 my $uurl='/'.$cid;
                   13083:                 $uurl=~s/\_/\//g;
                   13084:                 if ($oldsec) {
                   13085:                     $uurl.='/'.$oldsec;
                   13086:                 }
1.626     raeburn  13087:                 $oldsecurl = $uurl;
1.628     raeburn  13088:                 $expire_role_result = 
1.652     raeburn  13089:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  13090:                 if ($env{'request.course.sec'} ne '') { 
                   13091:                     if ($expire_role_result eq 'refused') {
                   13092:                         my @roles = ('st');
                   13093:                         my @statuses = ('previous');
                   13094:                         my @roledoms = ($one);
                   13095:                         my $withsec = 1;
                   13096:                         my %roleshash = 
                   13097:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   13098:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   13099:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   13100:                             my ($oldstart,$oldend) = 
                   13101:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   13102:                             if ($oldend > 0 && $oldend <= $now) {
                   13103:                                 $expire_role_result = 'ok';
                   13104:                             }
                   13105:                         }
                   13106:                     }
                   13107:                 }
1.443     albertel 13108:                 $result = $expire_role_result;
                   13109:             }
                   13110:         }
                   13111:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.652     raeburn  13112:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
1.443     albertel 13113:             if ($modify_section_result =~ /^ok/) {
                   13114:                 if ($secchange == 1) {
1.628     raeburn  13115:                     if ($sec eq '') {
                   13116:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   13117:                     } else {
                   13118:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   13119:                     }
1.443     albertel 13120:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  13121:                     if ($sec eq '') {
                   13122:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   13123:                     } else {
                   13124:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   13125:                     }
1.443     albertel 13126:                 } else {
1.628     raeburn  13127:                     if ($sec eq '') {
                   13128:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   13129:                     } else {
                   13130:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   13131:                     }
1.443     albertel 13132:                 }
                   13133:             } else {
1.628     raeburn  13134:                 if ($secchange) {       
                   13135:                     $$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;
                   13136:                 } else {
                   13137:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   13138:                 }
1.443     albertel 13139:             }
                   13140:             $result = $modify_section_result;
                   13141:         } elsif ($secchange == 1) {
1.628     raeburn  13142:             if ($oldsec eq '') {
                   13143:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
                   13144:             } else {
                   13145:                 $$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;
                   13146:             }
1.626     raeburn  13147:             if ($expire_role_result eq 'refused') {
                   13148:                 my $newsecurl = '/'.$cid;
                   13149:                 $newsecurl =~ s/\_/\//g;
                   13150:                 if ($sec ne '') {
                   13151:                     $newsecurl.='/'.$sec;
                   13152:                 }
                   13153:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   13154:                     if ($sec eq '') {
                   13155:                         $$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;
                   13156:                     } else {
                   13157:                         $$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;
                   13158:                     }
                   13159:                 }
                   13160:             }
1.443     albertel 13161:         }
                   13162:     } else {
1.626     raeburn  13163:         $$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 13164:         $result = "error: incomplete course id\n";
                   13165:     }
                   13166:     return $result;
                   13167: }
                   13168: 
                   13169: ############################################################
                   13170: ############################################################
                   13171: 
1.566     albertel 13172: sub check_clone {
1.578     raeburn  13173:     my ($args,$linefeed) = @_;
1.566     albertel 13174:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   13175:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   13176:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   13177:     my $clonemsg;
                   13178:     my $can_clone = 0;
1.944     raeburn  13179:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  13180:     if ($lctype ne 'community') {
                   13181:         $lctype = 'course';
                   13182:     }
1.566     albertel 13183:     if ($clonehome eq 'no_host') {
1.944     raeburn  13184:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13185:             $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
                   13186:         } else {
                   13187:             $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'});
                   13188:         }     
1.566     albertel 13189:     } else {
                   13190: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  13191:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13192:             if ($clonedesc{'type'} ne 'Community') {
                   13193:                  $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
                   13194:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   13195:             }
                   13196:         }
1.882     raeburn  13197: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
                   13198:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 13199: 	    $can_clone = 1;
                   13200: 	} else {
                   13201: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
                   13202: 						 $args->{'clonedomain'},$args->{'clonecourse'});
                   13203: 	    my @cloners = split(/,/,$clonehash{'cloners'});
1.578     raeburn  13204:             if (grep(/^\*$/,@cloners)) {
                   13205:                 $can_clone = 1;
                   13206:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   13207:                 $can_clone = 1;
                   13208:             } else {
1.908     raeburn  13209:                 my $ccrole = 'cc';
1.944     raeburn  13210:                 if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13211:                     $ccrole = 'co';
                   13212:                 }
1.578     raeburn  13213: 	        my %roleshash =
                   13214: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   13215: 					 $args->{'ccdomain'},
1.908     raeburn  13216:                                          'userroles',['active'],[$ccrole],
1.578     raeburn  13217: 					 [$args->{'clonedomain'}]);
1.908     raeburn  13218: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
1.942     raeburn  13219:                     $can_clone = 1;
                   13220:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
                   13221:                     $can_clone = 1;
                   13222:                 } else {
1.944     raeburn  13223:                     if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13224:                         $clonemsg = &mt('No new community created.').$linefeed.&mt('The new community could not be cloned from the existing community because the new community owner ([_1]) does not have cloning rights in the existing community ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
                   13225:                     } else {
                   13226:                         $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'});
                   13227:                     }
1.578     raeburn  13228: 	        }
1.566     albertel 13229: 	    }
1.578     raeburn  13230:         }
1.566     albertel 13231:     }
                   13232:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   13233: }
                   13234: 
1.444     albertel 13235: sub construct_course {
1.885     raeburn  13236:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
1.444     albertel 13237:     my $outcome;
1.541     raeburn  13238:     my $linefeed =  '<br />'."\n";
                   13239:     if ($context eq 'auto') {
                   13240:         $linefeed = "\n";
                   13241:     }
1.566     albertel 13242: 
                   13243: #
                   13244: # Are we cloning?
                   13245: #
                   13246:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   13247:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  13248: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 13249: 	if ($context ne 'auto') {
1.578     raeburn  13250:             if ($clonemsg ne '') {
                   13251: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   13252:             }
1.566     albertel 13253: 	}
                   13254: 	$outcome .= $clonemsg.$linefeed;
                   13255: 
                   13256:         if (!$can_clone) {
                   13257: 	    return (0,$outcome);
                   13258: 	}
                   13259:     }
                   13260: 
1.444     albertel 13261: #
                   13262: # Open course
                   13263: #
                   13264:     my $crstype = lc($args->{'crstype'});
                   13265:     my %cenv=();
                   13266:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   13267:                                              $args->{'cdescr'},
                   13268:                                              $args->{'curl'},
                   13269:                                              $args->{'course_home'},
                   13270:                                              $args->{'nonstandard'},
                   13271:                                              $args->{'crscode'},
                   13272:                                              $args->{'ccuname'}.':'.
                   13273:                                              $args->{'ccdomain'},
1.882     raeburn  13274:                                              $args->{'crstype'},
1.885     raeburn  13275:                                              $cnum,$context,$category);
1.444     albertel 13276: 
                   13277:     # Note: The testing routines depend on this being output; see 
                   13278:     # Utils::Course. This needs to at least be output as a comment
                   13279:     # if anyone ever decides to not show this, and Utils::Course::new
                   13280:     # will need to be suitably modified.
1.541     raeburn  13281:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  13282:     if ($$courseid =~ /^error:/) {
                   13283:         return (0,$outcome);
                   13284:     }
                   13285: 
1.444     albertel 13286: #
                   13287: # Check if created correctly
                   13288: #
1.479     albertel 13289:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 13290:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  13291:     if ($crsuhome eq 'no_host') {
                   13292:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   13293:         return (0,$outcome);
                   13294:     }
1.541     raeburn  13295:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 13296: 
1.444     albertel 13297: #
1.566     albertel 13298: # Do the cloning
                   13299: #   
                   13300:     if ($can_clone && $cloneid) {
                   13301: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   13302: 	if ($context ne 'auto') {
                   13303: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   13304: 	}
                   13305: 	$outcome .= $clonemsg.$linefeed;
                   13306: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 13307: # Copy all files
1.637     www      13308: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 13309: # Restore URL
1.566     albertel 13310: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 13311: # Restore title
1.566     albertel 13312: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  13313: # Restore creation date, creator and creation context.
                   13314:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   13315:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   13316:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 13317: # Mark as cloned
1.566     albertel 13318: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      13319: # Need to clone grading mode
                   13320:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   13321:         $cenv{'grading'}=$newenv{'grading'};
                   13322: # Do not clone these environment entries
                   13323:         &Apache::lonnet::del('environment',
                   13324:                   ['default_enrollment_start_date',
                   13325:                    'default_enrollment_end_date',
                   13326:                    'question.email',
                   13327:                    'policy.email',
                   13328:                    'comment.email',
                   13329:                    'pch.users.denied',
1.725     raeburn  13330:                    'plc.users.denied',
                   13331:                    'hidefromcat',
                   13332:                    'categories'],
1.638     www      13333:                    $$crsudom,$$crsunum);
1.444     albertel 13334:     }
1.566     albertel 13335: 
1.444     albertel 13336: #
                   13337: # Set environment (will override cloned, if existing)
                   13338: #
                   13339:     my @sections = ();
                   13340:     my @xlists = ();
                   13341:     if ($args->{'crstype'}) {
                   13342:         $cenv{'type'}=$args->{'crstype'};
                   13343:     }
                   13344:     if ($args->{'crsid'}) {
                   13345:         $cenv{'courseid'}=$args->{'crsid'};
                   13346:     }
                   13347:     if ($args->{'crscode'}) {
                   13348:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   13349:     }
                   13350:     if ($args->{'crsquota'} ne '') {
                   13351:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   13352:     } else {
                   13353:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   13354:     }
                   13355:     if ($args->{'ccuname'}) {
                   13356:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   13357:                                         ':'.$args->{'ccdomain'};
                   13358:     } else {
                   13359:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   13360:     }
                   13361:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   13362:     if ($args->{'crssections'}) {
                   13363:         $cenv{'internal.sectionnums'} = '';
                   13364:         if ($args->{'crssections'} =~ m/,/) {
                   13365:             @sections = split/,/,$args->{'crssections'};
                   13366:         } else {
                   13367:             $sections[0] = $args->{'crssections'};
                   13368:         }
                   13369:         if (@sections > 0) {
                   13370:             foreach my $item (@sections) {
                   13371:                 my ($sec,$gp) = split/:/,$item;
                   13372:                 my $class = $args->{'crscode'}.$sec;
                   13373:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   13374:                 $cenv{'internal.sectionnums'} .= $item.',';
                   13375:                 unless ($addcheck eq 'ok') {
                   13376:                     push @badclasses, $class;
                   13377:                 }
                   13378:             }
                   13379:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   13380:         }
                   13381:     }
                   13382: # do not hide course coordinator from staff listing, 
                   13383: # even if privileged
                   13384:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   13385: # add crosslistings
                   13386:     if ($args->{'crsxlist'}) {
                   13387:         $cenv{'internal.crosslistings'}='';
                   13388:         if ($args->{'crsxlist'} =~ m/,/) {
                   13389:             @xlists = split/,/,$args->{'crsxlist'};
                   13390:         } else {
                   13391:             $xlists[0] = $args->{'crsxlist'};
                   13392:         }
                   13393:         if (@xlists > 0) {
                   13394:             foreach my $item (@xlists) {
                   13395:                 my ($xl,$gp) = split/:/,$item;
                   13396:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   13397:                 $cenv{'internal.crosslistings'} .= $item.',';
                   13398:                 unless ($addcheck eq 'ok') {
                   13399:                     push @badclasses, $xl;
                   13400:                 }
                   13401:             }
                   13402:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   13403:         }
                   13404:     }
                   13405:     if ($args->{'autoadds'}) {
                   13406:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   13407:     }
                   13408:     if ($args->{'autodrops'}) {
                   13409:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   13410:     }
                   13411: # check for notification of enrollment changes
                   13412:     my @notified = ();
                   13413:     if ($args->{'notify_owner'}) {
                   13414:         if ($args->{'ccuname'} ne '') {
                   13415:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   13416:         }
                   13417:     }
                   13418:     if ($args->{'notify_dc'}) {
                   13419:         if ($uname ne '') { 
1.630     raeburn  13420:             push(@notified,$uname.':'.$udom);
1.444     albertel 13421:         }
                   13422:     }
                   13423:     if (@notified > 0) {
                   13424:         my $notifylist;
                   13425:         if (@notified > 1) {
                   13426:             $notifylist = join(',',@notified);
                   13427:         } else {
                   13428:             $notifylist = $notified[0];
                   13429:         }
                   13430:         $cenv{'internal.notifylist'} = $notifylist;
                   13431:     }
                   13432:     if (@badclasses > 0) {
                   13433:         my %lt=&Apache::lonlocal::texthash(
                   13434:                 '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',
                   13435:                 'dnhr' => 'does not have rights to access enrollment in these classes',
                   13436:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
                   13437:         );
1.541     raeburn  13438:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
                   13439:                            ' ('.$lt{'adby'}.')';
                   13440:         if ($context eq 'auto') {
                   13441:             $outcome .= $badclass_msg.$linefeed;
1.566     albertel 13442:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.541     raeburn  13443:             foreach my $item (@badclasses) {
                   13444:                 if ($context eq 'auto') {
                   13445:                     $outcome .= " - $item\n";
                   13446:                 } else {
                   13447:                     $outcome .= "<li>$item</li>\n";
                   13448:                 }
                   13449:             }
                   13450:             if ($context eq 'auto') {
                   13451:                 $outcome .= $linefeed;
                   13452:             } else {
1.566     albertel 13453:                 $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  13454:             }
                   13455:         } 
1.444     albertel 13456:     }
                   13457:     if ($args->{'no_end_date'}) {
                   13458:         $args->{'endaccess'} = 0;
                   13459:     }
                   13460:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   13461:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   13462:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   13463:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   13464:     if ($args->{'showphotos'}) {
                   13465:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   13466:     }
                   13467:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   13468:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   13469:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   13470:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  13471:             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'); 
                   13472:             if ($context eq 'auto') {
                   13473:                 $outcome .= $krb_msg;
                   13474:             } else {
1.566     albertel 13475:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  13476:             }
                   13477:             $outcome .= $linefeed;
1.444     albertel 13478:         }
                   13479:     }
                   13480:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   13481:        if ($args->{'setpolicy'}) {
                   13482:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   13483:        }
                   13484:        if ($args->{'setcontent'}) {
                   13485:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   13486:        }
                   13487:     }
                   13488:     if ($args->{'reshome'}) {
                   13489: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   13490: 	$cenv{'reshome'}=~s/\/+$/\//;
                   13491:     }
                   13492: #
                   13493: # course has keyed access
                   13494: #
                   13495:     if ($args->{'setkeys'}) {
                   13496:        $cenv{'keyaccess'}='yes';
                   13497:     }
                   13498: # if specified, key authority is not course, but user
                   13499: # only active if keyaccess is yes
                   13500:     if ($args->{'keyauth'}) {
1.487     albertel 13501: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   13502: 	$user = &LONCAPA::clean_username($user);
                   13503: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     13504: 	if ($user ne '' && $domain ne '') {
1.487     albertel 13505: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 13506: 	}
                   13507:     }
                   13508: 
                   13509:     if ($args->{'disresdis'}) {
                   13510:         $cenv{'pch.roles.denied'}='st';
                   13511:     }
                   13512:     if ($args->{'disablechat'}) {
                   13513:         $cenv{'plc.roles.denied'}='st';
                   13514:     }
                   13515: 
                   13516:     # Record we've not yet viewed the Course Initialization Helper for this 
                   13517:     # course
                   13518:     $cenv{'course.helper.not.run'} = 1;
                   13519:     #
                   13520:     # Use new Randomseed
                   13521:     #
                   13522:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   13523:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   13524:     #
                   13525:     # The encryption code and receipt prefix for this course
                   13526:     #
                   13527:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   13528:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   13529:     #
                   13530:     # By default, use standard grading
                   13531:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   13532: 
1.541     raeburn  13533:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   13534:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 13535: #
                   13536: # Open all assignments
                   13537: #
                   13538:     if ($args->{'openall'}) {
                   13539:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   13540:        my %storecontent = ($storeunder         => time,
                   13541:                            $storeunder.'.type' => 'date_start');
                   13542:        
                   13543:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  13544:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 13545:    }
                   13546: #
                   13547: # Set first page
                   13548: #
                   13549:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   13550: 	    || ($cloneid)) {
1.445     albertel 13551: 	use LONCAPA::map;
1.444     albertel 13552: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 13553: 
                   13554: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   13555:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   13556: 
1.444     albertel 13557:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   13558:         my $title; my $url;
                   13559:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   13560: 	    $title=&mt('Syllabus');
1.444     albertel 13561:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   13562:         } else {
1.963     raeburn  13563:             $title=&mt('Table of Contents');
1.444     albertel 13564:             $url='/adm/navmaps';
                   13565:         }
1.445     albertel 13566: 
                   13567:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   13568: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   13569: 
                   13570: 	if ($errtext) { $fatal=2; }
1.541     raeburn  13571:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 13572:     }
1.566     albertel 13573: 
                   13574:     return (1,$outcome);
1.444     albertel 13575: }
                   13576: 
                   13577: ############################################################
                   13578: ############################################################
                   13579: 
1.953     droeschl 13580: #SD
                   13581: # only Community and Course, or anything else?
1.378     raeburn  13582: sub course_type {
                   13583:     my ($cid) = @_;
                   13584:     if (!defined($cid)) {
                   13585:         $cid = $env{'request.course.id'};
                   13586:     }
1.404     albertel 13587:     if (defined($env{'course.'.$cid.'.type'})) {
                   13588:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  13589:     } else {
                   13590:         return 'Course';
1.377     raeburn  13591:     }
                   13592: }
1.156     albertel 13593: 
1.406     raeburn  13594: sub group_term {
                   13595:     my $crstype = &course_type();
                   13596:     my %names = (
                   13597:                   'Course' => 'group',
1.865     raeburn  13598:                   'Community' => 'group',
1.406     raeburn  13599:                 );
                   13600:     return $names{$crstype};
                   13601: }
                   13602: 
1.902     raeburn  13603: sub course_types {
                   13604:     my @types = ('official','unofficial','community');
                   13605:     my %typename = (
                   13606:                          official   => 'Official course',
                   13607:                          unofficial => 'Unofficial course',
                   13608:                          community  => 'Community',
                   13609:                    );
                   13610:     return (\@types,\%typename);
                   13611: }
                   13612: 
1.156     albertel 13613: sub icon {
                   13614:     my ($file)=@_;
1.505     albertel 13615:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 13616:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 13617:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 13618:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   13619: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   13620: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   13621: 	            $curfext.".gif") {
                   13622: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   13623: 		$curfext.".gif";
                   13624: 	}
                   13625:     }
1.249     albertel 13626:     return &lonhttpdurl($iconname);
1.154     albertel 13627: } 
1.84      albertel 13628: 
1.575     albertel 13629: sub lonhttpdurl {
1.692     www      13630: #
                   13631: # Had been used for "small fry" static images on separate port 8080.
                   13632: # Modify here if lightweight http functionality desired again.
                   13633: # Currently eliminated due to increasing firewall issues.
                   13634: #
1.575     albertel 13635:     my ($url)=@_;
1.692     www      13636:     return $url;
1.215     albertel 13637: }
                   13638: 
1.213     albertel 13639: sub connection_aborted {
                   13640:     my ($r)=@_;
                   13641:     $r->print(" ");$r->rflush();
                   13642:     my $c = $r->connection;
                   13643:     return $c->aborted();
                   13644: }
                   13645: 
1.221     foxr     13646: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     13647: #    strings as 'strings'.
                   13648: sub escape_single {
1.221     foxr     13649:     my ($input) = @_;
1.223     albertel 13650:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     13651:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   13652:     return $input;
                   13653: }
1.223     albertel 13654: 
1.222     foxr     13655: #  Same as escape_single, but escape's "'s  This 
                   13656: #  can be used for  "strings"
                   13657: sub escape_double {
                   13658:     my ($input) = @_;
                   13659:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   13660:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   13661:     return $input;
                   13662: }
1.223     albertel 13663:  
1.222     foxr     13664: #   Escapes the last element of a full URL.
                   13665: sub escape_url {
                   13666:     my ($url)   = @_;
1.238     raeburn  13667:     my @urlslices = split(/\//, $url,-1);
1.369     www      13668:     my $lastitem = &escape(pop(@urlslices));
1.223     albertel 13669:     return join('/',@urlslices).'/'.$lastitem;
1.222     foxr     13670: }
1.462     albertel 13671: 
1.820     raeburn  13672: sub compare_arrays {
                   13673:     my ($arrayref1,$arrayref2) = @_;
                   13674:     my (@difference,%count);
                   13675:     @difference = ();
                   13676:     %count = ();
                   13677:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   13678:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   13679:         foreach my $element (keys(%count)) {
                   13680:             if ($count{$element} == 1) {
                   13681:                 push(@difference,$element);
                   13682:             }
                   13683:         }
                   13684:     }
                   13685:     return @difference;
                   13686: }
                   13687: 
1.817     bisitz   13688: # -------------------------------------------------------- Initialize user login
1.462     albertel 13689: sub init_user_environment {
1.463     albertel 13690:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 13691:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   13692: 
                   13693:     my $public=($username eq 'public' && $domain eq 'public');
                   13694: 
                   13695: # See if old ID present, if so, remove
                   13696: 
1.1062    raeburn  13697:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 13698:     my $now=time;
                   13699: 
                   13700:     if ($public) {
                   13701: 	my $max_public=100;
                   13702: 	my $oldest;
                   13703: 	my $oldest_time=0;
                   13704: 	for(my $next=1;$next<=$max_public;$next++) {
                   13705: 	    if (-e $lonids."/publicuser_$next.id") {
                   13706: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   13707: 		if ($mtime<$oldest_time || !$oldest_time) {
                   13708: 		    $oldest_time=$mtime;
                   13709: 		    $oldest=$next;
                   13710: 		}
                   13711: 	    } else {
                   13712: 		$cookie="publicuser_$next";
                   13713: 		last;
                   13714: 	    }
                   13715: 	}
                   13716: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   13717:     } else {
1.463     albertel 13718: 	# if this isn't a robot, kill any existing non-robot sessions
                   13719: 	if (!$args->{'robot'}) {
                   13720: 	    opendir(DIR,$lonids);
                   13721: 	    while ($filename=readdir(DIR)) {
                   13722: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   13723: 		    unlink($lonids.'/'.$filename);
                   13724: 		}
1.462     albertel 13725: 	    }
1.463     albertel 13726: 	    closedir(DIR);
1.462     albertel 13727: 	}
                   13728: # Give them a new cookie
1.463     albertel 13729: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      13730: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 13731: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 13732:     
                   13733: # Initialize roles
                   13734: 
1.1062    raeburn  13735: 	($userroles,$firstaccenv,$timerintenv) = 
                   13736:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 13737:     }
                   13738: # ------------------------------------ Check browser type and MathML capability
                   13739: 
                   13740:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
                   13741:         $clientunicode,$clientos) = &decode_user_agent($r);
                   13742: 
                   13743: # ------------------------------------------------------------- Get environment
                   13744: 
                   13745:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   13746:     my ($tmp) = keys(%userenv);
                   13747:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   13748:     } else {
                   13749: 	undef(%userenv);
                   13750:     }
                   13751:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   13752: 	$form->{'interface'}=$userenv{'interface'};
                   13753:     }
                   13754:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   13755: 
                   13756: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   13757:     foreach my $option ('interface','localpath','localres') {
                   13758:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 13759:     }
                   13760: # --------------------------------------------------------- Write first profile
                   13761: 
                   13762:     {
                   13763: 	my %initial_env = 
                   13764: 	    ("user.name"          => $username,
                   13765: 	     "user.domain"        => $domain,
                   13766: 	     "user.home"          => $authhost,
                   13767: 	     "browser.type"       => $clientbrowser,
                   13768: 	     "browser.version"    => $clientversion,
                   13769: 	     "browser.mathml"     => $clientmathml,
                   13770: 	     "browser.unicode"    => $clientunicode,
                   13771: 	     "browser.os"         => $clientos,
                   13772: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   13773: 	     "request.course.fn"  => '',
                   13774: 	     "request.course.uri" => '',
                   13775: 	     "request.course.sec" => '',
                   13776: 	     "request.role"       => 'cm',
                   13777: 	     "request.role.adv"   => $env{'user.adv'},
                   13778: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   13779: 
                   13780:         if ($form->{'localpath'}) {
                   13781: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   13782: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   13783:         }
                   13784: 	
                   13785: 	if ($form->{'interface'}) {
                   13786: 	    $form->{'interface'}=~s/\W//gs;
                   13787: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   13788: 	    $env{'browser.interface'}=$form->{'interface'};
                   13789: 	}
                   13790: 
1.981     raeburn  13791:         my %is_adv = ( is_adv => $env{'user.adv'} );
1.1016    raeburn  13792:         my %domdef;
                   13793:         unless ($domain eq 'public') {
                   13794:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   13795:         }
1.980     raeburn  13796: 
1.1081    raeburn  13797:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
1.724     raeburn  13798:             $userenv{'availabletools.'.$tool} = 
1.980     raeburn  13799:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   13800:                                                   undef,\%userenv,\%domdef,\%is_adv);
1.724     raeburn  13801:         }
                   13802: 
1.864     raeburn  13803:         foreach my $crstype ('official','unofficial','community') {
1.765     raeburn  13804:             $userenv{'canrequest.'.$crstype} =
                   13805:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
1.980     raeburn  13806:                                                   'reload','requestcourses',
                   13807:                                                   \%userenv,\%domdef,\%is_adv);
1.765     raeburn  13808:         }
                   13809: 
1.462     albertel 13810: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  13811: 
1.462     albertel 13812: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   13813: 		 &GDBM_WRCREAT(),0640)) {
                   13814: 	    &_add_to_env(\%disk_env,\%initial_env);
                   13815: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   13816: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  13817:             if (ref($firstaccenv) eq 'HASH') {
                   13818:                 &_add_to_env(\%disk_env,$firstaccenv);
                   13819:             }
                   13820:             if (ref($timerintenv) eq 'HASH') {
                   13821:                 &_add_to_env(\%disk_env,$timerintenv);
                   13822:             }
1.463     albertel 13823: 	    if (ref($args->{'extra_env'})) {
                   13824: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   13825: 	    }
1.462     albertel 13826: 	    untie(%disk_env);
                   13827: 	} else {
1.705     tempelho 13828: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   13829: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 13830: 	    return 'error: '.$!;
                   13831: 	}
                   13832:     }
                   13833:     $env{'request.role'}='cm';
                   13834:     $env{'request.role.adv'}=$env{'user.adv'};
                   13835:     $env{'browser.type'}=$clientbrowser;
                   13836: 
                   13837:     return $cookie;
                   13838: 
                   13839: }
                   13840: 
                   13841: sub _add_to_env {
                   13842:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  13843:     if (ref($env_data) eq 'HASH') {
                   13844:         while (my ($key,$value) = each(%$env_data)) {
                   13845: 	    $idf->{$prefix.$key} = $value;
                   13846: 	    $env{$prefix.$key}   = $value;
                   13847:         }
1.462     albertel 13848:     }
                   13849: }
                   13850: 
1.685     tempelho 13851: # --- Get the symbolic name of a problem and the url
                   13852: sub get_symb {
                   13853:     my ($request,$silent) = @_;
1.726     raeburn  13854:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 13855:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   13856:     if ($symb eq '') {
                   13857:         if (!$silent) {
1.1071    raeburn  13858:             if (ref($request)) { 
                   13859:                 $request->print("Unable to handle ambiguous references:$url:.");
                   13860:             }
1.685     tempelho 13861:             return ();
                   13862:         }
                   13863:     }
                   13864:     &Apache::lonenc::check_decrypt(\$symb);
                   13865:     return ($symb);
                   13866: }
                   13867: 
                   13868: # --------------------------------------------------------------Get annotation
                   13869: 
                   13870: sub get_annotation {
                   13871:     my ($symb,$enc) = @_;
                   13872: 
                   13873:     my $key = $symb;
                   13874:     if (!$enc) {
                   13875:         $key =
                   13876:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   13877:     }
                   13878:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   13879:     return $annotation{$key};
                   13880: }
                   13881: 
                   13882: sub clean_symb {
1.731     raeburn  13883:     my ($symb,$delete_enc) = @_;
1.685     tempelho 13884: 
                   13885:     &Apache::lonenc::check_decrypt(\$symb);
                   13886:     my $enc = $env{'request.enc'};
1.731     raeburn  13887:     if ($delete_enc) {
1.730     raeburn  13888:         delete($env{'request.enc'});
                   13889:     }
1.685     tempelho 13890: 
                   13891:     return ($symb,$enc);
                   13892: }
1.462     albertel 13893: 
1.990     raeburn  13894: sub build_release_hashes {
                   13895:     my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
                   13896:     return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
                   13897:                   (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
                   13898:                   (ref($randomizetry) eq 'HASH'));
                   13899:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   13900:         my ($item,$name,$value) = split(/:/,$key);
                   13901:         if ($item eq 'parameter') {
                   13902:             if (ref($checkparms->{$name}) eq 'ARRAY') {
                   13903:                 unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
                   13904:                     push(@{$checkparms->{$name}},$value);
                   13905:                 }
                   13906:             } else {
                   13907:                 push(@{$checkparms->{$name}},$value);
                   13908:             }
                   13909:         } elsif ($item eq 'resourcetag') {
                   13910:             if ($name eq 'responsetype') {
                   13911:                 $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
                   13912:             }
                   13913:         } elsif ($item eq 'course') {
                   13914:             if ($name eq 'crstype') {
                   13915:                 $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
                   13916:             }
                   13917:         }
                   13918:     }
                   13919:     ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
                   13920:     ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
                   13921:     return;
                   13922: }
                   13923: 
1.1083    raeburn  13924: sub update_content_constraints {
                   13925:     my ($cdom,$cnum,$chome,$cid) = @_;
                   13926:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   13927:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   13928:     my %checkresponsetypes;
                   13929:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   13930:         my ($item,$name,$value) = split(/:/,$key);
                   13931:         if ($item eq 'resourcetag') {
                   13932:             if ($name eq 'responsetype') {
                   13933:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   13934:             }
                   13935:         }
                   13936:     }
                   13937:     my $navmap = Apache::lonnavmaps::navmap->new();
                   13938:     if (defined($navmap)) {
                   13939:         my %allresponses;
                   13940:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   13941:             my %responses = $res->responseTypes();
                   13942:             foreach my $key (keys(%responses)) {
                   13943:                 next unless(exists($checkresponsetypes{$key}));
                   13944:                 $allresponses{$key} += $responses{$key};
                   13945:             }
                   13946:         }
                   13947:         foreach my $key (keys(%allresponses)) {
                   13948:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   13949:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   13950:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   13951:             }
                   13952:         }
                   13953:         undef($navmap);
                   13954:     }
                   13955:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   13956:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   13957:     }
                   13958:     return;
                   13959: }
                   13960: 
                   13961: sub parse_supplemental_title {
                   13962:     my ($title) = @_;
                   13963: 
                   13964:     my ($foldertitle,$renametitle);
                   13965:     if ($title =~ /&amp;&amp;&amp;/) {
                   13966:         $title = &HTML::Entites::decode($title);
                   13967:     }
                   13968:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   13969:         $renametitle=$4;
                   13970:         my ($time,$uname,$udom) = ($1,$2,$3);
                   13971:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   13972:         my $name =  &plainname($uname,$udom);
                   13973:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   13974:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   13975:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   13976:             $name.': <br />'.$foldertitle;
                   13977:     }
                   13978:     if (wantarray) {
                   13979:         return ($title,$foldertitle,$renametitle);
                   13980:     }
                   13981:     return $title;
                   13982: }
                   13983: 
1.41      ng       13984: =pod
                   13985: 
                   13986: =back
                   13987: 
1.112     bowersj2 13988: =cut
1.41      ng       13989: 
1.112     bowersj2 13990: 1;
                   13991: __END__;
1.41      ng       13992: 

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