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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1205  ! golterma    4: # $Id: loncommon.pm,v 1.1204 2014/12/21 16:26:31 raeburn Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.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.1108    raeburn    70: use Apache::lonuserutils();
1.1110    raeburn    71: use Apache::lonuserstate();
1.1182    raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.657     raeburn    74: use DateTime::TimeZone;
1.687     raeburn    75: use DateTime::Locale::Catalog;
1.1091    foxr       76: use Text::Aspell;
1.1094    raeburn    77: use Authen::Captcha;
                     78: use Captcha::reCAPTCHA;
1.1174    raeburn    79: use Crypt::DES;
                     80: use DynaLoader; # for Crypt::DES version
1.117     www        81: 
1.517     raeburn    82: # ---------------------------------------------- Designs
                     83: use vars qw(%defaultdesign);
                     84: 
1.22      www        85: my $readit;
                     86: 
1.517     raeburn    87: 
1.157     matthew    88: ##
                     89: ## Global Variables
                     90: ##
1.46      matthew    91: 
1.643     foxr       92: 
                     93: # ----------------------------------------------- SSI with retries:
                     94: #
                     95: 
                     96: =pod
                     97: 
1.648     raeburn    98: =head1 Server Side include with retries:
1.643     foxr       99: 
                    100: =over 4
                    101: 
1.648     raeburn   102: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      103: 
                    104: Performs an ssi with some number of retries.  Retries continue either
                    105: until the result is ok or until the retry count supplied by the
                    106: caller is exhausted.  
                    107: 
                    108: Inputs:
1.648     raeburn   109: 
                    110: =over 4
                    111: 
1.643     foxr      112: resource   - Identifies the resource to insert.
1.648     raeburn   113: 
1.643     foxr      114: retries    - Count of the number of retries allowed.
1.648     raeburn   115: 
1.643     foxr      116: form       - Hash that identifies the rendering options.
                    117: 
1.648     raeburn   118: =back
                    119: 
                    120: Returns:
                    121: 
                    122: =over 4
                    123: 
1.643     foxr      124: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   125: 
1.643     foxr      126: response   - The response from the last attempt (which may or may not have been successful.
                    127: 
1.648     raeburn   128: =back
                    129: 
                    130: =back
                    131: 
1.643     foxr      132: =cut
                    133: 
                    134: sub ssi_with_retries {
                    135:     my ($resource, $retries, %form) = @_;
                    136: 
                    137: 
                    138:     my $ok = 0;			# True if we got a good response.
                    139:     my $content;
                    140:     my $response;
                    141: 
                    142:     # Try to get the ssi done. within the retries count:
                    143: 
                    144:     do {
                    145: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    146: 	$ok      = $response->is_success;
1.650     www       147:         if (!$ok) {
                    148:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    149:         }
1.643     foxr      150: 	$retries--;
                    151:     } while (!$ok && ($retries > 0));
                    152: 
                    153:     if (!$ok) {
                    154: 	$content = '';		# On error return an empty content.
                    155:     }
                    156:     return ($content, $response);
                    157: 
                    158: }
                    159: 
                    160: 
                    161: 
1.20      www       162: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  163: my %language;
1.124     www       164: my %supported_language;
1.1088    foxr      165: my %supported_codes;
1.1048    foxr      166: my %latex_language;		# For choosing hyphenation in <transl..>
                    167: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  168: my %cprtag;
1.192     taceyjo1  169: my %scprtag;
1.351     www       170: my %fe; my %fd; my %fm;
1.41      ng        171: my %category_extensions;
1.12      harris41  172: 
1.46      matthew   173: # ---------------------------------------------- Thesaurus variables
1.144     matthew   174: #
                    175: # %Keywords:
                    176: #      A hash used by &keyword to determine if a word is considered a keyword.
                    177: # $thesaurus_db_file 
                    178: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   179: 
                    180: my %Keywords;
                    181: my $thesaurus_db_file;
                    182: 
1.144     matthew   183: #
                    184: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    185: # thesaurus.tab, and filecategories.tab.
                    186: #
1.18      www       187: BEGIN {
1.46      matthew   188:     # Variable initialization
                    189:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    190:     #
1.22      www       191:     unless ($readit) {
1.12      harris41  192: # ------------------------------------------------------------------- languages
                    193:     {
1.158     raeburn   194:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    195:                                    '/language.tab';
                    196:         if ( open(my $fh,"<$langtabfile") ) {
1.356     albertel  197:             while (my $line = <$fh>) {
                    198:                 next if ($line=~/^\#/);
                    199:                 chomp($line);
1.1088    foxr      200:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   201:                 $language{$key}=$val.' - '.$enc;
                    202:                 if ($sup) {
                    203:                     $supported_language{$key}=$sup;
1.1088    foxr      204: 		    $supported_codes{$key}   = $code;
1.158     raeburn   205:                 }
1.1048    foxr      206: 		if ($latex) {
                    207: 		    $latex_language_bykey{$key} = $latex;
1.1088    foxr      208: 		    $latex_language{$code} = $latex;
1.1048    foxr      209: 		}
1.158     raeburn   210:             }
                    211:             close($fh);
                    212:         }
1.12      harris41  213:     }
                    214: # ------------------------------------------------------------------ copyrights
                    215:     {
1.158     raeburn   216:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    217:                                   '/copyright.tab';
                    218:         if ( open (my $fh,"<$copyrightfile") ) {
1.356     albertel  219:             while (my $line = <$fh>) {
                    220:                 next if ($line=~/^\#/);
                    221:                 chomp($line);
                    222:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   223:                 $cprtag{$key}=$val;
                    224:             }
                    225:             close($fh);
                    226:         }
1.12      harris41  227:     }
1.351     www       228: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  229:     {
                    230:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    231:                                   '/source_copyright.tab';
                    232:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
1.356     albertel  233:             while (my $line = <$fh>) {
                    234:                 next if ($line =~ /^\#/);
                    235:                 chomp($line);
                    236:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  237:                 $scprtag{$key}=$val;
                    238:             }
                    239:             close($fh);
                    240:         }
                    241:     }
1.63      www       242: 
1.517     raeburn   243: # -------------------------------------------------------------- default domain designs
1.63      www       244:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   245:     my $designfile = $designdir.'/default.tab';
                    246:     if ( open (my $fh,"<$designfile") ) {
                    247:         while (my $line = <$fh>) {
                    248:             next if ($line =~ /^\#/);
                    249:             chomp($line);
                    250:             my ($key,$val)=(split(/\=/,$line));
                    251:             if ($val) { $defaultdesign{$key}=$val; }
                    252:         }
                    253:         close($fh);
1.63      www       254:     }
                    255: 
1.15      harris41  256: # ------------------------------------------------------------- file categories
                    257:     {
1.158     raeburn   258:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    259:                                   '/filecategories.tab';
                    260:         if ( open (my $fh,"<$categoryfile") ) {
1.356     albertel  261: 	    while (my $line = <$fh>) {
                    262: 		next if ($line =~ /^\#/);
                    263: 		chomp($line);
                    264:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.158     raeburn   265:                 push @{$category_extensions{lc($category)}},$extension;
                    266:             }
                    267:             close($fh);
                    268:         }
                    269: 
1.15      harris41  270:     }
1.12      harris41  271: # ------------------------------------------------------------------ file types
                    272:     {
1.158     raeburn   273:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    274:                '/filetypes.tab';
                    275:         if ( open (my $fh,"<$typesfile") ) {
1.356     albertel  276:             while (my $line = <$fh>) {
                    277: 		next if ($line =~ /^\#/);
                    278: 		chomp($line);
                    279:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   280:                 if ($descr ne '') {
                    281:                     $fe{$ending}=lc($emb);
                    282:                     $fd{$ending}=$descr;
1.351     www       283:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   284:                 }
                    285:             }
                    286:             close($fh);
                    287:         }
1.12      harris41  288:     }
1.22      www       289:     &Apache::lonnet::logthis(
1.705     tempelho  290:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       291:     $readit=1;
1.46      matthew   292:     }  # end of unless($readit) 
1.32      matthew   293:     
                    294: }
1.112     bowersj2  295: 
1.42      matthew   296: ###############################################################
                    297: ##           HTML and Javascript Helper Functions            ##
                    298: ###############################################################
                    299: 
                    300: =pod 
                    301: 
1.112     bowersj2  302: =head1 HTML and Javascript Functions
1.42      matthew   303: 
1.112     bowersj2  304: =over 4
                    305: 
1.648     raeburn   306: =item * &browser_and_searcher_javascript()
1.112     bowersj2  307: 
                    308: X<browsing, javascript>X<searching, javascript>Returns a string
                    309: containing javascript with two functions, C<openbrowser> and
                    310: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    311: tags.
1.42      matthew   312: 
1.648     raeburn   313: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   314: 
                    315: inputs: formname, elementname, only, omit
                    316: 
                    317: formname and elementname indicate the name of the html form and name of
                    318: the element that the results of the browsing selection are to be placed in. 
                    319: 
                    320: Specifying 'only' will restrict the browser to displaying only files
1.185     www       321: with the given extension.  Can be a comma separated list.
1.42      matthew   322: 
                    323: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       324: with the given extension.  Can be a comma separated list.
1.42      matthew   325: 
1.648     raeburn   326: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   327: 
                    328: Inputs: formname, elementname
                    329: 
                    330: formname and elementname specify the name of the html form and the name
                    331: of the element the selection from the search results will be placed in.
1.542     raeburn   332: 
1.42      matthew   333: =cut
                    334: 
                    335: sub browser_and_searcher_javascript {
1.199     albertel  336:     my ($mode)=@_;
                    337:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  338:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   339:     return <<END;
1.219     albertel  340: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   341:     var editbrowser = null;
1.135     albertel  342:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       343:         var url = '$resurl/?';
1.42      matthew   344:         if (editbrowser == null) {
                    345:             url += 'launch=1&';
                    346:         }
                    347:         url += 'catalogmode=interactive&';
1.199     albertel  348:         url += 'mode=$mode&';
1.611     albertel  349:         url += 'inhibitmenu=yes&';
1.42      matthew   350:         url += 'form=' + formname + '&';
                    351:         if (only != null) {
                    352:             url += 'only=' + only + '&';
1.217     albertel  353:         } else {
                    354:             url += 'only=&';
                    355: 	}
1.42      matthew   356:         if (omit != null) {
                    357:             url += 'omit=' + omit + '&';
1.217     albertel  358:         } else {
                    359:             url += 'omit=&';
                    360: 	}
1.135     albertel  361:         if (titleelement != null) {
                    362:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  363:         } else {
                    364: 	    url += 'titleelement=&';
                    365: 	}
1.42      matthew   366:         url += 'element=' + elementname + '';
                    367:         var title = 'Browser';
1.435     albertel  368:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   369:         options += ',width=700,height=600';
                    370:         editbrowser = open(url,title,options,'1');
                    371:         editbrowser.focus();
                    372:     }
                    373:     var editsearcher;
1.135     albertel  374:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   375:         var url = '/adm/searchcat?';
                    376:         if (editsearcher == null) {
                    377:             url += 'launch=1&';
                    378:         }
                    379:         url += 'catalogmode=interactive&';
1.199     albertel  380:         url += 'mode=$mode&';
1.42      matthew   381:         url += 'form=' + formname + '&';
1.135     albertel  382:         if (titleelement != null) {
                    383:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  384:         } else {
                    385: 	    url += 'titleelement=&';
                    386: 	}
1.42      matthew   387:         url += 'element=' + elementname + '';
                    388:         var title = 'Search';
1.435     albertel  389:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   390:         options += ',width=700,height=600';
                    391:         editsearcher = open(url,title,options,'1');
                    392:         editsearcher.focus();
                    393:     }
1.219     albertel  394: // END LON-CAPA Internal -->
1.42      matthew   395: END
1.170     www       396: }
                    397: 
                    398: sub lastresurl {
1.258     albertel  399:     if ($env{'environment.lastresurl'}) {
                    400: 	return $env{'environment.lastresurl'}
1.170     www       401:     } else {
                    402: 	return '/res';
                    403:     }
                    404: }
                    405: 
                    406: sub storeresurl {
                    407:     my $resurl=&Apache::lonnet::clutter(shift);
                    408:     unless ($resurl=~/^\/res/) { return 0; }
                    409:     $resurl=~s/\/$//;
                    410:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   411:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       412:     return 1;
1.42      matthew   413: }
                    414: 
1.74      www       415: sub studentbrowser_javascript {
1.111     www       416:    unless (
1.258     albertel  417:             (($env{'request.course.id'}) && 
1.302     albertel  418:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    419: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    420: 					  '/'.$env{'request.course.sec'})
                    421: 	      ))
1.258     albertel  422:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       423:           ) { return ''; }  
1.74      www       424:    return (<<'ENDSTDBRW');
1.776     bisitz    425: <script type="text/javascript" language="Javascript">
1.824     bisitz    426: // <![CDATA[
1.74      www       427:     var stdeditbrowser;
1.999     www       428:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
1.74      www       429:         var url = '/adm/pickstudent?';
                    430:         var filter;
1.558     albertel  431: 	if (!ignorefilter) {
                    432: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    433: 	}
1.74      www       434:         if (filter != null) {
                    435:            if (filter != '') {
                    436:                url += 'filter='+filter+'&';
                    437: 	   }
                    438:         }
                    439:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       440:                                     '&udomelement='+udom+
                    441:                                     '&clicker='+clicker;
1.111     www       442: 	if (roleflag) { url+="&roles=1"; }
1.793     raeburn   443:         if (courseadvonly) { url+="&courseadvonly=1"; }
1.102     www       444:         var title = 'Student_Browser';
1.74      www       445:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    446:         options += ',width=700,height=600';
                    447:         stdeditbrowser = open(url,title,options,'1');
                    448:         stdeditbrowser.focus();
                    449:     }
1.824     bisitz    450: // ]]>
1.74      www       451: </script>
                    452: ENDSTDBRW
                    453: }
1.42      matthew   454: 
1.1003    www       455: sub resourcebrowser_javascript {
                    456:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       457:    return (<<'ENDRESBRW');
1.1003    www       458: <script type="text/javascript" language="Javascript">
                    459: // <![CDATA[
                    460:     var reseditbrowser;
1.1004    www       461:     function openresbrowser(formname,reslink) {
1.1005    www       462:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       463:         var title = 'Resource_Browser';
                    464:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       465:         options += ',width=700,height=500';
1.1004    www       466:         reseditbrowser = open(url,title,options,'1');
                    467:         reseditbrowser.focus();
1.1003    www       468:     }
                    469: // ]]>
                    470: </script>
1.1004    www       471: ENDRESBRW
1.1003    www       472: }
                    473: 
1.74      www       474: sub selectstudent_link {
1.999     www       475:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
                    476:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    477:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    478:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  479:    if ($env{'request.course.id'}) {  
1.302     albertel  480:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    481: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    482: 					'/'.$env{'request.course.sec'})) {
1.111     www       483: 	   return '';
                    484:        }
1.999     www       485:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.793     raeburn   486:        if ($courseadvonly)  {
                    487:            $callargs .= ",'',1,1";
                    488:        }
                    489:        return '<span class="LC_nobreak">'.
                    490:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    491:               &mt('Select User').'</a></span>';
1.74      www       492:    }
1.258     albertel  493:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       494:        $callargs .= ",'',1"; 
1.793     raeburn   495:        return '<span class="LC_nobreak">'.
                    496:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    497:               &mt('Select User').'</a></span>';
1.111     www       498:    }
                    499:    return '';
1.91      www       500: }
                    501: 
1.1004    www       502: sub selectresource_link {
                    503:    my ($form,$reslink,$arg)=@_;
                    504:    
                    505:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    506:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    507:    unless ($env{'request.course.id'}) { return $arg; }
                    508:    return '<span class="LC_nobreak">'.
                    509:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    510:               $arg.'</a></span>';
                    511: }
                    512: 
                    513: 
                    514: 
1.653     raeburn   515: sub authorbrowser_javascript {
                    516:     return <<"ENDAUTHORBRW";
1.776     bisitz    517: <script type="text/javascript" language="JavaScript">
1.824     bisitz    518: // <![CDATA[
1.653     raeburn   519: var stdeditbrowser;
                    520: 
                    521: function openauthorbrowser(formname,udom) {
                    522:     var url = '/adm/pickauthor?';
                    523:     url += 'form='+formname+'&roledom='+udom;
                    524:     var title = 'Author_Browser';
                    525:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    526:     options += ',width=700,height=600';
                    527:     stdeditbrowser = open(url,title,options,'1');
                    528:     stdeditbrowser.focus();
                    529: }
                    530: 
1.824     bisitz    531: // ]]>
1.653     raeburn   532: </script>
                    533: ENDAUTHORBRW
                    534: }
                    535: 
1.91      www       536: sub coursebrowser_javascript {
1.1116    raeburn   537:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
                    538:         $credits_element) = @_;
1.932     raeburn   539:     my $wintitle = 'Course_Browser';
1.931     raeburn   540:     if ($crstype eq 'Community') {
1.932     raeburn   541:         $wintitle = 'Community_Browser';
1.909     raeburn   542:     }
1.876     raeburn   543:     my $id_functions = &javascript_index_functions();
                    544:     my $output = '
1.776     bisitz    545: <script type="text/javascript" language="JavaScript">
1.824     bisitz    546: // <![CDATA[
1.468     raeburn   547:     var stdeditbrowser;'."\n";
1.876     raeburn   548: 
                    549:     $output .= <<"ENDSTDBRW";
1.909     raeburn   550:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       551:         var url = '/adm/pickcourse?';
1.895     raeburn   552:         var formid = getFormIdByName(formname);
1.876     raeburn   553:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  554:         if (domainfilter != null) {
                    555:            if (domainfilter != '') {
                    556:                url += 'domainfilter='+domainfilter+'&';
                    557: 	   }
                    558:         }
1.91      www       559:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  560: 	                            '&cdomelement='+udom+
                    561:                                     '&cnameelement='+desc;
1.468     raeburn   562:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   563:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   564:                 url += '&roleelement='+extra_element;
                    565:                 if (domainfilter == null || domainfilter == '') {
                    566:                     url += '&domainfilter='+extra_element;
                    567:                 }
1.234     raeburn   568:             }
1.468     raeburn   569:             else {
                    570:                 if (formname == 'portform') {
                    571:                     url += '&setroles='+extra_element;
1.800     raeburn   572:                 } else {
                    573:                     if (formname == 'rules') {
                    574:                         url += '&fixeddom='+extra_element; 
                    575:                     }
1.468     raeburn   576:                 }
                    577:             }     
1.230     raeburn   578:         }
1.909     raeburn   579:         if (type != null && type != '') {
                    580:             url += '&type='+type;
                    581:         }
                    582:         if (type_elem != null && type_elem != '') {
                    583:             url += '&typeelement='+type_elem;
                    584:         }
1.872     raeburn   585:         if (formname == 'ccrs') {
                    586:             var ownername = document.forms[formid].ccuname.value;
                    587:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
                    588:             url += '&cloner='+ownername+':'+ownerdom;
                    589:         }
1.293     raeburn   590:         if (multflag !=null && multflag != '') {
                    591:             url += '&multiple='+multflag;
                    592:         }
1.909     raeburn   593:         var title = '$wintitle';
1.91      www       594:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    595:         options += ',width=700,height=600';
                    596:         stdeditbrowser = open(url,title,options,'1');
                    597:         stdeditbrowser.focus();
                    598:     }
1.876     raeburn   599: $id_functions
                    600: ENDSTDBRW
1.1116    raeburn   601:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    602:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    603:                                       $credits_element);
1.876     raeburn   604:     }
                    605:     $output .= '
                    606: // ]]>
                    607: </script>';
                    608:     return $output;
                    609: }
                    610: 
                    611: sub javascript_index_functions {
                    612:     return <<"ENDJS";
                    613: 
                    614: function getFormIdByName(formname) {
                    615:     for (var i=0;i<document.forms.length;i++) {
                    616:         if (document.forms[i].name == formname) {
                    617:             return i;
                    618:         }
                    619:     }
                    620:     return -1;
                    621: }
                    622: 
                    623: function getIndexByName(formid,item) {
                    624:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    625:         if (document.forms[formid].elements[i].name == item) {
                    626:             return i;
                    627:         }
                    628:     }
                    629:     return -1;
                    630: }
1.468     raeburn   631: 
1.876     raeburn   632: function getDomainFromSelectbox(formname,udom) {
                    633:     var userdom;
                    634:     var formid = getFormIdByName(formname);
                    635:     if (formid > -1) {
                    636:         var domid = getIndexByName(formid,udom);
                    637:         if (domid > -1) {
                    638:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    639:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    640:             }
                    641:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    642:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   643:             }
                    644:         }
                    645:     }
1.876     raeburn   646:     return userdom;
                    647: }
                    648: 
                    649: ENDJS
1.468     raeburn   650: 
1.876     raeburn   651: }
                    652: 
1.1017    raeburn   653: sub javascript_array_indexof {
1.1018    raeburn   654:     return <<ENDJS;
1.1017    raeburn   655: <script type="text/javascript" language="JavaScript">
                    656: // <![CDATA[
                    657: 
                    658: if (!Array.prototype.indexOf) {
                    659:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    660:         "use strict";
                    661:         if (this === void 0 || this === null) {
                    662:             throw new TypeError();
                    663:         }
                    664:         var t = Object(this);
                    665:         var len = t.length >>> 0;
                    666:         if (len === 0) {
                    667:             return -1;
                    668:         }
                    669:         var n = 0;
                    670:         if (arguments.length > 0) {
                    671:             n = Number(arguments[1]);
1.1088    foxr      672:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   673:                 n = 0;
                    674:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    675:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    676:             }
                    677:         }
                    678:         if (n >= len) {
                    679:             return -1;
                    680:         }
                    681:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    682:         for (; k < len; k++) {
                    683:             if (k in t && t[k] === searchElement) {
                    684:                 return k;
                    685:             }
                    686:         }
                    687:         return -1;
                    688:     }
                    689: }
                    690: 
                    691: // ]]>
                    692: </script>
                    693: 
                    694: ENDJS
                    695: 
                    696: }
                    697: 
1.876     raeburn   698: sub userbrowser_javascript {
                    699:     my $id_functions = &javascript_index_functions();
                    700:     return <<"ENDUSERBRW";
                    701: 
1.888     raeburn   702: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   703:     var url = '/adm/pickuser?';
                    704:     var userdom = getDomainFromSelectbox(formname,udom);
                    705:     if (userdom != null) {
                    706:        if (userdom != '') {
                    707:            url += 'srchdom='+userdom+'&';
                    708:        }
                    709:     }
                    710:     url += 'form=' + formname + '&unameelement='+uname+
                    711:                                 '&udomelement='+udom+
                    712:                                 '&ulastelement='+ulast+
                    713:                                 '&ufirstelement='+ufirst+
                    714:                                 '&uemailelement='+uemail+
1.881     raeburn   715:                                 '&hideudomelement='+hideudom+
                    716:                                 '&coursedom='+crsdom;
1.888     raeburn   717:     if ((caller != null) && (caller != undefined)) {
                    718:         url += '&caller='+caller;
                    719:     }
1.876     raeburn   720:     var title = 'User_Browser';
                    721:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    722:     options += ',width=700,height=600';
                    723:     var stdeditbrowser = open(url,title,options,'1');
                    724:     stdeditbrowser.focus();
                    725: }
                    726: 
1.888     raeburn   727: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   728:     var formid = getFormIdByName(formname);
                    729:     if (formid > -1) {
1.888     raeburn   730:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   731:         var domid = getIndexByName(formid,udom);
                    732:         var hidedomid = getIndexByName(formid,origdom);
                    733:         if (hidedomid > -1) {
                    734:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   735:             var unameval = document.forms[formid].elements[unameid].value;
                    736:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    737:                 if (domid > -1) {
                    738:                     var slct = document.forms[formid].elements[domid];
                    739:                     if (slct.type == 'select-one') {
                    740:                         var i;
                    741:                         for (i=0;i<slct.length;i++) {
                    742:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    743:                         }
                    744:                     }
                    745:                     if (slct.type == 'hidden') {
                    746:                         slct.value = fixeddom;
1.876     raeburn   747:                     }
                    748:                 }
1.468     raeburn   749:             }
                    750:         }
                    751:     }
1.876     raeburn   752:     return;
                    753: }
                    754: 
                    755: $id_functions
                    756: ENDUSERBRW
1.468     raeburn   757: }
                    758: 
                    759: sub setsec_javascript {
1.1116    raeburn   760:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   761:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    762:         $communityrolestr);
                    763:     if ($role_element ne '') {
                    764:         my @allroles = ('st','ta','ep','in','ad');
                    765:         foreach my $crstype ('Course','Community') {
                    766:             if ($crstype eq 'Community') {
                    767:                 foreach my $role (@allroles) {
                    768:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    769:                 }
                    770:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    771:             } else {
                    772:                 foreach my $role (@allroles) {
                    773:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    774:                 }
                    775:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    776:             }
                    777:         }
                    778:         $rolestr = '"'.join('","',@allroles).'"';
                    779:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    780:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    781:     }
1.468     raeburn   782:     my $setsections = qq|
                    783: function setSect(sectionlist) {
1.629     raeburn   784:     var sectionsArray = new Array();
                    785:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    786:         sectionsArray = sectionlist.split(",");
                    787:     }
1.468     raeburn   788:     var numSections = sectionsArray.length;
                    789:     document.$formname.$sec_element.length = 0;
                    790:     if (numSections == 0) {
                    791:         document.$formname.$sec_element.multiple=false;
                    792:         document.$formname.$sec_element.size=1;
                    793:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    794:     } else {
                    795:         if (numSections == 1) {
                    796:             document.$formname.$sec_element.multiple=false;
                    797:             document.$formname.$sec_element.size=1;
                    798:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    799:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    800:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    801:         } else {
                    802:             for (var i=0; i<numSections; i++) {
                    803:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    804:             }
                    805:             document.$formname.$sec_element.multiple=true
                    806:             if (numSections < 3) {
                    807:                 document.$formname.$sec_element.size=numSections;
                    808:             } else {
                    809:                 document.$formname.$sec_element.size=3;
                    810:             }
                    811:             document.$formname.$sec_element.options[0].selected = false
                    812:         }
                    813:     }
1.91      www       814: }
1.905     raeburn   815: 
                    816: function setRole(crstype) {
1.468     raeburn   817: |;
1.905     raeburn   818:     if ($role_element eq '') {
                    819:         $setsections .= '    return;
                    820: }
                    821: ';
                    822:     } else {
                    823:         $setsections .= qq|
                    824:     var elementLength = document.$formname.$role_element.length;
                    825:     var allroles = Array($rolestr);
                    826:     var courserolenames = Array($courserolestr);
                    827:     var communityrolenames = Array($communityrolestr);
                    828:     if (elementLength != undefined) {
                    829:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    830:             if (crstype == 'Course') {
                    831:                 return;
                    832:             } else {
                    833:                 allroles[5] = 'co';
                    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 = communityrolenames[i];
                    837:                 }
                    838:             }
                    839:         } else {
                    840:             if (crstype == 'Community') {
                    841:                 return;
                    842:             } else {
                    843:                 allroles[5] = 'cc';
                    844:                 for (var i=0; i<6; i++) {
                    845:                     document.$formname.$role_element.options[i].value = allroles[i];
                    846:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    847:                 }
                    848:             }
                    849:         }
                    850:     }
                    851:     return;
                    852: }
                    853: |;
                    854:     }
1.1116    raeburn   855:     if ($credits_element) {
                    856:         $setsections .= qq|
                    857: function setCredits(defaultcredits) {
                    858:     document.$formname.$credits_element.value = defaultcredits;
                    859:     return;
                    860: }
                    861: |;
                    862:     }
1.468     raeburn   863:     return $setsections;
                    864: }
                    865: 
1.91      www       866: sub selectcourse_link {
1.909     raeburn   867:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    868:        $typeelement) = @_;
                    869:    my $type = $selecttype;
1.871     raeburn   870:    my $linktext = &mt('Select Course');
                    871:    if ($selecttype eq 'Community') {
1.909     raeburn   872:        $linktext = &mt('Select Community');
1.906     raeburn   873:    } elsif ($selecttype eq 'Course/Community') {
                    874:        $linktext = &mt('Select Course/Community');
1.909     raeburn   875:        $type = '';
1.1019    raeburn   876:    } elsif ($selecttype eq 'Select') {
                    877:        $linktext = &mt('Select');
                    878:        $type = '';
1.871     raeburn   879:    }
1.787     bisitz    880:    return '<span class="LC_nobreak">'
                    881:          ."<a href='"
                    882:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    883:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   884:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   885:          ."'>".$linktext.'</a>'
1.787     bisitz    886:          .'</span>';
1.74      www       887: }
1.42      matthew   888: 
1.653     raeburn   889: sub selectauthor_link {
                    890:    my ($form,$udom)=@_;
                    891:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    892:           &mt('Select Author').'</a>';
                    893: }
                    894: 
1.876     raeburn   895: sub selectuser_link {
1.881     raeburn   896:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   897:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   898:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   899:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   900:            ');">'.$linktext.'</a>';
1.876     raeburn   901: }
                    902: 
1.273     raeburn   903: sub check_uncheck_jscript {
                    904:     my $jscript = <<"ENDSCRT";
                    905: function checkAll(field) {
                    906:     if (field.length > 0) {
                    907:         for (i = 0; i < field.length; i++) {
1.1093    raeburn   908:             if (!field[i].disabled) { 
                    909:                 field[i].checked = true;
                    910:             }
1.273     raeburn   911:         }
                    912:     } else {
1.1093    raeburn   913:         if (!field.disabled) { 
                    914:             field.checked = true;
                    915:         }
1.273     raeburn   916:     }
                    917: }
                    918:  
                    919: function uncheckAll(field) {
                    920:     if (field.length > 0) {
                    921:         for (i = 0; i < field.length; i++) {
                    922:             field[i].checked = false ;
1.543     albertel  923:         }
                    924:     } else {
1.273     raeburn   925:         field.checked = false ;
                    926:     }
                    927: }
                    928: ENDSCRT
                    929:     return $jscript;
                    930: }
                    931: 
1.656     www       932: sub select_timezone {
1.659     raeburn   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 '') || ($selected eq 'local')) {
                    938:            $output .= ' selected="selected" ';
                    939:        }
                    940:        $output .= '> </option>';
                    941:    }
1.657     raeburn   942:    my @timezones = DateTime::TimeZone->all_names;
                    943:    foreach my $tzone (@timezones) {
                    944:        $output.= '<option value="'.$tzone.'"';
                    945:        if ($tzone eq $selected) {
                    946:            $output.=' selected="selected"';
                    947:        }
                    948:        $output.=">$tzone</option>\n";
1.656     www       949:    }
                    950:    $output.="</select>";
                    951:    return $output;
                    952: }
1.273     raeburn   953: 
1.687     raeburn   954: sub select_datelocale {
                    955:     my ($name,$selected,$onchange,$includeempty)=@_;
                    956:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    957:     if ($includeempty) {
                    958:         $output .= '<option value=""';
                    959:         if ($selected eq '') {
                    960:             $output .= ' selected="selected" ';
                    961:         }
                    962:         $output .= '> </option>';
                    963:     }
                    964:     my (@possibles,%locale_names);
                    965:     my @locales = DateTime::Locale::Catalog::Locales;
                    966:     foreach my $locale (@locales) {
                    967:         if (ref($locale) eq 'HASH') {
                    968:             my $id = $locale->{'id'};
                    969:             if ($id ne '') {
                    970:                 my $en_terr = $locale->{'en_territory'};
                    971:                 my $native_terr = $locale->{'native_territory'};
1.695     raeburn   972:                 my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   973:                 if (grep(/^en$/,@languages) || !@languages) {
                    974:                     if ($en_terr ne '') {
                    975:                         $locale_names{$id} = '('.$en_terr.')';
                    976:                     } elsif ($native_terr ne '') {
                    977:                         $locale_names{$id} = $native_terr;
                    978:                     }
                    979:                 } else {
                    980:                     if ($native_terr ne '') {
                    981:                         $locale_names{$id} = $native_terr.' ';
                    982:                     } elsif ($en_terr ne '') {
                    983:                         $locale_names{$id} = '('.$en_terr.')';
                    984:                     }
                    985:                 }
                    986:                 push (@possibles,$id);
                    987:             }
                    988:         }
                    989:     }
                    990:     foreach my $item (sort(@possibles)) {
                    991:         $output.= '<option value="'.$item.'"';
                    992:         if ($item eq $selected) {
                    993:             $output.=' selected="selected"';
                    994:         }
                    995:         $output.=">$item";
                    996:         if ($locale_names{$item} ne '') {
                    997:             $output.="  $locale_names{$item}</option>\n";
                    998:         }
                    999:         $output.="</option>\n";
                   1000:     }
                   1001:     $output.="</select>";
                   1002:     return $output;
                   1003: }
                   1004: 
1.792     raeburn  1005: sub select_language {
                   1006:     my ($name,$selected,$includeempty) = @_;
                   1007:     my %langchoices;
                   1008:     if ($includeempty) {
1.1117    raeburn  1009:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1010:     }
                   1011:     foreach my $id (&languageids()) {
                   1012:         my $code = &supportedlanguagecode($id);
                   1013:         if ($code) {
                   1014:             $langchoices{$code} = &plainlanguagedescription($id);
                   1015:         }
                   1016:     }
1.1117    raeburn  1017:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.970     raeburn  1018:     return &select_form($selected,$name,\%langchoices);
1.792     raeburn  1019: }
                   1020: 
1.42      matthew  1021: =pod
1.36      matthew  1022: 
1.1088    foxr     1023: 
                   1024: =item * &list_languages()
                   1025: 
                   1026: Returns an array reference that is suitable for use in language prompters.
                   1027: Each array element is itself a two element array.  The first element
                   1028: is the language code.  The second element a descsriptiuon of the 
                   1029: language itself.  This is suitable for use in e.g.
                   1030: &Apache::edit::select_arg (once dereferenced that is).
                   1031: 
                   1032: =cut 
                   1033: 
                   1034: sub list_languages {
                   1035:     my @lang_choices;
                   1036: 
                   1037:     foreach my $id (&languageids()) {
                   1038: 	my $code = &supportedlanguagecode($id);
                   1039: 	if ($code) {
                   1040: 	    my $selector    = $supported_codes{$id};
                   1041: 	    my $description = &plainlanguagedescription($id);
                   1042: 	    push (@lang_choices, [$selector, $description]);
                   1043: 	}
                   1044:     }
                   1045:     return \@lang_choices;
                   1046: }
                   1047: 
                   1048: =pod
                   1049: 
1.648     raeburn  1050: =item * &linked_select_forms(...)
1.36      matthew  1051: 
                   1052: linked_select_forms returns a string containing a <script></script> block
                   1053: and html for two <select> menus.  The select menus will be linked in that
                   1054: changing the value of the first menu will result in new values being placed
                   1055: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1056: order unless a defined order is provided.
1.36      matthew  1057: 
                   1058: linked_select_forms takes the following ordered inputs:
                   1059: 
                   1060: =over 4
                   1061: 
1.112     bowersj2 1062: =item * $formname, the name of the <form> tag
1.36      matthew  1063: 
1.112     bowersj2 1064: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1065: 
1.112     bowersj2 1066: =item * $firstdefault, the default value for the first menu
1.36      matthew  1067: 
1.112     bowersj2 1068: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1069: 
1.112     bowersj2 1070: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1071: 
1.112     bowersj2 1072: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1073: 
1.609     raeburn  1074: =item * $menuorder, the order of values in the first menu
                   1075: 
1.1115    raeburn  1076: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1077:         event for the first <select> tag
                   1078: 
                   1079: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1080:         event for the second <select> tag
                   1081: 
1.41      ng       1082: =back 
                   1083: 
1.36      matthew  1084: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1085: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1086: values for the first select menu.  The text that coincides with the 
1.41      ng       1087: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1088: and text for the second menu are given in the hash pointed to by 
                   1089: $menu{$choice1}->{'select2'}.  
                   1090: 
1.112     bowersj2 1091:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1092:                        default => "B3",
                   1093:                        select2 => { 
                   1094:                            B1 => "Choice B1",
                   1095:                            B2 => "Choice B2",
                   1096:                            B3 => "Choice B3",
                   1097:                            B4 => "Choice B4"
1.609     raeburn  1098:                            },
                   1099:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1100:                    },
                   1101:                A2 => { text =>"Choice A2" ,
                   1102:                        default => "C2",
                   1103:                        select2 => { 
                   1104:                            C1 => "Choice C1",
                   1105:                            C2 => "Choice C2",
                   1106:                            C3 => "Choice C3"
1.609     raeburn  1107:                            },
                   1108:                        order => ['C2','C1','C3'],
1.112     bowersj2 1109:                    },
                   1110:                A3 => { text =>"Choice A3" ,
                   1111:                        default => "D6",
                   1112:                        select2 => { 
                   1113:                            D1 => "Choice D1",
                   1114:                            D2 => "Choice D2",
                   1115:                            D3 => "Choice D3",
                   1116:                            D4 => "Choice D4",
                   1117:                            D5 => "Choice D5",
                   1118:                            D6 => "Choice D6",
                   1119:                            D7 => "Choice D7"
1.609     raeburn  1120:                            },
                   1121:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1122:                    }
                   1123:                );
1.36      matthew  1124: 
                   1125: =cut
                   1126: 
                   1127: sub linked_select_forms {
                   1128:     my ($formname,
                   1129:         $middletext,
                   1130:         $firstdefault,
                   1131:         $firstselectname,
                   1132:         $secondselectname, 
1.609     raeburn  1133:         $hashref,
                   1134:         $menuorder,
1.1115    raeburn  1135:         $onchangefirst,
                   1136:         $onchangesecond
1.36      matthew  1137:         ) = @_;
                   1138:     my $second = "document.$formname.$secondselectname";
                   1139:     my $first = "document.$formname.$firstselectname";
                   1140:     # output the javascript to do the changing
                   1141:     my $result = '';
1.776     bisitz   1142:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1143:     $result.="// <![CDATA[\n";
1.36      matthew  1144:     $result.="var select2data = new Object();\n";
                   1145:     $" = '","';
                   1146:     my $debug = '';
                   1147:     foreach my $s1 (sort(keys(%$hashref))) {
                   1148:         $result.="select2data.d_$s1 = new Object();\n";        
                   1149:         $result.="select2data.d_$s1.def = new String('".
                   1150:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1151:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1152:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1153:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1154:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1155:         }
1.36      matthew  1156:         $result.="\"@s2values\");\n";
                   1157:         $result.="select2data.d_$s1.texts = new Array(";        
                   1158:         my @s2texts;
                   1159:         foreach my $value (@s2values) {
                   1160:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
                   1161:         }
                   1162:         $result.="\"@s2texts\");\n";
                   1163:     }
                   1164:     $"=' ';
                   1165:     $result.= <<"END";
                   1166: 
                   1167: function select1_changed() {
                   1168:     // Determine new choice
                   1169:     var newvalue = "d_" + $first.value;
                   1170:     // update select2
                   1171:     var values     = select2data[newvalue].values;
                   1172:     var texts      = select2data[newvalue].texts;
                   1173:     var select2def = select2data[newvalue].def;
                   1174:     var i;
                   1175:     // out with the old
                   1176:     for (i = 0; i < $second.options.length; i++) {
                   1177:         $second.options[i] = null;
                   1178:     }
                   1179:     // in with the nuclear
                   1180:     for (i=0;i<values.length; i++) {
                   1181:         $second.options[i] = new Option(values[i]);
1.143     matthew  1182:         $second.options[i].value = values[i];
1.36      matthew  1183:         $second.options[i].text = texts[i];
                   1184:         if (values[i] == select2def) {
                   1185:             $second.options[i].selected = true;
                   1186:         }
                   1187:     }
                   1188: }
1.824     bisitz   1189: // ]]>
1.36      matthew  1190: </script>
                   1191: END
                   1192:     # output the initial values for the selection lists
1.1115    raeburn  1193:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1.609     raeburn  1194:     my @order = sort(keys(%{$hashref}));
                   1195:     if (ref($menuorder) eq 'ARRAY') {
                   1196:         @order = @{$menuorder};
                   1197:     }
                   1198:     foreach my $value (@order) {
1.36      matthew  1199:         $result.="    <option value=\"$value\" ";
1.253     albertel 1200:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1201:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1202:     }
                   1203:     $result .= "</select>\n";
                   1204:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1205:     $result .= $middletext;
1.1115    raeburn  1206:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1207:     if ($onchangesecond) {
                   1208:         $result .= ' onchange="'.$onchangesecond.'"';
                   1209:     }
                   1210:     $result .= ">\n";
1.36      matthew  1211:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1212:     
                   1213:     my @secondorder = sort(keys(%select2));
                   1214:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1215:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1216:     }
                   1217:     foreach my $value (@secondorder) {
1.36      matthew  1218:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1219:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1220:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1221:     }
                   1222:     $result .= "</select>\n";
                   1223:     #    return $debug;
                   1224:     return $result;
                   1225: }   #  end of sub linked_select_forms {
                   1226: 
1.45      matthew  1227: =pod
1.44      bowersj2 1228: 
1.973     raeburn  1229: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1230: 
1.112     bowersj2 1231: Returns a string corresponding to an HTML link to the given help
                   1232: $topic, where $topic corresponds to the name of a .tex file in
                   1233: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1234: spaces. 
                   1235: 
                   1236: $text will optionally be linked to the same topic, allowing you to
                   1237: link text in addition to the graphic. If you do not want to link
                   1238: text, but wish to specify one of the later parameters, pass an
                   1239: empty string. 
                   1240: 
                   1241: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1242: the link will not open a new window. If false, the link will open
                   1243: a new window using Javascript. (Default is false.) 
                   1244: 
                   1245: $width and $height are optional numerical parameters that will
                   1246: override the width and height of the popped up window, which may
1.973     raeburn  1247: be useful for certain help topics with big pictures included.
                   1248: 
                   1249: $imgid is the id of the img tag used for the help icon. This may be
                   1250: used in a javascript call to switch the image src.  See 
                   1251: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1252: 
                   1253: =cut
                   1254: 
                   1255: sub help_open_topic {
1.973     raeburn  1256:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1257:     $text = "" if (not defined $text);
1.44      bowersj2 1258:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1259:     $width = 500 if (not defined $width);
1.44      bowersj2 1260:     $height = 400 if (not defined $height);
                   1261:     my $filename = $topic;
                   1262:     $filename =~ s/ /_/g;
                   1263: 
1.48      bowersj2 1264:     my $template = "";
                   1265:     my $link;
1.572     banghart 1266:     
1.159     www      1267:     $topic=~s/\W/\_/g;
1.44      bowersj2 1268: 
1.572     banghart 1269:     if (!$stayOnPage) {
1.1033    www      1270: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1271:     } elsif ($stayOnPage eq 'popup') {
                   1272:         $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 1273:     } else {
1.48      bowersj2 1274: 	$link = "/adm/help/${filename}.hlp";
                   1275:     }
                   1276: 
                   1277:     # Add the text
1.755     neumanie 1278:     if ($text ne "") {	
1.763     bisitz   1279: 	$template.='<span class="LC_help_open_topic">'
                   1280:                   .'<a target="_top" href="'.$link.'">'
                   1281:                   .$text.'</a>';
1.48      bowersj2 1282:     }
                   1283: 
1.763     bisitz   1284:     # (Always) Add the graphic
1.179     matthew  1285:     my $title = &mt('Online Help');
1.667     raeburn  1286:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1287:     if ($imgid ne '') {
                   1288:         $imgid = ' id="'.$imgid.'"';
                   1289:     }
1.763     bisitz   1290:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1291:               .'<img src="'.$helpicon.'" border="0"'
                   1292:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1293:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1294:               .' /></a>';
                   1295:     if ($text ne "") {	
                   1296:         $template.='</span>';
                   1297:     }
1.44      bowersj2 1298:     return $template;
                   1299: 
1.106     bowersj2 1300: }
                   1301: 
                   1302: # This is a quicky function for Latex cheatsheet editing, since it 
                   1303: # appears in at least four places
                   1304: sub helpLatexCheatsheet {
1.1037    www      1305:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1306:     my $out;
1.106     bowersj2 1307:     my $addOther = '';
1.732     raeburn  1308:     if ($topic) {
1.1037    www      1309: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1310:     }
                   1311:     $out = '<span>' # Start cheatsheet
                   1312: 	  .$addOther
                   1313:           .'<span>'
1.1037    www      1314: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1315: 	  .'</span> <span>'
1.1037    www      1316: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1317: 	  .'</span>';
1.732     raeburn  1318:     unless ($not_author) {
1.1186    kruse    1319:         $out .= '<span>'
                   1320:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
                   1321:                .'</span> <span>'
                   1322:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1.763     bisitz   1323: 	       .'</span>';
1.732     raeburn  1324:     }
1.763     bisitz   1325:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1326:     return $out;
1.172     www      1327: }
                   1328: 
1.430     albertel 1329: sub general_help {
                   1330:     my $helptopic='Student_Intro';
                   1331:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1332: 	$helptopic='Authoring_Intro';
1.907     raeburn  1333:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1334: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1335:     } elsif ($env{'request.role'}=~/^dc/) {
                   1336:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1337:     }
                   1338:     return $helptopic;
                   1339: }
                   1340: 
                   1341: sub update_help_link {
                   1342:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1343:     my $origurl = $ENV{'REQUEST_URI'};
                   1344:     $origurl=~s|^/~|/priv/|;
                   1345:     my $timestamp = time;
                   1346:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1347:         $$datum = &escape($$datum);
                   1348:     }
                   1349: 
                   1350:     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";
                   1351:     my $output .= <<"ENDOUTPUT";
                   1352: <script type="text/javascript">
1.824     bisitz   1353: // <![CDATA[
1.430     albertel 1354: banner_link = '$banner_link';
1.824     bisitz   1355: // ]]>
1.430     albertel 1356: </script>
                   1357: ENDOUTPUT
                   1358:     return $output;
                   1359: }
                   1360: 
                   1361: # now just updates the help link and generates a blue icon
1.193     raeburn  1362: sub help_open_menu {
1.430     albertel 1363:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1364: 	= @_;    
1.949     droeschl 1365:     $stayOnPage = 1;
1.430     albertel 1366:     my $output;
                   1367:     if ($component_help) {
                   1368: 	if (!$text) {
                   1369: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1370: 				       $width,$height);
                   1371: 	} else {
                   1372: 	    my $help_text;
                   1373: 	    $help_text=&unescape($topic);
                   1374: 	    $output='<table><tr><td>'.
                   1375: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1376: 				 $width,$height).'</td></tr></table>';
                   1377: 	}
                   1378:     }
                   1379:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1380:     return $output.$banner_link;
                   1381: }
                   1382: 
                   1383: sub top_nav_help {
                   1384:     my ($text) = @_;
1.436     albertel 1385:     $text = &mt($text);
1.949     droeschl 1386:     my $stay_on_page = 1;
                   1387: 
1.1168    raeburn  1388:     my ($link,$banner_link);
                   1389:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1390:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1391: 	                         : "javascript:helpMenu('open')";
                   1392:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1393:     }
1.201     raeburn  1394:     my $title = &mt('Get help');
1.1168    raeburn  1395:     if ($link) {
                   1396:         return <<"END";
1.436     albertel 1397: $banner_link
1.1159    raeburn  1398: <a href="$link" title="$title">$text</a>
1.436     albertel 1399: END
1.1168    raeburn  1400:     } else {
                   1401:         return '&nbsp;'.$text.'&nbsp;';
                   1402:     }
1.436     albertel 1403: }
                   1404: 
                   1405: sub help_menu_js {
1.1154    raeburn  1406:     my ($httphost) = @_;
1.949     droeschl 1407:     my $stayOnPage = 1;
1.436     albertel 1408:     my $width = 620;
                   1409:     my $height = 600;
1.430     albertel 1410:     my $helptopic=&general_help();
1.1154    raeburn  1411:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1412:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1413:     my $start_page =
                   1414:         &Apache::loncommon::start_page('Help Menu', undef,
                   1415: 				       {'frameset'    => 1,
                   1416: 					'js_ready'    => 1,
1.1154    raeburn  1417:                                         'use_absolute' => $httphost,
1.331     albertel 1418: 					'add_entries' => {
1.1168    raeburn  1419: 					    'border' => '0', 
1.579     raeburn  1420: 					    'rows'   => "110,*",},});
1.331     albertel 1421:     my $end_page =
                   1422:         &Apache::loncommon::end_page({'frameset' => 1,
                   1423: 				      'js_ready' => 1,});
                   1424: 
1.436     albertel 1425:     my $template .= <<"ENDTEMPLATE";
                   1426: <script type="text/javascript">
1.877     bisitz   1427: // <![CDATA[
1.253     albertel 1428: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1429: var banner_link = '';
1.243     raeburn  1430: function helpMenu(target) {
                   1431:     var caller = this;
                   1432:     if (target == 'open') {
                   1433:         var newWindow = null;
                   1434:         try {
1.262     albertel 1435:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1436:         }
                   1437:         catch(error) {
                   1438:             writeHelp(caller);
                   1439:             return;
                   1440:         }
                   1441:         if (newWindow) {
                   1442:             caller = newWindow;
                   1443:         }
1.193     raeburn  1444:     }
1.243     raeburn  1445:     writeHelp(caller);
                   1446:     return;
                   1447: }
                   1448: function writeHelp(caller) {
1.1168    raeburn  1449:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1450:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1451:     caller.document.close();
                   1452:     caller.focus();
1.193     raeburn  1453: }
1.877     bisitz   1454: // END LON-CAPA Internal -->
1.253     albertel 1455: // ]]>
1.436     albertel 1456: </script>
1.193     raeburn  1457: ENDTEMPLATE
                   1458:     return $template;
                   1459: }
                   1460: 
1.172     www      1461: sub help_open_bug {
                   1462:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1463:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1464:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1465:     $text = "" if (not defined $text);
                   1466: 	$stayOnPage=1;
1.184     albertel 1467:     $width = 600 if (not defined $width);
                   1468:     $height = 600 if (not defined $height);
1.172     www      1469: 
                   1470:     $topic=~s/\W+/\+/g;
                   1471:     my $link='';
                   1472:     my $template='';
1.379     albertel 1473:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1474: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1475:     if (!$stayOnPage)
                   1476:     {
                   1477: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1478:     }
                   1479:     else
                   1480:     {
                   1481: 	$link = $url;
                   1482:     }
                   1483:     # Add the text
                   1484:     if ($text ne "")
                   1485:     {
                   1486: 	$template .= 
                   1487:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1488:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1489:     }
                   1490: 
                   1491:     # Add the graphic
1.179     matthew  1492:     my $title = &mt('Report a Bug');
1.215     albertel 1493:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1494:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1495:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1496: ENDTEMPLATE
                   1497:     if ($text ne '') { $template.='</td></tr></table>' };
                   1498:     return $template;
                   1499: 
                   1500: }
                   1501: 
                   1502: sub help_open_faq {
                   1503:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1504:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1505:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1506:     $text = "" if (not defined $text);
                   1507: 	$stayOnPage=1;
                   1508:     $width = 350 if (not defined $width);
                   1509:     $height = 400 if (not defined $height);
                   1510: 
                   1511:     $topic=~s/\W+/\+/g;
                   1512:     my $link='';
                   1513:     my $template='';
                   1514:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1515:     if (!$stayOnPage)
                   1516:     {
                   1517: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1518:     }
                   1519:     else
                   1520:     {
                   1521: 	$link = $url;
                   1522:     }
                   1523: 
                   1524:     # Add the text
                   1525:     if ($text ne "")
                   1526:     {
                   1527: 	$template .= 
1.173     www      1528:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1529:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1530:     }
                   1531: 
                   1532:     # Add the graphic
1.179     matthew  1533:     my $title = &mt('View the FAQ');
1.215     albertel 1534:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1535:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1536:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1537: ENDTEMPLATE
                   1538:     if ($text ne '') { $template.='</td></tr></table>' };
                   1539:     return $template;
                   1540: 
1.44      bowersj2 1541: }
1.37      matthew  1542: 
1.180     matthew  1543: ###############################################################
                   1544: ###############################################################
                   1545: 
1.45      matthew  1546: =pod
                   1547: 
1.648     raeburn  1548: =item * &change_content_javascript():
1.256     matthew  1549: 
                   1550: This and the next function allow you to create small sections of an
                   1551: otherwise static HTML page that you can update on the fly with
                   1552: Javascript, even in Netscape 4.
                   1553: 
                   1554: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1555: must be written to the HTML page once. It will prove the Javascript
                   1556: function "change(name, content)". Calling the change function with the
                   1557: name of the section 
                   1558: you want to update, matching the name passed to C<changable_area>, and
                   1559: the new content you want to put in there, will put the content into
                   1560: that area.
                   1561: 
                   1562: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1563: to contain room for the original contents. You need to "make space"
                   1564: for whatever changes you wish to make, and be B<sure> to check your
                   1565: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1566: it's adequate for updating a one-line status display, but little more.
                   1567: This script will set the space to 100% width, so you only need to
                   1568: worry about height in Netscape 4.
                   1569: 
                   1570: Modern browsers are much less limiting, and if you can commit to the
                   1571: user not using Netscape 4, this feature may be used freely with
                   1572: pretty much any HTML.
                   1573: 
                   1574: =cut
                   1575: 
                   1576: sub change_content_javascript {
                   1577:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1578:     if ($env{'browser.type'} eq 'netscape' &&
                   1579: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1580: 	return (<<NETSCAPE4);
                   1581: 	function change(name, content) {
                   1582: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1583: 	    doc.open();
                   1584: 	    doc.write(content);
                   1585: 	    doc.close();
                   1586: 	}
                   1587: NETSCAPE4
                   1588:     } else {
                   1589: 	# Otherwise, we need to use semi-standards-compliant code
                   1590: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1591: 	# is really scary, and every useful browser supports it
                   1592: 	return (<<DOMBASED);
                   1593: 	function change(name, content) {
                   1594: 	    element = document.getElementById(name);
                   1595: 	    element.innerHTML = content;
                   1596: 	}
                   1597: DOMBASED
                   1598:     }
                   1599: }
                   1600: 
                   1601: =pod
                   1602: 
1.648     raeburn  1603: =item * &changable_area($name,$origContent):
1.256     matthew  1604: 
                   1605: This provides a "changable area" that can be modified on the fly via
                   1606: the Javascript code provided in C<change_content_javascript>. $name is
                   1607: the name you will use to reference the area later; do not repeat the
                   1608: same name on a given HTML page more then once. $origContent is what
                   1609: the area will originally contain, which can be left blank.
                   1610: 
                   1611: =cut
                   1612: 
                   1613: sub changable_area {
                   1614:     my ($name, $origContent) = @_;
                   1615: 
1.258     albertel 1616:     if ($env{'browser.type'} eq 'netscape' &&
                   1617: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1618: 	# If this is netscape 4, we need to use the Layer tag
                   1619: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1620:     } else {
                   1621: 	return "<span id='$name'>$origContent</span>";
                   1622:     }
                   1623: }
                   1624: 
                   1625: =pod
                   1626: 
1.648     raeburn  1627: =item * &viewport_geometry_js 
1.590     raeburn  1628: 
                   1629: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1630: 
                   1631: =cut
                   1632: 
                   1633: 
                   1634: sub viewport_geometry_js { 
                   1635:     return <<"GEOMETRY";
                   1636: var Geometry = {};
                   1637: function init_geometry() {
                   1638:     if (Geometry.init) { return };
                   1639:     Geometry.init=1;
                   1640:     if (window.innerHeight) {
                   1641:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1642:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1643:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1644:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1645:     }
                   1646:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1647:         Geometry.getViewportHeight =
                   1648:             function() { return document.documentElement.clientHeight; };
                   1649:         Geometry.getViewportWidth =
                   1650:             function() { return document.documentElement.clientWidth; };
                   1651: 
                   1652:         Geometry.getHorizontalScroll =
                   1653:             function() { return document.documentElement.scrollLeft; };
                   1654:         Geometry.getVerticalScroll =
                   1655:             function() { return document.documentElement.scrollTop; };
                   1656:     }
                   1657:     else if (document.body.clientHeight) {
                   1658:         Geometry.getViewportHeight =
                   1659:             function() { return document.body.clientHeight; };
                   1660:         Geometry.getViewportWidth =
                   1661:             function() { return document.body.clientWidth; };
                   1662:         Geometry.getHorizontalScroll =
                   1663:             function() { return document.body.scrollLeft; };
                   1664:         Geometry.getVerticalScroll =
                   1665:             function() { return document.body.scrollTop; };
                   1666:     }
                   1667: }
                   1668: 
                   1669: GEOMETRY
                   1670: }
                   1671: 
                   1672: =pod
                   1673: 
1.648     raeburn  1674: =item * &viewport_size_js()
1.590     raeburn  1675: 
                   1676: 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. 
                   1677: 
                   1678: =cut
                   1679: 
                   1680: sub viewport_size_js {
                   1681:     my $geometry = &viewport_geometry_js();
                   1682:     return <<"DIMS";
                   1683: 
                   1684: $geometry
                   1685: 
                   1686: function getViewportDims(width,height) {
                   1687:     init_geometry();
                   1688:     width.value = Geometry.getViewportWidth();
                   1689:     height.value = Geometry.getViewportHeight();
                   1690:     return;
                   1691: }
                   1692: 
                   1693: DIMS
                   1694: }
                   1695: 
                   1696: =pod
                   1697: 
1.648     raeburn  1698: =item * &resize_textarea_js()
1.565     albertel 1699: 
                   1700: emits the needed javascript to resize a textarea to be as big as possible
                   1701: 
                   1702: creates a function resize_textrea that takes two IDs first should be
                   1703: the id of the element to resize, second should be the id of a div that
                   1704: surrounds everything that comes after the textarea, this routine needs
                   1705: to be attached to the <body> for the onload and onresize events.
                   1706: 
1.648     raeburn  1707: =back
1.565     albertel 1708: 
                   1709: =cut
                   1710: 
                   1711: sub resize_textarea_js {
1.590     raeburn  1712:     my $geometry = &viewport_geometry_js();
1.565     albertel 1713:     return <<"RESIZE";
                   1714:     <script type="text/javascript">
1.824     bisitz   1715: // <![CDATA[
1.590     raeburn  1716: $geometry
1.565     albertel 1717: 
1.588     albertel 1718: function getX(element) {
                   1719:     var x = 0;
                   1720:     while (element) {
                   1721: 	x += element.offsetLeft;
                   1722: 	element = element.offsetParent;
                   1723:     }
                   1724:     return x;
                   1725: }
                   1726: function getY(element) {
                   1727:     var y = 0;
                   1728:     while (element) {
                   1729: 	y += element.offsetTop;
                   1730: 	element = element.offsetParent;
                   1731:     }
                   1732:     return y;
                   1733: }
                   1734: 
                   1735: 
1.565     albertel 1736: function resize_textarea(textarea_id,bottom_id) {
                   1737:     init_geometry();
                   1738:     var textarea        = document.getElementById(textarea_id);
                   1739:     //alert(textarea);
                   1740: 
1.588     albertel 1741:     var textarea_top    = getY(textarea);
1.565     albertel 1742:     var textarea_height = textarea.offsetHeight;
                   1743:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1744:     var bottom_top      = getY(bottom);
1.565     albertel 1745:     var bottom_height   = bottom.offsetHeight;
                   1746:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1747:     var fudge           = 23;
1.565     albertel 1748:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1749:     if (new_height < 300) {
                   1750: 	new_height = 300;
                   1751:     }
                   1752:     textarea.style.height=new_height+'px';
                   1753: }
1.824     bisitz   1754: // ]]>
1.565     albertel 1755: </script>
                   1756: RESIZE
                   1757: 
                   1758: }
                   1759: 
1.1205  ! golterma 1760: sub colorfuleditor_js {
        !          1761:     return <<"COLORFULEDIT"
        !          1762: <script type="text/javascript">
        !          1763: // <![CDATA[>
        !          1764:     function fold_box(curDepth, lastresource){
        !          1765: 
        !          1766:     // we need a list because there can be several blocks you need to fold in one tag
        !          1767:         var block = document.getElementsByName('foldblock_'+curDepth);
        !          1768:     // but there is only one folding button per tag
        !          1769:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
        !          1770: 
        !          1771:         if(block.item(0).style.display == 'none'){
        !          1772: 
        !          1773:             foldbutton.value = '@{[&mt("Hide")]}';
        !          1774:             for (i = 0; i < block.length; i++){
        !          1775:                 block.item(i).style.display = '';
        !          1776:             }
        !          1777:         }else{
        !          1778: 
        !          1779:             foldbutton.value = '@{[&mt("Show")]}';
        !          1780:             for (i = 0; i < block.length; i++){
        !          1781:                 // block.item(i).style.visibility = 'collapse';
        !          1782:                 block.item(i).style.display = 'none';
        !          1783:             }
        !          1784:         };
        !          1785:         saveState(lastresource);
        !          1786:     }
        !          1787: 
        !          1788:     function saveState (lastresource) {
        !          1789: 
        !          1790:         var tag_list = getTagList();
        !          1791:         if(tag_list != null){
        !          1792:             var timestamp = new Date().getTime();
        !          1793:             var key = lastresource;
        !          1794: 
        !          1795:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
        !          1796:             // starting with timestamp
        !          1797:             var value = timestamp+';';
        !          1798: 
        !          1799:             // building the list of key-value pairs
        !          1800:             for(var i = 0; i < tag_list.length; i++){
        !          1801:                 value += tag_list[i]+',';
        !          1802:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
        !          1803:             }
        !          1804: 
        !          1805:             // only iterate whole storage if nothing to override
        !          1806:             if(localStorage.getItem(key) == null){        
        !          1807: 
        !          1808:                 // prevent storage from growing large
        !          1809:                 if(localStorage.length > 50){
        !          1810:                     var regex_getTimestamp = /^(?:\d)+;/;
        !          1811:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
        !          1812:                     var oldest_key;
        !          1813:                     
        !          1814:                     for(var i = 1; i < localStorage.length; i++){
        !          1815:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
        !          1816:                             oldest_key = localStorage.key(i);
        !          1817:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
        !          1818:                         }
        !          1819:                     }
        !          1820:                     localStorage.removeItem(oldest_key);
        !          1821:                 }
        !          1822:             }
        !          1823:             localStorage.setItem(key,value);
        !          1824:         }
        !          1825:     }
        !          1826: 
        !          1827:     // restore folding status of blocks (on page load)
        !          1828:     function restoreState (lastresource) {
        !          1829:         if(localStorage.getItem(lastresource) != null){
        !          1830:             var key = lastresource;
        !          1831:             var value = localStorage.getItem(key);
        !          1832:             var regex_delTimestamp = /^\d+;/;
        !          1833: 
        !          1834:             value.replace(regex_delTimestamp, '');
        !          1835: 
        !          1836:             var valueArr = value.split(';');
        !          1837:             var pairs;
        !          1838:             var elements;
        !          1839:             for (var i = 0; i < valueArr.length; i++){
        !          1840:                 pairs = valueArr[i].split(',');
        !          1841:                 elements = document.getElementsByName(pairs[0]);
        !          1842: 
        !          1843:                 for (var j = 0; j < elements.length; j++){  
        !          1844:                     elements[j].style.display = pairs[1];
        !          1845:                     if (pairs[1] == "none"){
        !          1846:                         var regex_id = /([_\\d]+)\$/;
        !          1847:                         regex_id.exec(pairs[0]);
        !          1848:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
        !          1849:                     }
        !          1850:                 }
        !          1851:             }
        !          1852:         }
        !          1853:     }
        !          1854: 
        !          1855:     function getTagList () {
        !          1856:         
        !          1857:         var stringToSearch = document.lonhomework.innerHTML;
        !          1858: 
        !          1859:         var ret = new Array();
        !          1860:         var regex_findBlock = /(foldblock_.*?)"/g;
        !          1861:         var tag_list = stringToSearch.match(regex_findBlock);
        !          1862: 
        !          1863:         if(tag_list != null){
        !          1864:             for(var i = 0; i < tag_list.length; i++){            
        !          1865:                 ret.push(tag_list[i].replace(/"/, ''));
        !          1866:             }
        !          1867:         }
        !          1868:         return ret;
        !          1869:     }
        !          1870: 
        !          1871:     function saveScrollPosition (resource) {
        !          1872:         var tag_list = getTagList();
        !          1873: 
        !          1874:         // we dont always want to jump to the first block
        !          1875:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
        !          1876:         if(\$(window).scrollTop() > 170){
        !          1877:             if(tag_list != null){
        !          1878:                 var result;
        !          1879:                 for(var i = 0; i < tag_list.length; i++){
        !          1880:                     if(isElementInViewport(tag_list[i])){
        !          1881:                         result += tag_list[i]+';';
        !          1882:                     }
        !          1883:                 }
        !          1884:                 sessionStorage.setItem('anchor_'+resource, result);
        !          1885:             }
        !          1886:         } else {
        !          1887:             // we dont need to save zero, just delete the item to leave everything tidy
        !          1888:             sessionStorage.removeItem('anchor_'+resource);
        !          1889:         }
        !          1890:     }
        !          1891: 
        !          1892:     function restoreScrollPosition(resource){
        !          1893: 
        !          1894:         var elem = sessionStorage.getItem('anchor_'+resource);
        !          1895:         if(elem != null){
        !          1896:             var tag_list = elem.split(';');
        !          1897:             var elem_list;
        !          1898: 
        !          1899:             for(var i = 0; i < tag_list.length; i++){
        !          1900:                 elem_list = document.getElementsByName(tag_list[i]);
        !          1901:                 
        !          1902:                 if(elem_list.length > 0){
        !          1903:                     elem = elem_list[0];
        !          1904:                     break;
        !          1905:                 }
        !          1906:             }
        !          1907:             elem.scrollIntoView();
        !          1908:         }
        !          1909:     }
        !          1910: 
        !          1911:     function isElementInViewport(el) {
        !          1912: 
        !          1913:         // change to last element instead of first
        !          1914:         var elem = document.getElementsByName(el);
        !          1915:         var rect = elem[0].getBoundingClientRect();
        !          1916: 
        !          1917:         return (
        !          1918:             rect.top >= 0 &&
        !          1919:             rect.left >= 0 &&
        !          1920:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
        !          1921:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
        !          1922:         );
        !          1923:     }
        !          1924:     
        !          1925:     function autosize(depth){
        !          1926:         var cmInst = window['cm'+depth];
        !          1927:         var fitsizeButton = document.getElementById('fitsize'+depth);
        !          1928: 
        !          1929:         // is fixed size, switching to dynamic
        !          1930:         if (sessionStorage.getItem("autosized_"+depth) == null) {
        !          1931:             cmInst.setSize("","auto");
        !          1932:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
        !          1933:             sessionStorage.setItem("autosized_"+depth, "yes");
        !          1934: 
        !          1935:         // is dynamic size, switching to fixed
        !          1936:         } else {
        !          1937:             cmInst.setSize("","300px");
        !          1938:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
        !          1939:             sessionStorage.removeItem("autosized_"+depth);
        !          1940:         }
        !          1941:     }
        !          1942: 
        !          1943: 
        !          1944: 
        !          1945: // ]]>
        !          1946: </script>
        !          1947: COLORFULEDIT
        !          1948: }
        !          1949: 
        !          1950: sub xmleditor_js {
        !          1951:     return <<XMLEDIT
        !          1952: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
        !          1953: <script type="text/javascript">
        !          1954: // <![CDATA[>
        !          1955: 
        !          1956:     function saveScrollPosition (resource) {
        !          1957: 
        !          1958:         var scrollPos = \$(window).scrollTop();
        !          1959:         sessionStorage.setItem(resource,scrollPos);
        !          1960:     }
        !          1961: 
        !          1962:     function restoreScrollPosition(resource){
        !          1963: 
        !          1964:         var scrollPos = sessionStorage.getItem(resource);
        !          1965:         \$(window).scrollTop(scrollPos);
        !          1966:     }
        !          1967: 
        !          1968:     // unless internet explorer
        !          1969:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
        !          1970: 
        !          1971:         \$(document).ready(function() {
        !          1972:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
        !          1973:         });
        !          1974:     }
        !          1975: 
        !          1976:     // inserts text at cursor position into codemirror (xml editor only)
        !          1977:     function insertText(text){
        !          1978:         cm.focus();
        !          1979:         var curPos = cm.getCursor();
        !          1980:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
        !          1981:     }
        !          1982: // ]]>
        !          1983: </script>
        !          1984: XMLEDIT
        !          1985: }
        !          1986: 
        !          1987: sub insert_folding_button {
        !          1988:     my $curDepth = $Apache::lonxml::curdepth;
        !          1989:     my $lastresource = $env{'request.ambiguous'};
        !          1990: 
        !          1991:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
        !          1992:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
        !          1993: }
        !          1994: 
1.565     albertel 1995: =pod
                   1996: 
1.256     matthew  1997: =head1 Excel and CSV file utility routines
                   1998: 
                   1999: =cut
                   2000: 
                   2001: ###############################################################
                   2002: ###############################################################
                   2003: 
                   2004: =pod
                   2005: 
1.1162    raeburn  2006: =over 4
                   2007: 
1.648     raeburn  2008: =item * &csv_translate($text) 
1.37      matthew  2009: 
1.185     www      2010: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2011: format.
                   2012: 
                   2013: =cut
                   2014: 
1.180     matthew  2015: ###############################################################
                   2016: ###############################################################
1.37      matthew  2017: sub csv_translate {
                   2018:     my $text = shift;
                   2019:     $text =~ s/\"/\"\"/g;
1.209     albertel 2020:     $text =~ s/\n/ /g;
1.37      matthew  2021:     return $text;
                   2022: }
1.180     matthew  2023: 
                   2024: ###############################################################
                   2025: ###############################################################
                   2026: 
                   2027: =pod
                   2028: 
1.648     raeburn  2029: =item * &define_excel_formats()
1.180     matthew  2030: 
                   2031: Define some commonly used Excel cell formats.
                   2032: 
                   2033: Currently supported formats:
                   2034: 
                   2035: =over 4
                   2036: 
                   2037: =item header
                   2038: 
                   2039: =item bold
                   2040: 
                   2041: =item h1
                   2042: 
                   2043: =item h2
                   2044: 
                   2045: =item h3
                   2046: 
1.256     matthew  2047: =item h4
                   2048: 
                   2049: =item i
                   2050: 
1.180     matthew  2051: =item date
                   2052: 
                   2053: =back
                   2054: 
                   2055: Inputs: $workbook
                   2056: 
                   2057: Returns: $format, a hash reference.
                   2058: 
1.1057    foxr     2059: 
1.180     matthew  2060: =cut
                   2061: 
                   2062: ###############################################################
                   2063: ###############################################################
                   2064: sub define_excel_formats {
                   2065:     my ($workbook) = @_;
                   2066:     my $format;
                   2067:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2068:                                                 bottom    => 1,
                   2069:                                                 align     => 'center');
                   2070:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2071:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2072:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2073:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2074:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2075:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2076:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2077:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2078:     return $format;
                   2079: }
                   2080: 
                   2081: ###############################################################
                   2082: ###############################################################
1.113     bowersj2 2083: 
                   2084: =pod
                   2085: 
1.648     raeburn  2086: =item * &create_workbook()
1.255     matthew  2087: 
                   2088: Create an Excel worksheet.  If it fails, output message on the
                   2089: request object and return undefs.
                   2090: 
                   2091: Inputs: Apache request object
                   2092: 
                   2093: Returns (undef) on failure, 
                   2094:     Excel worksheet object, scalar with filename, and formats 
                   2095:     from &Apache::loncommon::define_excel_formats on success
                   2096: 
                   2097: =cut
                   2098: 
                   2099: ###############################################################
                   2100: ###############################################################
                   2101: sub create_workbook {
                   2102:     my ($r) = @_;
                   2103:         #
                   2104:     # Create the excel spreadsheet
                   2105:     my $filename = '/prtspool/'.
1.258     albertel 2106:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2107:         time.'_'.rand(1000000000).'.xls';
                   2108:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2109:     if (! defined($workbook)) {
                   2110:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2111:         $r->print(
                   2112:             '<p class="LC_error">'
                   2113:            .&mt('Problems occurred in creating the new Excel file.')
                   2114:            .' '.&mt('This error has been logged.')
                   2115:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2116:            .'</p>'
                   2117:         );
1.255     matthew  2118:         return (undef);
                   2119:     }
                   2120:     #
1.1014    foxr     2121:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2122:     #
                   2123:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2124:     return ($workbook,$filename,$format);
                   2125: }
                   2126: 
                   2127: ###############################################################
                   2128: ###############################################################
                   2129: 
                   2130: =pod
                   2131: 
1.648     raeburn  2132: =item * &create_text_file()
1.113     bowersj2 2133: 
1.542     raeburn  2134: Create a file to write to and eventually make available to the user.
1.256     matthew  2135: If file creation fails, outputs an error message on the request object and 
                   2136: return undefs.
1.113     bowersj2 2137: 
1.256     matthew  2138: Inputs: Apache request object, and file suffix
1.113     bowersj2 2139: 
1.256     matthew  2140: Returns (undef) on failure, 
                   2141:     Filehandle and filename on success.
1.113     bowersj2 2142: 
                   2143: =cut
                   2144: 
1.256     matthew  2145: ###############################################################
                   2146: ###############################################################
                   2147: sub create_text_file {
                   2148:     my ($r,$suffix) = @_;
                   2149:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2150:     my $fh;
                   2151:     my $filename = '/prtspool/'.
1.258     albertel 2152:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2153:         time.'_'.rand(1000000000).'.'.$suffix;
                   2154:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2155:     if (! defined($fh)) {
                   2156:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2157:         $r->print(
                   2158:             '<p class="LC_error">'
                   2159:            .&mt('Problems occurred in creating the output file.')
                   2160:            .' '.&mt('This error has been logged.')
                   2161:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2162:            .'</p>'
                   2163:         );
1.113     bowersj2 2164:     }
1.256     matthew  2165:     return ($fh,$filename)
1.113     bowersj2 2166: }
                   2167: 
                   2168: 
1.256     matthew  2169: =pod 
1.113     bowersj2 2170: 
                   2171: =back
                   2172: 
                   2173: =cut
1.37      matthew  2174: 
                   2175: ###############################################################
1.33      matthew  2176: ##        Home server <option> list generating code          ##
                   2177: ###############################################################
1.35      matthew  2178: 
1.169     www      2179: # ------------------------------------------
                   2180: 
                   2181: sub domain_select {
                   2182:     my ($name,$value,$multiple)=@_;
                   2183:     my %domains=map { 
1.514     albertel 2184: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 2185:     } &Apache::lonnet::all_domains();
1.169     www      2186:     if ($multiple) {
                   2187: 	$domains{''}=&mt('Any domain');
1.550     albertel 2188: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2189: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2190:     } else {
1.550     albertel 2191: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2192: 	return &select_form($name,$value,\%domains);
1.169     www      2193:     }
                   2194: }
                   2195: 
1.282     albertel 2196: #-------------------------------------------
                   2197: 
                   2198: =pod
                   2199: 
1.519     raeburn  2200: =head1 Routines for form select boxes
                   2201: 
                   2202: =over 4
                   2203: 
1.648     raeburn  2204: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2205: 
                   2206: Returns a string containing a <select> element int multiple mode
                   2207: 
                   2208: 
                   2209: Args:
                   2210:   $name - name of the <select> element
1.506     raeburn  2211:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2212:   $size - number of rows long the select element is
1.283     albertel 2213:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2214:           (shown text should already have been &mt())
1.506     raeburn  2215:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2216: 
1.282     albertel 2217: =cut
                   2218: 
                   2219: #-------------------------------------------
1.169     www      2220: sub multiple_select_form {
1.284     albertel 2221:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2222:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2223:     my $output='';
1.191     matthew  2224:     if (! defined($size)) {
                   2225:         $size = 4;
1.283     albertel 2226:         if (scalar(keys(%$hash))<4) {
                   2227:             $size = scalar(keys(%$hash));
1.191     matthew  2228:         }
                   2229:     }
1.734     bisitz   2230:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2231:     my @order;
1.506     raeburn  2232:     if (ref($order) eq 'ARRAY')  {
                   2233:         @order = @{$order};
                   2234:     } else {
                   2235:         @order = sort(keys(%$hash));
1.501     banghart 2236:     }
                   2237:     if (exists($$hash{'select_form_order'})) {
                   2238:         @order = @{$$hash{'select_form_order'}};
                   2239:     }
                   2240:         
1.284     albertel 2241:     foreach my $key (@order) {
1.356     albertel 2242:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2243:         $output.='selected="selected" ' if ($selected{$key});
                   2244:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2245:     }
                   2246:     $output.="</select>\n";
                   2247:     return $output;
                   2248: }
                   2249: 
1.88      www      2250: #-------------------------------------------
                   2251: 
                   2252: =pod
                   2253: 
1.970     raeburn  2254: =item * &select_form($defdom,$name,$hashref,$onchange)
1.88      www      2255: 
                   2256: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2257: allow a user to select options from a ref to a hash containing:
                   2258: option_name => displayed text. An optional $onchange can include
                   2259: a javascript onchange item, e.g., onchange="this.form.submit();"  
                   2260: 
1.88      www      2261: See lonrights.pm for an example invocation and use.
                   2262: 
                   2263: =cut
                   2264: 
                   2265: #-------------------------------------------
                   2266: sub select_form {
1.970     raeburn  2267:     my ($def,$name,$hashref,$onchange) = @_;
                   2268:     return unless (ref($hashref) eq 'HASH');
                   2269:     if ($onchange) {
                   2270:         $onchange = ' onchange="'.$onchange.'"';
                   2271:     }
                   2272:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.128     albertel 2273:     my @keys;
1.970     raeburn  2274:     if (exists($hashref->{'select_form_order'})) {
                   2275: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2276:     } else {
1.970     raeburn  2277: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2278:     }
1.356     albertel 2279:     foreach my $key (@keys) {
                   2280:         $selectform.=
                   2281: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2282:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2283:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2284:     }
                   2285:     $selectform.="</select>";
                   2286:     return $selectform;
                   2287: }
                   2288: 
1.475     www      2289: # For display filters
                   2290: 
                   2291: sub display_filter {
1.1074    raeburn  2292:     my ($context) = @_;
1.475     www      2293:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2294:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2295:     my $phraseinput = 'hidden';
                   2296:     my $includeinput = 'hidden';
                   2297:     my ($checked,$includetypestext);
                   2298:     if ($env{'form.displayfilter'} eq 'containing') {
                   2299:         $phraseinput = 'text'; 
                   2300:         if ($context eq 'parmslog') {
                   2301:             $includeinput = 'checkbox';
                   2302:             if ($env{'form.includetypes'}) {
                   2303:                 $checked = ' checked="checked"';
                   2304:             }
                   2305:             $includetypestext = &mt('Include parameter types');
                   2306:         }
                   2307:     } else {
                   2308:         $includetypestext = '&nbsp;';
                   2309:     }
                   2310:     my ($additional,$secondid,$thirdid);
                   2311:     if ($context eq 'parmslog') {
                   2312:         $additional = 
                   2313:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2314:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2315:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2316:             '</label>';
                   2317:         $secondid = 'includetypes';
                   2318:         $thirdid = 'includetypestext';
                   2319:     }
                   2320:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2321:                                                     '$secondid','$thirdid')";
                   2322:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2323: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2324: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2325: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2326:            &mt('Filter: [_1]',
1.477     www      2327: 	   &select_form($env{'form.displayfilter'},
                   2328: 			'displayfilter',
1.970     raeburn  2329: 			{'currentfolder' => 'Current folder/page',
1.477     www      2330: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2331: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2332: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2333:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2334:                          '" />'.$additional;
                   2335: }
                   2336: 
                   2337: sub display_filter_js {
                   2338:     my $includetext = &mt('Include parameter types');
                   2339:     return <<"ENDJS";
                   2340:   
                   2341: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2342:     var firstType = 'hidden';
                   2343:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2344:         firstType = 'text';
                   2345:     }
                   2346:     firstObject = document.getElementById(firstid);
                   2347:     if (typeof(firstObject) == 'object') {
                   2348:         if (firstObject.type != firstType) {
                   2349:             changeInputType(firstObject,firstType);
                   2350:         }
                   2351:     }
                   2352:     if (context == 'parmslog') {
                   2353:         var secondType = 'hidden';
                   2354:         if (firstType == 'text') {
                   2355:             secondType = 'checkbox';
                   2356:         }
                   2357:         secondObject = document.getElementById(secondid);  
                   2358:         if (typeof(secondObject) == 'object') {
                   2359:             if (secondObject.type != secondType) {
                   2360:                 changeInputType(secondObject,secondType);
                   2361:             }
                   2362:         }
                   2363:         var textItem = document.getElementById(thirdid);
                   2364:         var currtext = textItem.innerHTML;
                   2365:         var newtext;
                   2366:         if (firstType == 'text') {
                   2367:             newtext = '$includetext';
                   2368:         } else {
                   2369:             newtext = '&nbsp;';
                   2370:         }
                   2371:         if (currtext != newtext) {
                   2372:             textItem.innerHTML = newtext;
                   2373:         }
                   2374:     }
                   2375:     return;
                   2376: }
                   2377: 
                   2378: function changeInputType(oldObject,newType) {
                   2379:     var newObject = document.createElement('input');
                   2380:     newObject.type = newType;
                   2381:     if (oldObject.size) {
                   2382:         newObject.size = oldObject.size;
                   2383:     }
                   2384:     if (oldObject.value) {
                   2385:         newObject.value = oldObject.value;
                   2386:     }
                   2387:     if (oldObject.name) {
                   2388:         newObject.name = oldObject.name;
                   2389:     }
                   2390:     if (oldObject.id) {
                   2391:         newObject.id = oldObject.id;
                   2392:     }
                   2393:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2394:     return;
                   2395: }
                   2396: 
                   2397: ENDJS
1.475     www      2398: }
                   2399: 
1.167     www      2400: sub gradeleveldescription {
                   2401:     my $gradelevel=shift;
                   2402:     my %gradelevels=(0 => 'Not specified',
                   2403: 		     1 => 'Grade 1',
                   2404: 		     2 => 'Grade 2',
                   2405: 		     3 => 'Grade 3',
                   2406: 		     4 => 'Grade 4',
                   2407: 		     5 => 'Grade 5',
                   2408: 		     6 => 'Grade 6',
                   2409: 		     7 => 'Grade 7',
                   2410: 		     8 => 'Grade 8',
                   2411: 		     9 => 'Grade 9',
                   2412: 		     10 => 'Grade 10',
                   2413: 		     11 => 'Grade 11',
                   2414: 		     12 => 'Grade 12',
                   2415: 		     13 => 'Grade 13',
                   2416: 		     14 => '100 Level',
                   2417: 		     15 => '200 Level',
                   2418: 		     16 => '300 Level',
                   2419: 		     17 => '400 Level',
                   2420: 		     18 => 'Graduate Level');
                   2421:     return &mt($gradelevels{$gradelevel});
                   2422: }
                   2423: 
1.163     www      2424: sub select_level_form {
                   2425:     my ($deflevel,$name)=@_;
                   2426:     unless ($deflevel) { $deflevel=0; }
1.167     www      2427:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2428:     for (my $i=0; $i<=18; $i++) {
                   2429:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2430:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2431:                 ">".&gradeleveldescription($i)."</option>\n";
                   2432:     }
                   2433:     $selectform.="</select>";
                   2434:     return $selectform;
1.163     www      2435: }
1.167     www      2436: 
1.35      matthew  2437: #-------------------------------------------
                   2438: 
1.45      matthew  2439: =pod
                   2440: 
1.1121    raeburn  2441: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
1.35      matthew  2442: 
                   2443: Returns a string containing a <select name='$name' size='1'> form to 
                   2444: allow a user to select the domain to preform an operation in.  
                   2445: See loncreateuser.pm for an example invocation and use.
                   2446: 
1.90      www      2447: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2448: selected");
                   2449: 
1.743     raeburn  2450: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2451: 
1.910     raeburn  2452: 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.
                   2453: 
1.1121    raeburn  2454: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2455: 
                   2456: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  2457: 
1.35      matthew  2458: =cut
                   2459: 
                   2460: #-------------------------------------------
1.34      matthew  2461: sub select_dom_form {
1.1121    raeburn  2462:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
1.872     raeburn  2463:     if ($onchange) {
1.874     raeburn  2464:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2465:     }
1.1121    raeburn  2466:     my (@domains,%exclude);
1.910     raeburn  2467:     if (ref($incdoms) eq 'ARRAY') {
                   2468:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2469:     } else {
                   2470:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2471:     }
1.90      www      2472:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  2473:     if (ref($excdoms) eq 'ARRAY') {
                   2474:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   2475:     }
1.743     raeburn  2476:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.356     albertel 2477:     foreach my $dom (@domains) {
1.1121    raeburn  2478:         next if ($exclude{$dom});
1.356     albertel 2479:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2480:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2481:         if ($showdomdesc) {
                   2482:             if ($dom ne '') {
                   2483:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2484:                 if ($domdesc ne '') {
                   2485:                     $selectdomain .= ' ('.$domdesc.')';
                   2486:                 }
                   2487:             } 
                   2488:         }
                   2489:         $selectdomain .= "</option>\n";
1.34      matthew  2490:     }
                   2491:     $selectdomain.="</select>";
                   2492:     return $selectdomain;
                   2493: }
                   2494: 
1.35      matthew  2495: #-------------------------------------------
                   2496: 
1.45      matthew  2497: =pod
                   2498: 
1.648     raeburn  2499: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2500: 
1.586     raeburn  2501: input: 4 arguments (two required, two optional) - 
                   2502:     $domain - domain of new user
                   2503:     $name - name of form element
                   2504:     $default - Value of 'default' causes a default item to be first 
                   2505:                             option, and selected by default. 
                   2506:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2507:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2508: output: returns 2 items: 
1.586     raeburn  2509: (a) form element which contains either:
                   2510:    (i) <select name="$name">
                   2511:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2512:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2513:        </select>
                   2514:        form item if there are multiple library servers in $domain, or
                   2515:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2516:        if there is only one library server in $domain.
                   2517: 
                   2518: (b) number of library servers found.
                   2519: 
                   2520: See loncreateuser.pm for example of use.
1.35      matthew  2521: 
                   2522: =cut
                   2523: 
                   2524: #-------------------------------------------
1.586     raeburn  2525: sub home_server_form_item {
                   2526:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2527:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2528:     my $result;
                   2529:     my $numlib = keys(%servers);
                   2530:     if ($numlib > 1) {
                   2531:         $result .= '<select name="'.$name.'" />'."\n";
                   2532:         if ($default) {
1.804     bisitz   2533:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2534:                        '</option>'."\n";
                   2535:         }
                   2536:         foreach my $hostid (sort(keys(%servers))) {
                   2537:             $result.= '<option value="'.$hostid.'">'.
                   2538: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2539:         }
                   2540:         $result .= '</select>'."\n";
                   2541:     } elsif ($numlib == 1) {
                   2542:         my $hostid;
                   2543:         foreach my $item (keys(%servers)) {
                   2544:             $hostid = $item;
                   2545:         }
                   2546:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2547:                    $hostid.'" />';
                   2548:                    if (!$hide) {
                   2549:                        $result .= $hostid.' '.$servers{$hostid};
                   2550:                    }
                   2551:                    $result .= "\n";
                   2552:     } elsif ($default) {
                   2553:         $result .= '<input type="hidden" name="'.$name.
                   2554:                    '" value="default" />';
                   2555:                    if (!$hide) {
                   2556:                        $result .= &mt('default');
                   2557:                    }
                   2558:                    $result .= "\n";
1.33      matthew  2559:     }
1.586     raeburn  2560:     return ($result,$numlib);
1.33      matthew  2561: }
1.112     bowersj2 2562: 
                   2563: =pod
                   2564: 
1.534     albertel 2565: =back 
                   2566: 
1.112     bowersj2 2567: =cut
1.87      matthew  2568: 
                   2569: ###############################################################
1.112     bowersj2 2570: ##                  Decoding User Agent                      ##
1.87      matthew  2571: ###############################################################
                   2572: 
                   2573: =pod
                   2574: 
1.112     bowersj2 2575: =head1 Decoding the User Agent
                   2576: 
                   2577: =over 4
                   2578: 
                   2579: =item * &decode_user_agent()
1.87      matthew  2580: 
                   2581: Inputs: $r
                   2582: 
                   2583: Outputs:
                   2584: 
                   2585: =over 4
                   2586: 
1.112     bowersj2 2587: =item * $httpbrowser
1.87      matthew  2588: 
1.112     bowersj2 2589: =item * $clientbrowser
1.87      matthew  2590: 
1.112     bowersj2 2591: =item * $clientversion
1.87      matthew  2592: 
1.112     bowersj2 2593: =item * $clientmathml
1.87      matthew  2594: 
1.112     bowersj2 2595: =item * $clientunicode
1.87      matthew  2596: 
1.112     bowersj2 2597: =item * $clientos
1.87      matthew  2598: 
1.1137    raeburn  2599: =item * $clientmobile
                   2600: 
1.1141    raeburn  2601: =item * $clientinfo
                   2602: 
1.1194    raeburn  2603: =item * $clientosversion
                   2604: 
1.87      matthew  2605: =back
                   2606: 
1.157     matthew  2607: =back 
                   2608: 
1.87      matthew  2609: =cut
                   2610: 
                   2611: ###############################################################
                   2612: ###############################################################
                   2613: sub decode_user_agent {
1.247     albertel 2614:     my ($r)=@_;
1.87      matthew  2615:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2616:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2617:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2618:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2619:     my $clientbrowser='unknown';
                   2620:     my $clientversion='0';
                   2621:     my $clientmathml='';
                   2622:     my $clientunicode='0';
1.1137    raeburn  2623:     my $clientmobile=0;
1.1194    raeburn  2624:     my $clientosversion='';
1.87      matthew  2625:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  2626:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2627: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2628: 	    $clientbrowser=$bname;
                   2629:             $httpbrowser=~/$vreg/i;
                   2630: 	    $clientversion=$1;
                   2631:             $clientmathml=($clientversion>=$minv);
                   2632:             $clientunicode=($clientversion>=$univ);
                   2633: 	}
                   2634:     }
                   2635:     my $clientos='unknown';
1.1141    raeburn  2636:     my $clientinfo;
1.87      matthew  2637:     if (($httpbrowser=~/linux/i) ||
                   2638:         ($httpbrowser=~/unix/i) ||
                   2639:         ($httpbrowser=~/ux/i) ||
                   2640:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2641:     if (($httpbrowser=~/vax/i) ||
                   2642:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2643:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2644:     if (($httpbrowser=~/mac/i) ||
                   2645:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  2646:     if ($httpbrowser=~/win/i) {
                   2647:         $clientos='win';
                   2648:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2649:             $clientosversion = $1;
                   2650:         }
                   2651:     }
1.87      matthew  2652:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  2653:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2654:         $clientmobile=lc($1);
                   2655:     }
1.1141    raeburn  2656:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2657:         $clientinfo = 'firefox-'.$1;
                   2658:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2659:         $clientinfo = 'chromeframe-'.$1;
                   2660:     }
1.87      matthew  2661:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  2662:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2663:             $clientosversion);
1.87      matthew  2664: }
                   2665: 
1.32      matthew  2666: ###############################################################
                   2667: ##    Authentication changing form generation subroutines    ##
                   2668: ###############################################################
                   2669: ##
                   2670: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2671: ## hash, and have reasonable default values.
                   2672: ##
                   2673: ##    formname = the name given in the <form> tag.
1.35      matthew  2674: #-------------------------------------------
                   2675: 
1.45      matthew  2676: =pod
                   2677: 
1.112     bowersj2 2678: =head1 Authentication Routines
                   2679: 
                   2680: =over 4
                   2681: 
1.648     raeburn  2682: =item * &authform_xxxxxx()
1.35      matthew  2683: 
                   2684: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2685: handle some of the conveniences required for authentication forms.  
                   2686: This is not an optimal method, but it works.  
                   2687: 
                   2688: =over 4
                   2689: 
1.112     bowersj2 2690: =item * authform_header
1.35      matthew  2691: 
1.112     bowersj2 2692: =item * authform_authorwarning
1.35      matthew  2693: 
1.112     bowersj2 2694: =item * authform_nochange
1.35      matthew  2695: 
1.112     bowersj2 2696: =item * authform_kerberos
1.35      matthew  2697: 
1.112     bowersj2 2698: =item * authform_internal
1.35      matthew  2699: 
1.112     bowersj2 2700: =item * authform_filesystem
1.35      matthew  2701: 
                   2702: =back
                   2703: 
1.648     raeburn  2704: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2705: 
1.35      matthew  2706: =cut
                   2707: 
                   2708: #-------------------------------------------
1.32      matthew  2709: sub authform_header{  
                   2710:     my %in = (
                   2711:         formname => 'cu',
1.80      albertel 2712:         kerb_def_dom => '',
1.32      matthew  2713:         @_,
                   2714:     );
                   2715:     $in{'formname'} = 'document.' . $in{'formname'};
                   2716:     my $result='';
1.80      albertel 2717: 
                   2718: #---------------------------------------------- Code for upper case translation
                   2719:     my $Javascript_toUpperCase;
                   2720:     unless ($in{kerb_def_dom}) {
                   2721:         $Javascript_toUpperCase =<<"END";
                   2722:         switch (choice) {
                   2723:            case 'krb': currentform.elements[choicearg].value =
                   2724:                currentform.elements[choicearg].value.toUpperCase();
                   2725:                break;
                   2726:            default:
                   2727:         }
                   2728: END
                   2729:     } else {
                   2730:         $Javascript_toUpperCase = "";
                   2731:     }
                   2732: 
1.165     raeburn  2733:     my $radioval = "'nochange'";
1.591     raeburn  2734:     if (defined($in{'curr_authtype'})) {
                   2735:         if ($in{'curr_authtype'} ne '') {
                   2736:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2737:         }
1.174     matthew  2738:     }
1.165     raeburn  2739:     my $argfield = 'null';
1.591     raeburn  2740:     if (defined($in{'mode'})) {
1.165     raeburn  2741:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2742:             if (defined($in{'curr_autharg'})) {
                   2743:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2744:                     $argfield = "'$in{'curr_autharg'}'";
                   2745:                 }
                   2746:             }
                   2747:         }
                   2748:     }
                   2749: 
1.32      matthew  2750:     $result.=<<"END";
                   2751: var current = new Object();
1.165     raeburn  2752: current.radiovalue = $radioval;
                   2753: current.argfield = $argfield;
1.32      matthew  2754: 
                   2755: function changed_radio(choice,currentform) {
                   2756:     var choicearg = choice + 'arg';
                   2757:     // If a radio button in changed, we need to change the argfield
                   2758:     if (current.radiovalue != choice) {
                   2759:         current.radiovalue = choice;
                   2760:         if (current.argfield != null) {
                   2761:             currentform.elements[current.argfield].value = '';
                   2762:         }
                   2763:         if (choice == 'nochange') {
                   2764:             current.argfield = null;
                   2765:         } else {
                   2766:             current.argfield = choicearg;
                   2767:             switch(choice) {
                   2768:                 case 'krb': 
                   2769:                     currentform.elements[current.argfield].value = 
                   2770:                         "$in{'kerb_def_dom'}";
                   2771:                 break;
                   2772:               default:
                   2773:                 break;
                   2774:             }
                   2775:         }
                   2776:     }
                   2777:     return;
                   2778: }
1.22      www      2779: 
1.32      matthew  2780: function changed_text(choice,currentform) {
                   2781:     var choicearg = choice + 'arg';
                   2782:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2783:         $Javascript_toUpperCase
1.32      matthew  2784:         // clear old field
                   2785:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2786:             currentform.elements[current.argfield].value = '';
                   2787:         }
                   2788:         current.argfield = choicearg;
                   2789:     }
                   2790:     set_auth_radio_buttons(choice,currentform);
                   2791:     return;
1.20      www      2792: }
1.32      matthew  2793: 
                   2794: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2795:     var numauthchoices = currentform.login.length;
                   2796:     if (typeof numauthchoices  == "undefined") {
                   2797:         return;
                   2798:     } 
1.32      matthew  2799:     var i=0;
1.986     raeburn  2800:     while (i < numauthchoices) {
1.32      matthew  2801:         if (currentform.login[i].value == newvalue) { break; }
                   2802:         i++;
                   2803:     }
1.986     raeburn  2804:     if (i == numauthchoices) {
1.32      matthew  2805:         return;
                   2806:     }
                   2807:     current.radiovalue = newvalue;
                   2808:     currentform.login[i].checked = true;
                   2809:     return;
                   2810: }
                   2811: END
                   2812:     return $result;
                   2813: }
                   2814: 
1.1106    raeburn  2815: sub authform_authorwarning {
1.32      matthew  2816:     my $result='';
1.144     matthew  2817:     $result='<i>'.
                   2818:         &mt('As a general rule, only authors or co-authors should be '.
                   2819:             'filesystem authenticated '.
                   2820:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2821:     return $result;
                   2822: }
                   2823: 
1.1106    raeburn  2824: sub authform_nochange {
1.32      matthew  2825:     my %in = (
                   2826:               formname => 'document.cu',
                   2827:               kerb_def_dom => 'MSU.EDU',
                   2828:               @_,
                   2829:           );
1.1106    raeburn  2830:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  2831:     my $result;
1.1104    raeburn  2832:     if (!$authnum) {
1.1105    raeburn  2833:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2834:     } else {
                   2835:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2836:                   '<input type="radio" name="login" value="nochange" '.
                   2837:                   'checked="checked" onclick="'.
1.281     albertel 2838:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2839: 	    '</label>';
1.586     raeburn  2840:     }
1.32      matthew  2841:     return $result;
                   2842: }
                   2843: 
1.591     raeburn  2844: sub authform_kerberos {
1.32      matthew  2845:     my %in = (
                   2846:               formname => 'document.cu',
                   2847:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2848:               kerb_def_auth => 'krb4',
1.32      matthew  2849:               @_,
                   2850:               );
1.586     raeburn  2851:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
                   2852:         $autharg,$jscall);
1.1106    raeburn  2853:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2854:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2855:        $check5 = ' checked="checked"';
1.80      albertel 2856:     } else {
1.772     bisitz   2857:        $check4 = ' checked="checked"';
1.80      albertel 2858:     }
1.165     raeburn  2859:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2860:     if (defined($in{'curr_authtype'})) {
                   2861:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2862:             $krbcheck = ' checked="checked"';
1.623     raeburn  2863:             if (defined($in{'mode'})) {
                   2864:                 if ($in{'mode'} eq 'modifyuser') {
                   2865:                     $krbcheck = '';
                   2866:                 }
                   2867:             }
1.591     raeburn  2868:             if (defined($in{'curr_kerb_ver'})) {
                   2869:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2870:                     $check5 = ' checked="checked"';
1.591     raeburn  2871:                     $check4 = '';
                   2872:                 } else {
1.772     bisitz   2873:                     $check4 = ' checked="checked"';
1.591     raeburn  2874:                     $check5 = '';
                   2875:                 }
1.586     raeburn  2876:             }
1.591     raeburn  2877:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2878:                 $krbarg = $in{'curr_autharg'};
                   2879:             }
1.586     raeburn  2880:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2881:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2882:                     $result = 
                   2883:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2884:         $in{'curr_autharg'},$krbver);
                   2885:                 } else {
                   2886:                     $result =
                   2887:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2888:                 }
                   2889:                 return $result; 
                   2890:             }
                   2891:         }
                   2892:     } else {
                   2893:         if ($authnum == 1) {
1.784     bisitz   2894:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2895:         }
                   2896:     }
1.586     raeburn  2897:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2898:         return;
1.587     raeburn  2899:     } elsif ($authtype eq '') {
1.591     raeburn  2900:         if (defined($in{'mode'})) {
1.587     raeburn  2901:             if ($in{'mode'} eq 'modifycourse') {
                   2902:                 if ($authnum == 1) {
1.1104    raeburn  2903:                     $authtype = '<input type="radio" name="login" value="krb" />';
1.587     raeburn  2904:                 }
                   2905:             }
                   2906:         }
1.586     raeburn  2907:     }
                   2908:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2909:     if ($authtype eq '') {
                   2910:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2911:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
                   2912:                     $krbcheck.' />';
                   2913:     }
                   2914:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  2915:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2916:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  2917:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2918:          $in{'curr_authtype'} eq 'krb4')) {
                   2919:         $result .= &mt
1.144     matthew  2920:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2921:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2922:          '<label>'.$authtype,
1.281     albertel 2923:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2924:              'value="'.$krbarg.'" '.
1.144     matthew  2925:              'onchange="'.$jscall.'" />',
1.281     albertel 2926:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
                   2927:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
                   2928: 	 '</label>');
1.586     raeburn  2929:     } elsif ($can_assign{'krb4'}) {
                   2930:         $result .= &mt
                   2931:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2932:          '[_3] Version 4 [_4]',
                   2933:          '<label>'.$authtype,
                   2934:          '</label><input type="text" size="10" name="krbarg" '.
                   2935:              'value="'.$krbarg.'" '.
                   2936:              'onchange="'.$jscall.'" />',
                   2937:          '<label><input type="hidden" name="krbver" value="4" />',
                   2938:          '</label>');
                   2939:     } elsif ($can_assign{'krb5'}) {
                   2940:         $result .= &mt
                   2941:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2942:          '[_3] Version 5 [_4]',
                   2943:          '<label>'.$authtype,
                   2944:          '</label><input type="text" size="10" name="krbarg" '.
                   2945:              'value="'.$krbarg.'" '.
                   2946:              'onchange="'.$jscall.'" />',
                   2947:          '<label><input type="hidden" name="krbver" value="5" />',
                   2948:          '</label>');
                   2949:     }
1.32      matthew  2950:     return $result;
                   2951: }
                   2952: 
1.1106    raeburn  2953: sub authform_internal {
1.586     raeburn  2954:     my %in = (
1.32      matthew  2955:                 formname => 'document.cu',
                   2956:                 kerb_def_dom => 'MSU.EDU',
                   2957:                 @_,
                   2958:                 );
1.586     raeburn  2959:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
1.1106    raeburn  2960:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2961:     if (defined($in{'curr_authtype'})) {
                   2962:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2963:             if ($can_assign{'int'}) {
1.772     bisitz   2964:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2965:                 if (defined($in{'mode'})) {
                   2966:                     if ($in{'mode'} eq 'modifyuser') {
                   2967:                         $intcheck = '';
                   2968:                     }
                   2969:                 }
1.591     raeburn  2970:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2971:                     $intarg = $in{'curr_autharg'};
                   2972:                 }
                   2973:             } else {
                   2974:                 $result = &mt('Currently internally authenticated.');
                   2975:                 return $result;
1.165     raeburn  2976:             }
                   2977:         }
1.586     raeburn  2978:     } else {
                   2979:         if ($authnum == 1) {
1.784     bisitz   2980:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  2981:         }
                   2982:     }
                   2983:     if (!$can_assign{'int'}) {
                   2984:         return;
1.587     raeburn  2985:     } elsif ($authtype eq '') {
1.591     raeburn  2986:         if (defined($in{'mode'})) {
1.587     raeburn  2987:             if ($in{'mode'} eq 'modifycourse') {
                   2988:                 if ($authnum == 1) {
1.1104    raeburn  2989:                     $authtype = '<input type="radio" name="login" value="int" />';
1.587     raeburn  2990:                 }
                   2991:             }
                   2992:         }
1.165     raeburn  2993:     }
1.586     raeburn  2994:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   2995:     if ($authtype eq '') {
                   2996:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
                   2997:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
                   2998:     }
1.605     bisitz   2999:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.586     raeburn  3000:                $intarg.'" onchange="'.$jscall.'" />';
                   3001:     $result = &mt
1.144     matthew  3002:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3003:          '<label>'.$authtype,'</label>'.$autharg);
1.824     bisitz   3004:     $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  3005:     return $result;
                   3006: }
                   3007: 
1.1104    raeburn  3008: sub authform_local {
1.32      matthew  3009:     my %in = (
                   3010:               formname => 'document.cu',
                   3011:               kerb_def_dom => 'MSU.EDU',
                   3012:               @_,
                   3013:               );
1.586     raeburn  3014:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
1.1106    raeburn  3015:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  3016:     if (defined($in{'curr_authtype'})) {
                   3017:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3018:             if ($can_assign{'loc'}) {
1.772     bisitz   3019:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3020:                 if (defined($in{'mode'})) {
                   3021:                     if ($in{'mode'} eq 'modifyuser') {
                   3022:                         $loccheck = '';
                   3023:                     }
                   3024:                 }
1.591     raeburn  3025:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3026:                     $locarg = $in{'curr_autharg'};
                   3027:                 }
                   3028:             } else {
                   3029:                 $result = &mt('Currently using local (institutional) authentication.');
                   3030:                 return $result;
1.165     raeburn  3031:             }
                   3032:         }
1.586     raeburn  3033:     } else {
                   3034:         if ($authnum == 1) {
1.784     bisitz   3035:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3036:         }
                   3037:     }
                   3038:     if (!$can_assign{'loc'}) {
                   3039:         return;
1.587     raeburn  3040:     } elsif ($authtype eq '') {
1.591     raeburn  3041:         if (defined($in{'mode'})) {
1.587     raeburn  3042:             if ($in{'mode'} eq 'modifycourse') {
                   3043:                 if ($authnum == 1) {
1.1104    raeburn  3044:                     $authtype = '<input type="radio" name="login" value="loc" />';
1.587     raeburn  3045:                 }
                   3046:             }
                   3047:         }
1.165     raeburn  3048:     }
1.586     raeburn  3049:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3050:     if ($authtype eq '') {
                   3051:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3052:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
                   3053:                     $jscall.'" />';
                   3054:     }
                   3055:     $autharg = '<input type="text" size="10" name="locarg" value="'.
                   3056:                $locarg.'" onchange="'.$jscall.'" />';
                   3057:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3058:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3059:     return $result;
                   3060: }
                   3061: 
1.1106    raeburn  3062: sub authform_filesystem {
1.32      matthew  3063:     my %in = (
                   3064:               formname => 'document.cu',
                   3065:               kerb_def_dom => 'MSU.EDU',
                   3066:               @_,
                   3067:               );
1.586     raeburn  3068:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
1.1106    raeburn  3069:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  3070:     if (defined($in{'curr_authtype'})) {
                   3071:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3072:             if ($can_assign{'fsys'}) {
1.772     bisitz   3073:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3074:                 if (defined($in{'mode'})) {
                   3075:                     if ($in{'mode'} eq 'modifyuser') {
                   3076:                         $fsyscheck = '';
                   3077:                     }
                   3078:                 }
1.586     raeburn  3079:             } else {
                   3080:                 $result = &mt('Currently Filesystem Authenticated.');
                   3081:                 return $result;
                   3082:             }           
                   3083:         }
                   3084:     } else {
                   3085:         if ($authnum == 1) {
1.784     bisitz   3086:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3087:         }
                   3088:     }
                   3089:     if (!$can_assign{'fsys'}) {
                   3090:         return;
1.587     raeburn  3091:     } elsif ($authtype eq '') {
1.591     raeburn  3092:         if (defined($in{'mode'})) {
1.587     raeburn  3093:             if ($in{'mode'} eq 'modifycourse') {
                   3094:                 if ($authnum == 1) {
1.1104    raeburn  3095:                     $authtype = '<input type="radio" name="login" value="fsys" />';
1.587     raeburn  3096:                 }
                   3097:             }
                   3098:         }
1.586     raeburn  3099:     }
                   3100:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3101:     if ($authtype eq '') {
                   3102:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3103:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
                   3104:                     $jscall.'" />';
                   3105:     }
                   3106:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
                   3107:                ' onchange="'.$jscall.'" />';
                   3108:     $result = &mt
1.144     matthew  3109:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 3110:          '<label><input type="radio" name="login" value="fsys" '.
1.586     raeburn  3111:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1.605     bisitz   3112:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.144     matthew  3113:                   'onchange="'.$jscall.'" />');
1.32      matthew  3114:     return $result;
                   3115: }
                   3116: 
1.586     raeburn  3117: sub get_assignable_auth {
                   3118:     my ($dom) = @_;
                   3119:     if ($dom eq '') {
                   3120:         $dom = $env{'request.role.domain'};
                   3121:     }
                   3122:     my %can_assign = (
                   3123:                           krb4 => 1,
                   3124:                           krb5 => 1,
                   3125:                           int  => 1,
                   3126:                           loc  => 1,
                   3127:                      );
                   3128:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3129:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3130:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3131:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3132:             my $context;
                   3133:             if ($env{'request.role'} =~ /^au/) {
                   3134:                 $context = 'author';
                   3135:             } elsif ($env{'request.role'} =~ /^dc/) {
                   3136:                 $context = 'domain';
                   3137:             } elsif ($env{'request.course.id'}) {
                   3138:                 $context = 'course';
                   3139:             }
                   3140:             if ($context) {
                   3141:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3142:                    %can_assign = %{$authhash->{$context}}; 
                   3143:                 }
                   3144:             }
                   3145:         }
                   3146:     }
                   3147:     my $authnum = 0;
                   3148:     foreach my $key (keys(%can_assign)) {
                   3149:         if ($can_assign{$key}) {
                   3150:             $authnum ++;
                   3151:         }
                   3152:     }
                   3153:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3154:         $authnum --;
                   3155:     }
                   3156:     return ($authnum,%can_assign);
                   3157: }
                   3158: 
1.80      albertel 3159: ###############################################################
                   3160: ##    Get Kerberos Defaults for Domain                 ##
                   3161: ###############################################################
                   3162: ##
                   3163: ## Returns default kerberos version and an associated argument
                   3164: ## as listed in file domain.tab. If not listed, provides
                   3165: ## appropriate default domain and kerberos version.
                   3166: ##
                   3167: #-------------------------------------------
                   3168: 
                   3169: =pod
                   3170: 
1.648     raeburn  3171: =item * &get_kerberos_defaults()
1.80      albertel 3172: 
                   3173: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3174: version and domain. If not found, it defaults to version 4 and the 
                   3175: domain of the server.
1.80      albertel 3176: 
1.648     raeburn  3177: =over 4
                   3178: 
1.80      albertel 3179: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3180: 
1.648     raeburn  3181: =back
                   3182: 
                   3183: =back
                   3184: 
1.80      albertel 3185: =cut
                   3186: 
                   3187: #-------------------------------------------
                   3188: sub get_kerberos_defaults {
                   3189:     my $domain=shift;
1.641     raeburn  3190:     my ($krbdef,$krbdefdom);
                   3191:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3192:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3193:         $krbdef = $domdefaults{'auth_def'};
                   3194:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3195:     } else {
1.80      albertel 3196:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3197:         my $krbdefdom=$1;
                   3198:         $krbdefdom=~tr/a-z/A-Z/;
                   3199:         $krbdef = "krb4";
                   3200:     }
                   3201:     return ($krbdef,$krbdefdom);
                   3202: }
1.112     bowersj2 3203: 
1.32      matthew  3204: 
1.46      matthew  3205: ###############################################################
                   3206: ##                Thesaurus Functions                        ##
                   3207: ###############################################################
1.20      www      3208: 
1.46      matthew  3209: =pod
1.20      www      3210: 
1.112     bowersj2 3211: =head1 Thesaurus Functions
                   3212: 
                   3213: =over 4
                   3214: 
1.648     raeburn  3215: =item * &initialize_keywords()
1.46      matthew  3216: 
                   3217: Initializes the package variable %Keywords if it is empty.  Uses the
                   3218: package variable $thesaurus_db_file.
                   3219: 
                   3220: =cut
                   3221: 
                   3222: ###################################################
                   3223: 
                   3224: sub initialize_keywords {
                   3225:     return 1 if (scalar keys(%Keywords));
                   3226:     # If we are here, %Keywords is empty, so fill it up
                   3227:     #   Make sure the file we need exists...
                   3228:     if (! -e $thesaurus_db_file) {
                   3229:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3230:                                  " failed because it does not exist");
                   3231:         return 0;
                   3232:     }
                   3233:     #   Set up the hash as a database
                   3234:     my %thesaurus_db;
                   3235:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3236:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3237:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3238:                                  $thesaurus_db_file);
                   3239:         return 0;
                   3240:     } 
                   3241:     #  Get the average number of appearances of a word.
                   3242:     my $avecount = $thesaurus_db{'average.count'};
                   3243:     #  Put keywords (those that appear > average) into %Keywords
                   3244:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3245:         my ($count,undef) = split /:/,$data;
                   3246:         $Keywords{$word}++ if ($count > $avecount);
                   3247:     }
                   3248:     untie %thesaurus_db;
                   3249:     # Remove special values from %Keywords.
1.356     albertel 3250:     foreach my $value ('total.count','average.count') {
                   3251:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3252:   }
1.46      matthew  3253:     return 1;
                   3254: }
                   3255: 
                   3256: ###################################################
                   3257: 
                   3258: =pod
                   3259: 
1.648     raeburn  3260: =item * &keyword($word)
1.46      matthew  3261: 
                   3262: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3263: than the average number of times in the thesaurus database.  Calls 
                   3264: &initialize_keywords
                   3265: 
                   3266: =cut
                   3267: 
                   3268: ###################################################
1.20      www      3269: 
                   3270: sub keyword {
1.46      matthew  3271:     return if (!&initialize_keywords());
                   3272:     my $word=lc(shift());
                   3273:     $word=~s/\W//g;
                   3274:     return exists($Keywords{$word});
1.20      www      3275: }
1.46      matthew  3276: 
                   3277: ###############################################################
                   3278: 
                   3279: =pod 
1.20      www      3280: 
1.648     raeburn  3281: =item * &get_related_words()
1.46      matthew  3282: 
1.160     matthew  3283: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3284: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3285: will be returned.  The order of the words returned is determined by the
                   3286: database which holds them.
                   3287: 
                   3288: Uses global $thesaurus_db_file.
                   3289: 
1.1057    foxr     3290: 
1.46      matthew  3291: =cut
                   3292: 
                   3293: ###############################################################
                   3294: sub get_related_words {
                   3295:     my $keyword = shift;
                   3296:     my %thesaurus_db;
                   3297:     if (! -e $thesaurus_db_file) {
                   3298:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3299:                                  "failed because the file does not exist");
                   3300:         return ();
                   3301:     }
                   3302:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3303:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3304:         return ();
                   3305:     } 
                   3306:     my @Words=();
1.429     www      3307:     my $count=0;
1.46      matthew  3308:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3309: 	# The first element is the number of times
                   3310: 	# the word appears.  We do not need it now.
1.429     www      3311: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3312: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3313: 	my $threshold=$mostfrequentcount/10;
                   3314:         foreach my $possibleword (@RelatedWords) {
                   3315:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3316:             if ($wordcount>$threshold) {
                   3317: 		push(@Words,$word);
                   3318:                 $count++;
                   3319:                 if ($count>10) { last; }
                   3320: 	    }
1.20      www      3321:         }
                   3322:     }
1.46      matthew  3323:     untie %thesaurus_db;
                   3324:     return @Words;
1.14      harris41 3325: }
1.1090    foxr     3326: ###############################################################
                   3327: #
                   3328: #  Spell checking
                   3329: #
                   3330: 
                   3331: =pod
                   3332: 
1.1142    raeburn  3333: =back
                   3334: 
1.1090    foxr     3335: =head1 Spell checking
                   3336: 
                   3337: =over 4
                   3338: 
                   3339: =item * &check_spelling($wordlist $language)
                   3340: 
                   3341: Takes a string containing words and feeds it to an external
                   3342: spellcheck program via a pipeline. Returns a string containing
                   3343: them mis-spelled words.
                   3344: 
                   3345: Parameters:
                   3346: 
                   3347: =over 4
                   3348: 
                   3349: =item - $wordlist
                   3350: 
                   3351: String that will be fed into the spellcheck program.
                   3352: 
                   3353: =item - $language
                   3354: 
                   3355: Language string that specifies the language for which the spell
                   3356: check will be performed.
                   3357: 
                   3358: =back
                   3359: 
                   3360: =back
                   3361: 
                   3362: Note: This sub assumes that aspell is installed.
                   3363: 
                   3364: 
                   3365: =cut
                   3366: 
1.46      matthew  3367: 
1.1090    foxr     3368: sub check_spelling {
                   3369:     my ($wordlist, $language) = @_;
1.1091    foxr     3370:     my @misspellings;
                   3371:     
                   3372:     # Generate the speller and set the langauge.
                   3373:     # if explicitly selected:
1.1090    foxr     3374: 
1.1091    foxr     3375:     my $speller = Text::Aspell->new;
1.1090    foxr     3376:     if ($language) {
1.1091    foxr     3377: 	$speller->set_option('lang', $language);
1.1090    foxr     3378:     }
                   3379: 
1.1091    foxr     3380:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     3381: 
1.1091    foxr     3382:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     3383: 
1.1091    foxr     3384:     foreach my $word (@words) {
                   3385: 	if(! $speller->check($word)) {
                   3386: 	    push(@misspellings, $word);
1.1090    foxr     3387: 	}
                   3388:     }
1.1091    foxr     3389:     return join(' ', @misspellings);
                   3390:     
1.1090    foxr     3391: }
                   3392: 
1.61      www      3393: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3394: =pod
                   3395: 
1.112     bowersj2 3396: =head1 User Name Functions
                   3397: 
                   3398: =over 4
                   3399: 
1.648     raeburn  3400: =item * &plainname($uname,$udom,$first)
1.81      albertel 3401: 
1.112     bowersj2 3402: Takes a users logon name and returns it as a string in
1.226     albertel 3403: "first middle last generation" form 
                   3404: if $first is set to 'lastname' then it returns it as
                   3405: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3406: 
                   3407: =cut
1.61      www      3408: 
1.295     www      3409: 
1.81      albertel 3410: ###############################################################
1.61      www      3411: sub plainname {
1.226     albertel 3412:     my ($uname,$udom,$first)=@_;
1.537     albertel 3413:     return if (!defined($uname) || !defined($udom));
1.295     www      3414:     my %names=&getnames($uname,$udom);
1.226     albertel 3415:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3416: 					  $names{'middlename'},
                   3417: 					  $names{'lastname'},
                   3418: 					  $names{'generation'},$first);
                   3419:     $name=~s/^\s+//;
1.62      www      3420:     $name=~s/\s+$//;
                   3421:     $name=~s/\s+/ /g;
1.353     albertel 3422:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3423:     return $name;
1.61      www      3424: }
1.66      www      3425: 
                   3426: # -------------------------------------------------------------------- Nickname
1.81      albertel 3427: =pod
                   3428: 
1.648     raeburn  3429: =item * &nickname($uname,$udom)
1.81      albertel 3430: 
                   3431: Gets a users name and returns it as a string as
                   3432: 
                   3433: "&quot;nickname&quot;"
1.66      www      3434: 
1.81      albertel 3435: if the user has a nickname or
                   3436: 
                   3437: "first middle last generation"
                   3438: 
                   3439: if the user does not
                   3440: 
                   3441: =cut
1.66      www      3442: 
                   3443: sub nickname {
                   3444:     my ($uname,$udom)=@_;
1.537     albertel 3445:     return if (!defined($uname) || !defined($udom));
1.295     www      3446:     my %names=&getnames($uname,$udom);
1.68      albertel 3447:     my $name=$names{'nickname'};
1.66      www      3448:     if ($name) {
                   3449:        $name='&quot;'.$name.'&quot;'; 
                   3450:     } else {
                   3451:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3452: 	     $names{'lastname'}.' '.$names{'generation'};
                   3453:        $name=~s/\s+$//;
                   3454:        $name=~s/\s+/ /g;
                   3455:     }
                   3456:     return $name;
                   3457: }
                   3458: 
1.295     www      3459: sub getnames {
                   3460:     my ($uname,$udom)=@_;
1.537     albertel 3461:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3462:     if ($udom eq 'public' && $uname eq 'public') {
                   3463: 	return ('lastname' => &mt('Public'));
                   3464:     }
1.295     www      3465:     my $id=$uname.':'.$udom;
                   3466:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3467:     if ($cached) {
                   3468: 	return %{$names};
                   3469:     } else {
                   3470: 	my %loadnames=&Apache::lonnet::get('environment',
                   3471:                     ['firstname','middlename','lastname','generation','nickname'],
                   3472: 					 $udom,$uname);
                   3473: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3474: 	return %loadnames;
                   3475:     }
                   3476: }
1.61      www      3477: 
1.542     raeburn  3478: # -------------------------------------------------------------------- getemails
1.648     raeburn  3479: 
1.542     raeburn  3480: =pod
                   3481: 
1.648     raeburn  3482: =item * &getemails($uname,$udom)
1.542     raeburn  3483: 
                   3484: Gets a user's email information and returns it as a hash with keys:
                   3485: notification, critnotification, permanentemail
                   3486: 
                   3487: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3488: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3489:  
1.648     raeburn  3490: 
1.542     raeburn  3491: =cut
                   3492: 
1.648     raeburn  3493: 
1.466     albertel 3494: sub getemails {
                   3495:     my ($uname,$udom)=@_;
                   3496:     if ($udom eq 'public' && $uname eq 'public') {
                   3497: 	return;
                   3498:     }
1.467     www      3499:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3500:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3501:     my $id=$uname.':'.$udom;
                   3502:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3503:     if ($cached) {
                   3504: 	return %{$names};
                   3505:     } else {
                   3506: 	my %loadnames=&Apache::lonnet::get('environment',
                   3507:                     			   ['notification','critnotification',
                   3508: 					    'permanentemail'],
                   3509: 					   $udom,$uname);
                   3510: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3511: 	return %loadnames;
                   3512:     }
                   3513: }
                   3514: 
1.551     albertel 3515: sub flush_email_cache {
                   3516:     my ($uname,$udom)=@_;
                   3517:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3518:     if (!$uname) { $uname=$env{'user.name'};   }
                   3519:     return if ($udom eq 'public' && $uname eq 'public');
                   3520:     my $id=$uname.':'.$udom;
                   3521:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3522: }
                   3523: 
1.728     raeburn  3524: # -------------------------------------------------------------------- getlangs
                   3525: 
                   3526: =pod
                   3527: 
                   3528: =item * &getlangs($uname,$udom)
                   3529: 
                   3530: Gets a user's language preference and returns it as a hash with key:
                   3531: language.
                   3532: 
                   3533: =cut
                   3534: 
                   3535: 
                   3536: sub getlangs {
                   3537:     my ($uname,$udom) = @_;
                   3538:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3539:     if (!$uname) { $uname=$env{'user.name'};   }
                   3540:     my $id=$uname.':'.$udom;
                   3541:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3542:     if ($cached) {
                   3543:         return %{$langs};
                   3544:     } else {
                   3545:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3546:                                            $udom,$uname);
                   3547:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3548:         return %loadlangs;
                   3549:     }
                   3550: }
                   3551: 
                   3552: sub flush_langs_cache {
                   3553:     my ($uname,$udom)=@_;
                   3554:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3555:     if (!$uname) { $uname=$env{'user.name'};   }
                   3556:     return if ($udom eq 'public' && $uname eq 'public');
                   3557:     my $id=$uname.':'.$udom;
                   3558:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3559: }
                   3560: 
1.61      www      3561: # ------------------------------------------------------------------ Screenname
1.81      albertel 3562: 
                   3563: =pod
                   3564: 
1.648     raeburn  3565: =item * &screenname($uname,$udom)
1.81      albertel 3566: 
                   3567: Gets a users screenname and returns it as a string
                   3568: 
                   3569: =cut
1.61      www      3570: 
                   3571: sub screenname {
                   3572:     my ($uname,$udom)=@_;
1.258     albertel 3573:     if ($uname eq $env{'user.name'} &&
                   3574: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3575:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3576:     return $names{'screenname'};
1.62      www      3577: }
                   3578: 
1.212     albertel 3579: 
1.802     bisitz   3580: # ------------------------------------------------------------- Confirm Wrapper
                   3581: =pod
                   3582: 
1.1142    raeburn  3583: =item * &confirmwrapper($message)
1.802     bisitz   3584: 
                   3585: Wrap messages about completion of operation in box
                   3586: 
                   3587: =cut
                   3588: 
                   3589: sub confirmwrapper {
                   3590:     my ($message)=@_;
                   3591:     if ($message) {
                   3592:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3593:                .$message."\n"
                   3594:                .'</div>'."\n";
                   3595:     } else {
                   3596:         return $message;
                   3597:     }
                   3598: }
                   3599: 
1.62      www      3600: # ------------------------------------------------------------- Message Wrapper
                   3601: 
                   3602: sub messagewrapper {
1.369     www      3603:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3604:     return 
1.441     albertel 3605:         '<a href="/adm/email?compose=individual&amp;'.
                   3606:         'recname='.$username.'&amp;recdom='.$domain.
                   3607: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3608:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3609: }
1.802     bisitz   3610: 
1.74      www      3611: # --------------------------------------------------------------- Notes Wrapper
                   3612: 
                   3613: sub noteswrapper {
                   3614:     my ($link,$un,$do)=@_;
                   3615:     return 
1.896     amueller 3616: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3617: }
1.802     bisitz   3618: 
1.62      www      3619: # ------------------------------------------------------------- Aboutme Wrapper
                   3620: 
                   3621: sub aboutmewrapper {
1.1070    raeburn  3622:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3623:     if (!defined($username)  && !defined($domain)) {
                   3624:         return;
                   3625:     }
1.1096    raeburn  3626:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3627: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3628: }
                   3629: 
                   3630: # ------------------------------------------------------------ Syllabus Wrapper
                   3631: 
                   3632: sub syllabuswrapper {
1.707     bisitz   3633:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3634:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3635: }
1.14      harris41 3636: 
1.802     bisitz   3637: # -----------------------------------------------------------------------------
                   3638: 
1.208     matthew  3639: sub track_student_link {
1.887     raeburn  3640:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3641:     my $link ="/adm/trackstudent?";
1.208     matthew  3642:     my $title = 'View recent activity';
                   3643:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3644:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3645:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3646:         $title .= ' of this student';
1.268     albertel 3647:     } 
1.208     matthew  3648:     if (defined($target) && $target !~ /^\s*$/) {
                   3649:         $target = qq{target="$target"};
                   3650:     } else {
                   3651:         $target = '';
                   3652:     }
1.268     albertel 3653:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3654:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3655:     $title = &mt($title);
                   3656:     $linktext = &mt($linktext);
1.448     albertel 3657:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3658: 	&help_open_topic('View_recent_activity');
1.208     matthew  3659: }
                   3660: 
1.781     raeburn  3661: sub slot_reservations_link {
                   3662:     my ($linktext,$sname,$sdom,$target) = @_;
                   3663:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3664:     my $title = 'View slot reservation history';
                   3665:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3666:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3667:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3668:         $title .= ' of this student';
                   3669:     }
                   3670:     if (defined($target) && $target !~ /^\s*$/) {
                   3671:         $target = qq{target="$target"};
                   3672:     } else {
                   3673:         $target = '';
                   3674:     }
                   3675:     $title = &mt($title);
                   3676:     $linktext = &mt($linktext);
                   3677:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3678: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3679: 
                   3680: }
                   3681: 
1.508     www      3682: # ===================================================== Display a student photo
                   3683: 
                   3684: 
1.509     albertel 3685: sub student_image_tag {
1.508     www      3686:     my ($domain,$user)=@_;
                   3687:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3688:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3689: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3690:     } else {
                   3691: 	return '';
                   3692:     }
                   3693: }
                   3694: 
1.112     bowersj2 3695: =pod
                   3696: 
                   3697: =back
                   3698: 
                   3699: =head1 Access .tab File Data
                   3700: 
                   3701: =over 4
                   3702: 
1.648     raeburn  3703: =item * &languageids() 
1.112     bowersj2 3704: 
                   3705: returns list of all language ids
                   3706: 
                   3707: =cut
                   3708: 
1.14      harris41 3709: sub languageids {
1.16      harris41 3710:     return sort(keys(%language));
1.14      harris41 3711: }
                   3712: 
1.112     bowersj2 3713: =pod
                   3714: 
1.648     raeburn  3715: =item * &languagedescription() 
1.112     bowersj2 3716: 
                   3717: returns description of a specified language id
                   3718: 
                   3719: =cut
                   3720: 
1.14      harris41 3721: sub languagedescription {
1.125     www      3722:     my $code=shift;
                   3723:     return  ($supported_language{$code}?'* ':'').
                   3724:             $language{$code}.
1.126     www      3725: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3726: }
                   3727: 
1.1048    foxr     3728: =pod
                   3729: 
                   3730: =item * &plainlanguagedescription
                   3731: 
                   3732: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3733: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3734: 
                   3735: =cut
                   3736: 
1.145     www      3737: sub plainlanguagedescription {
                   3738:     my $code=shift;
                   3739:     return $language{$code};
                   3740: }
                   3741: 
1.1048    foxr     3742: =pod
                   3743: 
                   3744: =item * &supportedlanguagecode
                   3745: 
                   3746: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3747: code.
                   3748: 
                   3749: =cut
                   3750: 
1.145     www      3751: sub supportedlanguagecode {
                   3752:     my $code=shift;
                   3753:     return $supported_language{$code};
1.97      www      3754: }
                   3755: 
1.112     bowersj2 3756: =pod
                   3757: 
1.1048    foxr     3758: =item * &latexlanguage()
                   3759: 
                   3760: Given a language key code returns the correspondnig language to use
                   3761: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3762: is no supported hyphenation for the language code.
                   3763: 
                   3764: =cut
                   3765: 
                   3766: sub latexlanguage {
                   3767:     my $code = shift;
                   3768:     return $latex_language{$code};
                   3769: }
                   3770: 
                   3771: =pod
                   3772: 
                   3773: =item * &latexhyphenation()
                   3774: 
                   3775: Same as above but what's supplied is the language as it might be stored
                   3776: in the metadata.
                   3777: 
                   3778: =cut
                   3779: 
                   3780: sub latexhyphenation {
                   3781:     my $key = shift;
                   3782:     return $latex_language_bykey{$key};
                   3783: }
                   3784: 
                   3785: =pod
                   3786: 
1.648     raeburn  3787: =item * &copyrightids() 
1.112     bowersj2 3788: 
                   3789: returns list of all copyrights
                   3790: 
                   3791: =cut
                   3792: 
                   3793: sub copyrightids {
                   3794:     return sort(keys(%cprtag));
                   3795: }
                   3796: 
                   3797: =pod
                   3798: 
1.648     raeburn  3799: =item * &copyrightdescription() 
1.112     bowersj2 3800: 
                   3801: returns description of a specified copyright id
                   3802: 
                   3803: =cut
                   3804: 
                   3805: sub copyrightdescription {
1.166     www      3806:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3807: }
1.197     matthew  3808: 
                   3809: =pod
                   3810: 
1.648     raeburn  3811: =item * &source_copyrightids() 
1.192     taceyjo1 3812: 
                   3813: returns list of all source copyrights
                   3814: 
                   3815: =cut
                   3816: 
                   3817: sub source_copyrightids {
                   3818:     return sort(keys(%scprtag));
                   3819: }
                   3820: 
                   3821: =pod
                   3822: 
1.648     raeburn  3823: =item * &source_copyrightdescription() 
1.192     taceyjo1 3824: 
                   3825: returns description of a specified source copyright id
                   3826: 
                   3827: =cut
                   3828: 
                   3829: sub source_copyrightdescription {
                   3830:     return &mt($scprtag{shift(@_)});
                   3831: }
1.112     bowersj2 3832: 
                   3833: =pod
                   3834: 
1.648     raeburn  3835: =item * &filecategories() 
1.112     bowersj2 3836: 
                   3837: returns list of all file categories
                   3838: 
                   3839: =cut
                   3840: 
                   3841: sub filecategories {
                   3842:     return sort(keys(%category_extensions));
                   3843: }
                   3844: 
                   3845: =pod
                   3846: 
1.648     raeburn  3847: =item * &filecategorytypes() 
1.112     bowersj2 3848: 
                   3849: returns list of file types belonging to a given file
                   3850: category
                   3851: 
                   3852: =cut
                   3853: 
                   3854: sub filecategorytypes {
1.356     albertel 3855:     my ($cat) = @_;
                   3856:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3857: }
                   3858: 
                   3859: =pod
                   3860: 
1.648     raeburn  3861: =item * &fileembstyle() 
1.112     bowersj2 3862: 
                   3863: returns embedding style for a specified file type
                   3864: 
                   3865: =cut
                   3866: 
                   3867: sub fileembstyle {
                   3868:     return $fe{lc(shift(@_))};
1.169     www      3869: }
                   3870: 
1.351     www      3871: sub filemimetype {
                   3872:     return $fm{lc(shift(@_))};
                   3873: }
                   3874: 
1.169     www      3875: 
                   3876: sub filecategoryselect {
                   3877:     my ($name,$value)=@_;
1.189     matthew  3878:     return &select_form($value,$name,
1.970     raeburn  3879:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 3880: }
                   3881: 
                   3882: =pod
                   3883: 
1.648     raeburn  3884: =item * &filedescription() 
1.112     bowersj2 3885: 
                   3886: returns description for a specified file type
                   3887: 
                   3888: =cut
                   3889: 
                   3890: sub filedescription {
1.188     matthew  3891:     my $file_description = $fd{lc(shift())};
                   3892:     $file_description =~ s:([\[\]]):~$1:g;
                   3893:     return &mt($file_description);
1.112     bowersj2 3894: }
                   3895: 
                   3896: =pod
                   3897: 
1.648     raeburn  3898: =item * &filedescriptionex() 
1.112     bowersj2 3899: 
                   3900: returns description for a specified file type with
                   3901: extra formatting
                   3902: 
                   3903: =cut
                   3904: 
                   3905: sub filedescriptionex {
                   3906:     my $ex=shift;
1.188     matthew  3907:     my $file_description = $fd{lc($ex)};
                   3908:     $file_description =~ s:([\[\]]):~$1:g;
                   3909:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3910: }
                   3911: 
                   3912: # End of .tab access
                   3913: =pod
                   3914: 
                   3915: =back
                   3916: 
                   3917: =cut
                   3918: 
                   3919: # ------------------------------------------------------------------ File Types
                   3920: sub fileextensions {
                   3921:     return sort(keys(%fe));
                   3922: }
                   3923: 
1.97      www      3924: # ----------------------------------------------------------- Display Languages
                   3925: # returns a hash with all desired display languages
                   3926: #
                   3927: 
                   3928: sub display_languages {
                   3929:     my %languages=();
1.695     raeburn  3930:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3931: 	$languages{$lang}=1;
1.97      www      3932:     }
                   3933:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3934:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3935: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3936: 	    $languages{$lang}=1;
1.97      www      3937:         }
                   3938:     }
                   3939:     return %languages;
1.14      harris41 3940: }
                   3941: 
1.582     albertel 3942: sub languages {
                   3943:     my ($possible_langs) = @_;
1.695     raeburn  3944:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3945:     if (!ref($possible_langs)) {
                   3946: 	if( wantarray ) {
                   3947: 	    return @preferred_langs;
                   3948: 	} else {
                   3949: 	    return $preferred_langs[0];
                   3950: 	}
                   3951:     }
                   3952:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3953:     my @preferred_possibilities;
                   3954:     foreach my $preferred_lang (@preferred_langs) {
                   3955: 	if (exists($possibilities{$preferred_lang})) {
                   3956: 	    push(@preferred_possibilities, $preferred_lang);
                   3957: 	}
                   3958:     }
                   3959:     if( wantarray ) {
                   3960: 	return @preferred_possibilities;
                   3961:     }
                   3962:     return $preferred_possibilities[0];
                   3963: }
                   3964: 
1.742     raeburn  3965: sub user_lang {
                   3966:     my ($touname,$toudom,$fromcid) = @_;
                   3967:     my @userlangs;
                   3968:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   3969:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   3970:                     $env{'course.'.$fromcid.'.languages'}));
                   3971:     } else {
                   3972:         my %langhash = &getlangs($touname,$toudom);
                   3973:         if ($langhash{'languages'} ne '') {
                   3974:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   3975:         } else {
                   3976:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   3977:             if ($domdefs{'lang_def'} ne '') {
                   3978:                 @userlangs = ($domdefs{'lang_def'});
                   3979:             }
                   3980:         }
                   3981:     }
                   3982:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   3983:     my $user_lh = Apache::localize->get_handle(@languages);
                   3984:     return $user_lh;
                   3985: }
                   3986: 
                   3987: 
1.112     bowersj2 3988: ###############################################################
                   3989: ##               Student Answer Attempts                     ##
                   3990: ###############################################################
                   3991: 
                   3992: =pod
                   3993: 
                   3994: =head1 Alternate Problem Views
                   3995: 
                   3996: =over 4
                   3997: 
1.648     raeburn  3998: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  3999:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4000: 
                   4001: Return string with previous attempt on problem. Arguments:
                   4002: 
                   4003: =over 4
                   4004: 
                   4005: =item * $symb: Problem, including path
                   4006: 
                   4007: =item * $username: username of the desired student
                   4008: 
                   4009: =item * $domain: domain of the desired student
1.14      harris41 4010: 
1.112     bowersj2 4011: =item * $course: Course ID
1.14      harris41 4012: 
1.112     bowersj2 4013: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4014:     something
1.14      harris41 4015: 
1.112     bowersj2 4016: =item * $regexp: if string matches this regexp, the string will be
                   4017:     sent to $gradesub
1.14      harris41 4018: 
1.112     bowersj2 4019: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4020: 
1.1199    raeburn  4021: =item * $usec: section of the desired student
                   4022: 
                   4023: =item * $identifier: counter for student (multiple students one problem) or 
                   4024:     problem (one student; whole sequence).
                   4025: 
1.112     bowersj2 4026: =back
1.14      harris41 4027: 
1.112     bowersj2 4028: The output string is a table containing all desired attempts, if any.
1.16      harris41 4029: 
1.112     bowersj2 4030: =cut
1.1       albertel 4031: 
                   4032: sub get_previous_attempt {
1.1199    raeburn  4033:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4034:   my $prevattempts='';
1.43      ng       4035:   no strict 'refs';
1.1       albertel 4036:   if ($symb) {
1.3       albertel 4037:     my (%returnhash)=
                   4038:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4039:     if ($returnhash{'version'}) {
                   4040:       my %lasthash=();
                   4041:       my $version;
                   4042:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.356     albertel 4043:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   4044: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
1.19      harris41 4045:         }
1.1       albertel 4046:       }
1.596     albertel 4047:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4048:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  4049:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4050:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4051:       foreach my $key (sort(keys(%lasthash))) {
                   4052: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4053: 	if ($#parts > 0) {
1.31      albertel 4054: 	  my $data=$parts[-1];
1.989     raeburn  4055:           next if ($data eq 'foilorder');
1.31      albertel 4056: 	  pop(@parts);
1.1010    www      4057:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4058:           if ($data eq 'type') {
                   4059:               unless ($showsurv) {
                   4060:                   my $id = join(',',@parts);
                   4061:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4062:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4063:                       $lasthidden{$ign.'.'.$id} = 1;
                   4064:                   }
1.945     raeburn  4065:               }
1.1199    raeburn  4066:               if ($identifier ne '') {
                   4067:                   my $id = join(',',@parts);
                   4068:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4069:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4070:                       $hidestatus{$ign.'.'.$id} = 1;
                   4071:                   }
                   4072:               }
                   4073:           } elsif ($data eq 'regrader') {
                   4074:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  4075:                   my $id = join(',',@parts);
                   4076:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  4077:               }
1.1010    www      4078:           } 
1.31      albertel 4079: 	} else {
1.41      ng       4080: 	  if ($#parts == 0) {
                   4081: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4082: 	  } else {
                   4083: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4084: 	  }
1.31      albertel 4085: 	}
1.16      harris41 4086:       }
1.596     albertel 4087:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4088:       if ($getattempt eq '') {
1.1199    raeburn  4089:         my (%solved,%resets,%probstatus);
1.1200    raeburn  4090:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4091:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4092:                 foreach my $id (keys(%regraded)) {
                   4093:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4094:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4095:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4096:                         push(@{$resets{$id}},$version);
1.1199    raeburn  4097:                     }
                   4098:                 }
                   4099:             }
1.1200    raeburn  4100:         }
                   4101: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  4102:             my (@hidden,@unsolved);
1.945     raeburn  4103:             if (%typeparts) {
                   4104:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  4105:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   4106:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4107:                         push(@hidden,$id);
1.1199    raeburn  4108:                     } elsif ($identifier ne '') {
                   4109:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4110:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4111:                                 ($hidestatus{$id})) {
1.1200    raeburn  4112:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  4113:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4114:                                 push(@{$solved{$id}},$version);
                   4115:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4116:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4117:                                 my $skip;
                   4118:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4119:                                     foreach my $reset (@{$resets{$id}}) {
                   4120:                                         if ($reset > $solved{$id}[-1]) {
                   4121:                                             $skip=1;
                   4122:                                             last;
                   4123:                                         }
                   4124:                                     }
                   4125:                                 }
                   4126:                                 unless ($skip) {
                   4127:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4128:                                     push(@unsolved,$partslist);
                   4129:                                 }
                   4130:                             }
                   4131:                         }
1.945     raeburn  4132:                     }
                   4133:                 }
                   4134:             }
                   4135:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  4136:                            '<td>'.&mt('Transaction [_1]',$version);
                   4137:             if (@unsolved) {
                   4138:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4139:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4140:                                  &mt('Hide').'</label></span>';
                   4141:             }
                   4142:             $prevattempts .= '</td>';
1.945     raeburn  4143:             if (@hidden) {
                   4144:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4145:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4146:                     my $hide;
                   4147:                     foreach my $id (@hidden) {
                   4148:                         if ($key =~ /^\Q$id\E/) {
                   4149:                             $hide = 1;
                   4150:                             last;
                   4151:                         }
                   4152:                     }
                   4153:                     if ($hide) {
                   4154:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4155:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4156:                             my $value = &format_previous_attempt_value($key,
                   4157:                                              $returnhash{$version.':'.$key});
1.1173    kruse    4158:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4159:                         } else {
                   4160:                             $prevattempts.='<td>&nbsp;</td>';
                   4161:                         }
                   4162:                     } else {
                   4163:                         if ($key =~ /\./) {
                   4164:                             my $value = &format_previous_attempt_value($key,
                   4165:                                               $returnhash{$version.':'.$key});
1.1173    kruse    4166:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4167:                         } else {
                   4168:                             $prevattempts.='<td>&nbsp;</td>';
                   4169:                         }
                   4170:                     }
                   4171:                 }
                   4172:             } else {
                   4173: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4174:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4175: 		    my $value = &format_previous_attempt_value($key,
                   4176: 			            $returnhash{$version.':'.$key});
1.1173    kruse    4177: 		    $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4178: 	        }
                   4179:             }
                   4180: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4181: 	 }
1.1       albertel 4182:       }
1.945     raeburn  4183:       my @currhidden = keys(%lasthidden);
1.596     albertel 4184:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4185:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4186:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4187:           if (%typeparts) {
                   4188:               my $hidden;
                   4189:               foreach my $id (@currhidden) {
                   4190:                   if ($key =~ /^\Q$id\E/) {
                   4191:                       $hidden = 1;
                   4192:                       last;
                   4193:                   }
                   4194:               }
                   4195:               if ($hidden) {
                   4196:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4197:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4198:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4199:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4200:                           $value = &$gradesub($value);
                   4201:                       }
1.1173    kruse    4202:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  4203:                   } else {
                   4204:                       $prevattempts.='<td>&nbsp;</td>';
                   4205:                   }
                   4206:               } else {
                   4207:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4208:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4209:                       $value = &$gradesub($value);
                   4210:                   }
1.1173    kruse    4211:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4212:               }
                   4213:           } else {
                   4214: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4215: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4216:                   $value = &$gradesub($value);
                   4217:               }
1.1173    kruse    4218: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4219:           }
1.16      harris41 4220:       }
1.596     albertel 4221:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4222:     } else {
1.596     albertel 4223:       $prevattempts=
                   4224: 	  &start_data_table().&start_data_table_row().
                   4225: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   4226: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4227:     }
                   4228:   } else {
1.596     albertel 4229:     $prevattempts=
                   4230: 	  &start_data_table().&start_data_table_row().
                   4231: 	  '<td>'.&mt('No data.').'</td>'.
                   4232: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4233:   }
1.10      albertel 4234: }
                   4235: 
1.581     albertel 4236: sub format_previous_attempt_value {
                   4237:     my ($key,$value) = @_;
1.1011    www      4238:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    4239:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 4240:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    4241:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  4242:     } elsif ($key =~ /answerstring$/) {
                   4243:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    4244:         my @answer = %answers;
                   4245:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  4246:         my @anskeys = sort(keys(%answers));
                   4247:         if (@anskeys == 1) {
                   4248:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4249:             if ($answer =~ m{\0}) {
                   4250:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4251:             }
                   4252:             my $tag_internal_answer_name = 'INTERNAL';
                   4253:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4254:                 $value = $answer; 
                   4255:             } else {
                   4256:                 $value = $anskeys[0].'='.$answer;
                   4257:             }
                   4258:         } else {
                   4259:             foreach my $ans (@anskeys) {
                   4260:                 my $answer = $answers{$ans};
1.1001    raeburn  4261:                 if ($answer =~ m{\0}) {
                   4262:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4263:                 }
                   4264:                 $value .=  $ans.'='.$answer.'<br />';;
                   4265:             } 
                   4266:         }
1.581     albertel 4267:     } else {
1.1173    kruse    4268:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 4269:     }
                   4270:     return $value;
                   4271: }
                   4272: 
                   4273: 
1.107     albertel 4274: sub relative_to_absolute {
                   4275:     my ($url,$output)=@_;
                   4276:     my $parser=HTML::TokeParser->new(\$output);
                   4277:     my $token;
                   4278:     my $thisdir=$url;
                   4279:     my @rlinks=();
                   4280:     while ($token=$parser->get_token) {
                   4281: 	if ($token->[0] eq 'S') {
                   4282: 	    if ($token->[1] eq 'a') {
                   4283: 		if ($token->[2]->{'href'}) {
                   4284: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4285: 		}
                   4286: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4287: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4288: 	    } elsif ($token->[1] eq 'base') {
                   4289: 		$thisdir=$token->[2]->{'href'};
                   4290: 	    }
                   4291: 	}
                   4292:     }
                   4293:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4294:     foreach my $link (@rlinks) {
1.726     raeburn  4295: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4296: 		($link=~/^\//) ||
                   4297: 		($link=~/^javascript:/i) ||
                   4298: 		($link=~/^mailto:/i) ||
                   4299: 		($link=~/^\#/)) {
                   4300: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4301: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4302: 	}
                   4303:     }
                   4304: # -------------------------------------------------- Deal with Applet codebases
                   4305:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4306:     return $output;
                   4307: }
                   4308: 
1.112     bowersj2 4309: =pod
                   4310: 
1.648     raeburn  4311: =item * &get_student_view()
1.112     bowersj2 4312: 
                   4313: show a snapshot of what student was looking at
                   4314: 
                   4315: =cut
                   4316: 
1.10      albertel 4317: sub get_student_view {
1.186     albertel 4318:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4319:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4320:   my (%form);
1.10      albertel 4321:   my @elements=('symb','courseid','domain','username');
                   4322:   foreach my $element (@elements) {
1.186     albertel 4323:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4324:   }
1.186     albertel 4325:   if (defined($moreenv)) {
                   4326:       %form=(%form,%{$moreenv});
                   4327:   }
1.236     albertel 4328:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4329:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4330:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4331:   $userview=~s/\<body[^\>]*\>//gi;
                   4332:   $userview=~s/\<\/body\>//gi;
                   4333:   $userview=~s/\<html\>//gi;
                   4334:   $userview=~s/\<\/html\>//gi;
                   4335:   $userview=~s/\<head\>//gi;
                   4336:   $userview=~s/\<\/head\>//gi;
                   4337:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4338:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4339:   if (wantarray) {
                   4340:      return ($userview,$response);
                   4341:   } else {
                   4342:      return $userview;
                   4343:   }
                   4344: }
                   4345: 
                   4346: sub get_student_view_with_retries {
                   4347:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4348: 
                   4349:     my $ok = 0;                 # True if we got a good response.
                   4350:     my $content;
                   4351:     my $response;
                   4352: 
                   4353:     # Try to get the student_view done. within the retries count:
                   4354:     
                   4355:     do {
                   4356:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4357:          $ok      = $response->is_success;
                   4358:          if (!$ok) {
                   4359:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4360:          }
                   4361:          $retries--;
                   4362:     } while (!$ok && ($retries > 0));
                   4363:     
                   4364:     if (!$ok) {
                   4365:        $content = '';          # On error return an empty content.
                   4366:     }
1.651     www      4367:     if (wantarray) {
                   4368:        return ($content, $response);
                   4369:     } else {
                   4370:        return $content;
                   4371:     }
1.11      albertel 4372: }
                   4373: 
1.112     bowersj2 4374: =pod
                   4375: 
1.648     raeburn  4376: =item * &get_student_answers() 
1.112     bowersj2 4377: 
                   4378: show a snapshot of how student was answering problem
                   4379: 
                   4380: =cut
                   4381: 
1.11      albertel 4382: sub get_student_answers {
1.100     sakharuk 4383:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4384:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4385:   my (%moreenv);
1.11      albertel 4386:   my @elements=('symb','courseid','domain','username');
                   4387:   foreach my $element (@elements) {
1.186     albertel 4388:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4389:   }
1.186     albertel 4390:   $moreenv{'grade_target'}='answer';
                   4391:   %moreenv=(%form,%moreenv);
1.497     raeburn  4392:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4393:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4394:   return $userview;
1.1       albertel 4395: }
1.116     albertel 4396: 
                   4397: =pod
                   4398: 
                   4399: =item * &submlink()
                   4400: 
1.242     albertel 4401: Inputs: $text $uname $udom $symb $target
1.116     albertel 4402: 
                   4403: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4404: 
                   4405: =cut
                   4406: 
                   4407: ###############################################
                   4408: sub submlink {
1.242     albertel 4409:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4410:     if (!($uname && $udom)) {
                   4411: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4412: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4413: 	if (!$symb) { $symb=$cursymb; }
                   4414:     }
1.254     matthew  4415:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4416:     $symb=&escape($symb);
1.960     bisitz   4417:     if ($target) { $target=" target=\"$target\""; }
                   4418:     return
                   4419:         '<a href="/adm/grades?command=submission'.
                   4420:         '&amp;symb='.$symb.
                   4421:         '&amp;student='.$uname.
                   4422:         '&amp;userdom='.$udom.'"'.
                   4423:         $target.'>'.$text.'</a>';
1.242     albertel 4424: }
                   4425: ##############################################
                   4426: 
                   4427: =pod
                   4428: 
                   4429: =item * &pgrdlink()
                   4430: 
                   4431: Inputs: $text $uname $udom $symb $target
                   4432: 
                   4433: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4434: 
                   4435: =cut
                   4436: 
                   4437: ###############################################
                   4438: sub pgrdlink {
                   4439:     my $link=&submlink(@_);
                   4440:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4441:     return $link;
                   4442: }
                   4443: ##############################################
                   4444: 
                   4445: =pod
                   4446: 
                   4447: =item * &pprmlink()
                   4448: 
                   4449: Inputs: $text $uname $udom $symb $target
                   4450: 
                   4451: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4452: student and a specific resource
1.242     albertel 4453: 
                   4454: =cut
                   4455: 
                   4456: ###############################################
                   4457: sub pprmlink {
                   4458:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4459:     if (!($uname && $udom)) {
                   4460: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4461: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4462: 	if (!$symb) { $symb=$cursymb; }
                   4463:     }
1.254     matthew  4464:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4465:     $symb=&escape($symb);
1.242     albertel 4466:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4467:     return '<a href="/adm/parmset?command=set&amp;'.
                   4468: 	'symb='.$symb.'&amp;uname='.$uname.
                   4469: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4470: }
                   4471: ##############################################
1.37      matthew  4472: 
1.112     bowersj2 4473: =pod
                   4474: 
                   4475: =back
                   4476: 
                   4477: =cut
                   4478: 
1.37      matthew  4479: ###############################################
1.51      www      4480: 
                   4481: 
                   4482: sub timehash {
1.687     raeburn  4483:     my ($thistime) = @_;
                   4484:     my $timezone = &Apache::lonlocal::gettimezone();
                   4485:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4486:                      ->set_time_zone($timezone);
                   4487:     my $wday = $dt->day_of_week();
                   4488:     if ($wday == 7) { $wday = 0; }
                   4489:     return ( 'second' => $dt->second(),
                   4490:              'minute' => $dt->minute(),
                   4491:              'hour'   => $dt->hour(),
                   4492:              'day'     => $dt->day_of_month(),
                   4493:              'month'   => $dt->month(),
                   4494:              'year'    => $dt->year(),
                   4495:              'weekday' => $wday,
                   4496:              'dayyear' => $dt->day_of_year(),
                   4497:              'dlsav'   => $dt->is_dst() );
1.51      www      4498: }
                   4499: 
1.370     www      4500: sub utc_string {
                   4501:     my ($date)=@_;
1.371     www      4502:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4503: }
                   4504: 
1.51      www      4505: sub maketime {
                   4506:     my %th=@_;
1.687     raeburn  4507:     my ($epoch_time,$timezone,$dt);
                   4508:     $timezone = &Apache::lonlocal::gettimezone();
                   4509:     eval {
                   4510:         $dt = DateTime->new( year   => $th{'year'},
                   4511:                              month  => $th{'month'},
                   4512:                              day    => $th{'day'},
                   4513:                              hour   => $th{'hour'},
                   4514:                              minute => $th{'minute'},
                   4515:                              second => $th{'second'},
                   4516:                              time_zone => $timezone,
                   4517:                          );
                   4518:     };
                   4519:     if (!$@) {
                   4520:         $epoch_time = $dt->epoch;
                   4521:         if ($epoch_time) {
                   4522:             return $epoch_time;
                   4523:         }
                   4524:     }
1.51      www      4525:     return POSIX::mktime(
                   4526:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4527:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4528: }
                   4529: 
                   4530: #########################################
1.51      www      4531: 
                   4532: sub findallcourses {
1.482     raeburn  4533:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4534:     my %roles;
                   4535:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4536:     my %courses;
1.51      www      4537:     my $now=time;
1.482     raeburn  4538:     if (!defined($uname)) {
                   4539:         $uname = $env{'user.name'};
                   4540:     }
                   4541:     if (!defined($udom)) {
                   4542:         $udom = $env{'user.domain'};
                   4543:     }
                   4544:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4545:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4546:         if (!%roles) {
                   4547:             %roles = (
                   4548:                        cc => 1,
1.907     raeburn  4549:                        co => 1,
1.482     raeburn  4550:                        in => 1,
                   4551:                        ep => 1,
                   4552:                        ta => 1,
                   4553:                        cr => 1,
                   4554:                        st => 1,
                   4555:              );
                   4556:         }
                   4557:         foreach my $entry (keys(%roleshash)) {
                   4558:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4559:             if ($trole =~ /^cr/) { 
                   4560:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4561:             } else {
                   4562:                 next if (!exists($roles{$trole}));
                   4563:             }
                   4564:             if ($tend) {
                   4565:                 next if ($tend < $now);
                   4566:             }
                   4567:             if ($tstart) {
                   4568:                 next if ($tstart > $now);
                   4569:             }
1.1058    raeburn  4570:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4571:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4572:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4573:             if ($secpart eq '') {
                   4574:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4575:                 $sec = 'none';
1.1058    raeburn  4576:                 $value .= $cnum.'/';
1.482     raeburn  4577:             } else {
                   4578:                 $cnum = $cnumpart;
                   4579:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4580:                 $value .= $cnum.'/'.$sec;
                   4581:             }
                   4582:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4583:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4584:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4585:                 }
                   4586:             } else {
                   4587:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4588:             }
1.482     raeburn  4589:         }
                   4590:     } else {
                   4591:         foreach my $key (keys(%env)) {
1.483     albertel 4592: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4593:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4594: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4595: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4596: 	        next if (%roles && !exists($roles{$role}));
                   4597: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4598:                 my $active=1;
                   4599:                 if ($starttime) {
                   4600: 		    if ($now<$starttime) { $active=0; }
                   4601:                 }
                   4602:                 if ($endtime) {
                   4603:                     if ($now>$endtime) { $active=0; }
                   4604:                 }
                   4605:                 if ($active) {
1.1058    raeburn  4606:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4607:                     if ($sec eq '') {
                   4608:                         $sec = 'none';
1.1058    raeburn  4609:                     } else {
                   4610:                         $value .= $sec;
                   4611:                     }
                   4612:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4613:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4614:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4615:                         }
                   4616:                     } else {
                   4617:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4618:                     }
1.474     raeburn  4619:                 }
                   4620:             }
1.51      www      4621:         }
                   4622:     }
1.474     raeburn  4623:     return %courses;
1.51      www      4624: }
1.37      matthew  4625: 
1.54      www      4626: ###############################################
1.474     raeburn  4627: 
                   4628: sub blockcheck {
1.1189    raeburn  4629:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
1.490     raeburn  4630: 
1.1189    raeburn  4631:     if (defined($udom) && defined($uname)) {
                   4632:         # If uname and udom are for a course, check for blocks in the course.
                   4633:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   4634:             my ($startblock,$endblock,$triggerblock) =
                   4635:                 &get_blocks($setters,$activity,$udom,$uname,$url);
                   4636:             return ($startblock,$endblock,$triggerblock);
                   4637:         }
                   4638:     } else {
1.490     raeburn  4639:         $udom = $env{'user.domain'};
                   4640:         $uname = $env{'user.name'};
                   4641:     }
                   4642: 
1.502     raeburn  4643:     my $startblock = 0;
                   4644:     my $endblock = 0;
1.1062    raeburn  4645:     my $triggerblock = '';
1.482     raeburn  4646:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4647: 
1.490     raeburn  4648:     # If uname is for a user, and activity is course-specific, i.e.,
                   4649:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4650: 
1.490     raeburn  4651:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1189    raeburn  4652:          $activity eq 'groups' || $activity eq 'printout') &&
                   4653:         ($env{'request.course.id'})) {
1.490     raeburn  4654:         foreach my $key (keys(%live_courses)) {
                   4655:             if ($key ne $env{'request.course.id'}) {
                   4656:                 delete($live_courses{$key});
                   4657:             }
                   4658:         }
                   4659:     }
                   4660: 
                   4661:     my $otheruser = 0;
                   4662:     my %own_courses;
                   4663:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4664:         # Resource belongs to user other than current user.
                   4665:         $otheruser = 1;
                   4666:         # Gather courses for current user
                   4667:         %own_courses = 
                   4668:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4669:     }
                   4670: 
                   4671:     # Gather active course roles - course coordinator, instructor, 
                   4672:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4673: 
                   4674:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4675:         my ($cdom,$cnum);
                   4676:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4677:             $cdom = $env{'course.'.$course.'.domain'};
                   4678:             $cnum = $env{'course.'.$course.'.num'};
                   4679:         } else {
1.490     raeburn  4680:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4681:         }
                   4682:         my $no_ownblock = 0;
                   4683:         my $no_userblock = 0;
1.533     raeburn  4684:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4685:             # Check if current user has 'evb' priv for this
                   4686:             if (defined($own_courses{$course})) {
                   4687:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4688:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4689:                     if ($sec ne 'none') {
                   4690:                         $checkrole .= '/'.$sec;
                   4691:                     }
                   4692:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4693:                         $no_ownblock = 1;
                   4694:                         last;
                   4695:                     }
                   4696:                 }
                   4697:             }
                   4698:             # if they have 'evb' priv and are currently not playing student
                   4699:             next if (($no_ownblock) &&
                   4700:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4701:         }
1.474     raeburn  4702:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4703:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4704:             if ($sec ne 'none') {
1.482     raeburn  4705:                 $checkrole .= '/'.$sec;
1.474     raeburn  4706:             }
1.490     raeburn  4707:             if ($otheruser) {
                   4708:                 # Resource belongs to user other than current user.
                   4709:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4710:                 my (%allroles,%userroles);
                   4711:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4712:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4713:                         my ($trole,$tdom,$tnum,$tsec);
                   4714:                         if ($entry =~ /^cr/) {
                   4715:                             ($trole,$tdom,$tnum,$tsec) = 
                   4716:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4717:                         } else {
                   4718:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4719:                         }
                   4720:                         my ($spec,$area,$trest);
                   4721:                         $area = '/'.$tdom.'/'.$tnum;
                   4722:                         $trest = $tnum;
                   4723:                         if ($tsec ne '') {
                   4724:                             $area .= '/'.$tsec;
                   4725:                             $trest .= '/'.$tsec;
                   4726:                         }
                   4727:                         $spec = $trole.'.'.$area;
                   4728:                         if ($trole =~ /^cr/) {
                   4729:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4730:                                                               $tdom,$spec,$trest,$area);
                   4731:                         } else {
                   4732:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4733:                                                                 $tdom,$spec,$trest,$area);
                   4734:                         }
                   4735:                     }
                   4736:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
                   4737:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   4738:                         if ($1) {
                   4739:                             $no_userblock = 1;
                   4740:                             last;
                   4741:                         }
1.486     raeburn  4742:                     }
                   4743:                 }
1.490     raeburn  4744:             } else {
                   4745:                 # Resource belongs to current user
                   4746:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  4747:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4748:                     $no_ownblock = 1;
                   4749:                     last;
                   4750:                 }
1.474     raeburn  4751:             }
                   4752:         }
                   4753:         # if they have the evb priv and are currently not playing student
1.482     raeburn  4754:         next if (($no_ownblock) &&
1.491     albertel 4755:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  4756:         next if ($no_userblock);
1.474     raeburn  4757: 
1.866     kalberla 4758:         # Retrieve blocking times and identity of locker for course
1.490     raeburn  4759:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  4760:         
1.1062    raeburn  4761:         my ($start,$end,$trigger) = 
                   4762:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  4763:         if (($start != 0) && 
                   4764:             (($startblock == 0) || ($startblock > $start))) {
                   4765:             $startblock = $start;
1.1062    raeburn  4766:             if ($trigger ne '') {
                   4767:                 $triggerblock = $trigger;
                   4768:             }
1.502     raeburn  4769:         }
                   4770:         if (($end != 0)  &&
                   4771:             (($endblock == 0) || ($endblock < $end))) {
                   4772:             $endblock = $end;
1.1062    raeburn  4773:             if ($trigger ne '') {
                   4774:                 $triggerblock = $trigger;
                   4775:             }
1.502     raeburn  4776:         }
1.490     raeburn  4777:     }
1.1062    raeburn  4778:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4779: }
                   4780: 
                   4781: sub get_blocks {
1.1062    raeburn  4782:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  4783:     my $startblock = 0;
                   4784:     my $endblock = 0;
1.1062    raeburn  4785:     my $triggerblock = '';
1.490     raeburn  4786:     my $course = $cdom.'_'.$cnum;
                   4787:     $setters->{$course} = {};
                   4788:     $setters->{$course}{'staff'} = [];
                   4789:     $setters->{$course}{'times'} = [];
1.1062    raeburn  4790:     $setters->{$course}{'triggers'} = [];
                   4791:     my (@blockers,%triggered);
                   4792:     my $now = time;
                   4793:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   4794:     if ($activity eq 'docs') {
                   4795:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   4796:         foreach my $block (@blockers) {
                   4797:             if ($block =~ /^firstaccess____(.+)$/) {
                   4798:                 my $item = $1;
                   4799:                 my $type = 'map';
                   4800:                 my $timersymb = $item;
                   4801:                 if ($item eq 'course') {
                   4802:                     $type = 'course';
                   4803:                 } elsif ($item =~ /___\d+___/) {
                   4804:                     $type = 'resource';
                   4805:                 } else {
                   4806:                     $timersymb = &Apache::lonnet::symbread($item);
                   4807:                 }
                   4808:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4809:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   4810:                 $triggered{$block} = {
                   4811:                                        start => $start,
                   4812:                                        end   => $end,
                   4813:                                        type  => $type,
                   4814:                                      };
                   4815:             }
                   4816:         }
                   4817:     } else {
                   4818:         foreach my $block (keys(%commblocks)) {
                   4819:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   4820:                 my ($start,$end) = ($1,$2);
                   4821:                 if ($start <= time && $end >= time) {
                   4822:                     if (ref($commblocks{$block}) eq 'HASH') {
                   4823:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   4824:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   4825:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   4826:                                     push(@blockers,$block);
                   4827:                                 }
                   4828:                             }
                   4829:                         }
                   4830:                     }
                   4831:                 }
                   4832:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   4833:                 my $item = $1;
                   4834:                 my $timersymb = $item; 
                   4835:                 my $type = 'map';
                   4836:                 if ($item eq 'course') {
                   4837:                     $type = 'course';
                   4838:                 } elsif ($item =~ /___\d+___/) {
                   4839:                     $type = 'resource';
                   4840:                 } else {
                   4841:                     $timersymb = &Apache::lonnet::symbread($item);
                   4842:                 }
                   4843:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4844:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   4845:                 if ($start && $end) {
                   4846:                     if (($start <= time) && ($end >= time)) {
                   4847:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   4848:                             push(@blockers,$block);
                   4849:                             $triggered{$block} = {
                   4850:                                                    start => $start,
                   4851:                                                    end   => $end,
                   4852:                                                    type  => $type,
                   4853:                                                  };
                   4854:                         }
                   4855:                     }
1.490     raeburn  4856:                 }
1.1062    raeburn  4857:             }
                   4858:         }
                   4859:     }
                   4860:     foreach my $blocker (@blockers) {
                   4861:         my ($staff_name,$staff_dom,$title,$blocks) =
                   4862:             &parse_block_record($commblocks{$blocker});
                   4863:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   4864:         my ($start,$end,$triggertype);
                   4865:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   4866:             ($start,$end) = ($1,$2);
                   4867:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   4868:             $start = $triggered{$blocker}{'start'};
                   4869:             $end = $triggered{$blocker}{'end'};
                   4870:             $triggertype = $triggered{$blocker}{'type'};
                   4871:         }
                   4872:         if ($start) {
                   4873:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   4874:             if ($triggertype) {
                   4875:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   4876:             } else {
                   4877:                 push(@{$$setters{$course}{'triggers'}},0);
                   4878:             }
                   4879:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   4880:                 $startblock = $start;
                   4881:                 if ($triggertype) {
                   4882:                     $triggerblock = $blocker;
1.474     raeburn  4883:                 }
                   4884:             }
1.1062    raeburn  4885:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   4886:                $endblock = $end;
                   4887:                if ($triggertype) {
                   4888:                    $triggerblock = $blocker;
                   4889:                }
                   4890:             }
1.474     raeburn  4891:         }
                   4892:     }
1.1062    raeburn  4893:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  4894: }
                   4895: 
                   4896: sub parse_block_record {
                   4897:     my ($record) = @_;
                   4898:     my ($setuname,$setudom,$title,$blocks);
                   4899:     if (ref($record) eq 'HASH') {
                   4900:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   4901:         $title = &unescape($record->{'event'});
                   4902:         $blocks = $record->{'blocks'};
                   4903:     } else {
                   4904:         my @data = split(/:/,$record,3);
                   4905:         if (scalar(@data) eq 2) {
                   4906:             $title = $data[1];
                   4907:             ($setuname,$setudom) = split(/@/,$data[0]);
                   4908:         } else {
                   4909:             ($setuname,$setudom,$title) = @data;
                   4910:         }
                   4911:         $blocks = { 'com' => 'on' };
                   4912:     }
                   4913:     return ($setuname,$setudom,$title,$blocks);
                   4914: }
                   4915: 
1.854     kalberla 4916: sub blocking_status {
1.1189    raeburn  4917:     my ($activity,$uname,$udom,$url,$is_course) = @_;
1.1061    raeburn  4918:     my %setters;
1.890     droeschl 4919: 
1.1061    raeburn  4920: # check for active blocking
1.1062    raeburn  4921:     my ($startblock,$endblock,$triggerblock) = 
1.1189    raeburn  4922:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
1.1062    raeburn  4923:     my $blocked = 0;
                   4924:     if ($startblock && $endblock) {
                   4925:         $blocked = 1;
                   4926:     }
1.890     droeschl 4927: 
1.1061    raeburn  4928: # caller just wants to know whether a block is active
                   4929:     if (!wantarray) { return $blocked; }
                   4930: 
                   4931: # build a link to a popup window containing the details
                   4932:     my $querystring  = "?activity=$activity";
                   4933: # $uname and $udom decide whose portfolio the user is trying to look at
1.1062    raeburn  4934:     if ($activity eq 'port') {
                   4935:         $querystring .= "&amp;udom=$udom"      if $udom;
                   4936:         $querystring .= "&amp;uname=$uname"    if $uname;
                   4937:     } elsif ($activity eq 'docs') {
                   4938:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   4939:     }
1.1061    raeburn  4940: 
                   4941:     my $output .= <<'END_MYBLOCK';
                   4942: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   4943:     var options = "width=" + w + ",height=" + h + ",";
                   4944:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   4945:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   4946:     var newWin = window.open(url, wdwName, options);
                   4947:     newWin.focus();
                   4948: }
1.890     droeschl 4949: END_MYBLOCK
1.854     kalberla 4950: 
1.1061    raeburn  4951:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 4952:   
1.1061    raeburn  4953:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  4954:     my $text = &mt('Communication Blocked');
                   4955:     if ($activity eq 'docs') {
                   4956:         $text = &mt('Content Access Blocked');
1.1063    raeburn  4957:     } elsif ($activity eq 'printout') {
                   4958:         $text = &mt('Printing Blocked');
1.1062    raeburn  4959:     }
1.1061    raeburn  4960:     $output .= <<"END_BLOCK";
1.867     kalberla 4961: <div class='LC_comblock'>
1.869     kalberla 4962:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 4963:   title='$text'>
                   4964:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 4965:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 4966:   title='$text'>$text</a>
1.867     kalberla 4967: </div>
                   4968: 
                   4969: END_BLOCK
1.474     raeburn  4970: 
1.1061    raeburn  4971:     return ($blocked, $output);
1.854     kalberla 4972: }
1.490     raeburn  4973: 
1.60      matthew  4974: ###############################################
                   4975: 
1.682     raeburn  4976: sub check_ip_acc {
1.1201    raeburn  4977:     my ($acc,$clientip)=@_;
1.682     raeburn  4978:     &Apache::lonxml::debug("acc is $acc");
                   4979:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   4980:         return 1;
                   4981:     }
                   4982:     my $allowed=0;
1.1201    raeburn  4983:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
1.682     raeburn  4984: 
                   4985:     my $name;
                   4986:     foreach my $pattern (split(',',$acc)) {
                   4987:         $pattern =~ s/^\s*//;
                   4988:         $pattern =~ s/\s*$//;
                   4989:         if ($pattern =~ /\*$/) {
                   4990:             #35.8.*
                   4991:             $pattern=~s/\*//;
                   4992:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4993:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   4994:             #35.8.3.[34-56]
                   4995:             my $low=$2;
                   4996:             my $high=$3;
                   4997:             $pattern=$1;
                   4998:             if ($ip =~ /^\Q$pattern\E/) {
                   4999:                 my $last=(split(/\./,$ip))[3];
                   5000:                 if ($last <=$high && $last >=$low) { $allowed=1; }
                   5001:             }
                   5002:         } elsif ($pattern =~ /^\*/) {
                   5003:             #*.msu.edu
                   5004:             $pattern=~s/\*//;
                   5005:             if (!defined($name)) {
                   5006:                 use Socket;
                   5007:                 my $netaddr=inet_aton($ip);
                   5008:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5009:             }
                   5010:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   5011:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5012:             #127.0.0.1
                   5013:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   5014:         } else {
                   5015:             #some.name.com
                   5016:             if (!defined($name)) {
                   5017:                 use Socket;
                   5018:                 my $netaddr=inet_aton($ip);
                   5019:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5020:             }
                   5021:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   5022:         }
                   5023:         if ($allowed) { last; }
                   5024:     }
                   5025:     return $allowed;
                   5026: }
                   5027: 
                   5028: ###############################################
                   5029: 
1.60      matthew  5030: =pod
                   5031: 
1.112     bowersj2 5032: =head1 Domain Template Functions
                   5033: 
                   5034: =over 4
                   5035: 
                   5036: =item * &determinedomain()
1.60      matthew  5037: 
                   5038: Inputs: $domain (usually will be undef)
                   5039: 
1.63      www      5040: Returns: Determines which domain should be used for designs
1.60      matthew  5041: 
                   5042: =cut
1.54      www      5043: 
1.60      matthew  5044: ###############################################
1.63      www      5045: sub determinedomain {
                   5046:     my $domain=shift;
1.531     albertel 5047:     if (! $domain) {
1.60      matthew  5048:         # Determine domain if we have not been given one
1.893     raeburn  5049:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5050:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5051:         if ($env{'request.role.domain'}) { 
                   5052:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5053:         }
                   5054:     }
1.63      www      5055:     return $domain;
                   5056: }
                   5057: ###############################################
1.517     raeburn  5058: 
1.518     albertel 5059: sub devalidate_domconfig_cache {
                   5060:     my ($udom)=@_;
                   5061:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5062: }
                   5063: 
                   5064: # ---------------------- Get domain configuration for a domain
                   5065: sub get_domainconf {
                   5066:     my ($udom) = @_;
                   5067:     my $cachetime=1800;
                   5068:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5069:     if (defined($cached)) { return %{$result}; }
                   5070: 
                   5071:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5072: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5073:     my (%designhash,%legacy);
1.518     albertel 5074:     if (keys(%domconfig) > 0) {
                   5075:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5076:             if (keys(%{$domconfig{'login'}})) {
                   5077:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5078:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.946     raeburn  5079:                         if ($key eq 'loginvia') {
                   5080:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
1.1013    raeburn  5081:                                 foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
1.948     raeburn  5082:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
                   5083:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5084:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5085:                                             $designhash{$udom.'.login.loginvia'} = $server;
                   5086:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5087: 
                   5088:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5089:                                             } else {
1.1013    raeburn  5090:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
1.948     raeburn  5091:                                             }
                   5092:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
                   5093:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
                   5094:                                             }
1.946     raeburn  5095:                                         }
                   5096:                                     }
                   5097:                                 }
                   5098:                             }
                   5099:                         } else {
                   5100:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5101:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5102:                                     $domconfig{'login'}{$key}{$img};
                   5103:                             }
1.699     raeburn  5104:                         }
                   5105:                     } else {
                   5106:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5107:                     }
1.632     raeburn  5108:                 }
                   5109:             } else {
                   5110:                 $legacy{'login'} = 1;
1.518     albertel 5111:             }
1.632     raeburn  5112:         } else {
                   5113:             $legacy{'login'} = 1;
1.518     albertel 5114:         }
                   5115:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5116:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5117:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5118:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5119:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5120:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5121:                         }
1.518     albertel 5122:                     }
                   5123:                 }
1.632     raeburn  5124:             } else {
                   5125:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5126:             }
1.632     raeburn  5127:         } else {
                   5128:             $legacy{'rolecolors'} = 1;
1.518     albertel 5129:         }
1.948     raeburn  5130:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5131:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5132:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5133:             }
                   5134:         }
1.632     raeburn  5135:         if (keys(%legacy) > 0) {
                   5136:             my %legacyhash = &get_legacy_domconf($udom);
                   5137:             foreach my $item (keys(%legacyhash)) {
                   5138:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5139:                     if ($legacy{'login'}) { 
                   5140:                         $designhash{$item} = $legacyhash{$item};
                   5141:                     }
                   5142:                 } else {
                   5143:                     if ($legacy{'rolecolors'}) {
                   5144:                         $designhash{$item} = $legacyhash{$item};
                   5145:                     }
1.518     albertel 5146:                 }
                   5147:             }
                   5148:         }
1.632     raeburn  5149:     } else {
                   5150:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5151:     }
                   5152:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5153: 				  $cachetime);
                   5154:     return %designhash;
                   5155: }
                   5156: 
1.632     raeburn  5157: sub get_legacy_domconf {
                   5158:     my ($udom) = @_;
                   5159:     my %legacyhash;
                   5160:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5161:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5162:     if (-e $designfile) {
                   5163:         if ( open (my $fh,"<$designfile") ) {
                   5164:             while (my $line = <$fh>) {
                   5165:                 next if ($line =~ /^\#/);
                   5166:                 chomp($line);
                   5167:                 my ($key,$val)=(split(/\=/,$line));
                   5168:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5169:             }
                   5170:             close($fh);
                   5171:         }
                   5172:     }
1.1026    raeburn  5173:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5174:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5175:     }
                   5176:     return %legacyhash;
                   5177: }
                   5178: 
1.63      www      5179: =pod
                   5180: 
1.112     bowersj2 5181: =item * &domainlogo()
1.63      www      5182: 
                   5183: Inputs: $domain (usually will be undef)
                   5184: 
                   5185: Returns: A link to a domain logo, if the domain logo exists.
                   5186: If the domain logo does not exist, a description of the domain.
                   5187: 
                   5188: =cut
1.112     bowersj2 5189: 
1.63      www      5190: ###############################################
                   5191: sub domainlogo {
1.517     raeburn  5192:     my $domain = &determinedomain(shift);
1.518     albertel 5193:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5194:     # See if there is a logo
                   5195:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5196:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5197:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5198: 	    if ($imgsrc =~ m{^/res/}) {
                   5199: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5200: 		&Apache::lonnet::repcopy($local_name);
                   5201: 	    }
                   5202: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5203:         } 
                   5204:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5205:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5206:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5207:     } else {
1.60      matthew  5208:         return '';
1.59      www      5209:     }
                   5210: }
1.63      www      5211: ##############################################
                   5212: 
                   5213: =pod
                   5214: 
1.112     bowersj2 5215: =item * &designparm()
1.63      www      5216: 
                   5217: Inputs: $which parameter; $domain (usually will be undef)
                   5218: 
                   5219: Returns: value of designparamter $which
                   5220: 
                   5221: =cut
1.112     bowersj2 5222: 
1.397     albertel 5223: 
1.400     albertel 5224: ##############################################
1.397     albertel 5225: sub designparm {
                   5226:     my ($which,$domain)=@_;
                   5227:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5228:         return $env{'environment.color.'.$which};
1.96      www      5229:     }
1.63      www      5230:     $domain=&determinedomain($domain);
1.1016    raeburn  5231:     my %domdesign;
                   5232:     unless ($domain eq 'public') {
                   5233:         %domdesign = &get_domainconf($domain);
                   5234:     }
1.520     raeburn  5235:     my $output;
1.517     raeburn  5236:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5237:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5238:     } else {
1.520     raeburn  5239:         $output = $defaultdesign{$which};
                   5240:     }
                   5241:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5242:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5243:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5244:             if ($output =~ m{^/res/}) {
                   5245:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5246:                 &Apache::lonnet::repcopy($local_name);
                   5247:             }
1.520     raeburn  5248:             $output = &lonhttpdurl($output);
                   5249:         }
1.63      www      5250:     }
1.520     raeburn  5251:     return $output;
1.63      www      5252: }
1.59      www      5253: 
1.822     bisitz   5254: ##############################################
                   5255: =pod
                   5256: 
1.832     bisitz   5257: =item * &authorspace()
                   5258: 
1.1028    raeburn  5259: Inputs: $url (usually will be undef).
1.832     bisitz   5260: 
1.1132    raeburn  5261: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5262:          directory being viewed (or for which action is being taken). 
                   5263:          If $url is provided, and begins /priv/<domain>/<uname>
                   5264:          the path will be that portion of the $context argument.
                   5265:          Otherwise the path will be for the author space of the current
                   5266:          user when the current role is author, or for that of the 
                   5267:          co-author/assistant co-author space when the current role 
                   5268:          is co-author or assistant co-author.
1.832     bisitz   5269: 
                   5270: =cut
                   5271: 
                   5272: sub authorspace {
1.1028    raeburn  5273:     my ($url) = @_;
                   5274:     if ($url ne '') {
                   5275:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5276:            return $1;
                   5277:         }
                   5278:     }
1.832     bisitz   5279:     my $caname = '';
1.1024    www      5280:     my $cadom = '';
1.1028    raeburn  5281:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5282:         ($cadom,$caname) =
1.832     bisitz   5283:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5284:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5285:         $caname = $env{'user.name'};
1.1024    www      5286:         $cadom = $env{'user.domain'};
1.832     bisitz   5287:     }
1.1028    raeburn  5288:     if (($caname ne '') && ($cadom ne '')) {
                   5289:         return "/priv/$cadom/$caname/";
                   5290:     }
                   5291:     return;
1.832     bisitz   5292: }
                   5293: 
                   5294: ##############################################
                   5295: =pod
                   5296: 
1.822     bisitz   5297: =item * &head_subbox()
                   5298: 
                   5299: Inputs: $content (contains HTML code with page functions, etc.)
                   5300: 
                   5301: Returns: HTML div with $content
                   5302:          To be included in page header
                   5303: 
                   5304: =cut
                   5305: 
                   5306: sub head_subbox {
                   5307:     my ($content)=@_;
                   5308:     my $output =
1.993     raeburn  5309:         '<div class="LC_head_subbox">'
1.822     bisitz   5310:        .$content
                   5311:        .'</div>'
                   5312: }
                   5313: 
                   5314: ##############################################
                   5315: =pod
                   5316: 
                   5317: =item * &CSTR_pageheader()
                   5318: 
1.1026    raeburn  5319: Input: (optional) filename from which breadcrumb trail is built.
                   5320:        In most cases no input as needed, as $env{'request.filename'}
                   5321:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5322: 
                   5323: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  5324:          To be included on Authoring Space pages
1.822     bisitz   5325: 
                   5326: =cut
                   5327: 
                   5328: sub CSTR_pageheader {
1.1026    raeburn  5329:     my ($trailfile) = @_;
                   5330:     if ($trailfile eq '') {
                   5331:         $trailfile = $env{'request.filename'};
                   5332:     }
                   5333: 
                   5334: # this is for resources; directories have customtitle, and crumbs
                   5335: # and select recent are created in lonpubdir.pm
                   5336: 
                   5337:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5338:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  5339:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5340:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5341:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5342: 
                   5343:     my $parentpath = '';
                   5344:     my $lastitem = '';
                   5345:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5346:         $parentpath = $1;
                   5347:         $lastitem = $2;
                   5348:     } else {
                   5349:         $lastitem = $thisdisfn;
                   5350:     }
1.921     bisitz   5351: 
                   5352:     my $output =
1.822     bisitz   5353:          '<div>'
                   5354:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1132    raeburn  5355:         .'<b>'.&mt('Authoring Space:').'</b> '
1.822     bisitz   5356:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5357:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5358:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5359: 
                   5360:     if ($lastitem) {
                   5361:         $output .=
                   5362:              '<span class="LC_filename">'
                   5363:             .$lastitem
                   5364:             .'</span>';
                   5365:     }
                   5366:     $output .=
                   5367:          '<br />'
1.822     bisitz   5368:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5369:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5370:         .'</form>'
                   5371:         .&Apache::lonmenu::constspaceform()
                   5372:         .'</div>';
1.921     bisitz   5373: 
                   5374:     return $output;
1.822     bisitz   5375: }
                   5376: 
1.60      matthew  5377: ###############################################
                   5378: ###############################################
                   5379: 
                   5380: =pod
                   5381: 
1.112     bowersj2 5382: =back
                   5383: 
1.549     albertel 5384: =head1 HTML Helpers
1.112     bowersj2 5385: 
                   5386: =over 4
                   5387: 
                   5388: =item * &bodytag()
1.60      matthew  5389: 
                   5390: Returns a uniform header for LON-CAPA web pages.
                   5391: 
                   5392: Inputs: 
                   5393: 
1.112     bowersj2 5394: =over 4
                   5395: 
                   5396: =item * $title, A title to be displayed on the page.
                   5397: 
                   5398: =item * $function, the current role (can be undef).
                   5399: 
                   5400: =item * $addentries, extra parameters for the <body> tag.
                   5401: 
                   5402: =item * $bodyonly, if defined, only return the <body> tag.
                   5403: 
                   5404: =item * $domain, if defined, force a given domain.
                   5405: 
                   5406: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5407:             text interface only)
1.60      matthew  5408: 
1.814     bisitz   5409: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5410:                      navigational links
1.317     albertel 5411: 
1.338     albertel 5412: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5413: 
1.460     albertel 5414: =item * $args, optional argument valid values are
                   5415:             no_auto_mt_title -> prevents &mt()ing the title arg
1.562     albertel 5416:             inherit_jsmath -> when creating popup window in a page,
                   5417:                               should it have jsmath forced on by the
                   5418:                               current page
1.460     albertel 5419: 
1.1096    raeburn  5420: =item * $advtoolsref, optional argument, ref to an array containing
                   5421:             inlineremote items to be added in "Functions" menu below
                   5422:             breadcrumbs.
                   5423: 
1.112     bowersj2 5424: =back
                   5425: 
1.60      matthew  5426: Returns: A uniform header for LON-CAPA web pages.  
                   5427: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5428: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5429: other decorations will be returned.
                   5430: 
                   5431: =cut
                   5432: 
1.54      www      5433: sub bodytag {
1.831     bisitz   5434:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1096    raeburn  5435:         $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
1.339     albertel 5436: 
1.954     raeburn  5437:     my $public;
                   5438:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5439:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5440:         $public = 1;
                   5441:     }
1.460     albertel 5442:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  5443:     my $httphost = $args->{'use_absolute'};
1.339     albertel 5444: 
1.183     matthew  5445:     $function = &get_users_function() if (!$function);
1.339     albertel 5446:     my $img =    &designparm($function.'.img',$domain);
                   5447:     my $font =   &designparm($function.'.font',$domain);
                   5448:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5449: 
1.803     bisitz   5450:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5451: 		   'bgcolor' => $pgbg,
1.339     albertel 5452: 		   'text'    => $font,
                   5453:                    'alink'   => &designparm($function.'.alink',$domain),
                   5454: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5455: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5456:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5457: 
1.63      www      5458:  # role and realm
1.1178    raeburn  5459:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5460:     if ($realm) {
                   5461:         $realm = '/'.$realm;
                   5462:     }
1.378     raeburn  5463:     if ($role  eq 'ca') {
1.479     albertel 5464:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5465:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5466:     } 
1.55      www      5467: # realm
1.258     albertel 5468:     if ($env{'request.course.id'}) {
1.378     raeburn  5469:         if ($env{'request.role'} !~ /^cr/) {
                   5470:             $role = &Apache::lonnet::plaintext($role,&course_type());
                   5471:         }
1.898     raeburn  5472:         if ($env{'request.course.sec'}) {
                   5473:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5474:         }   
1.359     albertel 5475: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5476:     } else {
                   5477:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5478:     }
1.433     albertel 5479: 
1.359     albertel 5480:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5481: 
1.438     albertel 5482:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5483: 
1.101     www      5484: # construct main body tag
1.359     albertel 5485:     my $bodytag = "<body $extra_body_attr>".
1.562     albertel 5486: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
1.252     albertel 5487: 
1.1131    raeburn  5488:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5489: 
1.1130    raeburn  5490:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5491:         return $bodytag;
1.1130    raeburn  5492:     }
1.359     albertel 5493: 
1.954     raeburn  5494:     if ($public) {
1.433     albertel 5495: 	undef($role);
                   5496:     }
1.359     albertel 5497:     
1.762     bisitz   5498:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5499:     #
                   5500:     # Extra info if you are the DC
                   5501:     my $dc_info = '';
                   5502:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5503:                         $env{'course.'.$env{'request.course.id'}.
                   5504:                                  '.domain'}.'/'})) {
                   5505:         my $cid = $env{'request.course.id'};
1.917     raeburn  5506:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5507:         $dc_info =~ s/\s+$//;
1.359     albertel 5508:     }
                   5509: 
1.898     raeburn  5510:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
1.853     droeschl 5511: 
1.903     droeschl 5512:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5513: 
                   5514:         #    if ($env{'request.state'} eq 'construct') {
                   5515:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5516:         #    }
                   5517: 
1.1130    raeburn  5518:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  5519:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5520: 
1.1130    raeburn  5521:         my ($left,$right) = Apache::lonmenu::primary_menu();
1.359     albertel 5522: 
1.916     droeschl 5523:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.917     raeburn  5524:              if ($dc_info) {
                   5525:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   5526:              }
1.1130    raeburn  5527:              $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.916     droeschl 5528:                 <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5529:             return $bodytag;
                   5530:         }
1.894     droeschl 5531: 
1.927     raeburn  5532:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1130    raeburn  5533:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5534:         }
1.916     droeschl 5535: 
1.1130    raeburn  5536:         $bodytag .= $right;
1.852     droeschl 5537: 
1.917     raeburn  5538:         if ($dc_info) {
                   5539:             $dc_info = &dc_courseid_toggle($dc_info);
                   5540:         }
                   5541:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5542: 
1.1169    raeburn  5543:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  5544:         if ($args->{'no_secondary_menu'}) {
                   5545:             return $bodytag;
                   5546:         }
1.1169    raeburn  5547:         #don't show menus for public users
1.954     raeburn  5548:         if (!$public){
1.1154    raeburn  5549:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5550:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5551:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5552:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5553:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.920     raeburn  5554:                                 $args->{'bread_crumbs'});
1.1096    raeburn  5555:             } elsif ($forcereg) {
                   5556:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
                   5557:                                                             $args->{'group'});
                   5558:             } else {
                   5559:                 $bodytag .= 
                   5560:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5561:                                                         $forcereg,$args->{'group'},
                   5562:                                                         $args->{'bread_crumbs'},
                   5563:                                                         $advtoolsref);
1.920     raeburn  5564:             }
1.903     droeschl 5565:         }else{
                   5566:             # this is to seperate menu from content when there's no secondary
                   5567:             # menu. Especially needed for public accessible ressources.
                   5568:             $bodytag .= '<hr style="clear:both" />';
                   5569:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5570:         }
1.903     droeschl 5571: 
1.235     raeburn  5572:         return $bodytag;
1.182     matthew  5573: }
                   5574: 
1.917     raeburn  5575: sub dc_courseid_toggle {
                   5576:     my ($dc_info) = @_;
1.980     raeburn  5577:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5578:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5579:            &mt('(More ...)').'</a></span>'.
                   5580:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5581: }
                   5582: 
1.330     albertel 5583: sub make_attr_string {
                   5584:     my ($register,$attr_ref) = @_;
                   5585: 
                   5586:     if ($attr_ref && !ref($attr_ref)) {
                   5587: 	die("addentries Must be a hash ref ".
                   5588: 	    join(':',caller(1))." ".
                   5589: 	    join(':',caller(0))." ");
                   5590:     }
                   5591: 
                   5592:     if ($register) {
1.339     albertel 5593: 	my ($on_load,$on_unload);
                   5594: 	foreach my $key (keys(%{$attr_ref})) {
                   5595: 	    if      (lc($key) eq 'onload') {
                   5596: 		$on_load.=$attr_ref->{$key}.';';
                   5597: 		delete($attr_ref->{$key});
                   5598: 
                   5599: 	    } elsif (lc($key) eq 'onunload') {
                   5600: 		$on_unload.=$attr_ref->{$key}.';';
                   5601: 		delete($attr_ref->{$key});
                   5602: 	    }
                   5603: 	}
1.953     droeschl 5604: 	$attr_ref->{'onload'}  = $on_load;
                   5605: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 5606:     }
1.339     albertel 5607: 
1.330     albertel 5608:     my $attr_string;
1.1159    raeburn  5609:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 5610: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5611:     }
                   5612:     return $attr_string;
                   5613: }
                   5614: 
                   5615: 
1.182     matthew  5616: ###############################################
1.251     albertel 5617: ###############################################
                   5618: 
                   5619: =pod
                   5620: 
                   5621: =item * &endbodytag()
                   5622: 
                   5623: Returns a uniform footer for LON-CAPA web pages.
                   5624: 
1.635     raeburn  5625: Inputs: 1 - optional reference to an args hash
                   5626: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5627: a 'Continue' link is not displayed if the page contains an
                   5628: internal redirect in the <head></head> section,
                   5629: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5630: 
                   5631: =cut
                   5632: 
                   5633: sub endbodytag {
1.635     raeburn  5634:     my ($args) = @_;
1.1080    raeburn  5635:     my $endbodytag;
                   5636:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5637:         $endbodytag='</body>';
                   5638:     }
1.269     albertel 5639:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
1.315     albertel 5640:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5641:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5642: 	    $endbodytag=
                   5643: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5644: 	        &mt('Continue').'</a>'.
                   5645: 	        $endbodytag;
                   5646:         }
1.315     albertel 5647:     }
1.251     albertel 5648:     return $endbodytag;
                   5649: }
                   5650: 
1.352     albertel 5651: =pod
                   5652: 
                   5653: =item * &standard_css()
                   5654: 
                   5655: Returns a style sheet
                   5656: 
                   5657: Inputs: (all optional)
                   5658:             domain         -> force to color decorate a page for a specific
                   5659:                                domain
                   5660:             function       -> force usage of a specific rolish color scheme
                   5661:             bgcolor        -> override the default page bgcolor
                   5662: 
                   5663: =cut
                   5664: 
1.343     albertel 5665: sub standard_css {
1.345     albertel 5666:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5667:     $function  = &get_users_function() if (!$function);
                   5668:     my $img    = &designparm($function.'.img',   $domain);
                   5669:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5670:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5671:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5672: #second colour for later usage
1.345     albertel 5673:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5674:     my $pgbg_or_bgcolor =
                   5675: 	         $bgcolor ||
1.352     albertel 5676: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5677:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5678:     my $alink  = &designparm($function.'.alink', $domain);
                   5679:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5680:     my $link   = &designparm($function.'.link',  $domain);
                   5681: 
1.602     albertel 5682:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5683:     my $mono                 = 'monospace';
1.850     bisitz   5684:     my $data_table_head      = $sidebg;
                   5685:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5686:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5687:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5688:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5689:     my $mail_new             = '#FFBB77';
                   5690:     my $mail_new_hover       = '#DD9955';
                   5691:     my $mail_read            = '#BBBB77';
                   5692:     my $mail_read_hover      = '#999944';
                   5693:     my $mail_replied         = '#AAAA88';
                   5694:     my $mail_replied_hover   = '#888855';
                   5695:     my $mail_other           = '#99BBBB';
                   5696:     my $mail_other_hover     = '#669999';
1.391     albertel 5697:     my $table_header         = '#DDDDDD';
1.489     raeburn  5698:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5699:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5700:     my $button_hover         = '#BF2317';
1.392     albertel 5701: 
1.608     albertel 5702:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5703:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5704:                                              : '0 3px 0 4px';
1.448     albertel 5705: 
1.523     albertel 5706: 
1.343     albertel 5707:     return <<END;
1.947     droeschl 5708: 
                   5709: /* needed for iframe to allow 100% height in FF */
                   5710: body, html { 
                   5711:     margin: 0;
                   5712:     padding: 0 0.5%;
                   5713:     height: 99%; /* to avoid scrollbars */
                   5714: }
                   5715: 
1.795     www      5716: body {
1.911     bisitz   5717:   font-family: $sans;
                   5718:   line-height:130%;
                   5719:   font-size:0.83em;
                   5720:   color:$font;
1.795     www      5721: }
                   5722: 
1.959     onken    5723: a:focus,
                   5724: a:focus img {
1.795     www      5725:   color: red;
                   5726: }
1.698     harmsja  5727: 
1.911     bisitz   5728: form, .inline {
                   5729:   display: inline;
1.795     www      5730: }
1.721     harmsja  5731: 
1.795     www      5732: .LC_right {
1.911     bisitz   5733:   text-align:right;
1.795     www      5734: }
                   5735: 
                   5736: .LC_middle {
1.911     bisitz   5737:   vertical-align:middle;
1.795     www      5738: }
1.721     harmsja  5739: 
1.1130    raeburn  5740: .LC_floatleft {
                   5741:   float: left;
                   5742: }
                   5743: 
                   5744: .LC_floatright {
                   5745:   float: right;
                   5746: }
                   5747: 
1.911     bisitz   5748: .LC_400Box {
                   5749:   width:400px;
                   5750: }
1.721     harmsja  5751: 
1.947     droeschl 5752: .LC_iframecontainer {
                   5753:     width: 98%;
                   5754:     margin: 0;
                   5755:     position: fixed;
                   5756:     top: 8.5em;
                   5757:     bottom: 0;
                   5758: }
                   5759: 
                   5760: .LC_iframecontainer iframe{
                   5761:     border: none;
                   5762:     width: 100%;
                   5763:     height: 100%;
                   5764: }
                   5765: 
1.778     bisitz   5766: .LC_filename {
                   5767:   font-family: $mono;
                   5768:   white-space:pre;
1.921     bisitz   5769:   font-size: 120%;
1.778     bisitz   5770: }
                   5771: 
                   5772: .LC_fileicon {
                   5773:   border: none;
                   5774:   height: 1.3em;
                   5775:   vertical-align: text-bottom;
                   5776:   margin-right: 0.3em;
                   5777:   text-decoration:none;
                   5778: }
                   5779: 
1.1008    www      5780: .LC_setting {
                   5781:   text-decoration:underline;
                   5782: }
                   5783: 
1.350     albertel 5784: .LC_error {
                   5785:   color: red;
                   5786: }
1.795     www      5787: 
1.1097    bisitz   5788: .LC_warning {
                   5789:   color: darkorange;
                   5790: }
                   5791: 
1.457     albertel 5792: .LC_diff_removed {
1.733     bisitz   5793:   color: red;
1.394     albertel 5794: }
1.532     albertel 5795: 
                   5796: .LC_info,
1.457     albertel 5797: .LC_success,
                   5798: .LC_diff_added {
1.350     albertel 5799:   color: green;
                   5800: }
1.795     www      5801: 
1.802     bisitz   5802: div.LC_confirm_box {
                   5803:   background-color: #FAFAFA;
                   5804:   border: 1px solid $lg_border_color;
                   5805:   margin-right: 0;
                   5806:   padding: 5px;
                   5807: }
                   5808: 
                   5809: div.LC_confirm_box .LC_error img,
                   5810: div.LC_confirm_box .LC_success img {
                   5811:   vertical-align: middle;
                   5812: }
                   5813: 
1.440     albertel 5814: .LC_icon {
1.771     droeschl 5815:   border: none;
1.790     droeschl 5816:   vertical-align: middle;
1.771     droeschl 5817: }
                   5818: 
1.543     albertel 5819: .LC_docs_spacer {
                   5820:   width: 25px;
                   5821:   height: 1px;
1.771     droeschl 5822:   border: none;
1.543     albertel 5823: }
1.346     albertel 5824: 
1.532     albertel 5825: .LC_internal_info {
1.735     bisitz   5826:   color: #999999;
1.532     albertel 5827: }
                   5828: 
1.794     www      5829: .LC_discussion {
1.1050    www      5830:   background: $data_table_dark;
1.911     bisitz   5831:   border: 1px solid black;
                   5832:   margin: 2px;
1.794     www      5833: }
                   5834: 
                   5835: .LC_disc_action_left {
1.1050    www      5836:   background: $sidebg;
1.911     bisitz   5837:   text-align: left;
1.1050    www      5838:   padding: 4px;
                   5839:   margin: 2px;
1.794     www      5840: }
                   5841: 
                   5842: .LC_disc_action_right {
1.1050    www      5843:   background: $sidebg;
1.911     bisitz   5844:   text-align: right;
1.1050    www      5845:   padding: 4px;
                   5846:   margin: 2px;
1.794     www      5847: }
                   5848: 
                   5849: .LC_disc_new_item {
1.911     bisitz   5850:   background: white;
                   5851:   border: 2px solid red;
1.1050    www      5852:   margin: 4px;
                   5853:   padding: 4px;
1.794     www      5854: }
                   5855: 
                   5856: .LC_disc_old_item {
1.911     bisitz   5857:   background: white;
1.1050    www      5858:   margin: 4px;
                   5859:   padding: 4px;
1.794     www      5860: }
                   5861: 
1.458     albertel 5862: table.LC_pastsubmission {
                   5863:   border: 1px solid black;
                   5864:   margin: 2px;
                   5865: }
                   5866: 
1.924     bisitz   5867: table#LC_menubuttons {
1.345     albertel 5868:   width: 100%;
                   5869:   background: $pgbg;
1.392     albertel 5870:   border: 2px;
1.402     albertel 5871:   border-collapse: separate;
1.803     bisitz   5872:   padding: 0;
1.345     albertel 5873: }
1.392     albertel 5874: 
1.801     tempelho 5875: table#LC_title_bar a {
                   5876:   color: $fontmenu;
                   5877: }
1.836     bisitz   5878: 
1.807     droeschl 5879: table#LC_title_bar {
1.819     tempelho 5880:   clear: both;
1.836     bisitz   5881:   display: none;
1.807     droeschl 5882: }
                   5883: 
1.795     www      5884: table#LC_title_bar,
1.933     droeschl 5885: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 5886: table#LC_title_bar.LC_with_remote {
1.359     albertel 5887:   width: 100%;
1.392     albertel 5888:   border-color: $pgbg;
                   5889:   border-style: solid;
                   5890:   border-width: $border;
1.379     albertel 5891:   background: $pgbg;
1.801     tempelho 5892:   color: $fontmenu;
1.392     albertel 5893:   border-collapse: collapse;
1.803     bisitz   5894:   padding: 0;
1.819     tempelho 5895:   margin: 0;
1.359     albertel 5896: }
1.795     www      5897: 
1.933     droeschl 5898: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 5899:     margin: 0;
                   5900:     padding: 0;
1.933     droeschl 5901:     position: relative;
                   5902:     list-style: none;
1.913     droeschl 5903: }
1.933     droeschl 5904: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 5905:     display: inline;
                   5906: }
1.933     droeschl 5907: 
                   5908: .LC_breadcrumb_tools_navigation {
1.913     droeschl 5909:     padding: 0;
1.933     droeschl 5910:     margin: 0;
                   5911:     float: left;
1.913     droeschl 5912: }
1.933     droeschl 5913: .LC_breadcrumb_tools_tools {
                   5914:     padding: 0;
                   5915:     margin: 0;
1.913     droeschl 5916:     float: right;
                   5917: }
                   5918: 
1.359     albertel 5919: table#LC_title_bar td {
                   5920:   background: $tabbg;
                   5921: }
1.795     www      5922: 
1.911     bisitz   5923: table#LC_menubuttons img {
1.803     bisitz   5924:   border: none;
1.346     albertel 5925: }
1.795     www      5926: 
1.842     droeschl 5927: .LC_breadcrumbs_component {
1.911     bisitz   5928:   float: right;
                   5929:   margin: 0 1em;
1.357     albertel 5930: }
1.842     droeschl 5931: .LC_breadcrumbs_component img {
1.911     bisitz   5932:   vertical-align: middle;
1.777     tempelho 5933: }
1.795     www      5934: 
1.383     albertel 5935: td.LC_table_cell_checkbox {
                   5936:   text-align: center;
                   5937: }
1.795     www      5938: 
                   5939: .LC_fontsize_small {
1.911     bisitz   5940:   font-size: 70%;
1.705     tempelho 5941: }
                   5942: 
1.844     bisitz   5943: #LC_breadcrumbs {
1.911     bisitz   5944:   clear:both;
                   5945:   background: $sidebg;
                   5946:   border-bottom: 1px solid $lg_border_color;
                   5947:   line-height: 2.5em;
1.933     droeschl 5948:   overflow: hidden;
1.911     bisitz   5949:   margin: 0;
                   5950:   padding: 0;
1.995     raeburn  5951:   text-align: left;
1.819     tempelho 5952: }
1.862     bisitz   5953: 
1.1098    bisitz   5954: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   5955:   clear:both;
                   5956:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 5957:   border: 1px solid $sidebg;
1.1098    bisitz   5958:   margin: 0 0 10px 0;
1.966     bisitz   5959:   padding: 3px;
1.995     raeburn  5960:   text-align: left;
1.822     bisitz   5961: }
                   5962: 
1.795     www      5963: .LC_fontsize_medium {
1.911     bisitz   5964:   font-size: 85%;
1.705     tempelho 5965: }
                   5966: 
1.795     www      5967: .LC_fontsize_large {
1.911     bisitz   5968:   font-size: 120%;
1.705     tempelho 5969: }
                   5970: 
1.346     albertel 5971: .LC_menubuttons_inline_text {
                   5972:   color: $font;
1.698     harmsja  5973:   font-size: 90%;
1.701     harmsja  5974:   padding-left:3px;
1.346     albertel 5975: }
                   5976: 
1.934     droeschl 5977: .LC_menubuttons_inline_text img{
                   5978:   vertical-align: middle;
                   5979: }
                   5980: 
1.1051    www      5981: li.LC_menubuttons_inline_text img {
1.951     onken    5982:   cursor:pointer;
1.1002    droeschl 5983:   text-decoration: none;
1.951     onken    5984: }
                   5985: 
1.526     www      5986: .LC_menubuttons_link {
                   5987:   text-decoration: none;
                   5988: }
1.795     www      5989: 
1.522     albertel 5990: .LC_menubuttons_category {
1.521     www      5991:   color: $font;
1.526     www      5992:   background: $pgbg;
1.521     www      5993:   font-size: larger;
                   5994:   font-weight: bold;
                   5995: }
                   5996: 
1.346     albertel 5997: td.LC_menubuttons_text {
1.911     bisitz   5998:   color: $font;
1.346     albertel 5999: }
1.706     harmsja  6000: 
1.346     albertel 6001: .LC_current_location {
                   6002:   background: $tabbg;
                   6003: }
1.795     www      6004: 
1.938     bisitz   6005: table.LC_data_table {
1.347     albertel 6006:   border: 1px solid #000000;
1.402     albertel 6007:   border-collapse: separate;
1.426     albertel 6008:   border-spacing: 1px;
1.610     albertel 6009:   background: $pgbg;
1.347     albertel 6010: }
1.795     www      6011: 
1.422     albertel 6012: .LC_data_table_dense {
                   6013:   font-size: small;
                   6014: }
1.795     www      6015: 
1.507     raeburn  6016: table.LC_nested_outer {
                   6017:   border: 1px solid #000000;
1.589     raeburn  6018:   border-collapse: collapse;
1.803     bisitz   6019:   border-spacing: 0;
1.507     raeburn  6020:   width: 100%;
                   6021: }
1.795     www      6022: 
1.879     raeburn  6023: table.LC_innerpickbox,
1.507     raeburn  6024: table.LC_nested {
1.803     bisitz   6025:   border: none;
1.589     raeburn  6026:   border-collapse: collapse;
1.803     bisitz   6027:   border-spacing: 0;
1.507     raeburn  6028:   width: 100%;
                   6029: }
1.795     www      6030: 
1.911     bisitz   6031: table.LC_data_table tr th,
                   6032: table.LC_calendar tr th,
1.879     raeburn  6033: table.LC_prior_tries tr th,
                   6034: table.LC_innerpickbox tr th {
1.349     albertel 6035:   font-weight: bold;
                   6036:   background-color: $data_table_head;
1.801     tempelho 6037:   color:$fontmenu;
1.701     harmsja  6038:   font-size:90%;
1.347     albertel 6039: }
1.795     www      6040: 
1.879     raeburn  6041: table.LC_innerpickbox tr th,
                   6042: table.LC_innerpickbox tr td {
                   6043:   vertical-align: top;
                   6044: }
                   6045: 
1.711     raeburn  6046: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6047:   background-color: #CCCCCC;
1.711     raeburn  6048:   font-weight: bold;
                   6049:   text-align: left;
                   6050: }
1.795     www      6051: 
1.912     bisitz   6052: table.LC_data_table tr.LC_odd_row > td {
                   6053:   background-color: $data_table_light;
                   6054:   padding: 2px;
                   6055:   vertical-align: top;
                   6056: }
                   6057: 
1.809     bisitz   6058: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6059:   background-color: $data_table_light;
1.912     bisitz   6060:   vertical-align: top;
                   6061: }
                   6062: 
                   6063: table.LC_data_table tr.LC_even_row > td {
                   6064:   background-color: $data_table_dark;
1.425     albertel 6065:   padding: 2px;
1.900     bisitz   6066:   vertical-align: top;
1.347     albertel 6067: }
1.795     www      6068: 
1.809     bisitz   6069: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6070:   background-color: $data_table_dark;
1.900     bisitz   6071:   vertical-align: top;
1.347     albertel 6072: }
1.795     www      6073: 
1.425     albertel 6074: table.LC_data_table tr.LC_data_table_highlight td {
                   6075:   background-color: $data_table_darker;
                   6076: }
1.795     www      6077: 
1.639     raeburn  6078: table.LC_data_table tr td.LC_leftcol_header {
                   6079:   background-color: $data_table_head;
                   6080:   font-weight: bold;
                   6081: }
1.795     www      6082: 
1.451     albertel 6083: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6084: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6085:   font-weight: bold;
                   6086:   font-style: italic;
                   6087:   text-align: center;
                   6088:   padding: 8px;
1.347     albertel 6089: }
1.795     www      6090: 
1.1114    raeburn  6091: table.LC_data_table tr.LC_empty_row td,
                   6092: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6093:   background-color: $sidebg;
                   6094: }
                   6095: 
                   6096: table.LC_nested tr.LC_empty_row td {
                   6097:   background-color: #FFFFFF;
                   6098: }
                   6099: 
1.890     droeschl 6100: table.LC_caption {
                   6101: }
                   6102: 
1.507     raeburn  6103: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6104:   padding: 4ex
                   6105: }
1.795     www      6106: 
1.507     raeburn  6107: table.LC_nested_outer tr th {
                   6108:   font-weight: bold;
1.801     tempelho 6109:   color:$fontmenu;
1.507     raeburn  6110:   background-color: $data_table_head;
1.701     harmsja  6111:   font-size: small;
1.507     raeburn  6112:   border-bottom: 1px solid #000000;
                   6113: }
1.795     www      6114: 
1.507     raeburn  6115: table.LC_nested_outer tr td.LC_subheader {
                   6116:   background-color: $data_table_head;
                   6117:   font-weight: bold;
                   6118:   font-size: small;
                   6119:   border-bottom: 1px solid #000000;
                   6120:   text-align: right;
1.451     albertel 6121: }
1.795     www      6122: 
1.507     raeburn  6123: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6124:   background-color: #CCCCCC;
1.451     albertel 6125:   font-weight: bold;
                   6126:   font-size: small;
1.507     raeburn  6127:   text-align: center;
                   6128: }
1.795     www      6129: 
1.589     raeburn  6130: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6131: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6132:   text-align: left;
1.451     albertel 6133: }
1.795     www      6134: 
1.507     raeburn  6135: table.LC_nested td {
1.735     bisitz   6136:   background-color: #FFFFFF;
1.451     albertel 6137:   font-size: small;
1.507     raeburn  6138: }
1.795     www      6139: 
1.507     raeburn  6140: table.LC_nested_outer tr th.LC_right_item,
                   6141: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6142: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6143: table.LC_nested tr td.LC_right_item {
1.451     albertel 6144:   text-align: right;
                   6145: }
                   6146: 
1.507     raeburn  6147: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6148:   background-color: #EEEEEE;
1.451     albertel 6149: }
                   6150: 
1.473     raeburn  6151: table.LC_createuser {
                   6152: }
                   6153: 
                   6154: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6155:   font-size: small;
1.473     raeburn  6156: }
                   6157: 
                   6158: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6159:   background-color: #CCCCCC;
1.473     raeburn  6160:   font-weight: bold;
                   6161:   text-align: center;
                   6162: }
                   6163: 
1.349     albertel 6164: table.LC_calendar {
                   6165:   border: 1px solid #000000;
                   6166:   border-collapse: collapse;
1.917     raeburn  6167:   width: 98%;
1.349     albertel 6168: }
1.795     www      6169: 
1.349     albertel 6170: table.LC_calendar_pickdate {
                   6171:   font-size: xx-small;
                   6172: }
1.795     www      6173: 
1.349     albertel 6174: table.LC_calendar tr td {
                   6175:   border: 1px solid #000000;
                   6176:   vertical-align: top;
1.917     raeburn  6177:   width: 14%;
1.349     albertel 6178: }
1.795     www      6179: 
1.349     albertel 6180: table.LC_calendar tr td.LC_calendar_day_empty {
                   6181:   background-color: $data_table_dark;
                   6182: }
1.795     www      6183: 
1.779     bisitz   6184: table.LC_calendar tr td.LC_calendar_day_current {
                   6185:   background-color: $data_table_highlight;
1.777     tempelho 6186: }
1.795     www      6187: 
1.938     bisitz   6188: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6189:   background-color: $mail_new;
                   6190: }
1.795     www      6191: 
1.938     bisitz   6192: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6193:   background-color: $mail_new_hover;
                   6194: }
1.795     www      6195: 
1.938     bisitz   6196: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6197:   background-color: $mail_read;
                   6198: }
1.795     www      6199: 
1.938     bisitz   6200: /*
                   6201: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6202:   background-color: $mail_read_hover;
                   6203: }
1.938     bisitz   6204: */
1.795     www      6205: 
1.938     bisitz   6206: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6207:   background-color: $mail_replied;
                   6208: }
1.795     www      6209: 
1.938     bisitz   6210: /*
                   6211: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6212:   background-color: $mail_replied_hover;
                   6213: }
1.938     bisitz   6214: */
1.795     www      6215: 
1.938     bisitz   6216: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6217:   background-color: $mail_other;
                   6218: }
1.795     www      6219: 
1.938     bisitz   6220: /*
                   6221: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6222:   background-color: $mail_other_hover;
                   6223: }
1.938     bisitz   6224: */
1.494     raeburn  6225: 
1.777     tempelho 6226: table.LC_data_table tr > td.LC_browser_file,
                   6227: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6228:   background: #AAEE77;
1.389     albertel 6229: }
1.795     www      6230: 
1.777     tempelho 6231: table.LC_data_table tr > td.LC_browser_file_locked,
                   6232: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6233:   background: #FFAA99;
1.387     albertel 6234: }
1.795     www      6235: 
1.777     tempelho 6236: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6237:   background: #888888;
1.779     bisitz   6238: }
1.795     www      6239: 
1.777     tempelho 6240: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6241: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6242:   background: #F8F866;
1.777     tempelho 6243: }
1.795     www      6244: 
1.696     bisitz   6245: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6246:   background: #E0E8FF;
1.387     albertel 6247: }
1.696     bisitz   6248: 
1.707     bisitz   6249: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6250:   /* background: #77FF77; */
1.707     bisitz   6251: }
1.795     www      6252: 
1.707     bisitz   6253: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6254:   border-right: 8px solid #FFFF77;
1.707     bisitz   6255: }
1.795     www      6256: 
1.707     bisitz   6257: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6258:   border-right: 8px solid #FFAA77;
1.707     bisitz   6259: }
1.795     www      6260: 
1.707     bisitz   6261: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6262:   border-right: 8px solid #FF7777;
1.707     bisitz   6263: }
1.795     www      6264: 
1.707     bisitz   6265: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6266:   border-right: 8px solid #AAFF77;
1.707     bisitz   6267: }
1.795     www      6268: 
1.707     bisitz   6269: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6270:   border-right: 8px solid #11CC55;
1.707     bisitz   6271: }
                   6272: 
1.388     albertel 6273: span.LC_current_location {
1.701     harmsja  6274:   font-size:larger;
1.388     albertel 6275:   background: $pgbg;
                   6276: }
1.387     albertel 6277: 
1.1029    www      6278: span.LC_current_nav_location {
                   6279:   font-weight:bold;
                   6280:   background: $sidebg;
                   6281: }
                   6282: 
1.395     albertel 6283: span.LC_parm_menu_item {
                   6284:   font-size: larger;
                   6285: }
1.795     www      6286: 
1.395     albertel 6287: span.LC_parm_scope_all {
                   6288:   color: red;
                   6289: }
1.795     www      6290: 
1.395     albertel 6291: span.LC_parm_scope_folder {
                   6292:   color: green;
                   6293: }
1.795     www      6294: 
1.395     albertel 6295: span.LC_parm_scope_resource {
                   6296:   color: orange;
                   6297: }
1.795     www      6298: 
1.395     albertel 6299: span.LC_parm_part {
                   6300:   color: blue;
                   6301: }
1.795     www      6302: 
1.911     bisitz   6303: span.LC_parm_folder,
                   6304: span.LC_parm_symb {
1.395     albertel 6305:   font-size: x-small;
                   6306:   font-family: $mono;
                   6307:   color: #AAAAAA;
                   6308: }
                   6309: 
1.977     bisitz   6310: ul.LC_parm_parmlist li {
                   6311:   display: inline-block;
                   6312:   padding: 0.3em 0.8em;
                   6313:   vertical-align: top;
                   6314:   width: 150px;
                   6315:   border-top:1px solid $lg_border_color;
                   6316: }
                   6317: 
1.795     www      6318: td.LC_parm_overview_level_menu,
                   6319: td.LC_parm_overview_map_menu,
                   6320: td.LC_parm_overview_parm_selectors,
                   6321: td.LC_parm_overview_restrictions  {
1.396     albertel 6322:   border: 1px solid black;
                   6323:   border-collapse: collapse;
                   6324: }
1.795     www      6325: 
1.396     albertel 6326: table.LC_parm_overview_restrictions td {
                   6327:   border-width: 1px 4px 1px 4px;
                   6328:   border-style: solid;
                   6329:   border-color: $pgbg;
                   6330:   text-align: center;
                   6331: }
1.795     www      6332: 
1.396     albertel 6333: table.LC_parm_overview_restrictions th {
                   6334:   background: $tabbg;
                   6335:   border-width: 1px 4px 1px 4px;
                   6336:   border-style: solid;
                   6337:   border-color: $pgbg;
                   6338: }
1.795     www      6339: 
1.398     albertel 6340: table#LC_helpmenu {
1.803     bisitz   6341:   border: none;
1.398     albertel 6342:   height: 55px;
1.803     bisitz   6343:   border-spacing: 0;
1.398     albertel 6344: }
                   6345: 
                   6346: table#LC_helpmenu fieldset legend {
                   6347:   font-size: larger;
                   6348: }
1.795     www      6349: 
1.397     albertel 6350: table#LC_helpmenu_links {
                   6351:   width: 100%;
                   6352:   border: 1px solid black;
                   6353:   background: $pgbg;
1.803     bisitz   6354:   padding: 0;
1.397     albertel 6355:   border-spacing: 1px;
                   6356: }
1.795     www      6357: 
1.397     albertel 6358: table#LC_helpmenu_links tr td {
                   6359:   padding: 1px;
                   6360:   background: $tabbg;
1.399     albertel 6361:   text-align: center;
                   6362:   font-weight: bold;
1.397     albertel 6363: }
1.396     albertel 6364: 
1.795     www      6365: table#LC_helpmenu_links a:link,
                   6366: table#LC_helpmenu_links a:visited,
1.397     albertel 6367: table#LC_helpmenu_links a:active {
                   6368:   text-decoration: none;
                   6369:   color: $font;
                   6370: }
1.795     www      6371: 
1.397     albertel 6372: table#LC_helpmenu_links a:hover {
                   6373:   text-decoration: underline;
                   6374:   color: $vlink;
                   6375: }
1.396     albertel 6376: 
1.417     albertel 6377: .LC_chrt_popup_exists {
                   6378:   border: 1px solid #339933;
                   6379:   margin: -1px;
                   6380: }
1.795     www      6381: 
1.417     albertel 6382: .LC_chrt_popup_up {
                   6383:   border: 1px solid yellow;
                   6384:   margin: -1px;
                   6385: }
1.795     www      6386: 
1.417     albertel 6387: .LC_chrt_popup {
                   6388:   border: 1px solid #8888FF;
                   6389:   background: #CCCCFF;
                   6390: }
1.795     www      6391: 
1.421     albertel 6392: table.LC_pick_box {
                   6393:   border-collapse: separate;
                   6394:   background: white;
                   6395:   border: 1px solid black;
                   6396:   border-spacing: 1px;
                   6397: }
1.795     www      6398: 
1.421     albertel 6399: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6400:   background: $sidebg;
1.421     albertel 6401:   font-weight: bold;
1.900     bisitz   6402:   text-align: left;
1.740     bisitz   6403:   vertical-align: top;
1.421     albertel 6404:   width: 184px;
                   6405:   padding: 8px;
                   6406: }
1.795     www      6407: 
1.579     raeburn  6408: table.LC_pick_box td.LC_pick_box_value {
                   6409:   text-align: left;
                   6410:   padding: 8px;
                   6411: }
1.795     www      6412: 
1.579     raeburn  6413: table.LC_pick_box td.LC_pick_box_select {
                   6414:   text-align: left;
                   6415:   padding: 8px;
                   6416: }
1.795     www      6417: 
1.424     albertel 6418: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6419:   padding: 0;
1.421     albertel 6420:   height: 1px;
                   6421:   background: black;
                   6422: }
1.795     www      6423: 
1.421     albertel 6424: table.LC_pick_box td.LC_pick_box_submit {
                   6425:   text-align: right;
                   6426: }
1.795     www      6427: 
1.579     raeburn  6428: table.LC_pick_box td.LC_evenrow_value {
                   6429:   text-align: left;
                   6430:   padding: 8px;
                   6431:   background-color: $data_table_light;
                   6432: }
1.795     www      6433: 
1.579     raeburn  6434: table.LC_pick_box td.LC_oddrow_value {
                   6435:   text-align: left;
                   6436:   padding: 8px;
                   6437:   background-color: $data_table_light;
                   6438: }
1.795     www      6439: 
1.579     raeburn  6440: span.LC_helpform_receipt_cat {
                   6441:   font-weight: bold;
                   6442: }
1.795     www      6443: 
1.424     albertel 6444: table.LC_group_priv_box {
                   6445:   background: white;
                   6446:   border: 1px solid black;
                   6447:   border-spacing: 1px;
                   6448: }
1.795     www      6449: 
1.424     albertel 6450: table.LC_group_priv_box td.LC_pick_box_title {
                   6451:   background: $tabbg;
                   6452:   font-weight: bold;
                   6453:   text-align: right;
                   6454:   width: 184px;
                   6455: }
1.795     www      6456: 
1.424     albertel 6457: table.LC_group_priv_box td.LC_groups_fixed {
                   6458:   background: $data_table_light;
                   6459:   text-align: center;
                   6460: }
1.795     www      6461: 
1.424     albertel 6462: table.LC_group_priv_box td.LC_groups_optional {
                   6463:   background: $data_table_dark;
                   6464:   text-align: center;
                   6465: }
1.795     www      6466: 
1.424     albertel 6467: table.LC_group_priv_box td.LC_groups_functionality {
                   6468:   background: $data_table_darker;
                   6469:   text-align: center;
                   6470:   font-weight: bold;
                   6471: }
1.795     www      6472: 
1.424     albertel 6473: table.LC_group_priv td {
                   6474:   text-align: left;
1.803     bisitz   6475:   padding: 0;
1.424     albertel 6476: }
                   6477: 
                   6478: .LC_navbuttons {
                   6479:   margin: 2ex 0ex 2ex 0ex;
                   6480: }
1.795     www      6481: 
1.423     albertel 6482: .LC_topic_bar {
                   6483:   font-weight: bold;
                   6484:   background: $tabbg;
1.918     wenzelju 6485:   margin: 1em 0em 1em 2em;
1.805     bisitz   6486:   padding: 3px;
1.918     wenzelju 6487:   font-size: 1.2em;
1.423     albertel 6488: }
1.795     www      6489: 
1.423     albertel 6490: .LC_topic_bar span {
1.918     wenzelju 6491:   left: 0.5em;
                   6492:   position: absolute;
1.423     albertel 6493:   vertical-align: middle;
1.918     wenzelju 6494:   font-size: 1.2em;
1.423     albertel 6495: }
1.795     www      6496: 
1.423     albertel 6497: table.LC_course_group_status {
                   6498:   margin: 20px;
                   6499: }
1.795     www      6500: 
1.423     albertel 6501: table.LC_status_selector td {
                   6502:   vertical-align: top;
                   6503:   text-align: center;
1.424     albertel 6504:   padding: 4px;
                   6505: }
1.795     www      6506: 
1.599     albertel 6507: div.LC_feedback_link {
1.616     albertel 6508:   clear: both;
1.829     kalberla 6509:   background: $sidebg;
1.779     bisitz   6510:   width: 100%;
1.829     kalberla 6511:   padding-bottom: 10px;
                   6512:   border: 1px $tabbg solid;
1.833     kalberla 6513:   height: 22px;
                   6514:   line-height: 22px;
                   6515:   padding-top: 5px;
                   6516: }
                   6517: 
                   6518: div.LC_feedback_link img {
                   6519:   height: 22px;
1.867     kalberla 6520:   vertical-align:middle;
1.829     kalberla 6521: }
                   6522: 
1.911     bisitz   6523: div.LC_feedback_link a {
1.829     kalberla 6524:   text-decoration: none;
1.489     raeburn  6525: }
1.795     www      6526: 
1.867     kalberla 6527: div.LC_comblock {
1.911     bisitz   6528:   display:inline;
1.867     kalberla 6529:   color:$font;
                   6530:   font-size:90%;
                   6531: }
                   6532: 
                   6533: div.LC_feedback_link div.LC_comblock {
                   6534:   padding-left:5px;
                   6535: }
                   6536: 
                   6537: div.LC_feedback_link div.LC_comblock a {
                   6538:   color:$font;
                   6539: }
                   6540: 
1.489     raeburn  6541: span.LC_feedback_link {
1.858     bisitz   6542:   /* background: $feedback_link_bg; */
1.599     albertel 6543:   font-size: larger;
                   6544: }
1.795     www      6545: 
1.599     albertel 6546: span.LC_message_link {
1.858     bisitz   6547:   /* background: $feedback_link_bg; */
1.599     albertel 6548:   font-size: larger;
                   6549:   position: absolute;
                   6550:   right: 1em;
1.489     raeburn  6551: }
1.421     albertel 6552: 
1.515     albertel 6553: table.LC_prior_tries {
1.524     albertel 6554:   border: 1px solid #000000;
                   6555:   border-collapse: separate;
                   6556:   border-spacing: 1px;
1.515     albertel 6557: }
1.523     albertel 6558: 
1.515     albertel 6559: table.LC_prior_tries td {
1.524     albertel 6560:   padding: 2px;
1.515     albertel 6561: }
1.523     albertel 6562: 
                   6563: .LC_answer_correct {
1.795     www      6564:   background: lightgreen;
                   6565:   color: darkgreen;
                   6566:   padding: 6px;
1.523     albertel 6567: }
1.795     www      6568: 
1.523     albertel 6569: .LC_answer_charged_try {
1.797     www      6570:   background: #FFAAAA;
1.795     www      6571:   color: darkred;
                   6572:   padding: 6px;
1.523     albertel 6573: }
1.795     www      6574: 
1.779     bisitz   6575: .LC_answer_not_charged_try,
1.523     albertel 6576: .LC_answer_no_grade,
                   6577: .LC_answer_late {
1.795     www      6578:   background: lightyellow;
1.523     albertel 6579:   color: black;
1.795     www      6580:   padding: 6px;
1.523     albertel 6581: }
1.795     www      6582: 
1.523     albertel 6583: .LC_answer_previous {
1.795     www      6584:   background: lightblue;
                   6585:   color: darkblue;
                   6586:   padding: 6px;
1.523     albertel 6587: }
1.795     www      6588: 
1.779     bisitz   6589: .LC_answer_no_message {
1.777     tempelho 6590:   background: #FFFFFF;
                   6591:   color: black;
1.795     www      6592:   padding: 6px;
1.779     bisitz   6593: }
1.795     www      6594: 
1.779     bisitz   6595: .LC_answer_unknown {
                   6596:   background: orange;
                   6597:   color: black;
1.795     www      6598:   padding: 6px;
1.777     tempelho 6599: }
1.795     www      6600: 
1.529     albertel 6601: span.LC_prior_numerical,
                   6602: span.LC_prior_string,
                   6603: span.LC_prior_custom,
                   6604: span.LC_prior_reaction,
                   6605: span.LC_prior_math {
1.925     bisitz   6606:   font-family: $mono;
1.523     albertel 6607:   white-space: pre;
                   6608: }
                   6609: 
1.525     albertel 6610: span.LC_prior_string {
1.925     bisitz   6611:   font-family: $mono;
1.525     albertel 6612:   white-space: pre;
                   6613: }
                   6614: 
1.523     albertel 6615: table.LC_prior_option {
                   6616:   width: 100%;
                   6617:   border-collapse: collapse;
                   6618: }
1.795     www      6619: 
1.911     bisitz   6620: table.LC_prior_rank,
1.795     www      6621: table.LC_prior_match {
1.528     albertel 6622:   border-collapse: collapse;
                   6623: }
1.795     www      6624: 
1.528     albertel 6625: table.LC_prior_option tr td,
                   6626: table.LC_prior_rank tr td,
                   6627: table.LC_prior_match tr td {
1.524     albertel 6628:   border: 1px solid #000000;
1.515     albertel 6629: }
                   6630: 
1.855     bisitz   6631: .LC_nobreak {
1.544     albertel 6632:   white-space: nowrap;
1.519     raeburn  6633: }
                   6634: 
1.576     raeburn  6635: span.LC_cusr_emph {
                   6636:   font-style: italic;
                   6637: }
                   6638: 
1.633     raeburn  6639: span.LC_cusr_subheading {
                   6640:   font-weight: normal;
                   6641:   font-size: 85%;
                   6642: }
                   6643: 
1.861     bisitz   6644: div.LC_docs_entry_move {
1.859     bisitz   6645:   border: 1px solid #BBBBBB;
1.545     albertel 6646:   background: #DDDDDD;
1.861     bisitz   6647:   width: 22px;
1.859     bisitz   6648:   padding: 1px;
                   6649:   margin: 0;
1.545     albertel 6650: }
                   6651: 
1.861     bisitz   6652: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6653: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6654:   font-size: x-small;
                   6655: }
1.795     www      6656: 
1.861     bisitz   6657: .LC_docs_entry_parameter {
                   6658:   white-space: nowrap;
                   6659: }
                   6660: 
1.544     albertel 6661: .LC_docs_copy {
1.545     albertel 6662:   color: #000099;
1.544     albertel 6663: }
1.795     www      6664: 
1.544     albertel 6665: .LC_docs_cut {
1.545     albertel 6666:   color: #550044;
1.544     albertel 6667: }
1.795     www      6668: 
1.544     albertel 6669: .LC_docs_rename {
1.545     albertel 6670:   color: #009900;
1.544     albertel 6671: }
1.795     www      6672: 
1.544     albertel 6673: .LC_docs_remove {
1.545     albertel 6674:   color: #990000;
                   6675: }
                   6676: 
1.547     albertel 6677: .LC_docs_reinit_warn,
                   6678: .LC_docs_ext_edit {
                   6679:   font-size: x-small;
                   6680: }
                   6681: 
1.545     albertel 6682: table.LC_docs_adddocs td,
                   6683: table.LC_docs_adddocs th {
                   6684:   border: 1px solid #BBBBBB;
                   6685:   padding: 4px;
                   6686:   background: #DDDDDD;
1.543     albertel 6687: }
                   6688: 
1.584     albertel 6689: table.LC_sty_begin {
                   6690:   background: #BBFFBB;
                   6691: }
1.795     www      6692: 
1.584     albertel 6693: table.LC_sty_end {
                   6694:   background: #FFBBBB;
                   6695: }
                   6696: 
1.589     raeburn  6697: table.LC_double_column {
1.803     bisitz   6698:   border-width: 0;
1.589     raeburn  6699:   border-collapse: collapse;
                   6700:   width: 100%;
                   6701:   padding: 2px;
                   6702: }
                   6703: 
                   6704: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6705:   top: 2px;
1.589     raeburn  6706:   left: 2px;
                   6707:   width: 47%;
                   6708:   vertical-align: top;
                   6709: }
                   6710: 
                   6711: table.LC_double_column tr td.LC_right_col {
                   6712:   top: 2px;
1.779     bisitz   6713:   right: 2px;
1.589     raeburn  6714:   width: 47%;
                   6715:   vertical-align: top;
                   6716: }
                   6717: 
1.591     raeburn  6718: div.LC_left_float {
                   6719:   float: left;
                   6720:   padding-right: 5%;
1.597     albertel 6721:   padding-bottom: 4px;
1.591     raeburn  6722: }
                   6723: 
                   6724: div.LC_clear_float_header {
1.597     albertel 6725:   padding-bottom: 2px;
1.591     raeburn  6726: }
                   6727: 
                   6728: div.LC_clear_float_footer {
1.597     albertel 6729:   padding-top: 10px;
1.591     raeburn  6730:   clear: both;
                   6731: }
                   6732: 
1.597     albertel 6733: div.LC_grade_show_user {
1.941     bisitz   6734: /*  border-left: 5px solid $sidebg; */
                   6735:   border-top: 5px solid #000000;
                   6736:   margin: 50px 0 0 0;
1.936     bisitz   6737:   padding: 15px 0 5px 10px;
1.597     albertel 6738: }
1.795     www      6739: 
1.936     bisitz   6740: div.LC_grade_show_user_odd_row {
1.941     bisitz   6741: /*  border-left: 5px solid #000000; */
                   6742: }
                   6743: 
                   6744: div.LC_grade_show_user div.LC_Box {
                   6745:   margin-right: 50px;
1.597     albertel 6746: }
                   6747: 
                   6748: div.LC_grade_submissions,
                   6749: div.LC_grade_message_center,
1.936     bisitz   6750: div.LC_grade_info_links {
1.597     albertel 6751:   margin: 5px;
                   6752:   width: 99%;
                   6753:   background: #FFFFFF;
                   6754: }
1.795     www      6755: 
1.597     albertel 6756: div.LC_grade_submissions_header,
1.936     bisitz   6757: div.LC_grade_message_center_header {
1.705     tempelho 6758:   font-weight: bold;
                   6759:   font-size: large;
1.597     albertel 6760: }
1.795     www      6761: 
1.597     albertel 6762: div.LC_grade_submissions_body,
1.936     bisitz   6763: div.LC_grade_message_center_body {
1.597     albertel 6764:   border: 1px solid black;
                   6765:   width: 99%;
                   6766:   background: #FFFFFF;
                   6767: }
1.795     www      6768: 
1.613     albertel 6769: table.LC_scantron_action {
                   6770:   width: 100%;
                   6771: }
1.795     www      6772: 
1.613     albertel 6773: table.LC_scantron_action tr th {
1.698     harmsja  6774:   font-weight:bold;
                   6775:   font-style:normal;
1.613     albertel 6776: }
1.795     www      6777: 
1.779     bisitz   6778: .LC_edit_problem_header,
1.614     albertel 6779: div.LC_edit_problem_footer {
1.705     tempelho 6780:   font-weight: normal;
                   6781:   font-size:  medium;
1.602     albertel 6782:   margin: 2px;
1.1060    bisitz   6783:   background-color: $sidebg;
1.600     albertel 6784: }
1.795     www      6785: 
1.600     albertel 6786: div.LC_edit_problem_header,
1.602     albertel 6787: div.LC_edit_problem_header div,
1.614     albertel 6788: div.LC_edit_problem_footer,
                   6789: div.LC_edit_problem_footer div,
1.602     albertel 6790: div.LC_edit_problem_editxml_header,
                   6791: div.LC_edit_problem_editxml_header div {
1.600     albertel 6792:   margin-top: 5px;
1.1205  ! golterma 6793:   z-index: 100;
1.600     albertel 6794: }
1.795     www      6795: 
1.600     albertel 6796: div.LC_edit_problem_header_title {
1.705     tempelho 6797:   font-weight: bold;
                   6798:   font-size: larger;
1.602     albertel 6799:   background: $tabbg;
                   6800:   padding: 3px;
1.1060    bisitz   6801:   margin: 0 0 5px 0;
1.602     albertel 6802: }
1.795     www      6803: 
1.602     albertel 6804: table.LC_edit_problem_header_title {
                   6805:   width: 100%;
1.600     albertel 6806:   background: $tabbg;
1.602     albertel 6807: }
                   6808: 
                   6809: div.LC_edit_problem_discards {
                   6810:   float: left;
1.1205  ! golterma 6811: }
        !          6812: 
        !          6813: div.LC_edit_actionbar {
        !          6814:     margin: -5px 0px 0px 0px !important;
        !          6815:     background-color: $sidebg;
        !          6816:     height: 31px;
1.602     albertel 6817: }
1.795     www      6818: 
1.602     albertel 6819: div.LC_edit_problem_saves {
                   6820:   float: right;
                   6821:   padding-bottom: 5px;
1.600     albertel 6822: }
1.795     www      6823: 
1.1124    bisitz   6824: .LC_edit_opt {
                   6825:   padding-left: 1em;
                   6826:   white-space: nowrap;
                   6827: }
                   6828: 
1.1152    golterma 6829: .LC_edit_problem_latexhelper{
                   6830:     text-align: right;
                   6831: }
                   6832: 
                   6833: #LC_edit_problem_colorful div{
                   6834:     margin-left: 40px;
                   6835: }
                   6836: 
1.1205  ! golterma 6837: #LC_edit_problem_codemirror div{
        !          6838:     margin-left: 0px;
        !          6839: }
        !          6840: 
1.911     bisitz   6841: img.stift {
1.803     bisitz   6842:   border-width: 0;
                   6843:   vertical-align: middle;
1.677     riegler  6844: }
1.680     riegler  6845: 
1.923     bisitz   6846: table td.LC_mainmenu_col_fieldset {
1.680     riegler  6847:   vertical-align: top;
1.777     tempelho 6848: }
1.795     www      6849: 
1.716     raeburn  6850: div.LC_createcourse {
1.911     bisitz   6851:   margin: 10px 10px 10px 10px;
1.716     raeburn  6852: }
                   6853: 
1.917     raeburn  6854: .LC_dccid {
1.1130    raeburn  6855:   float: right;
1.917     raeburn  6856:   margin: 0.2em 0 0 0;
                   6857:   padding: 0;
                   6858:   font-size: 90%;
                   6859:   display:none;
                   6860: }
                   6861: 
1.897     wenzelju 6862: ol.LC_primary_menu a:hover,
1.721     harmsja  6863: ol#LC_MenuBreadcrumbs a:hover,
                   6864: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 6865: ul#LC_secondary_menu a:hover,
1.721     harmsja  6866: .LC_FormSectionClearButton input:hover
1.795     www      6867: ul.LC_TabContent   li:hover a {
1.952     onken    6868:   color:$button_hover;
1.911     bisitz   6869:   text-decoration:none;
1.693     droeschl 6870: }
                   6871: 
1.779     bisitz   6872: h1 {
1.911     bisitz   6873:   padding: 0;
                   6874:   line-height:130%;
1.693     droeschl 6875: }
1.698     harmsja  6876: 
1.911     bisitz   6877: h2,
                   6878: h3,
                   6879: h4,
                   6880: h5,
                   6881: h6 {
                   6882:   margin: 5px 0 5px 0;
                   6883:   padding: 0;
                   6884:   line-height:130%;
1.693     droeschl 6885: }
1.795     www      6886: 
                   6887: .LC_hcell {
1.911     bisitz   6888:   padding:3px 15px 3px 15px;
                   6889:   margin: 0;
                   6890:   background-color:$tabbg;
                   6891:   color:$fontmenu;
                   6892:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 6893: }
1.795     www      6894: 
1.840     bisitz   6895: .LC_Box > .LC_hcell {
1.911     bisitz   6896:   margin: 0 -10px 10px -10px;
1.835     bisitz   6897: }
                   6898: 
1.721     harmsja  6899: .LC_noBorder {
1.911     bisitz   6900:   border: 0;
1.698     harmsja  6901: }
1.693     droeschl 6902: 
1.721     harmsja  6903: .LC_FormSectionClearButton input {
1.911     bisitz   6904:   background-color:transparent;
                   6905:   border: none;
                   6906:   cursor:pointer;
                   6907:   text-decoration:underline;
1.693     droeschl 6908: }
1.763     bisitz   6909: 
                   6910: .LC_help_open_topic {
1.911     bisitz   6911:   color: #FFFFFF;
                   6912:   background-color: #EEEEFF;
                   6913:   margin: 1px;
                   6914:   padding: 4px;
                   6915:   border: 1px solid #000033;
                   6916:   white-space: nowrap;
                   6917:   /* vertical-align: middle; */
1.759     neumanie 6918: }
1.693     droeschl 6919: 
1.911     bisitz   6920: dl,
                   6921: ul,
                   6922: div,
                   6923: fieldset {
                   6924:   margin: 10px 10px 10px 0;
                   6925:   /* overflow: hidden; */
1.693     droeschl 6926: }
1.795     www      6927: 
1.838     bisitz   6928: fieldset > legend {
1.911     bisitz   6929:   font-weight: bold;
                   6930:   padding: 0 5px 0 5px;
1.838     bisitz   6931: }
                   6932: 
1.813     bisitz   6933: #LC_nav_bar {
1.911     bisitz   6934:   float: left;
1.995     raeburn  6935:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   6936:   margin: 0 0 2px 0;
1.807     droeschl 6937: }
                   6938: 
1.916     droeschl 6939: #LC_realm {
                   6940:   margin: 0.2em 0 0 0;
                   6941:   padding: 0;
                   6942:   font-weight: bold;
                   6943:   text-align: center;
1.995     raeburn  6944:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 6945: }
                   6946: 
1.911     bisitz   6947: #LC_nav_bar em {
                   6948:   font-weight: bold;
                   6949:   font-style: normal;
1.807     droeschl 6950: }
                   6951: 
1.897     wenzelju 6952: ol.LC_primary_menu {
1.934     droeschl 6953:   margin: 0;
1.1076    raeburn  6954:   padding: 0;
1.807     droeschl 6955: }
                   6956: 
1.852     droeschl 6957: ol#LC_PathBreadcrumbs {
1.911     bisitz   6958:   margin: 0;
1.693     droeschl 6959: }
                   6960: 
1.897     wenzelju 6961: ol.LC_primary_menu li {
1.1076    raeburn  6962:   color: RGB(80, 80, 80);
                   6963:   vertical-align: middle;
                   6964:   text-align: left;
                   6965:   list-style: none;
1.1205  ! golterma 6966:   position: relative;
1.1076    raeburn  6967:   float: left;
1.1205  ! golterma 6968:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
        !          6969:   line-height: 1.5em;
1.1076    raeburn  6970: }
                   6971: 
1.1205  ! golterma 6972: ol.LC_primary_menu li a,
        !          6973: ol.LC_primary_menu li p {
1.1076    raeburn  6974:   display: block;
                   6975:   margin: 0;
                   6976:   padding: 0 5px 0 10px;
                   6977:   text-decoration: none;
                   6978: }
                   6979: 
1.1205  ! golterma 6980: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
        !          6981:   display: inline-block;
        !          6982:   width: 95%;
        !          6983:   text-align: left;
        !          6984: }
        !          6985: 
        !          6986: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
        !          6987:   display: inline-block;	
        !          6988:   width: 5%;
        !          6989:   float: right;
        !          6990:   text-align: right;
        !          6991:   font-size: 70%;
        !          6992: }
        !          6993: 
        !          6994: ol.LC_primary_menu ul {
1.1076    raeburn  6995:   display: none;
1.1205  ! golterma 6996:   width: 15em;
1.1076    raeburn  6997:   background-color: $data_table_light;
1.1205  ! golterma 6998:   position: absolute;
        !          6999:   top: 100%;
1.1076    raeburn  7000: }
                   7001: 
1.1205  ! golterma 7002: ol.LC_primary_menu ul ul {
        !          7003:   left: 100%;
        !          7004:   top: 0;
        !          7005: }
        !          7006: 
        !          7007: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  7008:   display: block;
                   7009:   position: absolute;
                   7010:   margin: 0;
                   7011:   padding: 0;
1.1078    raeburn  7012:   z-index: 2;
1.1076    raeburn  7013: }
                   7014: 
                   7015: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205  ! golterma 7016: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  7017:   font-size: 90%;
1.911     bisitz   7018:   vertical-align: top;
1.1076    raeburn  7019:   float: none;
1.1079    raeburn  7020:   border-left: 1px solid black;
                   7021:   border-right: 1px solid black;
1.1205  ! golterma 7022: /* A dark bottom border to visualize different menu options; 
        !          7023: overwritten in the create_submenu routine for the last border-bottom of the menu */
        !          7024:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  7025: }
                   7026: 
1.1205  ! golterma 7027: ol.LC_primary_menu li li p:hover {
        !          7028:   color:$button_hover;
        !          7029:   text-decoration:none;
        !          7030:   background-color:$data_table_dark;
1.1076    raeburn  7031: }
                   7032: 
                   7033: ol.LC_primary_menu li li a:hover {
                   7034:    color:$button_hover;
                   7035:    background-color:$data_table_dark;
1.693     droeschl 7036: }
                   7037: 
1.1205  ! golterma 7038: /* Font-size equal to the size of the predecessors*/
        !          7039: ol.LC_primary_menu li:hover li li {
        !          7040:   font-size: 100%;
        !          7041: }
        !          7042: 
1.897     wenzelju 7043: ol.LC_primary_menu li img {
1.911     bisitz   7044:   vertical-align: bottom;
1.934     droeschl 7045:   height: 1.1em;
1.1077    raeburn  7046:   margin: 0.2em 0 0 0;
1.693     droeschl 7047: }
                   7048: 
1.897     wenzelju 7049: ol.LC_primary_menu a {
1.911     bisitz   7050:   color: RGB(80, 80, 80);
                   7051:   text-decoration: none;
1.693     droeschl 7052: }
1.795     www      7053: 
1.949     droeschl 7054: ol.LC_primary_menu a.LC_new_message {
                   7055:   font-weight:bold;
                   7056:   color: darkred;
                   7057: }
                   7058: 
1.975     raeburn  7059: ol.LC_docs_parameters {
                   7060:   margin-left: 0;
                   7061:   padding: 0;
                   7062:   list-style: none;
                   7063: }
                   7064: 
                   7065: ol.LC_docs_parameters li {
                   7066:   margin: 0;
                   7067:   padding-right: 20px;
                   7068:   display: inline;
                   7069: }
                   7070: 
1.976     raeburn  7071: ol.LC_docs_parameters li:before {
                   7072:   content: "\\002022 \\0020";
                   7073: }
                   7074: 
                   7075: li.LC_docs_parameters_title {
                   7076:   font-weight: bold;
                   7077: }
                   7078: 
                   7079: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7080:   content: "";
                   7081: }
                   7082: 
1.897     wenzelju 7083: ul#LC_secondary_menu {
1.1107    raeburn  7084:   clear: right;
1.911     bisitz   7085:   color: $fontmenu;
                   7086:   background: $tabbg;
                   7087:   list-style: none;
                   7088:   padding: 0;
                   7089:   margin: 0;
                   7090:   width: 100%;
1.995     raeburn  7091:   text-align: left;
1.1107    raeburn  7092:   float: left;
1.808     droeschl 7093: }
                   7094: 
1.897     wenzelju 7095: ul#LC_secondary_menu li {
1.911     bisitz   7096:   font-weight: bold;
                   7097:   line-height: 1.8em;
1.1107    raeburn  7098:   border-right: 1px solid black;
                   7099:   float: left;
                   7100: }
                   7101: 
                   7102: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7103:   background-color: $data_table_light;
                   7104: }
                   7105: 
                   7106: ul#LC_secondary_menu li a {
1.911     bisitz   7107:   padding: 0 0.8em;
1.1107    raeburn  7108: }
                   7109: 
                   7110: ul#LC_secondary_menu li ul {
                   7111:   display: none;
                   7112: }
                   7113: 
                   7114: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7115:   display: block;
                   7116:   position: absolute;
                   7117:   margin: 0;
                   7118:   padding: 0;
                   7119:   list-style:none;
                   7120:   float: none;
                   7121:   background-color: $data_table_light;
                   7122:   z-index: 2;
                   7123:   margin-left: -1px;
                   7124: }
                   7125: 
                   7126: ul#LC_secondary_menu li ul li {
                   7127:   font-size: 90%;
                   7128:   vertical-align: top;
                   7129:   border-left: 1px solid black;
1.911     bisitz   7130:   border-right: 1px solid black;
1.1119    raeburn  7131:   background-color: $data_table_light;
1.1107    raeburn  7132:   list-style:none;
                   7133:   float: none;
                   7134: }
                   7135: 
                   7136: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7137:   background-color: $data_table_dark;
1.807     droeschl 7138: }
                   7139: 
1.847     tempelho 7140: ul.LC_TabContent {
1.911     bisitz   7141:   display:block;
                   7142:   background: $sidebg;
                   7143:   border-bottom: solid 1px $lg_border_color;
                   7144:   list-style:none;
1.1020    raeburn  7145:   margin: -1px -10px 0 -10px;
1.911     bisitz   7146:   padding: 0;
1.693     droeschl 7147: }
                   7148: 
1.795     www      7149: ul.LC_TabContent li,
                   7150: ul.LC_TabContentBigger li {
1.911     bisitz   7151:   float:left;
1.741     harmsja  7152: }
1.795     www      7153: 
1.897     wenzelju 7154: ul#LC_secondary_menu li a {
1.911     bisitz   7155:   color: $fontmenu;
                   7156:   text-decoration: none;
1.693     droeschl 7157: }
1.795     www      7158: 
1.721     harmsja  7159: ul.LC_TabContent {
1.952     onken    7160:   min-height:20px;
1.721     harmsja  7161: }
1.795     www      7162: 
                   7163: ul.LC_TabContent li {
1.911     bisitz   7164:   vertical-align:middle;
1.959     onken    7165:   padding: 0 16px 0 10px;
1.911     bisitz   7166:   background-color:$tabbg;
                   7167:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7168:   border-left: solid 1px $font;
1.721     harmsja  7169: }
1.795     www      7170: 
1.847     tempelho 7171: ul.LC_TabContent .right {
1.911     bisitz   7172:   float:right;
1.847     tempelho 7173: }
                   7174: 
1.911     bisitz   7175: ul.LC_TabContent li a,
                   7176: ul.LC_TabContent li {
                   7177:   color:rgb(47,47,47);
                   7178:   text-decoration:none;
                   7179:   font-size:95%;
                   7180:   font-weight:bold;
1.952     onken    7181:   min-height:20px;
                   7182: }
                   7183: 
1.959     onken    7184: ul.LC_TabContent li a:hover,
                   7185: ul.LC_TabContent li a:focus {
1.952     onken    7186:   color: $button_hover;
1.959     onken    7187:   background:none;
                   7188:   outline:none;
1.952     onken    7189: }
                   7190: 
                   7191: ul.LC_TabContent li:hover {
                   7192:   color: $button_hover;
                   7193:   cursor:pointer;
1.721     harmsja  7194: }
1.795     www      7195: 
1.911     bisitz   7196: ul.LC_TabContent li.active {
1.952     onken    7197:   color: $font;
1.911     bisitz   7198:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7199:   border-bottom:solid 1px #FFFFFF;
                   7200:   cursor: default;
1.744     ehlerst  7201: }
1.795     www      7202: 
1.959     onken    7203: ul.LC_TabContent li.active a {
                   7204:   color:$font;
                   7205:   background:#FFFFFF;
                   7206:   outline: none;
                   7207: }
1.1047    raeburn  7208: 
                   7209: ul.LC_TabContent li.goback {
                   7210:   float: left;
                   7211:   border-left: none;
                   7212: }
                   7213: 
1.870     tempelho 7214: #maincoursedoc {
1.911     bisitz   7215:   clear:both;
1.870     tempelho 7216: }
                   7217: 
                   7218: ul.LC_TabContentBigger {
1.911     bisitz   7219:   display:block;
                   7220:   list-style:none;
                   7221:   padding: 0;
1.870     tempelho 7222: }
                   7223: 
1.795     www      7224: ul.LC_TabContentBigger li {
1.911     bisitz   7225:   vertical-align:bottom;
                   7226:   height: 30px;
                   7227:   font-size:110%;
                   7228:   font-weight:bold;
                   7229:   color: #737373;
1.841     tempelho 7230: }
                   7231: 
1.957     onken    7232: ul.LC_TabContentBigger li.active {
                   7233:   position: relative;
                   7234:   top: 1px;
                   7235: }
                   7236: 
1.870     tempelho 7237: ul.LC_TabContentBigger li a {
1.911     bisitz   7238:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7239:   height: 30px;
                   7240:   line-height: 30px;
                   7241:   text-align: center;
                   7242:   display: block;
                   7243:   text-decoration: none;
1.958     onken    7244:   outline: none;  
1.741     harmsja  7245: }
1.795     www      7246: 
1.870     tempelho 7247: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7248:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7249:   color:$font;
1.744     ehlerst  7250: }
1.795     www      7251: 
1.870     tempelho 7252: ul.LC_TabContentBigger li b {
1.911     bisitz   7253:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7254:   display: block;
                   7255:   float: left;
                   7256:   padding: 0 30px;
1.957     onken    7257:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7258: }
                   7259: 
1.956     onken    7260: ul.LC_TabContentBigger li:hover b {
                   7261:   color:$button_hover;
                   7262: }
                   7263: 
1.870     tempelho 7264: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7265:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7266:   color:$font;
1.957     onken    7267:   border: 0;
1.741     harmsja  7268: }
1.693     droeschl 7269: 
1.870     tempelho 7270: 
1.862     bisitz   7271: ul.LC_CourseBreadcrumbs {
                   7272:   background: $sidebg;
1.1020    raeburn  7273:   height: 2em;
1.862     bisitz   7274:   padding-left: 10px;
1.1020    raeburn  7275:   margin: 0;
1.862     bisitz   7276:   list-style-position: inside;
                   7277: }
                   7278: 
1.911     bisitz   7279: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7280: ol#LC_PathBreadcrumbs {
1.911     bisitz   7281:   padding-left: 10px;
                   7282:   margin: 0;
1.933     droeschl 7283:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7284: }
                   7285: 
1.911     bisitz   7286: ol#LC_MenuBreadcrumbs li,
                   7287: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7288: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7289:   display: inline;
1.933     droeschl 7290:   white-space: normal;  
1.693     droeschl 7291: }
                   7292: 
1.823     bisitz   7293: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7294: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7295:   text-decoration: none;
                   7296:   font-size:90%;
1.693     droeschl 7297: }
1.795     www      7298: 
1.969     droeschl 7299: ol#LC_MenuBreadcrumbs h1 {
                   7300:   display: inline;
                   7301:   font-size: 90%;
                   7302:   line-height: 2.5em;
                   7303:   margin: 0;
                   7304:   padding: 0;
                   7305: }
                   7306: 
1.795     www      7307: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7308:   text-decoration:none;
                   7309:   font-size:100%;
                   7310:   font-weight:bold;
1.693     droeschl 7311: }
1.795     www      7312: 
1.840     bisitz   7313: .LC_Box {
1.911     bisitz   7314:   border: solid 1px $lg_border_color;
                   7315:   padding: 0 10px 10px 10px;
1.746     neumanie 7316: }
1.795     www      7317: 
1.1020    raeburn  7318: .LC_DocsBox {
                   7319:   border: solid 1px $lg_border_color;
                   7320:   padding: 0 0 10px 10px;
                   7321: }
                   7322: 
1.795     www      7323: .LC_AboutMe_Image {
1.911     bisitz   7324:   float:left;
                   7325:   margin-right:10px;
1.747     neumanie 7326: }
1.795     www      7327: 
                   7328: .LC_Clear_AboutMe_Image {
1.911     bisitz   7329:   clear:left;
1.747     neumanie 7330: }
1.795     www      7331: 
1.721     harmsja  7332: dl.LC_ListStyleClean dt {
1.911     bisitz   7333:   padding-right: 5px;
                   7334:   display: table-header-group;
1.693     droeschl 7335: }
                   7336: 
1.721     harmsja  7337: dl.LC_ListStyleClean dd {
1.911     bisitz   7338:   display: table-row;
1.693     droeschl 7339: }
                   7340: 
1.721     harmsja  7341: .LC_ListStyleClean,
                   7342: .LC_ListStyleSimple,
                   7343: .LC_ListStyleNormal,
1.795     www      7344: .LC_ListStyleSpecial {
1.911     bisitz   7345:   /* display:block; */
                   7346:   list-style-position: inside;
                   7347:   list-style-type: none;
                   7348:   overflow: hidden;
                   7349:   padding: 0;
1.693     droeschl 7350: }
                   7351: 
1.721     harmsja  7352: .LC_ListStyleSimple li,
                   7353: .LC_ListStyleSimple dd,
                   7354: .LC_ListStyleNormal li,
                   7355: .LC_ListStyleNormal dd,
                   7356: .LC_ListStyleSpecial li,
1.795     www      7357: .LC_ListStyleSpecial dd {
1.911     bisitz   7358:   margin: 0;
                   7359:   padding: 5px 5px 5px 10px;
                   7360:   clear: both;
1.693     droeschl 7361: }
                   7362: 
1.721     harmsja  7363: .LC_ListStyleClean li,
                   7364: .LC_ListStyleClean dd {
1.911     bisitz   7365:   padding-top: 0;
                   7366:   padding-bottom: 0;
1.693     droeschl 7367: }
                   7368: 
1.721     harmsja  7369: .LC_ListStyleSimple dd,
1.795     www      7370: .LC_ListStyleSimple li {
1.911     bisitz   7371:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7372: }
                   7373: 
1.721     harmsja  7374: .LC_ListStyleSpecial li,
                   7375: .LC_ListStyleSpecial dd {
1.911     bisitz   7376:   list-style-type: none;
                   7377:   background-color: RGB(220, 220, 220);
                   7378:   margin-bottom: 4px;
1.693     droeschl 7379: }
                   7380: 
1.721     harmsja  7381: table.LC_SimpleTable {
1.911     bisitz   7382:   margin:5px;
                   7383:   border:solid 1px $lg_border_color;
1.795     www      7384: }
1.693     droeschl 7385: 
1.721     harmsja  7386: table.LC_SimpleTable tr {
1.911     bisitz   7387:   padding: 0;
                   7388:   border:solid 1px $lg_border_color;
1.693     droeschl 7389: }
1.795     www      7390: 
                   7391: table.LC_SimpleTable thead {
1.911     bisitz   7392:   background:rgb(220,220,220);
1.693     droeschl 7393: }
                   7394: 
1.721     harmsja  7395: div.LC_columnSection {
1.911     bisitz   7396:   display: block;
                   7397:   clear: both;
                   7398:   overflow: hidden;
                   7399:   margin: 0;
1.693     droeschl 7400: }
                   7401: 
1.721     harmsja  7402: div.LC_columnSection>* {
1.911     bisitz   7403:   float: left;
                   7404:   margin: 10px 20px 10px 0;
                   7405:   overflow:hidden;
1.693     droeschl 7406: }
1.721     harmsja  7407: 
1.795     www      7408: table em {
1.911     bisitz   7409:   font-weight: bold;
                   7410:   font-style: normal;
1.748     schulted 7411: }
1.795     www      7412: 
1.779     bisitz   7413: table.LC_tableBrowseRes,
1.795     www      7414: table.LC_tableOfContent {
1.911     bisitz   7415:   border:none;
                   7416:   border-spacing: 1px;
                   7417:   padding: 3px;
                   7418:   background-color: #FFFFFF;
                   7419:   font-size: 90%;
1.753     droeschl 7420: }
1.789     droeschl 7421: 
1.911     bisitz   7422: table.LC_tableOfContent {
                   7423:   border-collapse: collapse;
1.789     droeschl 7424: }
                   7425: 
1.771     droeschl 7426: table.LC_tableBrowseRes a,
1.768     schulted 7427: table.LC_tableOfContent a {
1.911     bisitz   7428:   background-color: transparent;
                   7429:   text-decoration: none;
1.753     droeschl 7430: }
                   7431: 
1.795     www      7432: table.LC_tableOfContent img {
1.911     bisitz   7433:   border: none;
                   7434:   height: 1.3em;
                   7435:   vertical-align: text-bottom;
                   7436:   margin-right: 0.3em;
1.753     droeschl 7437: }
1.757     schulted 7438: 
1.795     www      7439: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7440:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7441: }
                   7442: 
1.795     www      7443: a#LC_content_toolbar_everything {
1.911     bisitz   7444:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7445: }
                   7446: 
1.795     www      7447: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7448:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7449: }
                   7450: 
1.795     www      7451: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7452:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7453: }
                   7454: 
1.795     www      7455: a#LC_content_toolbar_changefolder {
1.911     bisitz   7456:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7457: }
                   7458: 
1.795     www      7459: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7460:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7461: }
                   7462: 
1.1043    raeburn  7463: a#LC_content_toolbar_edittoplevel {
                   7464:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7465: }
                   7466: 
1.795     www      7467: ul#LC_toolbar li a:hover {
1.911     bisitz   7468:   background-position: bottom center;
1.757     schulted 7469: }
                   7470: 
1.795     www      7471: ul#LC_toolbar {
1.911     bisitz   7472:   padding: 0;
                   7473:   margin: 2px;
                   7474:   list-style:none;
                   7475:   position:relative;
                   7476:   background-color:white;
1.1082    raeburn  7477:   overflow: auto;
1.757     schulted 7478: }
                   7479: 
1.795     www      7480: ul#LC_toolbar li {
1.911     bisitz   7481:   border:1px solid white;
                   7482:   padding: 0;
                   7483:   margin: 0;
                   7484:   float: left;
                   7485:   display:inline;
                   7486:   vertical-align:middle;
1.1082    raeburn  7487:   white-space: nowrap;
1.911     bisitz   7488: }
1.757     schulted 7489: 
1.783     amueller 7490: 
1.795     www      7491: a.LC_toolbarItem {
1.911     bisitz   7492:   display:block;
                   7493:   padding: 0;
                   7494:   margin: 0;
                   7495:   height: 32px;
                   7496:   width: 32px;
                   7497:   color:white;
                   7498:   border: none;
                   7499:   background-repeat:no-repeat;
                   7500:   background-color:transparent;
1.757     schulted 7501: }
                   7502: 
1.915     droeschl 7503: ul.LC_funclist {
                   7504:     margin: 0;
                   7505:     padding: 0.5em 1em 0.5em 0;
                   7506: }
                   7507: 
1.933     droeschl 7508: ul.LC_funclist > li:first-child {
                   7509:     font-weight:bold; 
                   7510:     margin-left:0.8em;
                   7511: }
                   7512: 
1.915     droeschl 7513: ul.LC_funclist + ul.LC_funclist {
                   7514:     /* 
                   7515:        left border as a seperator if we have more than
                   7516:        one list 
                   7517:     */
                   7518:     border-left: 1px solid $sidebg;
                   7519:     /* 
                   7520:        this hides the left border behind the border of the 
                   7521:        outer box if element is wrapped to the next 'line' 
                   7522:     */
                   7523:     margin-left: -1px;
                   7524: }
                   7525: 
1.843     bisitz   7526: ul.LC_funclist li {
1.915     droeschl 7527:   display: inline;
1.782     bisitz   7528:   white-space: nowrap;
1.915     droeschl 7529:   margin: 0 0 0 25px;
                   7530:   line-height: 150%;
1.782     bisitz   7531: }
                   7532: 
1.974     wenzelju 7533: .LC_hidden {
                   7534:   display: none;
                   7535: }
                   7536: 
1.1030    www      7537: .LCmodal-overlay {
                   7538: 		position:fixed;
                   7539: 		top:0;
                   7540: 		right:0;
                   7541: 		bottom:0;
                   7542: 		left:0;
                   7543: 		height:100%;
                   7544: 		width:100%;
                   7545: 		margin:0;
                   7546: 		padding:0;
                   7547: 		background:#999;
                   7548: 		opacity:.75;
                   7549: 		filter: alpha(opacity=75);
                   7550: 		-moz-opacity: 0.75;
                   7551: 		z-index:101;
                   7552: }
                   7553: 
                   7554: * html .LCmodal-overlay {   
                   7555: 		position: absolute;
                   7556: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7557: }
                   7558: 
                   7559: .LCmodal-window {
                   7560: 		position:fixed;
                   7561: 		top:50%;
                   7562: 		left:50%;
                   7563: 		margin:0;
                   7564: 		padding:0;
                   7565: 		z-index:102;
                   7566: 	}
                   7567: 
                   7568: * html .LCmodal-window {
                   7569: 		position:absolute;
                   7570: }
                   7571: 
                   7572: .LCclose-window {
                   7573: 		position:absolute;
                   7574: 		width:32px;
                   7575: 		height:32px;
                   7576: 		right:8px;
                   7577: 		top:8px;
                   7578: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7579: 		text-indent:-99999px;
                   7580: 		overflow:hidden;
                   7581: 		cursor:pointer;
                   7582: }
                   7583: 
1.1100    raeburn  7584: /*
                   7585:   styles used by TTH when "Default set of options to pass to tth/m
                   7586:   when converting TeX" in course settings has been set
                   7587: 
                   7588:   option passed: -t
                   7589: 
                   7590: */
                   7591: 
                   7592: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7593: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7594: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7595: td div.norm {line-height:normal;}
                   7596: 
                   7597: /*
                   7598:   option passed -y3
                   7599: */
                   7600: 
                   7601: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7602: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7603: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7604: 
1.343     albertel 7605: END
                   7606: }
                   7607: 
1.306     albertel 7608: =pod
                   7609: 
                   7610: =item * &headtag()
                   7611: 
                   7612: Returns a uniform footer for LON-CAPA web pages.
                   7613: 
1.307     albertel 7614: Inputs: $title - optional title for the head
                   7615:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7616:         $args - optional arguments
1.319     albertel 7617:             force_register - if is true call registerurl so the remote is 
                   7618:                              informed
1.415     albertel 7619:             redirect       -> array ref of
                   7620:                                    1- seconds before redirect occurs
                   7621:                                    2- url to redirect to
                   7622:                                    3- whether the side effect should occur
1.315     albertel 7623:                            (side effect of setting 
                   7624:                                $env{'internal.head.redirect'} to the url 
                   7625:                                redirected too)
1.352     albertel 7626:             domain         -> force to color decorate a page for a specific
                   7627:                                domain
                   7628:             function       -> force usage of a specific rolish color scheme
                   7629:             bgcolor        -> override the default page bgcolor
1.460     albertel 7630:             no_auto_mt_title
                   7631:                            -> prevent &mt()ing the title arg
1.464     albertel 7632: 
1.306     albertel 7633: =cut
                   7634: 
                   7635: sub headtag {
1.313     albertel 7636:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7637:     
1.363     albertel 7638:     my $function = $args->{'function'} || &get_users_function();
                   7639:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7640:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  7641:     my $httphost = $args->{'use_absolute'};
1.418     albertel 7642:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7643: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7644: 		   #time(),
1.418     albertel 7645: 		   $env{'environment.color.timestamp'},
1.363     albertel 7646: 		   $function,$domain,$bgcolor);
                   7647: 
1.369     www      7648:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7649: 
1.308     albertel 7650:     my $result =
                   7651: 	'<head>'.
1.1160    raeburn  7652: 	&font_settings($args);
1.319     albertel 7653: 
1.1188    raeburn  7654:     my $inhibitprint;
                   7655:     if ($args->{'print_suppress'}) {
                   7656:         $inhibitprint = &print_suppression();
                   7657:     }
1.1064    raeburn  7658: 
1.461     albertel 7659:     if (!$args->{'frameset'}) {
                   7660: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7661:     }
1.962     droeschl 7662:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   7663:         $result .= Apache::lonxml::display_title();
1.319     albertel 7664:     }
1.436     albertel 7665:     if (!$args->{'no_nav_bar'} 
                   7666: 	&& !$args->{'only_body'}
                   7667: 	&& !$args->{'frameset'}) {
1.1154    raeburn  7668: 	$result .= &help_menu_js($httphost);
1.1032    www      7669:         $result.=&modal_window();
1.1038    www      7670:         $result.=&togglebox_script();
1.1034    www      7671:         $result.=&wishlist_window();
1.1041    www      7672:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7673:     } else {
                   7674:         if ($args->{'add_modal'}) {
                   7675:            $result.=&modal_window();
                   7676:         }
                   7677:         if ($args->{'add_wishlist'}) {
                   7678:            $result.=&wishlist_window();
                   7679:         }
1.1038    www      7680:         if ($args->{'add_togglebox'}) {
                   7681:            $result.=&togglebox_script();
                   7682:         }
1.1041    www      7683:         if ($args->{'add_progressbar'}) {
                   7684:            $result.=&LCprogressbarUpdate_script();
                   7685:         }
1.436     albertel 7686:     }
1.314     albertel 7687:     if (ref($args->{'redirect'})) {
1.414     albertel 7688: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7689: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7690: 	if (!$inhibit_continue) {
                   7691: 	    $env{'internal.head.redirect'} = $url;
                   7692: 	}
1.313     albertel 7693: 	$result.=<<ADDMETA
                   7694: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7695: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7696: ADDMETA
                   7697:     }
1.306     albertel 7698:     if (!defined($title)) {
                   7699: 	$title = 'The LearningOnline Network with CAPA';
                   7700:     }
1.460     albertel 7701:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   7702:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  7703: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   7704:     if (!$args->{'frameset'}) {
                   7705:         $result .= ' /';
                   7706:     }
                   7707:     $result .= '>' 
1.1064    raeburn  7708:         .$inhibitprint
1.414     albertel 7709: 	.$head_extra;
1.1137    raeburn  7710:     if ($env{'browser.mobile'}) {
                   7711:         $result .= '
                   7712: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   7713: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   7714:     }
1.962     droeschl 7715:     return $result.'</head>';
1.306     albertel 7716: }
                   7717: 
                   7718: =pod
                   7719: 
1.340     albertel 7720: =item * &font_settings()
                   7721: 
                   7722: Returns neccessary <meta> to set the proper encoding
                   7723: 
1.1160    raeburn  7724: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 7725: 
                   7726: =cut
                   7727: 
                   7728: sub font_settings {
1.1160    raeburn  7729:     my ($args) = @_;
1.340     albertel 7730:     my $headerstring='';
1.1160    raeburn  7731:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   7732:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  7733:         $headerstring.=
                   7734:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   7735:         if (!$args->{'frameset'}) {
                   7736: 	    $headerstring.= ' /';
                   7737:         }
                   7738: 	$headerstring .= '>'."\n";
1.340     albertel 7739:     }
                   7740:     return $headerstring;
                   7741: }
                   7742: 
1.341     albertel 7743: =pod
                   7744: 
1.1064    raeburn  7745: =item * &print_suppression()
                   7746: 
                   7747: In course context returns css which causes the body to be blank when media="print",
                   7748: if printout generation is unavailable for the current resource.
                   7749: 
                   7750: This could be because:
                   7751: 
                   7752: (a) printstartdate is in the future
                   7753: 
                   7754: (b) printenddate is in the past
                   7755: 
                   7756: (c) there is an active exam block with "printout"
                   7757: functionality blocked
                   7758: 
                   7759: Users with pav, pfo or evb privileges are exempt.
                   7760: 
                   7761: Inputs: none
                   7762: 
                   7763: =cut
                   7764: 
                   7765: 
                   7766: sub print_suppression {
                   7767:     my $noprint;
                   7768:     if ($env{'request.course.id'}) {
                   7769:         my $scope = $env{'request.course.id'};
                   7770:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7771:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   7772:             return;
                   7773:         }
                   7774:         if ($env{'request.course.sec'} ne '') {
                   7775:             $scope .= "/$env{'request.course.sec'}";
                   7776:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7777:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  7778:                 return;
1.1064    raeburn  7779:             }
                   7780:         }
                   7781:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7782:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1189    raeburn  7783:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  7784:         if ($blocked) {
                   7785:             my $checkrole = "cm./$cdom/$cnum";
                   7786:             if ($env{'request.course.sec'} ne '') {
                   7787:                 $checkrole .= "/$env{'request.course.sec'}";
                   7788:             }
                   7789:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   7790:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   7791:                 $noprint = 1;
                   7792:             }
                   7793:         }
                   7794:         unless ($noprint) {
                   7795:             my $symb = &Apache::lonnet::symbread();
                   7796:             if ($symb ne '') {
                   7797:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   7798:                 if (ref($navmap)) {
                   7799:                     my $res = $navmap->getBySymb($symb);
                   7800:                     if (ref($res)) {
                   7801:                         if (!$res->resprintable()) {
                   7802:                             $noprint = 1;
                   7803:                         }
                   7804:                     }
                   7805:                 }
                   7806:             }
                   7807:         }
                   7808:         if ($noprint) {
                   7809:             return <<"ENDSTYLE";
                   7810: <style type="text/css" media="print">
                   7811:     body { display:none }
                   7812: </style>
                   7813: ENDSTYLE
                   7814:         }
                   7815:     }
                   7816:     return;
                   7817: }
                   7818: 
                   7819: =pod
                   7820: 
1.341     albertel 7821: =item * &xml_begin()
                   7822: 
                   7823: Returns the needed doctype and <html>
                   7824: 
                   7825: Inputs: none
                   7826: 
                   7827: =cut
                   7828: 
                   7829: sub xml_begin {
1.1168    raeburn  7830:     my ($is_frameset) = @_;
1.341     albertel 7831:     my $output='';
                   7832: 
                   7833:     if ($env{'browser.mathml'}) {
                   7834: 	$output='<?xml version="1.0"?>'
                   7835:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   7836: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   7837:             
                   7838: #	    .'<!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">] >'
                   7839: 	    .'<!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">'
                   7840:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   7841: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  7842:     } elsif ($is_frameset) {
                   7843:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   7844:                 '<html>'."\n";
1.341     albertel 7845:     } else {
1.1168    raeburn  7846: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   7847:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 7848:     }
                   7849:     return $output;
                   7850: }
1.340     albertel 7851: 
                   7852: =pod
                   7853: 
1.306     albertel 7854: =item * &start_page()
                   7855: 
                   7856: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   7857: 
1.648     raeburn  7858: Inputs:
                   7859: 
                   7860: =over 4
                   7861: 
                   7862: $title - optional title for the page
                   7863: 
                   7864: $head_extra - optional extra HTML to incude inside the <head>
                   7865: 
                   7866: $args - additional optional args supported are:
                   7867: 
                   7868: =over 8
                   7869: 
                   7870:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 7871:                                     arg on
1.814     bisitz   7872:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  7873:              add_entries    -> additional attributes to add to the  <body>
                   7874:              domain         -> force to color decorate a page for a 
1.317     albertel 7875:                                     specific domain
1.648     raeburn  7876:              function       -> force usage of a specific rolish color
1.317     albertel 7877:                                     scheme
1.648     raeburn  7878:              redirect       -> see &headtag()
                   7879:              bgcolor        -> override the default page bg color
                   7880:              js_ready       -> return a string ready for being used in 
1.317     albertel 7881:                                     a javascript writeln
1.648     raeburn  7882:              html_encode    -> return a string ready for being used in 
1.320     albertel 7883:                                     a html attribute
1.648     raeburn  7884:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 7885:                                     $forcereg arg
1.648     raeburn  7886:              frameset       -> if true will start with a <frameset>
1.330     albertel 7887:                                     rather than <body>
1.648     raeburn  7888:              skip_phases    -> hash ref of 
1.338     albertel 7889:                                     head -> skip the <html><head> generation
                   7890:                                     body -> skip all <body> generation
1.648     raeburn  7891:              no_auto_mt_title -> prevent &mt()ing the title arg
                   7892:              inherit_jsmath -> when creating popup window in a page,
                   7893:                                     should it have jsmath forced on by the
                   7894:                                     current page
1.867     kalberla 7895:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  7896:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1096    raeburn  7897:              group          -> includes the current group, if page is for a 
                   7898:                                specific group  
1.361     albertel 7899: 
1.648     raeburn  7900: =back
1.460     albertel 7901: 
1.648     raeburn  7902: =back
1.562     albertel 7903: 
1.306     albertel 7904: =cut
                   7905: 
                   7906: sub start_page {
1.309     albertel 7907:     my ($title,$head_extra,$args) = @_;
1.318     albertel 7908:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 7909: 
1.315     albertel 7910:     $env{'internal.start_page'}++;
1.1096    raeburn  7911:     my ($result,@advtools);
1.964     droeschl 7912: 
1.338     albertel 7913:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  7914:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 7915:     }
                   7916:     
                   7917:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   7918: 	if ($args->{'frameset'}) {
                   7919: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   7920: 						$args->{'add_entries'});
                   7921: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   7922:         } else {
                   7923:             $result .=
                   7924:                 &bodytag($title, 
                   7925:                          $args->{'function'},       $args->{'add_entries'},
                   7926:                          $args->{'only_body'},      $args->{'domain'},
                   7927:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  7928:                          $args->{'bgcolor'},        $args,
                   7929:                          \@advtools);
1.831     bisitz   7930:         }
1.330     albertel 7931:     }
1.338     albertel 7932: 
1.315     albertel 7933:     if ($args->{'js_ready'}) {
1.713     kaisler  7934: 		$result = &js_ready($result);
1.315     albertel 7935:     }
1.320     albertel 7936:     if ($args->{'html_encode'}) {
1.713     kaisler  7937: 		$result = &html_encode($result);
                   7938:     }
                   7939: 
1.813     bisitz   7940:     # Preparation for new and consistent functionlist at top of screen
                   7941:     # if ($args->{'functionlist'}) {
                   7942:     #            $result .= &build_functionlist();
                   7943:     #}
                   7944: 
1.964     droeschl 7945:     # Don't add anything more if only_body wanted or in const space
                   7946:     return $result if    $args->{'only_body'} 
                   7947:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   7948: 
                   7949:     #Breadcrumbs
1.758     kaisler  7950:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   7951: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   7952: 		#if any br links exists, add them to the breadcrumbs
                   7953: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   7954: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   7955: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   7956: 			}
                   7957: 		}
1.1096    raeburn  7958:                 # if @advtools array contains items add then to the breadcrumbs
                   7959:                 if (@advtools > 0) {
                   7960:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   7961:                 }
1.758     kaisler  7962: 
                   7963: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   7964: 		if(exists($args->{'bread_crumbs_component'})){
                   7965: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
                   7966: 		}else{
                   7967: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
                   7968: 		}
1.320     albertel 7969:     }
1.315     albertel 7970:     return $result;
1.306     albertel 7971: }
                   7972: 
                   7973: sub end_page {
1.315     albertel 7974:     my ($args) = @_;
                   7975:     $env{'internal.end_page'}++;
1.330     albertel 7976:     my $result;
1.335     albertel 7977:     if ($args->{'discussion'}) {
                   7978: 	my ($target,$parser);
                   7979: 	if (ref($args->{'discussion'})) {
                   7980: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   7981: 				$args->{'discussion'}{'parser'});
                   7982: 	}
                   7983: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   7984:     }
1.330     albertel 7985:     if ($args->{'frameset'}) {
                   7986: 	$result .= '</frameset>';
                   7987:     } else {
1.635     raeburn  7988: 	$result .= &endbodytag($args);
1.330     albertel 7989:     }
1.1080    raeburn  7990:     unless ($args->{'notbody'}) {
                   7991:         $result .= "\n</html>";
                   7992:     }
1.330     albertel 7993: 
1.315     albertel 7994:     if ($args->{'js_ready'}) {
1.317     albertel 7995: 	$result = &js_ready($result);
1.315     albertel 7996:     }
1.335     albertel 7997: 
1.320     albertel 7998:     if ($args->{'html_encode'}) {
                   7999: 	$result = &html_encode($result);
                   8000:     }
1.335     albertel 8001: 
1.315     albertel 8002:     return $result;
                   8003: }
                   8004: 
1.1034    www      8005: sub wishlist_window {
                   8006:     return(<<'ENDWISHLIST');
1.1046    raeburn  8007: <script type="text/javascript">
1.1034    www      8008: // <![CDATA[
                   8009: // <!-- BEGIN LON-CAPA Internal
                   8010: function set_wishlistlink(title, path) {
                   8011:     if (!title) {
                   8012:         title = document.title;
                   8013:         title = title.replace(/^LON-CAPA /,'');
                   8014:     }
1.1175    raeburn  8015:     title = encodeURIComponent(title);
1.1203    raeburn  8016:     title = title.replace("'","\\\'");
1.1034    www      8017:     if (!path) {
                   8018:         path = location.pathname;
                   8019:     }
1.1175    raeburn  8020:     path = encodeURIComponent(path);
1.1203    raeburn  8021:     path = path.replace("'","\\\'");
1.1034    www      8022:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8023:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8024: }
                   8025: // END LON-CAPA Internal -->
                   8026: // ]]>
                   8027: </script>
                   8028: ENDWISHLIST
                   8029: }
                   8030: 
1.1030    www      8031: sub modal_window {
                   8032:     return(<<'ENDMODAL');
1.1046    raeburn  8033: <script type="text/javascript">
1.1030    www      8034: // <![CDATA[
                   8035: // <!-- BEGIN LON-CAPA Internal
                   8036: var modalWindow = {
                   8037: 	parent:"body",
                   8038: 	windowId:null,
                   8039: 	content:null,
                   8040: 	width:null,
                   8041: 	height:null,
                   8042: 	close:function()
                   8043: 	{
                   8044: 	        $(".LCmodal-window").remove();
                   8045: 	        $(".LCmodal-overlay").remove();
                   8046: 	},
                   8047: 	open:function()
                   8048: 	{
                   8049: 		var modal = "";
                   8050: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8051: 		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;\">";
                   8052: 		modal += this.content;
                   8053: 		modal += "</div>";	
                   8054: 
                   8055: 		$(this.parent).append(modal);
                   8056: 
                   8057: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8058: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8059: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8060: 	}
                   8061: };
1.1140    raeburn  8062: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8063: 	{
1.1203    raeburn  8064:                 source = source.replace("'","&#39;");
1.1030    www      8065: 		modalWindow.windowId = "myModal";
                   8066: 		modalWindow.width = width;
                   8067: 		modalWindow.height = height;
1.1196    raeburn  8068: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8069: 		modalWindow.open();
                   8070: 	};	
                   8071: // END LON-CAPA Internal -->
                   8072: // ]]>
                   8073: </script>
                   8074: ENDMODAL
                   8075: }
                   8076: 
                   8077: sub modal_link {
1.1140    raeburn  8078:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8079:     unless ($width) { $width=480; }
                   8080:     unless ($height) { $height=400; }
1.1031    www      8081:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  8082:     unless ($transparency) { $transparency='true'; }
                   8083: 
1.1074    raeburn  8084:     my $target_attr;
                   8085:     if (defined($target)) {
                   8086:         $target_attr = 'target="'.$target.'"';
                   8087:     }
                   8088:     return <<"ENDLINK";
1.1140    raeburn  8089: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  8090:            $linktext</a>
                   8091: ENDLINK
1.1030    www      8092: }
                   8093: 
1.1032    www      8094: sub modal_adhoc_script {
                   8095:     my ($funcname,$width,$height,$content)=@_;
                   8096:     return (<<ENDADHOC);
1.1046    raeburn  8097: <script type="text/javascript">
1.1032    www      8098: // <![CDATA[
                   8099:         var $funcname = function()
                   8100:         {
                   8101:                 modalWindow.windowId = "myModal";
                   8102:                 modalWindow.width = $width;
                   8103:                 modalWindow.height = $height;
                   8104:                 modalWindow.content = '$content';
                   8105:                 modalWindow.open();
                   8106:         };  
                   8107: // ]]>
                   8108: </script>
                   8109: ENDADHOC
                   8110: }
                   8111: 
1.1041    www      8112: sub modal_adhoc_inner {
                   8113:     my ($funcname,$width,$height,$content)=@_;
                   8114:     my $innerwidth=$width-20;
                   8115:     $content=&js_ready(
1.1140    raeburn  8116:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   8117:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8118:                  $content.
1.1041    www      8119:                  &end_scrollbox().
1.1140    raeburn  8120:                  &end_page()
1.1041    www      8121:              );
                   8122:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   8123: }
                   8124: 
                   8125: sub modal_adhoc_window {
                   8126:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   8127:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   8128:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8129: }
                   8130: 
                   8131: sub modal_adhoc_launch {
                   8132:     my ($funcname,$width,$height,$content)=@_;
                   8133:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8134: <script type="text/javascript">
                   8135: // <![CDATA[
                   8136: $funcname();
                   8137: // ]]>
                   8138: </script>
                   8139: ENDLAUNCH
                   8140: }
                   8141: 
                   8142: sub modal_adhoc_close {
                   8143:     return (<<ENDCLOSE);
                   8144: <script type="text/javascript">
                   8145: // <![CDATA[
                   8146: modalWindow.close();
                   8147: // ]]>
                   8148: </script>
                   8149: ENDCLOSE
                   8150: }
                   8151: 
1.1038    www      8152: sub togglebox_script {
                   8153:    return(<<ENDTOGGLE);
                   8154: <script type="text/javascript"> 
                   8155: // <![CDATA[
                   8156: function LCtoggleDisplay(id,hidetext,showtext) {
                   8157:    link = document.getElementById(id + "link").childNodes[0];
                   8158:    with (document.getElementById(id).style) {
                   8159:       if (display == "none" ) {
                   8160:           display = "inline";
                   8161:           link.nodeValue = hidetext;
                   8162:         } else {
                   8163:           display = "none";
                   8164:           link.nodeValue = showtext;
                   8165:        }
                   8166:    }
                   8167: }
                   8168: // ]]>
                   8169: </script>
                   8170: ENDTOGGLE
                   8171: }
                   8172: 
1.1039    www      8173: sub start_togglebox {
                   8174:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8175:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8176:     unless ($showtext) { $showtext=&mt('show'); }
                   8177:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8178:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8179:     return &start_data_table().
                   8180:            &start_data_table_header_row().
                   8181:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8182:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8183:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8184:            &end_data_table_header_row().
                   8185:            '<tr id="'.$id.'" style="display:none""><td>';
                   8186: }
                   8187: 
                   8188: sub end_togglebox {
                   8189:     return '</td></tr>'.&end_data_table();
                   8190: }
                   8191: 
1.1041    www      8192: sub LCprogressbar_script {
1.1045    www      8193:    my ($id)=@_;
1.1041    www      8194:    return(<<ENDPROGRESS);
                   8195: <script type="text/javascript">
                   8196: // <![CDATA[
1.1045    www      8197: \$('#progressbar$id').progressbar({
1.1041    www      8198:   value: 0,
                   8199:   change: function(event, ui) {
                   8200:     var newVal = \$(this).progressbar('option', 'value');
                   8201:     \$('.pblabel', this).text(LCprogressTxt);
                   8202:   }
                   8203: });
                   8204: // ]]>
                   8205: </script>
                   8206: ENDPROGRESS
                   8207: }
                   8208: 
                   8209: sub LCprogressbarUpdate_script {
                   8210:    return(<<ENDPROGRESSUPDATE);
                   8211: <style type="text/css">
                   8212: .ui-progressbar { position:relative; }
                   8213: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8214: </style>
                   8215: <script type="text/javascript">
                   8216: // <![CDATA[
1.1045    www      8217: var LCprogressTxt='---';
                   8218: 
                   8219: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      8220:    LCprogressTxt=progresstext;
1.1045    www      8221:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      8222: }
                   8223: // ]]>
                   8224: </script>
                   8225: ENDPROGRESSUPDATE
                   8226: }
                   8227: 
1.1042    www      8228: my $LClastpercent;
1.1045    www      8229: my $LCidcnt;
                   8230: my $LCcurrentid;
1.1042    www      8231: 
1.1041    www      8232: sub LCprogressbar {
1.1042    www      8233:     my ($r)=(@_);
                   8234:     $LClastpercent=0;
1.1045    www      8235:     $LCidcnt++;
                   8236:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      8237:     my $starting=&mt('Starting');
                   8238:     my $content=(<<ENDPROGBAR);
1.1045    www      8239:   <div id="progressbar$LCcurrentid">
1.1041    www      8240:     <span class="pblabel">$starting</span>
                   8241:   </div>
                   8242: ENDPROGBAR
1.1045    www      8243:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      8244: }
                   8245: 
                   8246: sub LCprogressbarUpdate {
1.1042    www      8247:     my ($r,$val,$text)=@_;
                   8248:     unless ($val) { 
                   8249:        if ($LClastpercent) {
                   8250:            $val=$LClastpercent;
                   8251:        } else {
                   8252:            $val=0;
                   8253:        }
                   8254:     }
1.1041    www      8255:     if ($val<0) { $val=0; }
                   8256:     if ($val>100) { $val=0; }
1.1042    www      8257:     $LClastpercent=$val;
1.1041    www      8258:     unless ($text) { $text=$val.'%'; }
                   8259:     $text=&js_ready($text);
1.1044    www      8260:     &r_print($r,<<ENDUPDATE);
1.1041    www      8261: <script type="text/javascript">
                   8262: // <![CDATA[
1.1045    www      8263: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      8264: // ]]>
                   8265: </script>
                   8266: ENDUPDATE
1.1035    www      8267: }
                   8268: 
1.1042    www      8269: sub LCprogressbarClose {
                   8270:     my ($r)=@_;
                   8271:     $LClastpercent=0;
1.1044    www      8272:     &r_print($r,<<ENDCLOSE);
1.1042    www      8273: <script type="text/javascript">
                   8274: // <![CDATA[
1.1045    www      8275: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8276: // ]]>
                   8277: </script>
                   8278: ENDCLOSE
1.1044    www      8279: }
                   8280: 
                   8281: sub r_print {
                   8282:     my ($r,$to_print)=@_;
                   8283:     if ($r) {
                   8284:       $r->print($to_print);
                   8285:       $r->rflush();
                   8286:     } else {
                   8287:       print($to_print);
                   8288:     }
1.1042    www      8289: }
                   8290: 
1.320     albertel 8291: sub html_encode {
                   8292:     my ($result) = @_;
                   8293: 
1.322     albertel 8294:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8295:     
                   8296:     return $result;
                   8297: }
1.1044    www      8298: 
1.317     albertel 8299: sub js_ready {
                   8300:     my ($result) = @_;
                   8301: 
1.323     albertel 8302:     $result =~ s/[\n\r]/ /xmsg;
                   8303:     $result =~ s/\\/\\\\/xmsg;
                   8304:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8305:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8306:     
                   8307:     return $result;
                   8308: }
                   8309: 
1.315     albertel 8310: sub validate_page {
                   8311:     if (  exists($env{'internal.start_page'})
1.316     albertel 8312: 	  &&     $env{'internal.start_page'} > 1) {
                   8313: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 8314: 				 $env{'internal.start_page'}.' '.
1.316     albertel 8315: 				 $ENV{'request.filename'});
1.315     albertel 8316:     }
                   8317:     if (  exists($env{'internal.end_page'})
1.316     albertel 8318: 	  &&     $env{'internal.end_page'} > 1) {
                   8319: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 8320: 				 $env{'internal.end_page'}.' '.
1.316     albertel 8321: 				 $env{'request.filename'});
1.315     albertel 8322:     }
                   8323:     if (     exists($env{'internal.start_page'})
                   8324: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 8325: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   8326: 				 $env{'request.filename'});
1.315     albertel 8327:     }
                   8328:     if (   ! exists($env{'internal.start_page'})
                   8329: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 8330: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   8331: 				 $env{'request.filename'});
1.315     albertel 8332:     }
1.306     albertel 8333: }
1.315     albertel 8334: 
1.996     www      8335: 
                   8336: sub start_scrollbox {
1.1140    raeburn  8337:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  8338:     unless ($outerwidth) { $outerwidth='520px'; }
                   8339:     unless ($width) { $width='500px'; }
                   8340:     unless ($height) { $height='200px'; }
1.1075    raeburn  8341:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  8342:     if ($id ne '') {
1.1140    raeburn  8343:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  8344:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  8345:     }
1.1075    raeburn  8346:     if ($bgcolor ne '') {
                   8347:         $tdcol = "background-color: $bgcolor;";
                   8348:     }
1.1137    raeburn  8349:     my $nicescroll_js;
                   8350:     if ($env{'browser.mobile'}) {
1.1140    raeburn  8351:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   8352:     }
                   8353:     return <<"END";
                   8354: $nicescroll_js
                   8355: 
                   8356: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   8357: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   8358: END
                   8359: }
                   8360: 
                   8361: sub end_scrollbox {
                   8362:     return '</div></td></tr></table>';
                   8363: }
                   8364: 
                   8365: sub nicescroll_javascript {
                   8366:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   8367:     my %options;
                   8368:     if (ref($cursor) eq 'HASH') {
                   8369:         %options = %{$cursor};
                   8370:     }
                   8371:     unless ($options{'railalign'} =~ /^left|right$/) {
                   8372:         $options{'railalign'} = 'left';
                   8373:     }
                   8374:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8375:         my $function  = &get_users_function();
                   8376:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  8377:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  8378:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  8379:         }
1.1140    raeburn  8380:     }
                   8381:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   8382:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  8383:             $options{'cursoropacity'}='1.0';
                   8384:         }
1.1140    raeburn  8385:     } else {
                   8386:         $options{'cursoropacity'}='1.0';
                   8387:     }
                   8388:     if ($options{'cursorfixedheight'} eq 'none') {
                   8389:         delete($options{'cursorfixedheight'});
                   8390:     } else {
                   8391:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   8392:     }
                   8393:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   8394:         delete($options{'railoffset'});
                   8395:     }
                   8396:     my @niceoptions;
                   8397:     while (my($key,$value) = each(%options)) {
                   8398:         if ($value =~ /^\{.+\}$/) {
                   8399:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  8400:         } else {
1.1140    raeburn  8401:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  8402:         }
1.1140    raeburn  8403:     }
                   8404:     my $nicescroll_js = '
1.1137    raeburn  8405: $(document).ready(
1.1140    raeburn  8406:       function() {
                   8407:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   8408:       }
1.1137    raeburn  8409: );
                   8410: ';
1.1140    raeburn  8411:     if ($framecheck) {
                   8412:         $nicescroll_js .= '
                   8413: function expand_div(caller) {
                   8414:     if (top === self) {
                   8415:         document.getElementById("'.$id.'").style.width = "auto";
                   8416:         document.getElementById("'.$id.'").style.height = "auto";
                   8417:     } else {
                   8418:         try {
                   8419:             if (parent.frames) {
                   8420:                 if (parent.frames.length > 1) {
                   8421:                     var framesrc = parent.frames[1].location.href;
                   8422:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   8423:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   8424:                         document.getElementById("'.$id.'").style.width = "auto";
                   8425:                         document.getElementById("'.$id.'").style.height = "auto";
                   8426:                     }
                   8427:                 }
                   8428:             }
                   8429:         } catch (e) {
                   8430:             return;
                   8431:         }
1.1137    raeburn  8432:     }
1.1140    raeburn  8433:     return;
1.996     www      8434: }
1.1140    raeburn  8435: ';
                   8436:     }
                   8437:     if ($needjsready) {
                   8438:         $nicescroll_js = '
                   8439: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   8440:     } else {
                   8441:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   8442:     }
                   8443:     return $nicescroll_js;
1.996     www      8444: }
                   8445: 
1.318     albertel 8446: sub simple_error_page {
1.1150    bisitz   8447:     my ($r,$title,$msg,$args) = @_;
1.1151    raeburn  8448:     if (ref($args) eq 'HASH') {
                   8449:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   8450:     } else {
                   8451:         $msg = &mt($msg);
                   8452:     }
1.1150    bisitz   8453: 
1.318     albertel 8454:     my $page =
                   8455: 	&Apache::loncommon::start_page($title).
1.1150    bisitz   8456: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 8457: 	&Apache::loncommon::end_page();
                   8458:     if (ref($r)) {
                   8459: 	$r->print($page);
1.327     albertel 8460: 	return;
1.318     albertel 8461:     }
                   8462:     return $page;
                   8463: }
1.347     albertel 8464: 
                   8465: {
1.610     albertel 8466:     my @row_count;
1.961     onken    8467: 
                   8468:     sub start_data_table_count {
                   8469:         unshift(@row_count, 0);
                   8470:         return;
                   8471:     }
                   8472: 
                   8473:     sub end_data_table_count {
                   8474:         shift(@row_count);
                   8475:         return;
                   8476:     }
                   8477: 
1.347     albertel 8478:     sub start_data_table {
1.1018    raeburn  8479: 	my ($add_class,$id) = @_;
1.422     albertel 8480: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  8481:         my $table_id;
                   8482:         if (defined($id)) {
                   8483:             $table_id = ' id="'.$id.'"';
                   8484:         }
1.961     onken    8485: 	&start_data_table_count();
1.1018    raeburn  8486: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 8487:     }
                   8488: 
                   8489:     sub end_data_table {
1.961     onken    8490: 	&end_data_table_count();
1.389     albertel 8491: 	return '</table>'."\n";;
1.347     albertel 8492:     }
                   8493: 
                   8494:     sub start_data_table_row {
1.974     wenzelju 8495: 	my ($add_class, $id) = @_;
1.610     albertel 8496: 	$row_count[0]++;
                   8497: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   8498: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 8499:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8500:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 8501:     }
1.471     banghart 8502:     
                   8503:     sub continue_data_table_row {
1.974     wenzelju 8504: 	my ($add_class, $id) = @_;
1.610     albertel 8505: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 8506: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   8507:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8508:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 8509:     }
1.347     albertel 8510: 
                   8511:     sub end_data_table_row {
1.389     albertel 8512: 	return '</tr>'."\n";;
1.347     albertel 8513:     }
1.367     www      8514: 
1.421     albertel 8515:     sub start_data_table_empty_row {
1.707     bisitz   8516: #	$row_count[0]++;
1.421     albertel 8517: 	return  '<tr class="LC_empty_row" >'."\n";;
                   8518:     }
                   8519: 
                   8520:     sub end_data_table_empty_row {
                   8521: 	return '</tr>'."\n";;
                   8522:     }
                   8523: 
1.367     www      8524:     sub start_data_table_header_row {
1.389     albertel 8525: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      8526:     }
                   8527: 
                   8528:     sub end_data_table_header_row {
1.389     albertel 8529: 	return '</tr>'."\n";;
1.367     www      8530:     }
1.890     droeschl 8531: 
                   8532:     sub data_table_caption {
                   8533:         my $caption = shift;
                   8534:         return "<caption class=\"LC_caption\">$caption</caption>";
                   8535:     }
1.347     albertel 8536: }
                   8537: 
1.548     albertel 8538: =pod
                   8539: 
                   8540: =item * &inhibit_menu_check($arg)
                   8541: 
                   8542: Checks for a inhibitmenu state and generates output to preserve it
                   8543: 
                   8544: Inputs:         $arg - can be any of
                   8545:                      - undef - in which case the return value is a string 
                   8546:                                to add  into arguments list of a uri
                   8547:                      - 'input' - in which case the return value is a HTML
                   8548:                                  <form> <input> field of type hidden to
                   8549:                                  preserve the value
                   8550:                      - a url - in which case the return value is the url with
                   8551:                                the neccesary cgi args added to preserve the
                   8552:                                inhibitmenu state
                   8553:                      - a ref to a url - no return value, but the string is
                   8554:                                         updated to include the neccessary cgi
                   8555:                                         args to preserve the inhibitmenu state
                   8556: 
                   8557: =cut
                   8558: 
                   8559: sub inhibit_menu_check {
                   8560:     my ($arg) = @_;
                   8561:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   8562:     if ($arg eq 'input') {
                   8563: 	if ($env{'form.inhibitmenu'}) {
                   8564: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   8565: 	} else {
                   8566: 	    return
                   8567: 	}
                   8568:     }
                   8569:     if ($env{'form.inhibitmenu'}) {
                   8570: 	if (ref($arg)) {
                   8571: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8572: 	} elsif ($arg eq '') {
                   8573: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   8574: 	} else {
                   8575: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8576: 	}
                   8577:     }
                   8578:     if (!ref($arg)) {
                   8579: 	return $arg;
                   8580:     }
                   8581: }
                   8582: 
1.251     albertel 8583: ###############################################
1.182     matthew  8584: 
                   8585: =pod
                   8586: 
1.549     albertel 8587: =back
                   8588: 
                   8589: =head1 User Information Routines
                   8590: 
                   8591: =over 4
                   8592: 
1.405     albertel 8593: =item * &get_users_function()
1.182     matthew  8594: 
                   8595: Used by &bodytag to determine the current users primary role.
                   8596: Returns either 'student','coordinator','admin', or 'author'.
                   8597: 
                   8598: =cut
                   8599: 
                   8600: ###############################################
                   8601: sub get_users_function {
1.815     tempelho 8602:     my $function = 'norole';
1.818     tempelho 8603:     if ($env{'request.role'}=~/^(st)/) {
                   8604:         $function='student';
                   8605:     }
1.907     raeburn  8606:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  8607:         $function='coordinator';
                   8608:     }
1.258     albertel 8609:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  8610:         $function='admin';
                   8611:     }
1.826     bisitz   8612:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  8613:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  8614:         $function='author';
                   8615:     }
                   8616:     return $function;
1.54      www      8617: }
1.99      www      8618: 
                   8619: ###############################################
                   8620: 
1.233     raeburn  8621: =pod
                   8622: 
1.821     raeburn  8623: =item * &show_course()
                   8624: 
                   8625: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   8626: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   8627: 
                   8628: Inputs:
                   8629: None
                   8630: 
                   8631: Outputs:
                   8632: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   8633: 
                   8634: =cut
                   8635: 
                   8636: ###############################################
                   8637: sub show_course {
                   8638:     my $course = !$env{'user.adv'};
                   8639:     if (!$env{'user.adv'}) {
                   8640:         foreach my $env (keys(%env)) {
                   8641:             next if ($env !~ m/^user\.priv\./);
                   8642:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   8643:                 $course = 0;
                   8644:                 last;
                   8645:             }
                   8646:         }
                   8647:     }
                   8648:     return $course;
                   8649: }
                   8650: 
                   8651: ###############################################
                   8652: 
                   8653: =pod
                   8654: 
1.542     raeburn  8655: =item * &check_user_status()
1.274     raeburn  8656: 
                   8657: Determines current status of supplied role for a
                   8658: specific user. Roles can be active, previous or future.
                   8659: 
                   8660: Inputs: 
                   8661: user's domain, user's username, course's domain,
1.375     raeburn  8662: course's number, optional section ID.
1.274     raeburn  8663: 
                   8664: Outputs:
                   8665: role status: active, previous or future. 
                   8666: 
                   8667: =cut
                   8668: 
                   8669: sub check_user_status {
1.412     raeburn  8670:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  8671:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  8672:     my @uroles = keys(%userinfo);
1.274     raeburn  8673:     my $srchstr;
                   8674:     my $active_chk = 'none';
1.412     raeburn  8675:     my $now = time;
1.274     raeburn  8676:     if (@uroles > 0) {
1.908     raeburn  8677:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  8678:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   8679:         } else {
1.412     raeburn  8680:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   8681:         }
                   8682:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  8683:             my $role_end = 0;
                   8684:             my $role_start = 0;
                   8685:             $active_chk = 'active';
1.412     raeburn  8686:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   8687:                 $role_end = $1;
                   8688:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   8689:                     $role_start = $1;
1.274     raeburn  8690:                 }
                   8691:             }
                   8692:             if ($role_start > 0) {
1.412     raeburn  8693:                 if ($now < $role_start) {
1.274     raeburn  8694:                     $active_chk = 'future';
                   8695:                 }
                   8696:             }
                   8697:             if ($role_end > 0) {
1.412     raeburn  8698:                 if ($now > $role_end) {
1.274     raeburn  8699:                     $active_chk = 'previous';
                   8700:                 }
                   8701:             }
                   8702:         }
                   8703:     }
                   8704:     return $active_chk;
                   8705: }
                   8706: 
                   8707: ###############################################
                   8708: 
                   8709: =pod
                   8710: 
1.405     albertel 8711: =item * &get_sections()
1.233     raeburn  8712: 
                   8713: Determines all the sections for a course including
                   8714: sections with students and sections containing other roles.
1.419     raeburn  8715: Incoming parameters: 
                   8716: 
                   8717: 1. domain
                   8718: 2. course number 
                   8719: 3. reference to array containing roles for which sections should 
                   8720: be gathered (optional).
                   8721: 4. reference to array containing status types for which sections 
                   8722: should be gathered (optional).
                   8723: 
                   8724: If the third argument is undefined, sections are gathered for any role. 
                   8725: If the fourth argument is undefined, sections are gathered for any status.
                   8726: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  8727:  
1.374     raeburn  8728: Returns section hash (keys are section IDs, values are
                   8729: number of users in each section), subject to the
1.419     raeburn  8730: optional roles filter, optional status filter 
1.233     raeburn  8731: 
                   8732: =cut
                   8733: 
                   8734: ###############################################
                   8735: sub get_sections {
1.419     raeburn  8736:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 8737:     if (!defined($cdom) || !defined($cnum)) {
                   8738:         my $cid =  $env{'request.course.id'};
                   8739: 
                   8740: 	return if (!defined($cid));
                   8741: 
                   8742:         $cdom = $env{'course.'.$cid.'.domain'};
                   8743:         $cnum = $env{'course.'.$cid.'.num'};
                   8744:     }
                   8745: 
                   8746:     my %sectioncount;
1.419     raeburn  8747:     my $now = time;
1.240     albertel 8748: 
1.1118    raeburn  8749:     my $check_students = 1;
                   8750:     my $only_students = 0;
                   8751:     if (ref($possible_roles) eq 'ARRAY') {
                   8752:         if (grep(/^st$/,@{$possible_roles})) {
                   8753:             if (@{$possible_roles} == 1) {
                   8754:                 $only_students = 1;
                   8755:             }
                   8756:         } else {
                   8757:             $check_students = 0;
                   8758:         }
                   8759:     }
                   8760: 
                   8761:     if ($check_students) { 
1.276     albertel 8762: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 8763: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   8764: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  8765:         my $start_index = &Apache::loncoursedata::CL_START();
                   8766:         my $end_index = &Apache::loncoursedata::CL_END();
                   8767:         my $status;
1.366     albertel 8768: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  8769: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   8770: 				                     $data->[$status_index],
                   8771:                                                      $data->[$start_index],
                   8772:                                                      $data->[$end_index]);
                   8773:             if ($stu_status eq 'Active') {
                   8774:                 $status = 'active';
                   8775:             } elsif ($end < $now) {
                   8776:                 $status = 'previous';
                   8777:             } elsif ($start > $now) {
                   8778:                 $status = 'future';
                   8779:             } 
                   8780: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   8781:                 if ((!defined($possible_status)) || (($status ne '') && 
                   8782:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   8783: 		    $sectioncount{$section}++;
                   8784:                 }
1.240     albertel 8785: 	    }
                   8786: 	}
                   8787:     }
1.1118    raeburn  8788:     if ($only_students) {
                   8789:         return %sectioncount;
                   8790:     }
1.240     albertel 8791:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8792:     foreach my $user (sort(keys(%courseroles))) {
                   8793: 	if ($user !~ /^(\w{2})/) { next; }
                   8794: 	my ($role) = ($user =~ /^(\w{2})/);
                   8795: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  8796: 	my ($section,$status);
1.240     albertel 8797: 	if ($role eq 'cr' &&
                   8798: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   8799: 	    $section=$1;
                   8800: 	}
                   8801: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   8802: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  8803:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   8804:         if ($end == -1 && $start == -1) {
                   8805:             next; #deleted role
                   8806:         }
                   8807:         if (!defined($possible_status)) { 
                   8808:             $sectioncount{$section}++;
                   8809:         } else {
                   8810:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   8811:                 $status = 'active';
                   8812:             } elsif ($end < $now) {
                   8813:                 $status = 'future';
                   8814:             } elsif ($start > $now) {
                   8815:                 $status = 'previous';
                   8816:             }
                   8817:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   8818:                 $sectioncount{$section}++;
                   8819:             }
                   8820:         }
1.233     raeburn  8821:     }
1.366     albertel 8822:     return %sectioncount;
1.233     raeburn  8823: }
                   8824: 
1.274     raeburn  8825: ###############################################
1.294     raeburn  8826: 
                   8827: =pod
1.405     albertel 8828: 
                   8829: =item * &get_course_users()
                   8830: 
1.275     raeburn  8831: Retrieves usernames:domains for users in the specified course
                   8832: with specific role(s), and access status. 
                   8833: 
                   8834: Incoming parameters:
1.277     albertel 8835: 1. course domain
                   8836: 2. course number
                   8837: 3. access status: users must have - either active, 
1.275     raeburn  8838: previous, future, or all.
1.277     albertel 8839: 4. reference to array of permissible roles
1.288     raeburn  8840: 5. reference to array of section restrictions (optional)
                   8841: 6. reference to results object (hash of hashes).
                   8842: 7. reference to optional userdata hash
1.609     raeburn  8843: 8. reference to optional statushash
1.630     raeburn  8844: 9. flag if privileged users (except those set to unhide in
                   8845:    course settings) should be excluded    
1.609     raeburn  8846: Keys of top level results hash are roles.
1.275     raeburn  8847: Keys of inner hashes are username:domain, with 
                   8848: values set to access type.
1.288     raeburn  8849: Optional userdata hash returns an array with arguments in the 
                   8850: same order as loncoursedata::get_classlist() for student data.
                   8851: 
1.609     raeburn  8852: Optional statushash returns
                   8853: 
1.288     raeburn  8854: Entries for end, start, section and status are blank because
                   8855: of the possibility of multiple values for non-student roles.
                   8856: 
1.275     raeburn  8857: =cut
1.405     albertel 8858: 
1.275     raeburn  8859: ###############################################
1.405     albertel 8860: 
1.275     raeburn  8861: sub get_course_users {
1.630     raeburn  8862:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  8863:     my %idx = ();
1.419     raeburn  8864:     my %seclists;
1.288     raeburn  8865: 
                   8866:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   8867:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   8868:     $idx{end} = &Apache::loncoursedata::CL_END();
                   8869:     $idx{start} = &Apache::loncoursedata::CL_START();
                   8870:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   8871:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   8872:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   8873:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   8874: 
1.290     albertel 8875:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 8876:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  8877:         my $now = time;
1.277     albertel 8878:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  8879:             my $match = 0;
1.412     raeburn  8880:             my $secmatch = 0;
1.419     raeburn  8881:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  8882:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  8883:             if ($section eq '') {
                   8884:                 $section = 'none';
                   8885:             }
1.291     albertel 8886:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8887:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8888:                     $secmatch = 1;
                   8889:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 8890:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8891:                         $secmatch = 1;
                   8892:                     }
                   8893:                 } else {  
1.419     raeburn  8894: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  8895: 		        $secmatch = 1;
                   8896:                     }
1.290     albertel 8897: 		}
1.412     raeburn  8898:                 if (!$secmatch) {
                   8899:                     next;
                   8900:                 }
1.419     raeburn  8901:             }
1.275     raeburn  8902:             if (defined($$types{'active'})) {
1.288     raeburn  8903:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  8904:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  8905:                     $match = 1;
1.275     raeburn  8906:                 }
                   8907:             }
                   8908:             if (defined($$types{'previous'})) {
1.609     raeburn  8909:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  8910:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  8911:                     $match = 1;
1.275     raeburn  8912:                 }
                   8913:             }
                   8914:             if (defined($$types{'future'})) {
1.609     raeburn  8915:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  8916:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  8917:                     $match = 1;
1.275     raeburn  8918:                 }
                   8919:             }
1.609     raeburn  8920:             if ($match) {
                   8921:                 push(@{$seclists{$student}},$section);
                   8922:                 if (ref($userdata) eq 'HASH') {
                   8923:                     $$userdata{$student} = $$classlist{$student};
                   8924:                 }
                   8925:                 if (ref($statushash) eq 'HASH') {
                   8926:                     $statushash->{$student}{'st'}{$section} = $status;
                   8927:                 }
1.288     raeburn  8928:             }
1.275     raeburn  8929:         }
                   8930:     }
1.412     raeburn  8931:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  8932:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8933:         my $now = time;
1.609     raeburn  8934:         my %displaystatus = ( previous => 'Expired',
                   8935:                               active   => 'Active',
                   8936:                               future   => 'Future',
                   8937:                             );
1.1121    raeburn  8938:         my (%nothide,@possdoms);
1.630     raeburn  8939:         if ($hidepriv) {
                   8940:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   8941:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   8942:                 if ($user !~ /:/) {
                   8943:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   8944:                 } else {
                   8945:                     $nothide{$user} = 1;
                   8946:                 }
                   8947:             }
1.1121    raeburn  8948:             my @possdoms = ($cdom);
                   8949:             if ($coursehash{'checkforpriv'}) {
                   8950:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   8951:             }
1.630     raeburn  8952:         }
1.439     raeburn  8953:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  8954:             my $match = 0;
1.412     raeburn  8955:             my $secmatch = 0;
1.439     raeburn  8956:             my $status;
1.412     raeburn  8957:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  8958:             $user =~ s/:$//;
1.439     raeburn  8959:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   8960:             if ($end == -1 || $start == -1) {
                   8961:                 next;
                   8962:             }
                   8963:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   8964:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  8965:                 my ($uname,$udom) = split(/:/,$user);
                   8966:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8967:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8968:                         $secmatch = 1;
                   8969:                     } elsif ($usec eq '') {
1.420     albertel 8970:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8971:                             $secmatch = 1;
                   8972:                         }
                   8973:                     } else {
                   8974:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   8975:                             $secmatch = 1;
                   8976:                         }
                   8977:                     }
                   8978:                     if (!$secmatch) {
                   8979:                         next;
                   8980:                     }
1.288     raeburn  8981:                 }
1.419     raeburn  8982:                 if ($usec eq '') {
                   8983:                     $usec = 'none';
                   8984:                 }
1.275     raeburn  8985:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  8986:                     if ($hidepriv) {
1.1121    raeburn  8987:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  8988:                             (!$nothide{$uname.':'.$udom})) {
                   8989:                             next;
                   8990:                         }
                   8991:                     }
1.503     raeburn  8992:                     if ($end > 0 && $end < $now) {
1.439     raeburn  8993:                         $status = 'previous';
                   8994:                     } elsif ($start > $now) {
                   8995:                         $status = 'future';
                   8996:                     } else {
                   8997:                         $status = 'active';
                   8998:                     }
1.277     albertel 8999:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9000:                         if ($status eq $type) {
1.420     albertel 9001:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9002:                                 push(@{$$users{$role}{$user}},$type);
                   9003:                             }
1.288     raeburn  9004:                             $match = 1;
                   9005:                         }
                   9006:                     }
1.419     raeburn  9007:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9008:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9009: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9010:                         }
1.420     albertel 9011:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9012:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9013:                         }
1.609     raeburn  9014:                         if (ref($statushash) eq 'HASH') {
                   9015:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9016:                         }
1.275     raeburn  9017:                     }
                   9018:                 }
                   9019:             }
                   9020:         }
1.290     albertel 9021:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9022:             if ((defined($cdom)) && (defined($cnum))) {
                   9023:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9024:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9025:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9026:                     next if ($owner eq '');
                   9027:                     my ($ownername,$ownerdom);
                   9028:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9029:                         $ownername = $1;
                   9030:                         $ownerdom = $2;
                   9031:                     } else {
                   9032:                         $ownername = $owner;
                   9033:                         $ownerdom = $cdom;
                   9034:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9035:                     }
                   9036:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9037:                     if (defined($userdata) && 
1.609     raeburn  9038: 			!exists($$userdata{$owner})) {
                   9039: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9040:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9041:                             push(@{$seclists{$owner}},'none');
                   9042:                         }
                   9043:                         if (ref($statushash) eq 'HASH') {
                   9044:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9045:                         }
1.290     albertel 9046: 		    }
1.279     raeburn  9047:                 }
                   9048:             }
                   9049:         }
1.419     raeburn  9050:         foreach my $user (keys(%seclists)) {
                   9051:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9052:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9053:         }
1.275     raeburn  9054:     }
                   9055:     return;
                   9056: }
                   9057: 
1.288     raeburn  9058: sub get_user_info {
                   9059:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9060:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9061: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9062:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9063:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9064:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9065:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9066:     return;
                   9067: }
1.275     raeburn  9068: 
1.472     raeburn  9069: ###############################################
                   9070: 
                   9071: =pod
                   9072: 
                   9073: =item * &get_user_quota()
                   9074: 
1.1134    raeburn  9075: Retrieves quota assigned for storage of user files.
                   9076: Default is to report quota for portfolio files.
1.472     raeburn  9077: 
                   9078: Incoming parameters:
                   9079: 1. user's username
                   9080: 2. user's domain
1.1134    raeburn  9081: 3. quota name - portfolio, author, or course
1.1136    raeburn  9082:    (if no quota name provided, defaults to portfolio).
1.1165    raeburn  9083: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1136    raeburn  9084:    course
1.472     raeburn  9085: 
                   9086: Returns:
1.1163    raeburn  9087: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9088: 2. (Optional) Type of setting: custom or default
                   9089:    (individually assigned or default for user's 
                   9090:    institutional status).
                   9091: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9092:    or student - types as defined in localenroll::inst_usertypes 
                   9093:    for user's domain, which determines default quota for user.
                   9094: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9095: 
                   9096: If a value has been stored in the user's environment, 
1.536     raeburn  9097: it will return that, otherwise it returns the maximal default
1.1134    raeburn  9098: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9099: 
                   9100: =cut
                   9101: 
                   9102: ###############################################
                   9103: 
                   9104: 
                   9105: sub get_user_quota {
1.1136    raeburn  9106:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9107:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9108:     if (!defined($udom)) {
                   9109:         $udom = $env{'user.domain'};
                   9110:     }
                   9111:     if (!defined($uname)) {
                   9112:         $uname = $env{'user.name'};
                   9113:     }
                   9114:     if (($udom eq '' || $uname eq '') ||
                   9115:         ($udom eq 'public') && ($uname eq 'public')) {
                   9116:         $quota = 0;
1.536     raeburn  9117:         $quotatype = 'default';
                   9118:         $defquota = 0; 
1.472     raeburn  9119:     } else {
1.536     raeburn  9120:         my $inststatus;
1.1134    raeburn  9121:         if ($quotaname eq 'course') {
                   9122:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9123:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9124:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9125:             } else {
                   9126:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9127:                 $quota = $cenv{'internal.uploadquota'};
                   9128:             }
1.536     raeburn  9129:         } else {
1.1134    raeburn  9130:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9131:                 if ($quotaname eq 'author') {
                   9132:                     $quota = $env{'environment.authorquota'};
                   9133:                 } else {
                   9134:                     $quota = $env{'environment.portfolioquota'};
                   9135:                 }
                   9136:                 $inststatus = $env{'environment.inststatus'};
                   9137:             } else {
                   9138:                 my %userenv = 
                   9139:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9140:                                          'authorquota','inststatus'],$udom,$uname);
                   9141:                 my ($tmp) = keys(%userenv);
                   9142:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9143:                     if ($quotaname eq 'author') {
                   9144:                         $quota = $userenv{'authorquota'};
                   9145:                     } else {
                   9146:                         $quota = $userenv{'portfolioquota'};
                   9147:                     }
                   9148:                     $inststatus = $userenv{'inststatus'};
                   9149:                 } else {
                   9150:                     undef(%userenv);
                   9151:                 }
                   9152:             }
                   9153:         }
                   9154:         if ($quota eq '' || wantarray) {
                   9155:             if ($quotaname eq 'course') {
                   9156:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  9157:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
                   9158:                     ($crstype eq 'community') || ($crstype eq 'textbook')) { 
1.1136    raeburn  9159:                     $defquota = $domdefs{$crstype.'quota'};
                   9160:                 }
                   9161:                 if ($defquota eq '') {
                   9162:                     $defquota = 500;
                   9163:                 }
1.1134    raeburn  9164:             } else {
                   9165:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   9166:             }
                   9167:             if ($quota eq '') {
                   9168:                 $quota = $defquota;
                   9169:                 $quotatype = 'default';
                   9170:             } else {
                   9171:                 $quotatype = 'custom';
                   9172:             }
1.472     raeburn  9173:         }
                   9174:     }
1.536     raeburn  9175:     if (wantarray) {
                   9176:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9177:     } else {
                   9178:         return $quota;
                   9179:     }
1.472     raeburn  9180: }
                   9181: 
                   9182: ###############################################
                   9183: 
                   9184: =pod
                   9185: 
                   9186: =item * &default_quota()
                   9187: 
1.536     raeburn  9188: Retrieves default quota assigned for storage of user portfolio files,
                   9189: given an (optional) user's institutional status.
1.472     raeburn  9190: 
                   9191: Incoming parameters:
1.1142    raeburn  9192: 
1.472     raeburn  9193: 1. domain
1.536     raeburn  9194: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9195:    status types (e.g., faculty, staff, student etc.)
                   9196:    which apply to the user for whom the default is being retrieved.
                   9197:    If the institutional status string in undefined, the domain
1.1134    raeburn  9198:    default quota will be returned.
                   9199: 3.  quota name - portfolio, author, or course
                   9200:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9201: 
                   9202: Returns:
1.1142    raeburn  9203: 
1.1163    raeburn  9204: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9205: 2. (Optional) institutional type which determined the value of the
                   9206:    default quota.
1.472     raeburn  9207: 
                   9208: If a value has been stored in the domain's configuration db,
                   9209: it will return that, otherwise it returns 20 (for backwards 
                   9210: compatibility with domains which have not set up a configuration
1.1163    raeburn  9211: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9212: 
1.536     raeburn  9213: If the user's status includes multiple types (e.g., staff and student),
                   9214: the largest default quota which applies to the user determines the
                   9215: default quota returned.
                   9216: 
1.472     raeburn  9217: =cut
                   9218: 
                   9219: ###############################################
                   9220: 
                   9221: 
                   9222: sub default_quota {
1.1134    raeburn  9223:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9224:     my ($defquota,$settingstatus);
                   9225:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9226:                                             ['quotas'],$udom);
1.1134    raeburn  9227:     my $key = 'defaultquota';
                   9228:     if ($quotaname eq 'author') {
                   9229:         $key = 'authorquota';
                   9230:     }
1.622     raeburn  9231:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9232:         if ($inststatus ne '') {
1.765     raeburn  9233:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9234:             foreach my $item (@statuses) {
1.1134    raeburn  9235:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9236:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9237:                         if ($defquota eq '') {
1.1134    raeburn  9238:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9239:                             $settingstatus = $item;
1.1134    raeburn  9240:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9241:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9242:                             $settingstatus = $item;
                   9243:                         }
                   9244:                     }
1.1134    raeburn  9245:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9246:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9247:                         if ($defquota eq '') {
                   9248:                             $defquota = $quotahash{'quotas'}{$item};
                   9249:                             $settingstatus = $item;
                   9250:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9251:                             $defquota = $quotahash{'quotas'}{$item};
                   9252:                             $settingstatus = $item;
                   9253:                         }
1.536     raeburn  9254:                     }
                   9255:                 }
                   9256:             }
                   9257:         }
                   9258:         if ($defquota eq '') {
1.1134    raeburn  9259:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9260:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9261:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9262:                 $defquota = $quotahash{'quotas'}{'default'};
                   9263:             }
1.536     raeburn  9264:             $settingstatus = 'default';
1.1139    raeburn  9265:             if ($defquota eq '') {
                   9266:                 if ($quotaname eq 'author') {
                   9267:                     $defquota = 500;
                   9268:                 }
                   9269:             }
1.536     raeburn  9270:         }
                   9271:     } else {
                   9272:         $settingstatus = 'default';
1.1134    raeburn  9273:         if ($quotaname eq 'author') {
                   9274:             $defquota = 500;
                   9275:         } else {
                   9276:             $defquota = 20;
                   9277:         }
1.536     raeburn  9278:     }
                   9279:     if (wantarray) {
                   9280:         return ($defquota,$settingstatus);
1.472     raeburn  9281:     } else {
1.536     raeburn  9282:         return $defquota;
1.472     raeburn  9283:     }
                   9284: }
                   9285: 
1.1135    raeburn  9286: ###############################################
                   9287: 
                   9288: =pod
                   9289: 
1.1136    raeburn  9290: =item * &excess_filesize_warning()
1.1135    raeburn  9291: 
                   9292: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  9293: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  9294: space to be exceeded.
1.1136    raeburn  9295: 
                   9296: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  9297: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  9298: 
1.1165    raeburn  9299: Inputs: 7 
1.1136    raeburn  9300: 1. username or coursenum
1.1135    raeburn  9301: 2. domain
1.1136    raeburn  9302: 3. context ('author' or 'course')
1.1135    raeburn  9303: 4. filename of file for which action is being requested
                   9304: 5. filesize (kB) of file
                   9305: 6. action being taken: copy or upload.
1.1165    raeburn  9306: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1135    raeburn  9307: 
                   9308: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  9309:          otherwise return null.
                   9310: 
                   9311: =back
1.1135    raeburn  9312: 
                   9313: =cut
                   9314: 
1.1136    raeburn  9315: sub excess_filesize_warning {
1.1165    raeburn  9316:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  9317:     my $current_disk_usage = 0;
1.1165    raeburn  9318:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  9319:     if ($context eq 'author') {
                   9320:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   9321:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   9322:     } else {
                   9323:         foreach my $subdir ('docs','supplemental') {
                   9324:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   9325:         }
                   9326:     }
1.1135    raeburn  9327:     $disk_quota = int($disk_quota * 1000);
                   9328:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   9329:         return '<p class="LC_warning">'.
1.1135    raeburn  9330:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   9331:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   9332:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  9333:                             $disk_quota,$current_disk_usage).
                   9334:                '</p>';
                   9335:     }
                   9336:     return;
                   9337: }
                   9338: 
                   9339: ###############################################
                   9340: 
                   9341: 
1.1136    raeburn  9342: 
                   9343: 
1.384     raeburn  9344: sub get_secgrprole_info {
                   9345:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   9346:     my %sections_count = &get_sections($cdom,$cnum);
                   9347:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   9348:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   9349:     my @groups = sort(keys(%curr_groups));
                   9350:     my $allroles = [];
                   9351:     my $rolehash;
                   9352:     my $accesshash = {
                   9353:                      active => 'Currently has access',
                   9354:                      future => 'Will have future access',
                   9355:                      previous => 'Previously had access',
                   9356:                   };
                   9357:     if ($needroles) {
                   9358:         $rolehash = {'all' => 'all'};
1.385     albertel 9359:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9360: 	if (&Apache::lonnet::error(%user_roles)) {
                   9361: 	    undef(%user_roles);
                   9362: 	}
                   9363:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  9364:             my ($role)=split(/\:/,$item,2);
                   9365:             if ($role eq 'cr') { next; }
                   9366:             if ($role =~ /^cr/) {
                   9367:                 $$rolehash{$role} = (split('/',$role))[3];
                   9368:             } else {
                   9369:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   9370:             }
                   9371:         }
                   9372:         foreach my $key (sort(keys(%{$rolehash}))) {
                   9373:             push(@{$allroles},$key);
                   9374:         }
                   9375:         push (@{$allroles},'st');
                   9376:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   9377:     }
                   9378:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   9379: }
                   9380: 
1.555     raeburn  9381: sub user_picker {
1.994     raeburn  9382:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
1.555     raeburn  9383:     my $currdom = $dom;
                   9384:     my %curr_selected = (
                   9385:                         srchin => 'dom',
1.580     raeburn  9386:                         srchby => 'lastname',
1.555     raeburn  9387:                       );
                   9388:     my $srchterm;
1.625     raeburn  9389:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  9390:         if ($srch->{'srchby'} ne '') {
                   9391:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   9392:         }
                   9393:         if ($srch->{'srchin'} ne '') {
                   9394:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   9395:         }
                   9396:         if ($srch->{'srchtype'} ne '') {
                   9397:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   9398:         }
                   9399:         if ($srch->{'srchdomain'} ne '') {
                   9400:             $currdom = $srch->{'srchdomain'};
                   9401:         }
                   9402:         $srchterm = $srch->{'srchterm'};
                   9403:     }
                   9404:     my %lt=&Apache::lonlocal::texthash(
1.573     raeburn  9405:                     'usr'       => 'Search criteria',
1.563     raeburn  9406:                     'doma'      => 'Domain/institution to search',
1.558     albertel 9407:                     'uname'     => 'username',
                   9408:                     'lastname'  => 'last name',
1.555     raeburn  9409:                     'lastfirst' => 'last name, first name',
1.558     albertel 9410:                     'crs'       => 'in this course',
1.576     raeburn  9411:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 9412:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  9413:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 9414:                     'exact'     => 'is',
                   9415:                     'contains'  => 'contains',
1.569     raeburn  9416:                     'begins'    => 'begins with',
1.571     raeburn  9417:                     'youm'      => "You must include some text to search for.",
                   9418:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   9419:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   9420:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   9421:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   9422:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   9423:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   9424:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  9425:                                        );
1.563     raeburn  9426:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   9427:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  9428: 
                   9429:     my @srchins = ('crs','dom','alc','instd');
                   9430: 
                   9431:     foreach my $option (@srchins) {
                   9432:         # FIXME 'alc' option unavailable until 
                   9433:         #       loncreateuser::print_user_query_page()
                   9434:         #       has been completed.
                   9435:         next if ($option eq 'alc');
1.880     raeburn  9436:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  9437:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  9438:         if ($curr_selected{'srchin'} eq $option) {
                   9439:             $srchinsel .= ' 
                   9440:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   9441:         } else {
                   9442:             $srchinsel .= '
                   9443:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   9444:         }
1.555     raeburn  9445:     }
1.563     raeburn  9446:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  9447: 
                   9448:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  9449:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  9450:         if ($curr_selected{'srchby'} eq $option) {
                   9451:             $srchbysel .= '
                   9452:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   9453:         } else {
                   9454:             $srchbysel .= '
                   9455:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   9456:          }
                   9457:     }
                   9458:     $srchbysel .= "\n  </select>\n";
                   9459: 
                   9460:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  9461:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  9462:         if ($curr_selected{'srchtype'} eq $option) {
                   9463:             $srchtypesel .= '
                   9464:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   9465:         } else {
                   9466:             $srchtypesel .= '
                   9467:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   9468:         }
                   9469:     }
                   9470:     $srchtypesel .= "\n  </select>\n";
                   9471: 
1.558     albertel 9472:     my ($newuserscript,$new_user_create);
1.994     raeburn  9473:     my $context_dom = $env{'request.role.domain'};
                   9474:     if ($context eq 'requestcrs') {
                   9475:         if ($env{'form.coursedom'} ne '') { 
                   9476:             $context_dom = $env{'form.coursedom'};
                   9477:         }
                   9478:     }
1.556     raeburn  9479:     if ($forcenewuser) {
1.576     raeburn  9480:         if (ref($srch) eq 'HASH') {
1.994     raeburn  9481:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  9482:                 if ($cancreate) {
                   9483:                     $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>';
                   9484:                 } else {
1.799     bisitz   9485:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  9486:                     my %usertypetext = (
                   9487:                         official   => 'institutional',
                   9488:                         unofficial => 'non-institutional',
                   9489:                     );
1.799     bisitz   9490:                     $new_user_create = '<p class="LC_warning">'
                   9491:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   9492:                                       .' '
                   9493:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   9494:                                           ,'<a href="'.$helplink.'">','</a>')
                   9495:                                       .'</p><br />';
1.627     raeburn  9496:                 }
1.576     raeburn  9497:             }
                   9498:         }
                   9499: 
1.556     raeburn  9500:         $newuserscript = <<"ENDSCRIPT";
                   9501: 
1.570     raeburn  9502: function setSearch(createnew,callingForm) {
1.556     raeburn  9503:     if (createnew == 1) {
1.570     raeburn  9504:         for (var i=0; i<callingForm.srchby.length; i++) {
                   9505:             if (callingForm.srchby.options[i].value == 'uname') {
                   9506:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  9507:             }
                   9508:         }
1.570     raeburn  9509:         for (var i=0; i<callingForm.srchin.length; i++) {
                   9510:             if ( callingForm.srchin.options[i].value == 'dom') {
                   9511: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  9512:             }
                   9513:         }
1.570     raeburn  9514:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   9515:             if (callingForm.srchtype.options[i].value == 'exact') {
                   9516:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  9517:             }
                   9518:         }
1.570     raeburn  9519:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  9520:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  9521:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  9522:             }
                   9523:         }
                   9524:     }
                   9525: }
                   9526: ENDSCRIPT
1.558     albertel 9527: 
1.556     raeburn  9528:     }
                   9529: 
1.555     raeburn  9530:     my $output = <<"END_BLOCK";
1.556     raeburn  9531: <script type="text/javascript">
1.824     bisitz   9532: // <![CDATA[
1.570     raeburn  9533: function validateEntry(callingForm) {
1.558     albertel 9534: 
1.556     raeburn  9535:     var checkok = 1;
1.558     albertel 9536:     var srchin;
1.570     raeburn  9537:     for (var i=0; i<callingForm.srchin.length; i++) {
                   9538: 	if ( callingForm.srchin[i].checked ) {
                   9539: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 9540: 	}
                   9541:     }
                   9542: 
1.570     raeburn  9543:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   9544:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   9545:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   9546:     var srchterm =  callingForm.srchterm.value;
                   9547:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  9548:     var msg = "";
                   9549: 
                   9550:     if (srchterm == "") {
                   9551:         checkok = 0;
1.571     raeburn  9552:         msg += "$lt{'youm'}\\n";
1.556     raeburn  9553:     }
                   9554: 
1.569     raeburn  9555:     if (srchtype== 'begins') {
                   9556:         if (srchterm.length < 2) {
                   9557:             checkok = 0;
1.571     raeburn  9558:             msg += "$lt{'thte'}\\n";
1.569     raeburn  9559:         }
                   9560:     }
                   9561: 
1.556     raeburn  9562:     if (srchtype== 'contains') {
                   9563:         if (srchterm.length < 3) {
                   9564:             checkok = 0;
1.571     raeburn  9565:             msg += "$lt{'thet'}\\n";
1.556     raeburn  9566:         }
                   9567:     }
                   9568:     if (srchin == 'instd') {
                   9569:         if (srchdomain == '') {
                   9570:             checkok = 0;
1.571     raeburn  9571:             msg += "$lt{'yomc'}\\n";
1.556     raeburn  9572:         }
                   9573:     }
                   9574:     if (srchin == 'dom') {
                   9575:         if (srchdomain == '') {
                   9576:             checkok = 0;
1.571     raeburn  9577:             msg += "$lt{'ymcd'}\\n";
1.556     raeburn  9578:         }
                   9579:     }
                   9580:     if (srchby == 'lastfirst') {
                   9581:         if (srchterm.indexOf(",") == -1) {
                   9582:             checkok = 0;
1.571     raeburn  9583:             msg += "$lt{'whus'}\\n";
1.556     raeburn  9584:         }
                   9585:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   9586:             checkok = 0;
1.571     raeburn  9587:             msg += "$lt{'whse'}\\n";
1.556     raeburn  9588:         }
                   9589:     }
                   9590:     if (checkok == 0) {
1.571     raeburn  9591:         alert("$lt{'thfo'}\\n"+msg);
1.556     raeburn  9592:         return;
                   9593:     }
                   9594:     if (checkok == 1) {
1.570     raeburn  9595:         callingForm.submit();
1.556     raeburn  9596:     }
                   9597: }
                   9598: 
                   9599: $newuserscript
                   9600: 
1.824     bisitz   9601: // ]]>
1.556     raeburn  9602: </script>
1.558     albertel 9603: 
                   9604: $new_user_create
                   9605: 
1.555     raeburn  9606: END_BLOCK
1.558     albertel 9607: 
1.876     raeburn  9608:     $output .= &Apache::lonhtmlcommon::start_pick_box().
                   9609:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
                   9610:                $domform.
                   9611:                &Apache::lonhtmlcommon::row_closure().
                   9612:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
                   9613:                $srchbysel.
                   9614:                $srchtypesel. 
                   9615:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   9616:                $srchinsel.
                   9617:                &Apache::lonhtmlcommon::row_closure(1). 
                   9618:                &Apache::lonhtmlcommon::end_pick_box().
                   9619:                '<br />';
1.555     raeburn  9620:     return $output;
                   9621: }
                   9622: 
1.612     raeburn  9623: sub user_rule_check {
1.615     raeburn  9624:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.612     raeburn  9625:     my $response;
                   9626:     if (ref($usershash) eq 'HASH') {
                   9627:         foreach my $user (keys(%{$usershash})) {
                   9628:             my ($uname,$udom) = split(/:/,$user);
                   9629:             next if ($udom eq '' || $uname eq '');
1.615     raeburn  9630:             my ($id,$newuser);
1.612     raeburn  9631:             if (ref($usershash->{$user}) eq 'HASH') {
1.615     raeburn  9632:                 $newuser = $usershash->{$user}->{'newuser'};
1.612     raeburn  9633:                 $id = $usershash->{$user}->{'id'};
                   9634:             }
                   9635:             my $inst_response;
                   9636:             if (ref($checks) eq 'HASH') {
                   9637:                 if (defined($checks->{'username'})) {
1.615     raeburn  9638:                     ($inst_response,%{$inst_results->{$user}}) = 
1.612     raeburn  9639:                         &Apache::lonnet::get_instuser($udom,$uname);
                   9640:                 } elsif (defined($checks->{'id'})) {
1.615     raeburn  9641:                     ($inst_response,%{$inst_results->{$user}}) =
1.612     raeburn  9642:                         &Apache::lonnet::get_instuser($udom,undef,$id);
                   9643:                 }
1.615     raeburn  9644:             } else {
                   9645:                 ($inst_response,%{$inst_results->{$user}}) =
                   9646:                     &Apache::lonnet::get_instuser($udom,$uname);
                   9647:                 return;
1.612     raeburn  9648:             }
1.615     raeburn  9649:             if (!$got_rules->{$udom}) {
1.612     raeburn  9650:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9651:                                                   ['usercreation'],$udom);
                   9652:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
1.615     raeburn  9653:                     foreach my $item ('username','id') {
1.612     raeburn  9654:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   9655:                             $$curr_rules{$udom}{$item} = 
                   9656:                                 $domconfig{'usercreation'}{$item.'_rule'};
1.585     raeburn  9657:                         }
                   9658:                     }
                   9659:                 }
1.615     raeburn  9660:                 $got_rules->{$udom} = 1;  
1.585     raeburn  9661:             }
1.612     raeburn  9662:             foreach my $item (keys(%{$checks})) {
                   9663:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   9664:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   9665:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
                   9666:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
                   9667:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   9668:                                 if ($rule_check{$rule}) {
                   9669:                                     $$rulematch{$user}{$item} = $rule;
                   9670:                                     if ($inst_response eq 'ok') {
1.615     raeburn  9671:                                         if (ref($inst_results) eq 'HASH') {
                   9672:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   9673:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   9674:                                                     $$alerts{$item}{$udom}{$uname} = 1;
                   9675:                                                 }
1.612     raeburn  9676:                                             }
                   9677:                                         }
1.615     raeburn  9678:                                     }
                   9679:                                     last;
1.585     raeburn  9680:                                 }
                   9681:                             }
                   9682:                         }
                   9683:                     }
                   9684:                 }
                   9685:             }
                   9686:         }
                   9687:     }
1.612     raeburn  9688:     return;
                   9689: }
                   9690: 
                   9691: sub user_rule_formats {
                   9692:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   9693:     my %text = ( 
                   9694:                  'username' => 'Usernames',
                   9695:                  'id'       => 'IDs',
                   9696:                );
                   9697:     my $output;
                   9698:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   9699:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   9700:         if (@{$ruleorder} > 0) {
1.1102    raeburn  9701:             $output = '<br />'.
                   9702:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   9703:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   9704:                       ' <ul>';
1.612     raeburn  9705:             foreach my $rule (@{$ruleorder}) {
                   9706:                 if (ref($curr_rules) eq 'ARRAY') {
                   9707:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   9708:                         if (ref($rules->{$rule}) eq 'HASH') {
                   9709:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   9710:                                         $rules->{$rule}{'desc'}.'</li>';
                   9711:                         }
                   9712:                     }
                   9713:                 }
                   9714:             }
                   9715:             $output .= '</ul>';
                   9716:         }
                   9717:     }
                   9718:     return $output;
                   9719: }
                   9720: 
                   9721: sub instrule_disallow_msg {
1.615     raeburn  9722:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  9723:     my $response;
                   9724:     my %text = (
                   9725:                   item   => 'username',
                   9726:                   items  => 'usernames',
                   9727:                   match  => 'matches',
                   9728:                   do     => 'does',
                   9729:                   action => 'a username',
                   9730:                   one    => 'one',
                   9731:                );
                   9732:     if ($count > 1) {
                   9733:         $text{'item'} = 'usernames';
                   9734:         $text{'match'} ='match';
                   9735:         $text{'do'} = 'do';
                   9736:         $text{'action'} = 'usernames',
                   9737:         $text{'one'} = 'ones';
                   9738:     }
                   9739:     if ($checkitem eq 'id') {
                   9740:         $text{'items'} = 'IDs';
                   9741:         $text{'item'} = 'ID';
                   9742:         $text{'action'} = 'an ID';
1.615     raeburn  9743:         if ($count > 1) {
                   9744:             $text{'item'} = 'IDs';
                   9745:             $text{'action'} = 'IDs';
                   9746:         }
1.612     raeburn  9747:     }
1.674     bisitz   9748:     $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  9749:     if ($mode eq 'upload') {
                   9750:         if ($checkitem eq 'username') {
                   9751:             $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'}.");
                   9752:         } elsif ($checkitem eq 'id') {
1.674     bisitz   9753:             $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  9754:         }
1.669     raeburn  9755:     } elsif ($mode eq 'selfcreate') {
                   9756:         if ($checkitem eq 'id') {
                   9757:             $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.");
                   9758:         }
1.615     raeburn  9759:     } else {
                   9760:         if ($checkitem eq 'username') {
                   9761:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   9762:         } elsif ($checkitem eq 'id') {
                   9763:             $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.");
                   9764:         }
1.612     raeburn  9765:     }
                   9766:     return $response;
1.585     raeburn  9767: }
                   9768: 
1.624     raeburn  9769: sub personal_data_fieldtitles {
                   9770:     my %fieldtitles = &Apache::lonlocal::texthash (
                   9771:                         id => 'Student/Employee ID',
                   9772:                         permanentemail => 'E-mail address',
                   9773:                         lastname => 'Last Name',
                   9774:                         firstname => 'First Name',
                   9775:                         middlename => 'Middle Name',
                   9776:                         generation => 'Generation',
                   9777:                         gen => 'Generation',
1.765     raeburn  9778:                         inststatus => 'Affiliation',
1.624     raeburn  9779:                    );
                   9780:     return %fieldtitles;
                   9781: }
                   9782: 
1.642     raeburn  9783: sub sorted_inst_types {
                   9784:     my ($dom) = @_;
1.1185    raeburn  9785:     my ($usertypes,$order);
                   9786:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   9787:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   9788:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   9789:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   9790:     } else {
                   9791:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   9792:     }
1.642     raeburn  9793:     my $othertitle = &mt('All users');
                   9794:     if ($env{'request.course.id'}) {
1.668     raeburn  9795:         $othertitle  = &mt('Any users');
1.642     raeburn  9796:     }
                   9797:     my @types;
                   9798:     if (ref($order) eq 'ARRAY') {
                   9799:         @types = @{$order};
                   9800:     }
                   9801:     if (@types == 0) {
                   9802:         if (ref($usertypes) eq 'HASH') {
                   9803:             @types = sort(keys(%{$usertypes}));
                   9804:         }
                   9805:     }
                   9806:     if (keys(%{$usertypes}) > 0) {
                   9807:         $othertitle = &mt('Other users');
                   9808:     }
                   9809:     return ($othertitle,$usertypes,\@types);
                   9810: }
                   9811: 
1.645     raeburn  9812: sub get_institutional_codes {
                   9813:     my ($settings,$allcourses,$LC_code) = @_;
                   9814: # Get complete list of course sections to update
                   9815:     my @currsections = ();
                   9816:     my @currxlists = ();
                   9817:     my $coursecode = $$settings{'internal.coursecode'};
                   9818: 
                   9819:     if ($$settings{'internal.sectionnums'} ne '') {
                   9820:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   9821:     }
                   9822: 
                   9823:     if ($$settings{'internal.crosslistings'} ne '') {
                   9824:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   9825:     }
                   9826: 
                   9827:     if (@currxlists > 0) {
                   9828:         foreach (@currxlists) {
                   9829:             if (m/^([^:]+):(\w*)$/) {
                   9830:                 unless (grep/^$1$/,@{$allcourses}) {
                   9831:                     push @{$allcourses},$1;
                   9832:                     $$LC_code{$1} = $2;
                   9833:                 }
                   9834:             }
                   9835:         }
                   9836:     }
                   9837:  
                   9838:     if (@currsections > 0) {
                   9839:         foreach (@currsections) {
                   9840:             if (m/^(\w+):(\w*)$/) {
                   9841:                 my $sec = $coursecode.$1;
                   9842:                 my $lc_sec = $2;
                   9843:                 unless (grep/^$sec$/,@{$allcourses}) {
                   9844:                     push @{$allcourses},$sec;
                   9845:                     $$LC_code{$sec} = $lc_sec;
                   9846:                 }
                   9847:             }
                   9848:         }
                   9849:     }
                   9850:     return;
                   9851: }
                   9852: 
1.971     raeburn  9853: sub get_standard_codeitems {
                   9854:     return ('Year','Semester','Department','Number','Section');
                   9855: }
                   9856: 
1.112     bowersj2 9857: =pod
                   9858: 
1.780     raeburn  9859: =head1 Slot Helpers
                   9860: 
                   9861: =over 4
                   9862: 
                   9863: =item * sorted_slots()
                   9864: 
1.1040    raeburn  9865: Sorts an array of slot names in order of an optional sort key,
                   9866: default sort is by slot start time (earliest first). 
1.780     raeburn  9867: 
                   9868: Inputs:
                   9869: 
                   9870: =over 4
                   9871: 
                   9872: slotsarr  - Reference to array of unsorted slot names.
                   9873: 
                   9874: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   9875: 
1.1040    raeburn  9876: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   9877: 
1.549     albertel 9878: =back
                   9879: 
1.780     raeburn  9880: Returns:
                   9881: 
                   9882: =over 4
                   9883: 
1.1040    raeburn  9884: sorted   - An array of slot names sorted by a specified sort key 
                   9885:            (default sort key is start time of the slot).
1.780     raeburn  9886: 
                   9887: =back
                   9888: 
                   9889: =cut
                   9890: 
                   9891: 
                   9892: sub sorted_slots {
1.1040    raeburn  9893:     my ($slotsarr,$slots,$sortkey) = @_;
                   9894:     if ($sortkey eq '') {
                   9895:         $sortkey = 'starttime';
                   9896:     }
1.780     raeburn  9897:     my @sorted;
                   9898:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   9899:         @sorted =
                   9900:             sort {
                   9901:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  9902:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  9903:                      }
                   9904:                      if (ref($slots->{$a})) { return -1;}
                   9905:                      if (ref($slots->{$b})) { return 1;}
                   9906:                      return 0;
                   9907:                  } @{$slotsarr};
                   9908:     }
                   9909:     return @sorted;
                   9910: }
                   9911: 
1.1040    raeburn  9912: =pod
                   9913: 
                   9914: =item * get_future_slots()
                   9915: 
                   9916: Inputs:
                   9917: 
                   9918: =over 4
                   9919: 
                   9920: cnum - course number
                   9921: 
                   9922: cdom - course domain
                   9923: 
                   9924: now - current UNIX time
                   9925: 
                   9926: symb - optional symb
                   9927: 
                   9928: =back
                   9929: 
                   9930: Returns:
                   9931: 
                   9932: =over 4
                   9933: 
                   9934: sorted_reservable - ref to array of student_schedulable slots currently 
                   9935:                     reservable, ordered by end date of reservation period.
                   9936: 
                   9937: reservable_now - ref to hash of student_schedulable slots currently
                   9938:                  reservable.
                   9939: 
                   9940:     Keys in inner hash are:
                   9941:     (a) symb: either blank or symb to which slot use is restricted.
                   9942:     (b) endreserve: end date of reservation period. 
                   9943: 
                   9944: sorted_future - ref to array of student_schedulable slots reservable in
                   9945:                 the future, ordered by start date of reservation period.
                   9946: 
                   9947: future_reservable - ref to hash of student_schedulable slots reservable
                   9948:                     in the future.
                   9949: 
                   9950:     Keys in inner hash are:
                   9951:     (a) symb: either blank or symb to which slot use is restricted.
                   9952:     (b) startreserve:  start date of reservation period.
                   9953: 
                   9954: =back
                   9955: 
                   9956: =cut
                   9957: 
                   9958: sub get_future_slots {
                   9959:     my ($cnum,$cdom,$now,$symb) = @_;
                   9960:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   9961:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   9962:     foreach my $slot (keys(%slots)) {
                   9963:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   9964:         if ($symb) {
                   9965:             next if (($slots{$slot}->{'symb'} ne '') && 
                   9966:                      ($slots{$slot}->{'symb'} ne $symb));
                   9967:         }
                   9968:         if (($slots{$slot}->{'starttime'} > $now) &&
                   9969:             ($slots{$slot}->{'endtime'} > $now)) {
                   9970:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   9971:                 my $userallowed = 0;
                   9972:                 if ($slots{$slot}->{'allowedsections'}) {
                   9973:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   9974:                     if (!defined($env{'request.role.sec'})
                   9975:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   9976:                         $userallowed=1;
                   9977:                     } else {
                   9978:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   9979:                             $userallowed=1;
                   9980:                         }
                   9981:                     }
                   9982:                     unless ($userallowed) {
                   9983:                         if (defined($env{'request.course.groups'})) {
                   9984:                             my @groups = split(/:/,$env{'request.course.groups'});
                   9985:                             foreach my $group (@groups) {
                   9986:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   9987:                                     $userallowed=1;
                   9988:                                     last;
                   9989:                                 }
                   9990:                             }
                   9991:                         }
                   9992:                     }
                   9993:                 }
                   9994:                 if ($slots{$slot}->{'allowedusers'}) {
                   9995:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   9996:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   9997:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   9998:                         $userallowed = 1;
                   9999:                     }
                   10000:                 }
                   10001:                 next unless($userallowed);
                   10002:             }
                   10003:             my $startreserve = $slots{$slot}->{'startreserve'};
                   10004:             my $endreserve = $slots{$slot}->{'endreserve'};
                   10005:             my $symb = $slots{$slot}->{'symb'};
                   10006:             if (($startreserve < $now) &&
                   10007:                 (!$endreserve || $endreserve > $now)) {
                   10008:                 my $lastres = $endreserve;
                   10009:                 if (!$lastres) {
                   10010:                     $lastres = $slots{$slot}->{'starttime'};
                   10011:                 }
                   10012:                 $reservable_now{$slot} = {
                   10013:                                            symb       => $symb,
                   10014:                                            endreserve => $lastres
                   10015:                                          };
                   10016:             } elsif (($startreserve > $now) &&
                   10017:                      (!$endreserve || $endreserve > $startreserve)) {
                   10018:                 $future_reservable{$slot} = {
                   10019:                                               symb         => $symb,
                   10020:                                               startreserve => $startreserve
                   10021:                                             };
                   10022:             }
                   10023:         }
                   10024:     }
                   10025:     my @unsorted_reservable = keys(%reservable_now);
                   10026:     if (@unsorted_reservable > 0) {
                   10027:         @sorted_reservable = 
                   10028:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   10029:     }
                   10030:     my @unsorted_future = keys(%future_reservable);
                   10031:     if (@unsorted_future > 0) {
                   10032:         @sorted_future =
                   10033:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   10034:     }
                   10035:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   10036: }
1.780     raeburn  10037: 
                   10038: =pod
                   10039: 
1.1057    foxr     10040: =back
                   10041: 
1.549     albertel 10042: =head1 HTTP Helpers
                   10043: 
                   10044: =over 4
                   10045: 
1.648     raeburn  10046: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 10047: 
1.258     albertel 10048: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 10049: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 10050: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 10051: 
                   10052: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   10053: $possible_names is an ref to an array of form element names.  As an example:
                   10054: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 10055: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 10056: 
                   10057: =cut
1.1       albertel 10058: 
1.6       albertel 10059: sub get_unprocessed_cgi {
1.25      albertel 10060:   my ($query,$possible_names)= @_;
1.26      matthew  10061:   # $Apache::lonxml::debug=1;
1.356     albertel 10062:   foreach my $pair (split(/&/,$query)) {
                   10063:     my ($name, $value) = split(/=/,$pair);
1.369     www      10064:     $name = &unescape($name);
1.25      albertel 10065:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   10066:       $value =~ tr/+/ /;
                   10067:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 10068:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 10069:     }
1.16      harris41 10070:   }
1.6       albertel 10071: }
                   10072: 
1.112     bowersj2 10073: =pod
                   10074: 
1.648     raeburn  10075: =item * &cacheheader() 
1.112     bowersj2 10076: 
                   10077: returns cache-controlling header code
                   10078: 
                   10079: =cut
                   10080: 
1.7       albertel 10081: sub cacheheader {
1.258     albertel 10082:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 10083:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   10084:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 10085:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   10086:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 10087:     return $output;
1.7       albertel 10088: }
                   10089: 
1.112     bowersj2 10090: =pod
                   10091: 
1.648     raeburn  10092: =item * &no_cache($r) 
1.112     bowersj2 10093: 
                   10094: specifies header code to not have cache
                   10095: 
                   10096: =cut
                   10097: 
1.9       albertel 10098: sub no_cache {
1.216     albertel 10099:     my ($r) = @_;
                   10100:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 10101: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 10102:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   10103:     $r->no_cache(1);
                   10104:     $r->header_out("Expires" => $date);
                   10105:     $r->header_out("Pragma" => "no-cache");
1.123     www      10106: }
                   10107: 
                   10108: sub content_type {
1.181     albertel 10109:     my ($r,$type,$charset) = @_;
1.299     foxr     10110:     if ($r) {
                   10111: 	#  Note that printout.pl calls this with undef for $r.
                   10112: 	&no_cache($r);
                   10113:     }
1.258     albertel 10114:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 10115:     unless ($charset) {
                   10116: 	$charset=&Apache::lonlocal::current_encoding;
                   10117:     }
                   10118:     if ($charset) { $type.='; charset='.$charset; }
                   10119:     if ($r) {
                   10120: 	$r->content_type($type);
                   10121:     } else {
                   10122: 	print("Content-type: $type\n\n");
                   10123:     }
1.9       albertel 10124: }
1.25      albertel 10125: 
1.112     bowersj2 10126: =pod
                   10127: 
1.648     raeburn  10128: =item * &add_to_env($name,$value) 
1.112     bowersj2 10129: 
1.258     albertel 10130: adds $name to the %env hash with value
1.112     bowersj2 10131: $value, if $name already exists, the entry is converted to an array
                   10132: reference and $value is added to the array.
                   10133: 
                   10134: =cut
                   10135: 
1.25      albertel 10136: sub add_to_env {
                   10137:   my ($name,$value)=@_;
1.258     albertel 10138:   if (defined($env{$name})) {
                   10139:     if (ref($env{$name})) {
1.25      albertel 10140:       #already have multiple values
1.258     albertel 10141:       push(@{ $env{$name} },$value);
1.25      albertel 10142:     } else {
                   10143:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 10144:       my $first=$env{$name};
                   10145:       undef($env{$name});
                   10146:       push(@{ $env{$name} },$first,$value);
1.25      albertel 10147:     }
                   10148:   } else {
1.258     albertel 10149:     $env{$name}=$value;
1.25      albertel 10150:   }
1.31      albertel 10151: }
1.149     albertel 10152: 
                   10153: =pod
                   10154: 
1.648     raeburn  10155: =item * &get_env_multiple($name) 
1.149     albertel 10156: 
1.258     albertel 10157: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 10158: values may be defined and end up as an array ref.
                   10159: 
                   10160: returns an array of values
                   10161: 
                   10162: =cut
                   10163: 
                   10164: sub get_env_multiple {
                   10165:     my ($name) = @_;
                   10166:     my @values;
1.258     albertel 10167:     if (defined($env{$name})) {
1.149     albertel 10168:         # exists is it an array
1.258     albertel 10169:         if (ref($env{$name})) {
                   10170:             @values=@{ $env{$name} };
1.149     albertel 10171:         } else {
1.258     albertel 10172:             $values[0]=$env{$name};
1.149     albertel 10173:         }
                   10174:     }
                   10175:     return(@values);
                   10176: }
                   10177: 
1.660     raeburn  10178: sub ask_for_embedded_content {
                   10179:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  10180:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  10181:         %currsubfile,%unused,$rem);
1.1071    raeburn  10182:     my $counter = 0;
                   10183:     my $numnew = 0;
1.987     raeburn  10184:     my $numremref = 0;
                   10185:     my $numinvalid = 0;
                   10186:     my $numpathchg = 0;
                   10187:     my $numexisting = 0;
1.1071    raeburn  10188:     my $numunused = 0;
                   10189:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  10190:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  10191:     my $heading = &mt('Upload embedded files');
                   10192:     my $buttontext = &mt('Upload');
                   10193: 
1.1085    raeburn  10194:     if ($env{'request.course.id'}) {
1.1123    raeburn  10195:         if ($actionurl eq '/adm/dependencies') {
                   10196:             $navmap = Apache::lonnavmaps::navmap->new();
                   10197:         }
                   10198:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10199:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  10200:     }
1.1123    raeburn  10201:     if (($actionurl eq '/adm/portfolio') || 
                   10202:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  10203:         my $current_path='/';
                   10204:         if ($env{'form.currentpath'}) {
                   10205:             $current_path = $env{'form.currentpath'};
                   10206:         }
                   10207:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  10208:             $udom = $cdom;
                   10209:             $uname = $cnum;
1.984     raeburn  10210:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   10211:         } else {
                   10212:             $udom = $env{'user.domain'};
                   10213:             $uname = $env{'user.name'};
                   10214:             $url = '/userfiles/portfolio';
                   10215:         }
1.987     raeburn  10216:         $toplevel = $url.'/';
1.984     raeburn  10217:         $url .= $current_path;
                   10218:         $getpropath = 1;
1.987     raeburn  10219:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   10220:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      10221:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  10222:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  10223:         $toplevel = $url;
1.984     raeburn  10224:         if ($rest ne '') {
1.987     raeburn  10225:             $url .= $rest;
                   10226:         }
                   10227:     } elsif ($actionurl eq '/adm/coursedocs') {
                   10228:         if (ref($args) eq 'HASH') {
1.1071    raeburn  10229:             $url = $args->{'docs_url'};
                   10230:             $toplevel = $url;
1.1084    raeburn  10231:             if ($args->{'context'} eq 'paste') {
                   10232:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   10233:                 ($path) = 
                   10234:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10235:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10236:                 $fileloc =~ s{^/}{};
                   10237:             }
1.1071    raeburn  10238:         }
1.1084    raeburn  10239:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  10240:         if ($env{'request.course.id'} ne '') {
                   10241:             if (ref($args) eq 'HASH') {
                   10242:                 $url = $args->{'docs_url'};
                   10243:                 $title = $args->{'docs_title'};
1.1126    raeburn  10244:                 $toplevel = $url; 
                   10245:                 unless ($toplevel =~ m{^/}) {
                   10246:                     $toplevel = "/$url";
                   10247:                 }
1.1085    raeburn  10248:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  10249:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   10250:                     $path = $1;
                   10251:                 } else {
                   10252:                     ($path) =
                   10253:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10254:                 }
1.1195    raeburn  10255:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   10256:                     $fileloc = $toplevel;
                   10257:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   10258:                     my ($udom,$uname,$fname) =
                   10259:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   10260:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   10261:                 } else {
                   10262:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10263:                 }
1.1071    raeburn  10264:                 $fileloc =~ s{^/}{};
                   10265:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   10266:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   10267:             }
1.987     raeburn  10268:         }
1.1123    raeburn  10269:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10270:         $udom = $cdom;
                   10271:         $uname = $cnum;
                   10272:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   10273:         $toplevel = $url;
                   10274:         $path = $url;
                   10275:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   10276:         $fileloc =~ s{^/}{};
1.987     raeburn  10277:     }
1.1126    raeburn  10278:     foreach my $file (keys(%{$allfiles})) {
                   10279:         my $embed_file;
                   10280:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   10281:             $embed_file = $1;
                   10282:         } else {
                   10283:             $embed_file = $file;
                   10284:         }
1.1158    raeburn  10285:         my ($absolutepath,$cleaned_file);
                   10286:         if ($embed_file =~ m{^\w+://}) {
                   10287:             $cleaned_file = $embed_file;
1.1147    raeburn  10288:             $newfiles{$cleaned_file} = 1;
                   10289:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10290:         } else {
1.1158    raeburn  10291:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  10292:             if ($embed_file =~ m{^/}) {
                   10293:                 $absolutepath = $embed_file;
                   10294:             }
1.1147    raeburn  10295:             if ($cleaned_file =~ m{/}) {
                   10296:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  10297:                 $path = &check_for_traversal($path,$url,$toplevel);
                   10298:                 my $item = $fname;
                   10299:                 if ($path ne '') {
                   10300:                     $item = $path.'/'.$fname;
                   10301:                     $subdependencies{$path}{$fname} = 1;
                   10302:                 } else {
                   10303:                     $dependencies{$item} = 1;
                   10304:                 }
                   10305:                 if ($absolutepath) {
                   10306:                     $mapping{$item} = $absolutepath;
                   10307:                 } else {
                   10308:                     $mapping{$item} = $embed_file;
                   10309:                 }
                   10310:             } else {
                   10311:                 $dependencies{$embed_file} = 1;
                   10312:                 if ($absolutepath) {
1.1147    raeburn  10313:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  10314:                 } else {
1.1147    raeburn  10315:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10316:                 }
                   10317:             }
1.984     raeburn  10318:         }
                   10319:     }
1.1071    raeburn  10320:     my $dirptr = 16384;
1.984     raeburn  10321:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  10322:         $currsubfile{$path} = {};
1.1123    raeburn  10323:         if (($actionurl eq '/adm/portfolio') || 
                   10324:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10325:             my ($sublistref,$listerror) =
                   10326:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   10327:             if (ref($sublistref) eq 'ARRAY') {
                   10328:                 foreach my $line (@{$sublistref}) {
                   10329:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  10330:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  10331:                 }
1.984     raeburn  10332:             }
1.987     raeburn  10333:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10334:             if (opendir(my $dir,$url.'/'.$path)) {
                   10335:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  10336:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   10337:             }
1.1084    raeburn  10338:         } elsif (($actionurl eq '/adm/dependencies') ||
                   10339:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  10340:                   ($args->{'context'} eq 'paste')) ||
                   10341:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10342:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  10343:                 my $dir;
                   10344:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10345:                     $dir = $fileloc;
                   10346:                 } else {
                   10347:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10348:                 }
1.1071    raeburn  10349:                 if ($dir ne '') {
                   10350:                     my ($sublistref,$listerror) =
                   10351:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   10352:                     if (ref($sublistref) eq 'ARRAY') {
                   10353:                         foreach my $line (@{$sublistref}) {
                   10354:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   10355:                                 undef,$mtime)=split(/\&/,$line,12);
                   10356:                             unless (($testdir&$dirptr) ||
                   10357:                                     ($file_name =~ /^\.\.?$/)) {
                   10358:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   10359:                             }
                   10360:                         }
                   10361:                     }
                   10362:                 }
1.984     raeburn  10363:             }
                   10364:         }
                   10365:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  10366:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  10367:                 my $item = $path.'/'.$file;
                   10368:                 unless ($mapping{$item} eq $item) {
                   10369:                     $pathchanges{$item} = 1;
                   10370:                 }
                   10371:                 $existing{$item} = 1;
                   10372:                 $numexisting ++;
                   10373:             } else {
                   10374:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  10375:             }
                   10376:         }
1.1071    raeburn  10377:         if ($actionurl eq '/adm/dependencies') {
                   10378:             foreach my $path (keys(%currsubfile)) {
                   10379:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   10380:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   10381:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  10382:                              next if (($rem ne '') &&
                   10383:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   10384:                                        (ref($navmap) &&
                   10385:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   10386:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10387:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  10388:                              $unused{$path.'/'.$file} = 1; 
                   10389:                          }
                   10390:                     }
                   10391:                 }
                   10392:             }
                   10393:         }
1.984     raeburn  10394:     }
1.987     raeburn  10395:     my %currfile;
1.1123    raeburn  10396:     if (($actionurl eq '/adm/portfolio') ||
                   10397:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10398:         my ($dirlistref,$listerror) =
                   10399:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   10400:         if (ref($dirlistref) eq 'ARRAY') {
                   10401:             foreach my $line (@{$dirlistref}) {
                   10402:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   10403:                 $currfile{$file_name} = 1;
                   10404:             }
1.984     raeburn  10405:         }
1.987     raeburn  10406:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10407:         if (opendir(my $dir,$url)) {
1.987     raeburn  10408:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  10409:             map {$currfile{$_} = 1;} @dir_list;
                   10410:         }
1.1084    raeburn  10411:     } elsif (($actionurl eq '/adm/dependencies') ||
                   10412:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  10413:               ($args->{'context'} eq 'paste')) ||
                   10414:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10415:         if ($env{'request.course.id'} ne '') {
                   10416:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10417:             if ($dir ne '') {
                   10418:                 my ($dirlistref,$listerror) =
                   10419:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   10420:                 if (ref($dirlistref) eq 'ARRAY') {
                   10421:                     foreach my $line (@{$dirlistref}) {
                   10422:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   10423:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   10424:                         unless (($testdir&$dirptr) ||
                   10425:                                 ($file_name =~ /^\.\.?$/)) {
                   10426:                             $currfile{$file_name} = [$size,$mtime];
                   10427:                         }
                   10428:                     }
                   10429:                 }
                   10430:             }
                   10431:         }
1.984     raeburn  10432:     }
                   10433:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  10434:         if (exists($currfile{$file})) {
1.987     raeburn  10435:             unless ($mapping{$file} eq $file) {
                   10436:                 $pathchanges{$file} = 1;
                   10437:             }
                   10438:             $existing{$file} = 1;
                   10439:             $numexisting ++;
                   10440:         } else {
1.984     raeburn  10441:             $newfiles{$file} = 1;
                   10442:         }
                   10443:     }
1.1071    raeburn  10444:     foreach my $file (keys(%currfile)) {
                   10445:         unless (($file eq $filename) ||
                   10446:                 ($file eq $filename.'.bak') ||
                   10447:                 ($dependencies{$file})) {
1.1085    raeburn  10448:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  10449:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   10450:                     next if (($rem ne '') &&
                   10451:                              (($env{"httpref.$rem".$file} ne '') ||
                   10452:                               (ref($navmap) &&
                   10453:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   10454:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10455:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   10456:                 }
1.1085    raeburn  10457:             }
1.1071    raeburn  10458:             $unused{$file} = 1;
                   10459:         }
                   10460:     }
1.1084    raeburn  10461:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   10462:         ($args->{'context'} eq 'paste')) {
                   10463:         $counter = scalar(keys(%existing));
                   10464:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  10465:         return ($output,$counter,$numpathchg,\%existing);
                   10466:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   10467:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   10468:         $counter = scalar(keys(%existing));
                   10469:         $numpathchg = scalar(keys(%pathchanges));
                   10470:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  10471:     }
1.984     raeburn  10472:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  10473:         if ($actionurl eq '/adm/dependencies') {
                   10474:             next if ($embed_file =~ m{^\w+://});
                   10475:         }
1.660     raeburn  10476:         $upload_output .= &start_data_table_row().
1.1123    raeburn  10477:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  10478:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  10479:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  10480:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   10481:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  10482:         }
1.1123    raeburn  10483:         $upload_output .= '</td>';
1.1071    raeburn  10484:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  10485:             $upload_output.='<td align="right">'.
                   10486:                             '<span class="LC_info LC_fontsize_medium">'.
                   10487:                             &mt("URL points to web address").'</span>';
1.987     raeburn  10488:             $numremref++;
1.660     raeburn  10489:         } elsif ($args->{'error_on_invalid_names'}
                   10490:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  10491:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   10492:                             &mt('Invalid characters').'</span>';
1.987     raeburn  10493:             $numinvalid++;
1.660     raeburn  10494:         } else {
1.1123    raeburn  10495:             $upload_output .= '<td>'.
                   10496:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  10497:                                                      $embed_file,\%mapping,
1.1071    raeburn  10498:                                                      $allfiles,$codebase,'upload');
                   10499:             $counter ++;
                   10500:             $numnew ++;
1.987     raeburn  10501:         }
                   10502:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   10503:     }
                   10504:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  10505:         if ($actionurl eq '/adm/dependencies') {
                   10506:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   10507:             $modify_output .= &start_data_table_row().
                   10508:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   10509:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   10510:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   10511:                               '<td>'.$size.'</td>'.
                   10512:                               '<td>'.$mtime.'</td>'.
                   10513:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   10514:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   10515:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   10516:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   10517:                               &embedded_file_element('upload_embedded',$counter,
                   10518:                                                      $embed_file,\%mapping,
                   10519:                                                      $allfiles,$codebase,'modify').
                   10520:                               '</div></td>'.
                   10521:                               &end_data_table_row()."\n";
                   10522:             $counter ++;
                   10523:         } else {
                   10524:             $upload_output .= &start_data_table_row().
1.1123    raeburn  10525:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   10526:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   10527:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  10528:                               &Apache::loncommon::end_data_table_row()."\n";
                   10529:         }
                   10530:     }
                   10531:     my $delidx = $counter;
                   10532:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   10533:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   10534:         $delete_output .= &start_data_table_row().
                   10535:                           '<td><img src="'.&icon($oldfile).'" />'.
                   10536:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   10537:                           '<td>'.$size.'</td>'.
                   10538:                           '<td>'.$mtime.'</td>'.
                   10539:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   10540:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   10541:                           &embedded_file_element('upload_embedded',$delidx,
                   10542:                                                  $oldfile,\%mapping,$allfiles,
                   10543:                                                  $codebase,'delete').'</td>'.
                   10544:                           &end_data_table_row()."\n"; 
                   10545:         $numunused ++;
                   10546:         $delidx ++;
1.987     raeburn  10547:     }
                   10548:     if ($upload_output) {
                   10549:         $upload_output = &start_data_table().
                   10550:                          $upload_output.
                   10551:                          &end_data_table()."\n";
                   10552:     }
1.1071    raeburn  10553:     if ($modify_output) {
                   10554:         $modify_output = &start_data_table().
                   10555:                          &start_data_table_header_row().
                   10556:                          '<th>'.&mt('File').'</th>'.
                   10557:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10558:                          '<th>'.&mt('Modified').'</th>'.
                   10559:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   10560:                          &end_data_table_header_row().
                   10561:                          $modify_output.
                   10562:                          &end_data_table()."\n";
                   10563:     }
                   10564:     if ($delete_output) {
                   10565:         $delete_output = &start_data_table().
                   10566:                          &start_data_table_header_row().
                   10567:                          '<th>'.&mt('File').'</th>'.
                   10568:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10569:                          '<th>'.&mt('Modified').'</th>'.
                   10570:                          '<th>'.&mt('Delete?').'</th>'.
                   10571:                          &end_data_table_header_row().
                   10572:                          $delete_output.
                   10573:                          &end_data_table()."\n";
                   10574:     }
1.987     raeburn  10575:     my $applies = 0;
                   10576:     if ($numremref) {
                   10577:         $applies ++;
                   10578:     }
                   10579:     if ($numinvalid) {
                   10580:         $applies ++;
                   10581:     }
                   10582:     if ($numexisting) {
                   10583:         $applies ++;
                   10584:     }
1.1071    raeburn  10585:     if ($counter || $numunused) {
1.987     raeburn  10586:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   10587:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  10588:                   $state.'<h3>'.$heading.'</h3>'; 
                   10589:         if ($actionurl eq '/adm/dependencies') {
                   10590:             if ($numnew) {
                   10591:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   10592:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   10593:                            $upload_output.'<br />'."\n";
                   10594:             }
                   10595:             if ($numexisting) {
                   10596:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   10597:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   10598:                            $modify_output.'<br />'."\n";
                   10599:                            $buttontext = &mt('Save changes');
                   10600:             }
                   10601:             if ($numunused) {
                   10602:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   10603:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   10604:                            $delete_output.'<br />'."\n";
                   10605:                            $buttontext = &mt('Save changes');
                   10606:             }
                   10607:         } else {
                   10608:             $output .= $upload_output.'<br />'."\n";
                   10609:         }
                   10610:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   10611:                    $counter.'" />'."\n";
                   10612:         if ($actionurl eq '/adm/dependencies') { 
                   10613:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   10614:                        $numnew.'" />'."\n";
                   10615:         } elsif ($actionurl eq '') {
1.987     raeburn  10616:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   10617:         }
                   10618:     } elsif ($applies) {
                   10619:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   10620:         if ($applies > 1) {
                   10621:             $output .=  
1.1123    raeburn  10622:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  10623:             if ($numremref) {
                   10624:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   10625:             }
                   10626:             if ($numinvalid) {
                   10627:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   10628:             }
                   10629:             if ($numexisting) {
                   10630:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   10631:             }
                   10632:             $output .= '</ul><br />';
                   10633:         } elsif ($numremref) {
                   10634:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   10635:         } elsif ($numinvalid) {
                   10636:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   10637:         } elsif ($numexisting) {
                   10638:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   10639:         }
                   10640:         $output .= $upload_output.'<br />';
                   10641:     }
                   10642:     my ($pathchange_output,$chgcount);
1.1071    raeburn  10643:     $chgcount = $counter;
1.987     raeburn  10644:     if (keys(%pathchanges) > 0) {
                   10645:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  10646:             if ($counter) {
1.987     raeburn  10647:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   10648:                                                   $embed_file,\%mapping,
1.1071    raeburn  10649:                                                   $allfiles,$codebase,'change');
1.987     raeburn  10650:             } else {
                   10651:                 $pathchange_output .= 
                   10652:                     &start_data_table_row().
                   10653:                     '<td><input type ="checkbox" name="namechange" value="'.
                   10654:                     $chgcount.'" checked="checked" /></td>'.
                   10655:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   10656:                     '<td>'.$embed_file.
                   10657:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  10658:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  10659:                     '</td>'.&end_data_table_row();
1.660     raeburn  10660:             }
1.987     raeburn  10661:             $numpathchg ++;
                   10662:             $chgcount ++;
1.660     raeburn  10663:         }
                   10664:     }
1.1127    raeburn  10665:     if (($counter) || ($numunused)) {
1.987     raeburn  10666:         if ($numpathchg) {
                   10667:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   10668:                        $numpathchg.'" />'."\n";
                   10669:         }
                   10670:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   10671:             ($actionurl eq '/adm/imsimport')) {
                   10672:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   10673:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   10674:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  10675:         } elsif ($actionurl eq '/adm/dependencies') {
                   10676:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  10677:         }
1.1123    raeburn  10678:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  10679:     } elsif ($numpathchg) {
                   10680:         my %pathchange = ();
                   10681:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   10682:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   10683:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  10684:         }
1.987     raeburn  10685:     }
1.1071    raeburn  10686:     return ($output,$counter,$numpathchg);
1.987     raeburn  10687: }
                   10688: 
1.1147    raeburn  10689: =pod
                   10690: 
                   10691: =item * clean_path($name)
                   10692: 
                   10693: Performs clean-up of directories, subdirectories and filename in an
                   10694: embedded object, referenced in an HTML file which is being uploaded
                   10695: to a course or portfolio, where 
                   10696: "Upload embedded images/multimedia files if HTML file" checkbox was
                   10697: checked.
                   10698: 
                   10699: Clean-up is similar to replacements in lonnet::clean_filename()
                   10700: except each / between sub-directory and next level is preserved.
                   10701: 
                   10702: =cut
                   10703: 
                   10704: sub clean_path {
                   10705:     my ($embed_file) = @_;
                   10706:     $embed_file =~s{^/+}{};
                   10707:     my @contents;
                   10708:     if ($embed_file =~ m{/}) {
                   10709:         @contents = split(/\//,$embed_file);
                   10710:     } else {
                   10711:         @contents = ($embed_file);
                   10712:     }
                   10713:     my $lastidx = scalar(@contents)-1;
                   10714:     for (my $i=0; $i<=$lastidx; $i++) { 
                   10715:         $contents[$i]=~s{\\}{/}g;
                   10716:         $contents[$i]=~s/\s+/\_/g;
                   10717:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   10718:         if ($i == $lastidx) {
                   10719:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   10720:         }
                   10721:     }
                   10722:     if ($lastidx > 0) {
                   10723:         return join('/',@contents);
                   10724:     } else {
                   10725:         return $contents[0];
                   10726:     }
                   10727: }
                   10728: 
1.987     raeburn  10729: sub embedded_file_element {
1.1071    raeburn  10730:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  10731:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   10732:                    (ref($codebase) eq 'HASH'));
                   10733:     my $output;
1.1071    raeburn  10734:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  10735:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   10736:     }
                   10737:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   10738:                &escape($embed_file).'" />';
                   10739:     unless (($context eq 'upload_embedded') && 
                   10740:             ($mapping->{$embed_file} eq $embed_file)) {
                   10741:         $output .='
                   10742:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   10743:     }
                   10744:     my $attrib;
                   10745:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   10746:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   10747:     }
                   10748:     $output .=
                   10749:         "\n\t\t".
                   10750:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   10751:         $attrib.'" />';
                   10752:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   10753:         $output .=
                   10754:             "\n\t\t".
                   10755:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   10756:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  10757:     }
1.987     raeburn  10758:     return $output;
1.660     raeburn  10759: }
                   10760: 
1.1071    raeburn  10761: sub get_dependency_details {
                   10762:     my ($currfile,$currsubfile,$embed_file) = @_;
                   10763:     my ($size,$mtime,$showsize,$showmtime);
                   10764:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   10765:         if ($embed_file =~ m{/}) {
                   10766:             my ($path,$fname) = split(/\//,$embed_file);
                   10767:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   10768:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   10769:             }
                   10770:         } else {
                   10771:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   10772:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   10773:             }
                   10774:         }
                   10775:         $showsize = $size/1024.0;
                   10776:         $showsize = sprintf("%.1f",$showsize);
                   10777:         if ($mtime > 0) {
                   10778:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   10779:         }
                   10780:     }
                   10781:     return ($showsize,$showmtime);
                   10782: }
                   10783: 
                   10784: sub ask_embedded_js {
                   10785:     return <<"END";
                   10786: <script type="text/javascript"">
                   10787: // <![CDATA[
                   10788: function toggleBrowse(counter) {
                   10789:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   10790:     var fileid = document.getElementById('embedded_item_'+counter);
                   10791:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   10792:     if (chkboxid.checked == true) {
                   10793:         uploaddivid.style.display='block';
                   10794:     } else {
                   10795:         uploaddivid.style.display='none';
                   10796:         fileid.value = '';
                   10797:     }
                   10798: }
                   10799: // ]]>
                   10800: </script>
                   10801: 
                   10802: END
                   10803: }
                   10804: 
1.661     raeburn  10805: sub upload_embedded {
                   10806:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  10807:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   10808:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  10809:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   10810:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   10811:         my $orig_uploaded_filename =
                   10812:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  10813:         foreach my $type ('orig','ref','attrib','codebase') {
                   10814:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   10815:                 $env{'form.embedded_'.$type.'_'.$i} =
                   10816:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   10817:             }
                   10818:         }
1.661     raeburn  10819:         my ($path,$fname) =
                   10820:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   10821:         # no path, whole string is fname
                   10822:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   10823:         $fname = &Apache::lonnet::clean_filename($fname);
                   10824:         # See if there is anything left
                   10825:         next if ($fname eq '');
                   10826: 
                   10827:         # Check if file already exists as a file or directory.
                   10828:         my ($state,$msg);
                   10829:         if ($context eq 'portfolio') {
                   10830:             my $port_path = $dirpath;
                   10831:             if ($group ne '') {
                   10832:                 $port_path = "groups/$group/$port_path";
                   10833:             }
1.987     raeburn  10834:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   10835:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  10836:                                               $dir_root,$port_path,$disk_quota,
                   10837:                                               $current_disk_usage,$uname,$udom);
                   10838:             if ($state eq 'will_exceed_quota'
1.984     raeburn  10839:                 || $state eq 'file_locked') {
1.661     raeburn  10840:                 $output .= $msg;
                   10841:                 next;
                   10842:             }
                   10843:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   10844:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   10845:             if ($state eq 'exists') {
                   10846:                 $output .= $msg;
                   10847:                 next;
                   10848:             }
                   10849:         }
                   10850:         # Check if extension is valid
                   10851:         if (($fname =~ /\.(\w+)$/) &&
                   10852:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   10853:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   10854:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  10855:             next;
                   10856:         } elsif (($fname =~ /\.(\w+)$/) &&
                   10857:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  10858:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  10859:             next;
                   10860:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   10861:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
1.661     raeburn  10862:             next;
                   10863:         }
                   10864:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  10865:         my $subdir = $path;
                   10866:         $subdir =~ s{/+$}{};
1.661     raeburn  10867:         if ($context eq 'portfolio') {
1.984     raeburn  10868:             my $result;
                   10869:             if ($state eq 'existingfile') {
                   10870:                 $result=
                   10871:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  10872:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  10873:             } else {
1.984     raeburn  10874:                 $result=
                   10875:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  10876:                                                     $dirpath.
1.1123    raeburn  10877:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  10878:                 if ($result !~ m|^/uploaded/|) {
                   10879:                     $output .= '<span class="LC_error">'
                   10880:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10881:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10882:                                .'</span><br />';
                   10883:                     next;
                   10884:                 } else {
1.987     raeburn  10885:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10886:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  10887:                 }
1.661     raeburn  10888:             }
1.1123    raeburn  10889:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  10890:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   10891:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  10892:             my $result =
1.1126    raeburn  10893:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  10894:             if ($result !~ m|^/uploaded/|) {
                   10895:                 $output .= '<span class="LC_error">'
                   10896:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10897:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10898:                            .'</span><br />';
                   10899:                     next;
                   10900:             } else {
                   10901:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10902:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  10903:                 if ($context eq 'syllabus') {
                   10904:                     &Apache::lonnet::make_public_indefinitely($result);
                   10905:                 }
1.987     raeburn  10906:             }
1.661     raeburn  10907:         } else {
                   10908: # Save the file
                   10909:             my $target = $env{'form.embedded_item_'.$i};
                   10910:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   10911:             my $dest = $fullpath.$fname;
                   10912:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  10913:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  10914:             my $count;
                   10915:             my $filepath = $dir_root;
1.1027    raeburn  10916:             foreach my $subdir (@parts) {
                   10917:                 $filepath .= "/$subdir";
                   10918:                 if (!-e $filepath) {
1.661     raeburn  10919:                     mkdir($filepath,0770);
                   10920:                 }
                   10921:             }
                   10922:             my $fh;
                   10923:             if (!open($fh,'>'.$dest)) {
                   10924:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   10925:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  10926:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   10927:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  10928:                            '</span><br />';
                   10929:             } else {
                   10930:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   10931:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   10932:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  10933:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   10934:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  10935:                               '</span><br />';
                   10936:                 } else {
1.987     raeburn  10937:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10938:                                $url.'</span>').'<br />';
                   10939:                     unless ($context eq 'testbank') {
                   10940:                         $footer .= &mt('View embedded file: [_1]',
                   10941:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   10942:                     }
                   10943:                 }
                   10944:                 close($fh);
                   10945:             }
                   10946:         }
                   10947:         if ($env{'form.embedded_ref_'.$i}) {
                   10948:             $pathchange{$i} = 1;
                   10949:         }
                   10950:     }
                   10951:     if ($output) {
                   10952:         $output = '<p>'.$output.'</p>';
                   10953:     }
                   10954:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   10955:     $returnflag = 'ok';
1.1071    raeburn  10956:     my $numpathchgs = scalar(keys(%pathchange));
                   10957:     if ($numpathchgs > 0) {
1.987     raeburn  10958:         if ($context eq 'portfolio') {
                   10959:             $output .= '<p>'.&mt('or').'</p>';
                   10960:         } elsif ($context eq 'testbank') {
1.1071    raeburn  10961:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   10962:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  10963:             $returnflag = 'modify_orightml';
                   10964:         }
                   10965:     }
1.1071    raeburn  10966:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  10967: }
                   10968: 
                   10969: sub modify_html_form {
                   10970:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   10971:     my $end = 0;
                   10972:     my $modifyform;
                   10973:     if ($context eq 'upload_embedded') {
                   10974:         return unless (ref($pathchange) eq 'HASH');
                   10975:         if ($env{'form.number_embedded_items'}) {
                   10976:             $end += $env{'form.number_embedded_items'};
                   10977:         }
                   10978:         if ($env{'form.number_pathchange_items'}) {
                   10979:             $end += $env{'form.number_pathchange_items'};
                   10980:         }
                   10981:         if ($end) {
                   10982:             for (my $i=0; $i<$end; $i++) {
                   10983:                 if ($i < $env{'form.number_embedded_items'}) {
                   10984:                     next unless($pathchange->{$i});
                   10985:                 }
                   10986:                 $modifyform .=
                   10987:                     &start_data_table_row().
                   10988:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   10989:                     'checked="checked" /></td>'.
                   10990:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   10991:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   10992:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   10993:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   10994:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   10995:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   10996:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   10997:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   10998:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   10999:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   11000:                     &end_data_table_row();
1.1071    raeburn  11001:             }
1.987     raeburn  11002:         }
                   11003:     } else {
                   11004:         $modifyform = $pathchgtable;
                   11005:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   11006:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   11007:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11008:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   11009:         }
                   11010:     }
                   11011:     if ($modifyform) {
1.1071    raeburn  11012:         if ($actionurl eq '/adm/dependencies') {
                   11013:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   11014:         }
1.987     raeburn  11015:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   11016:                '<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".
                   11017:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   11018:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   11019:                '</ol></p>'."\n".'<p>'.
                   11020:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   11021:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   11022:                &start_data_table()."\n".
                   11023:                &start_data_table_header_row().
                   11024:                '<th>'.&mt('Change?').'</th>'.
                   11025:                '<th>'.&mt('Current reference').'</th>'.
                   11026:                '<th>'.&mt('Required reference').'</th>'.
                   11027:                &end_data_table_header_row()."\n".
                   11028:                $modifyform.
                   11029:                &end_data_table().'<br />'."\n".$hiddenstate.
                   11030:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   11031:                '</form>'."\n";
                   11032:     }
                   11033:     return;
                   11034: }
                   11035: 
                   11036: sub modify_html_refs {
1.1123    raeburn  11037:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  11038:     my $container;
                   11039:     if ($context eq 'portfolio') {
                   11040:         $container = $env{'form.container'};
                   11041:     } elsif ($context eq 'coursedoc') {
                   11042:         $container = $env{'form.primaryurl'};
1.1071    raeburn  11043:     } elsif ($context eq 'manage_dependencies') {
                   11044:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   11045:         $container = "/$container";
1.1123    raeburn  11046:     } elsif ($context eq 'syllabus') {
                   11047:         $container = $url;
1.987     raeburn  11048:     } else {
1.1027    raeburn  11049:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  11050:     }
                   11051:     my (%allfiles,%codebase,$output,$content);
                   11052:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  11053:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  11054:         if (wantarray) {
                   11055:             return ('',0,0); 
                   11056:         } else {
                   11057:             return;
                   11058:         }
                   11059:     }
                   11060:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  11061:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  11062:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   11063:             if (wantarray) {
                   11064:                 return ('',0,0);
                   11065:             } else {
                   11066:                 return;
                   11067:             }
                   11068:         } 
1.987     raeburn  11069:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  11070:         if ($content eq '-1') {
                   11071:             if (wantarray) {
                   11072:                 return ('',0,0);
                   11073:             } else {
                   11074:                 return;
                   11075:             }
                   11076:         }
1.987     raeburn  11077:     } else {
1.1071    raeburn  11078:         unless ($container =~ /^\Q$dir_root\E/) {
                   11079:             if (wantarray) {
                   11080:                 return ('',0,0);
                   11081:             } else {
                   11082:                 return;
                   11083:             }
                   11084:         } 
1.987     raeburn  11085:         if (open(my $fh,"<$container")) {
                   11086:             $content = join('', <$fh>);
                   11087:             close($fh);
                   11088:         } else {
1.1071    raeburn  11089:             if (wantarray) {
                   11090:                 return ('',0,0);
                   11091:             } else {
                   11092:                 return;
                   11093:             }
1.987     raeburn  11094:         }
                   11095:     }
                   11096:     my ($count,$codebasecount) = (0,0);
                   11097:     my $mm = new File::MMagic;
                   11098:     my $mime_type = $mm->checktype_contents($content);
                   11099:     if ($mime_type eq 'text/html') {
                   11100:         my $parse_result = 
                   11101:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   11102:                                                     \%codebase,\$content);
                   11103:         if ($parse_result eq 'ok') {
                   11104:             foreach my $i (@changes) {
                   11105:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   11106:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   11107:                 if ($allfiles{$ref}) {
                   11108:                     my $newname =  $orig;
                   11109:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  11110:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  11111:                     if ($attrib_regexp =~ /:/) {
                   11112:                         $attrib_regexp =~ s/\:/|/g;
                   11113:                     }
                   11114:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11115:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11116:                         $count += $numchg;
1.1123    raeburn  11117:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  11118:                         delete($allfiles{$ref});
1.987     raeburn  11119:                     }
                   11120:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  11121:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  11122:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   11123:                         $codebasecount ++;
                   11124:                     }
                   11125:                 }
                   11126:             }
1.1123    raeburn  11127:             my $skiprewrites;
1.987     raeburn  11128:             if ($count || $codebasecount) {
                   11129:                 my $saveresult;
1.1071    raeburn  11130:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  11131:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  11132:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11133:                     if ($url eq $container) {
                   11134:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   11135:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11136:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  11137:                                             $fname.'</span>').'</p>';
1.987     raeburn  11138:                     } else {
                   11139:                          $output = '<p class="LC_error">'.
                   11140:                                    &mt('Error: update failed for: [_1].',
                   11141:                                    '<span class="LC_filename">'.
                   11142:                                    $container.'</span>').'</p>';
                   11143:                     }
1.1123    raeburn  11144:                     if ($context eq 'syllabus') {
                   11145:                         unless ($saveresult eq 'ok') {
                   11146:                             $skiprewrites = 1;
                   11147:                         }
                   11148:                     }
1.987     raeburn  11149:                 } else {
                   11150:                     if (open(my $fh,">$container")) {
                   11151:                         print $fh $content;
                   11152:                         close($fh);
                   11153:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11154:                                   $count,'<span class="LC_filename">'.
                   11155:                                   $container.'</span>').'</p>';
1.661     raeburn  11156:                     } else {
1.987     raeburn  11157:                          $output = '<p class="LC_error">'.
                   11158:                                    &mt('Error: could not update [_1].',
                   11159:                                    '<span class="LC_filename">'.
                   11160:                                    $container.'</span>').'</p>';
1.661     raeburn  11161:                     }
                   11162:                 }
                   11163:             }
1.1123    raeburn  11164:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   11165:                 my ($actionurl,$state);
                   11166:                 $actionurl = "/public/$udom/$uname/syllabus";
                   11167:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   11168:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   11169:                                               \%codebase,
                   11170:                                               {'context' => 'rewrites',
                   11171:                                                'ignore_remote_references' => 1,});
                   11172:                 if (ref($mapping) eq 'HASH') {
                   11173:                     my $rewrites = 0;
                   11174:                     foreach my $key (keys(%{$mapping})) {
                   11175:                         next if ($key =~ m{^https?://});
                   11176:                         my $ref = $mapping->{$key};
                   11177:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   11178:                         my $attrib;
                   11179:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   11180:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   11181:                         }
                   11182:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11183:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11184:                             $rewrites += $numchg;
                   11185:                         }
                   11186:                     }
                   11187:                     if ($rewrites) {
                   11188:                         my $saveresult; 
                   11189:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11190:                         if ($url eq $container) {
                   11191:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   11192:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   11193:                                             $count,'<span class="LC_filename">'.
                   11194:                                             $fname.'</span>').'</p>';
                   11195:                         } else {
                   11196:                             $output .= '<p class="LC_error">'.
                   11197:                                        &mt('Error: could not update links in [_1].',
                   11198:                                        '<span class="LC_filename">'.
                   11199:                                        $container.'</span>').'</p>';
                   11200: 
                   11201:                         }
                   11202:                     }
                   11203:                 }
                   11204:             }
1.987     raeburn  11205:         } else {
                   11206:             &logthis('Failed to parse '.$container.
                   11207:                      ' to modify references: '.$parse_result);
1.661     raeburn  11208:         }
                   11209:     }
1.1071    raeburn  11210:     if (wantarray) {
                   11211:         return ($output,$count,$codebasecount);
                   11212:     } else {
                   11213:         return $output;
                   11214:     }
1.661     raeburn  11215: }
                   11216: 
                   11217: sub check_for_existing {
                   11218:     my ($path,$fname,$element) = @_;
                   11219:     my ($state,$msg);
                   11220:     if (-d $path.'/'.$fname) {
                   11221:         $state = 'exists';
                   11222:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11223:     } elsif (-e $path.'/'.$fname) {
                   11224:         $state = 'exists';
                   11225:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11226:     }
                   11227:     if ($state eq 'exists') {
                   11228:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   11229:     }
                   11230:     return ($state,$msg);
                   11231: }
                   11232: 
                   11233: sub check_for_upload {
                   11234:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   11235:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  11236:     my $filesize = length($env{'form.'.$element});
                   11237:     if (!$filesize) {
                   11238:         my $msg = '<span class="LC_error">'.
                   11239:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   11240:                       '<span class="LC_filename">'.$fname.'</span>',
                   11241:                       $filesize).'<br />'.
1.1007    raeburn  11242:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  11243:                   '</span>';
                   11244:         return ('zero_bytes',$msg);
                   11245:     }
                   11246:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  11247:     my $getpropath = 1;
1.1021    raeburn  11248:     my ($dirlistref,$listerror) =
                   11249:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  11250:     my $found_file = 0;
                   11251:     my $locked_file = 0;
1.991     raeburn  11252:     my @lockers;
                   11253:     my $navmap;
                   11254:     if ($env{'request.course.id'}) {
                   11255:         $navmap = Apache::lonnavmaps::navmap->new();
                   11256:     }
1.1021    raeburn  11257:     if (ref($dirlistref) eq 'ARRAY') {
                   11258:         foreach my $line (@{$dirlistref}) {
                   11259:             my ($file_name,$rest)=split(/\&/,$line,2);
                   11260:             if ($file_name eq $fname){
                   11261:                 $file_name = $path.$file_name;
                   11262:                 if ($group ne '') {
                   11263:                     $file_name = $group.$file_name;
                   11264:                 }
                   11265:                 $found_file = 1;
                   11266:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   11267:                     foreach my $lock (@lockers) {
                   11268:                         if (ref($lock) eq 'ARRAY') {
                   11269:                             my ($symb,$crsid) = @{$lock};
                   11270:                             if ($crsid eq $env{'request.course.id'}) {
                   11271:                                 if (ref($navmap)) {
                   11272:                                     my $res = $navmap->getBySymb($symb);
                   11273:                                     foreach my $part (@{$res->parts()}) { 
                   11274:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   11275:                                         unless (($slot_status == $res->RESERVED) ||
                   11276:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   11277:                                             $locked_file = 1;
                   11278:                                         }
1.991     raeburn  11279:                                     }
1.1021    raeburn  11280:                                 } else {
                   11281:                                     $locked_file = 1;
1.991     raeburn  11282:                                 }
                   11283:                             } else {
                   11284:                                 $locked_file = 1;
                   11285:                             }
                   11286:                         }
1.1021    raeburn  11287:                    }
                   11288:                 } else {
                   11289:                     my @info = split(/\&/,$rest);
                   11290:                     my $currsize = $info[6]/1000;
                   11291:                     if ($currsize < $filesize) {
                   11292:                         my $extra = $filesize - $currsize;
                   11293:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   11294:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  11295:                                       &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.',
1.1179    bisitz   11296:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   11297:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   11298:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  11299:                             return ('will_exceed_quota',$msg);
                   11300:                         }
1.984     raeburn  11301:                     }
                   11302:                 }
1.661     raeburn  11303:             }
                   11304:         }
                   11305:     }
                   11306:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   11307:         my $msg = '<p class="LC_warning">'.
                   11308:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  11309:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  11310:         return ('will_exceed_quota',$msg);
                   11311:     } elsif ($found_file) {
                   11312:         if ($locked_file) {
1.1179    bisitz   11313:             my $msg = '<p class="LC_warning">';
1.661     raeburn  11314:             $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>');
1.1179    bisitz   11315:             $msg .= '</p>';
1.661     raeburn  11316:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   11317:             return ('file_locked',$msg);
                   11318:         } else {
1.1179    bisitz   11319:             my $msg = '<p class="LC_error">';
1.984     raeburn  11320:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
1.1179    bisitz   11321:             $msg .= '</p>';
1.984     raeburn  11322:             return ('existingfile',$msg);
1.661     raeburn  11323:         }
                   11324:     }
                   11325: }
                   11326: 
1.987     raeburn  11327: sub check_for_traversal {
                   11328:     my ($path,$url,$toplevel) = @_;
                   11329:     my @parts=split(/\//,$path);
                   11330:     my $cleanpath;
                   11331:     my $fullpath = $url;
                   11332:     for (my $i=0;$i<@parts;$i++) {
                   11333:         next if ($parts[$i] eq '.');
                   11334:         if ($parts[$i] eq '..') {
                   11335:             $fullpath =~ s{([^/]+/)$}{};
                   11336:         } else {
                   11337:             $fullpath .= $parts[$i].'/';
                   11338:         }
                   11339:     }
                   11340:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   11341:         $cleanpath = $1;
                   11342:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   11343:         my $curr_toprel = $1;
                   11344:         my @parts = split(/\//,$curr_toprel);
                   11345:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   11346:         my @urlparts = split(/\//,$url_toprel);
                   11347:         my $doubledots;
                   11348:         my $startdiff = -1;
                   11349:         for (my $i=0; $i<@urlparts; $i++) {
                   11350:             if ($startdiff == -1) {
                   11351:                 unless ($urlparts[$i] eq $parts[$i]) {
                   11352:                     $startdiff = $i;
                   11353:                     $doubledots .= '../';
                   11354:                 }
                   11355:             } else {
                   11356:                 $doubledots .= '../';
                   11357:             }
                   11358:         }
                   11359:         if ($startdiff > -1) {
                   11360:             $cleanpath = $doubledots;
                   11361:             for (my $i=$startdiff; $i<@parts; $i++) {
                   11362:                 $cleanpath .= $parts[$i].'/';
                   11363:             }
                   11364:         }
                   11365:     }
                   11366:     $cleanpath =~ s{(/)$}{};
                   11367:     return $cleanpath;
                   11368: }
1.31      albertel 11369: 
1.1053    raeburn  11370: sub is_archive_file {
                   11371:     my ($mimetype) = @_;
                   11372:     if (($mimetype eq 'application/octet-stream') ||
                   11373:         ($mimetype eq 'application/x-stuffit') ||
                   11374:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   11375:         return 1;
                   11376:     }
                   11377:     return;
                   11378: }
                   11379: 
                   11380: sub decompress_form {
1.1065    raeburn  11381:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  11382:     my %lt = &Apache::lonlocal::texthash (
                   11383:         this => 'This file is an archive file.',
1.1067    raeburn  11384:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  11385:         itsc => 'Its contents are as follows:',
1.1053    raeburn  11386:         youm => 'You may wish to extract its contents.',
                   11387:         extr => 'Extract contents',
1.1067    raeburn  11388:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   11389:         proa => 'Process automatically?',
1.1053    raeburn  11390:         yes  => 'Yes',
                   11391:         no   => 'No',
1.1067    raeburn  11392:         fold => 'Title for folder containing movie',
                   11393:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  11394:     );
1.1065    raeburn  11395:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  11396:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  11397:     my $info = &list_archive_contents($fileloc,\@paths);
                   11398:     if (@paths) {
                   11399:         foreach my $path (@paths) {
                   11400:             $path =~ s{^/}{};
1.1067    raeburn  11401:             if ($path =~ m{^([^/]+)/$}) {
                   11402:                 $topdir = $1;
                   11403:             }
1.1065    raeburn  11404:             if ($path =~ m{^([^/]+)/}) {
                   11405:                 $toplevel{$1} = $path;
                   11406:             } else {
                   11407:                 $toplevel{$path} = $path;
                   11408:             }
                   11409:         }
                   11410:     }
1.1067    raeburn  11411:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  11412:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  11413:                         "$topdir/media/",
                   11414:                         "$topdir/media/$topdir.mp4",
                   11415:                         "$topdir/media/FirstFrame.png",
                   11416:                         "$topdir/media/player.swf",
                   11417:                         "$topdir/media/swfobject.js",
                   11418:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  11419:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  11420:                          "$topdir/$topdir.mp4",
                   11421:                          "$topdir/$topdir\_config.xml",
                   11422:                          "$topdir/$topdir\_controller.swf",
                   11423:                          "$topdir/$topdir\_embed.css",
                   11424:                          "$topdir/$topdir\_First_Frame.png",
                   11425:                          "$topdir/$topdir\_player.html",
                   11426:                          "$topdir/$topdir\_Thumbnails.png",
                   11427:                          "$topdir/playerProductInstall.swf",
                   11428:                          "$topdir/scripts/",
                   11429:                          "$topdir/scripts/config_xml.js",
                   11430:                          "$topdir/scripts/handlebars.js",
                   11431:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   11432:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   11433:                          "$topdir/scripts/modernizr.js",
                   11434:                          "$topdir/scripts/player-min.js",
                   11435:                          "$topdir/scripts/swfobject.js",
                   11436:                          "$topdir/skins/",
                   11437:                          "$topdir/skins/configuration_express.xml",
                   11438:                          "$topdir/skins/express_show/",
                   11439:                          "$topdir/skins/express_show/player-min.css",
                   11440:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  11441:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   11442:                          "$topdir/$topdir.mp4",
                   11443:                          "$topdir/$topdir\_config.xml",
                   11444:                          "$topdir/$topdir\_controller.swf",
                   11445:                          "$topdir/$topdir\_embed.css",
                   11446:                          "$topdir/$topdir\_First_Frame.png",
                   11447:                          "$topdir/$topdir\_player.html",
                   11448:                          "$topdir/$topdir\_Thumbnails.png",
                   11449:                          "$topdir/playerProductInstall.swf",
                   11450:                          "$topdir/scripts/",
                   11451:                          "$topdir/scripts/config_xml.js",
                   11452:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   11453:                          "$topdir/skins/",
                   11454:                          "$topdir/skins/configuration_express.xml",
                   11455:                          "$topdir/skins/express_show/",
                   11456:                          "$topdir/skins/express_show/spritesheet.min.css",
                   11457:                          "$topdir/skins/express_show/spritesheet.png",
                   11458:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  11459:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  11460:         if (@diffs == 0) {
1.1164    raeburn  11461:             $is_camtasia = 6;
                   11462:         } else {
1.1197    raeburn  11463:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  11464:             if (@diffs == 0) {
                   11465:                 $is_camtasia = 8;
1.1197    raeburn  11466:             } else {
                   11467:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   11468:                 if (@diffs == 0) {
                   11469:                     $is_camtasia = 8;
                   11470:                 }
1.1164    raeburn  11471:             }
1.1067    raeburn  11472:         }
                   11473:     }
                   11474:     my $output;
                   11475:     if ($is_camtasia) {
                   11476:         $output = <<"ENDCAM";
                   11477: <script type="text/javascript" language="Javascript">
                   11478: // <![CDATA[
                   11479: 
                   11480: function camtasiaToggle() {
                   11481:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   11482:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  11483:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  11484: 
                   11485:                 document.getElementById('camtasia_titles').style.display='block';
                   11486:             } else {
                   11487:                 document.getElementById('camtasia_titles').style.display='none';
                   11488:             }
                   11489:         }
                   11490:     }
                   11491:     return;
                   11492: }
                   11493: 
                   11494: // ]]>
                   11495: </script>
                   11496: <p>$lt{'camt'}</p>
                   11497: ENDCAM
1.1065    raeburn  11498:     } else {
1.1067    raeburn  11499:         $output = '<p>'.$lt{'this'};
                   11500:         if ($info eq '') {
                   11501:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   11502:         } else {
                   11503:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   11504:                        '<div><pre>'.$info.'</pre></div>';
                   11505:         }
1.1065    raeburn  11506:     }
1.1067    raeburn  11507:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  11508:     my $duplicates;
                   11509:     my $num = 0;
                   11510:     if (ref($dirlist) eq 'ARRAY') {
                   11511:         foreach my $item (@{$dirlist}) {
                   11512:             if (ref($item) eq 'ARRAY') {
                   11513:                 if (exists($toplevel{$item->[0]})) {
                   11514:                     $duplicates .= 
                   11515:                         &start_data_table_row().
                   11516:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11517:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   11518:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11519:                         'value="1" />'.&mt('Yes').'</label>'.
                   11520:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   11521:                         '<td>'.$item->[0].'</td>';
                   11522:                     if ($item->[2]) {
                   11523:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   11524:                     } else {
                   11525:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   11526:                     }
                   11527:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   11528:                                    '<td>'.
                   11529:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   11530:                                    '</td>'.
                   11531:                                    &end_data_table_row();
                   11532:                     $num ++;
                   11533:                 }
                   11534:             }
                   11535:         }
                   11536:     }
                   11537:     my $itemcount;
                   11538:     if (@paths > 0) {
                   11539:         $itemcount = scalar(@paths);
                   11540:     } else {
                   11541:         $itemcount = 1;
                   11542:     }
1.1067    raeburn  11543:     if ($is_camtasia) {
                   11544:         $output .= $lt{'auto'}.'<br />'.
                   11545:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  11546:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  11547:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   11548:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   11549:                    $lt{'no'}.'</label></span><br />'.
                   11550:                    '<div id="camtasia_titles" style="display:block">'.
                   11551:                    &Apache::lonhtmlcommon::start_pick_box().
                   11552:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   11553:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   11554:                    &Apache::lonhtmlcommon::row_closure().
                   11555:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   11556:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   11557:                    &Apache::lonhtmlcommon::row_closure(1).
                   11558:                    &Apache::lonhtmlcommon::end_pick_box().
                   11559:                    '</div>';
                   11560:     }
1.1065    raeburn  11561:     $output .= 
                   11562:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  11563:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   11564:         "\n";
1.1065    raeburn  11565:     if ($duplicates ne '') {
                   11566:         $output .= '<p><span class="LC_warning">'.
                   11567:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   11568:                    &start_data_table().
                   11569:                    &start_data_table_header_row().
                   11570:                    '<th>'.&mt('Overwrite?').'</th>'.
                   11571:                    '<th>'.&mt('Name').'</th>'.
                   11572:                    '<th>'.&mt('Type').'</th>'.
                   11573:                    '<th>'.&mt('Size').'</th>'.
                   11574:                    '<th>'.&mt('Last modified').'</th>'.
                   11575:                    &end_data_table_header_row().
                   11576:                    $duplicates.
                   11577:                    &end_data_table().
                   11578:                    '</p>';
                   11579:     }
1.1067    raeburn  11580:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  11581:     if (ref($hiddenelements) eq 'HASH') {
                   11582:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   11583:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   11584:         }
                   11585:     }
                   11586:     $output .= <<"END";
1.1067    raeburn  11587: <br />
1.1053    raeburn  11588: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   11589: </form>
                   11590: $noextract
                   11591: END
                   11592:     return $output;
                   11593: }
                   11594: 
1.1065    raeburn  11595: sub decompression_utility {
                   11596:     my ($program) = @_;
                   11597:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   11598:     my $location;
                   11599:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   11600:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   11601:                          '/usr/sbin/') {
                   11602:             if (-x $dir.$program) {
                   11603:                 $location = $dir.$program;
                   11604:                 last;
                   11605:             }
                   11606:         }
                   11607:     }
                   11608:     return $location;
                   11609: }
                   11610: 
                   11611: sub list_archive_contents {
                   11612:     my ($file,$pathsref) = @_;
                   11613:     my (@cmd,$output);
                   11614:     my $needsregexp;
                   11615:     if ($file =~ /\.zip$/) {
                   11616:         @cmd = (&decompression_utility('unzip'),"-l");
                   11617:         $needsregexp = 1;
                   11618:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   11619:              ($file =~ /\.tgz$/)) {
                   11620:         @cmd = (&decompression_utility('tar'),"-ztf");
                   11621:     } elsif ($file =~ /\.tar\.bz2$/) {
                   11622:         @cmd = (&decompression_utility('tar'),"-jtf");
                   11623:     } elsif ($file =~ m|\.tar$|) {
                   11624:         @cmd = (&decompression_utility('tar'),"-tf");
                   11625:     }
                   11626:     if (@cmd) {
                   11627:         undef($!);
                   11628:         undef($@);
                   11629:         if (open(my $fh,"-|", @cmd, $file)) {
                   11630:             while (my $line = <$fh>) {
                   11631:                 $output .= $line;
                   11632:                 chomp($line);
                   11633:                 my $item;
                   11634:                 if ($needsregexp) {
                   11635:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   11636:                 } else {
                   11637:                     $item = $line;
                   11638:                 }
                   11639:                 if ($item ne '') {
                   11640:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   11641:                         push(@{$pathsref},$item);
                   11642:                     } 
                   11643:                 }
                   11644:             }
                   11645:             close($fh);
                   11646:         }
                   11647:     }
                   11648:     return $output;
                   11649: }
                   11650: 
1.1053    raeburn  11651: sub decompress_uploaded_file {
                   11652:     my ($file,$dir) = @_;
                   11653:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   11654:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   11655:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   11656:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   11657:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   11658:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   11659:     my $decompressed = $env{'cgi.decompressed'};
                   11660:     &Apache::lonnet::delenv('cgi.file');
                   11661:     &Apache::lonnet::delenv('cgi.dir');
                   11662:     &Apache::lonnet::delenv('cgi.decompressed');
                   11663:     return ($decompressed,$result);
                   11664: }
                   11665: 
1.1055    raeburn  11666: sub process_decompression {
                   11667:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   11668:     my ($dir,$error,$warning,$output);
1.1180    raeburn  11669:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   11670:         $error = &mt('Filename not a supported archive file type.').
                   11671:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  11672:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   11673:     } else {
                   11674:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   11675:         if ($docuhome eq 'no_host') {
                   11676:             $error = &mt('Could not determine home server for course.');
                   11677:         } else {
                   11678:             my @ids=&Apache::lonnet::current_machine_ids();
                   11679:             my $currdir = "$dir_root/$destination";
                   11680:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   11681:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   11682:                        "$dir_root/$destination";
                   11683:             } else {
                   11684:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   11685:                        "$dir_root/$docudom/$docuname/$destination";
                   11686:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   11687:                     $error = &mt('Archive file not found.');
                   11688:                 }
                   11689:             }
1.1065    raeburn  11690:             my (@to_overwrite,@to_skip);
                   11691:             if ($env{'form.archive_overwrite_total'} > 0) {
                   11692:                 my $total = $env{'form.archive_overwrite_total'};
                   11693:                 for (my $i=0; $i<$total; $i++) {
                   11694:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   11695:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   11696:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   11697:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   11698:                     }
                   11699:                 }
                   11700:             }
                   11701:             my $numskip = scalar(@to_skip);
                   11702:             if (($numskip > 0) && 
                   11703:                 ($numskip == $env{'form.archive_itemcount'})) {
                   11704:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   11705:             } elsif ($dir eq '') {
1.1055    raeburn  11706:                 $error = &mt('Directory containing archive file unavailable.');
                   11707:             } elsif (!$error) {
1.1065    raeburn  11708:                 my ($decompressed,$display);
                   11709:                 if ($numskip > 0) {
                   11710:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   11711:                     mkdir("$dir/$tempdir",0755);
                   11712:                     system("mv $dir/$file $dir/$tempdir/$file");
                   11713:                     ($decompressed,$display) = 
                   11714:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   11715:                     foreach my $item (@to_skip) {
                   11716:                         if (($item ne '') && ($item !~ /\.\./)) {
                   11717:                             if (-f "$dir/$tempdir/$item") { 
                   11718:                                 unlink("$dir/$tempdir/$item");
                   11719:                             } elsif (-d "$dir/$tempdir/$item") {
                   11720:                                 system("rm -rf $dir/$tempdir/$item");
                   11721:                             }
                   11722:                         }
                   11723:                     }
                   11724:                     system("mv $dir/$tempdir/* $dir");
                   11725:                     rmdir("$dir/$tempdir");   
                   11726:                 } else {
                   11727:                     ($decompressed,$display) = 
                   11728:                         &decompress_uploaded_file($file,$dir);
                   11729:                 }
1.1055    raeburn  11730:                 if ($decompressed eq 'ok') {
1.1065    raeburn  11731:                     $output = '<p class="LC_info">'.
                   11732:                               &mt('Files extracted successfully from archive.').
                   11733:                               '</p>'."\n";
1.1055    raeburn  11734:                     my ($warning,$result,@contents);
                   11735:                     my ($newdirlistref,$newlisterror) =
                   11736:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   11737:                                                  $docuname,1);
                   11738:                     my (%is_dir,%changes,@newitems);
                   11739:                     my $dirptr = 16384;
1.1065    raeburn  11740:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  11741:                         foreach my $dir_line (@{$newdirlistref}) {
                   11742:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  11743:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   11744:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  11745:                                 push(@newitems,$item);
                   11746:                                 if ($dirptr&$testdir) {
                   11747:                                     $is_dir{$item} = 1;
                   11748:                                 }
                   11749:                                 $changes{$item} = 1;
                   11750:                             }
                   11751:                         }
                   11752:                     }
                   11753:                     if (keys(%changes) > 0) {
                   11754:                         foreach my $item (sort(@newitems)) {
                   11755:                             if ($changes{$item}) {
                   11756:                                 push(@contents,$item);
                   11757:                             }
                   11758:                         }
                   11759:                     }
                   11760:                     if (@contents > 0) {
1.1067    raeburn  11761:                         my $wantform;
                   11762:                         unless ($env{'form.autoextract_camtasia'}) {
                   11763:                             $wantform = 1;
                   11764:                         }
1.1056    raeburn  11765:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  11766:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   11767:                                                                 $currdir,\%is_dir,
                   11768:                                                                 \%children,\%parent,
1.1056    raeburn  11769:                                                                 \@contents,\%dirorder,
                   11770:                                                                 \%titles,$wantform);
1.1055    raeburn  11771:                         if ($datatable ne '') {
                   11772:                             $output .= &archive_options_form('decompressed',$datatable,
                   11773:                                                              $count,$hiddenelem);
1.1065    raeburn  11774:                             my $startcount = 6;
1.1055    raeburn  11775:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  11776:                                                            \%titles,\%children);
1.1055    raeburn  11777:                         }
1.1067    raeburn  11778:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  11779:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  11780:                             my %displayed;
                   11781:                             my $total = 1;
                   11782:                             $env{'form.archive_directory'} = [];
                   11783:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   11784:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   11785:                                 $path =~ s{/$}{};
                   11786:                                 my $item;
                   11787:                                 if ($path ne '') {
                   11788:                                     $item = "$path/$titles{$i}";
                   11789:                                 } else {
                   11790:                                     $item = $titles{$i};
                   11791:                                 }
                   11792:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   11793:                                 if ($item eq $contents[0]) {
                   11794:                                     push(@{$env{'form.archive_directory'}},$i);
                   11795:                                     $env{'form.archive_'.$i} = 'display';
                   11796:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   11797:                                     $displayed{'folder'} = $i;
1.1164    raeburn  11798:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   11799:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  11800:                                     $env{'form.archive_'.$i} = 'display';
                   11801:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   11802:                                     $displayed{'web'} = $i;
                   11803:                                 } else {
1.1164    raeburn  11804:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   11805:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   11806:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  11807:                                         push(@{$env{'form.archive_directory'}},$i);
                   11808:                                     }
                   11809:                                     $env{'form.archive_'.$i} = 'dependency';
                   11810:                                 }
                   11811:                                 $total ++;
                   11812:                             }
                   11813:                             for (my $i=1; $i<$total; $i++) {
                   11814:                                 next if ($i == $displayed{'web'});
                   11815:                                 next if ($i == $displayed{'folder'});
                   11816:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   11817:                             }
                   11818:                             $env{'form.phase'} = 'decompress_cleanup';
                   11819:                             $env{'form.archivedelete'} = 1;
                   11820:                             $env{'form.archive_count'} = $total-1;
                   11821:                             $output .=
                   11822:                                 &process_extracted_files('coursedocs',$docudom,
                   11823:                                                          $docuname,$destination,
                   11824:                                                          $dir_root,$hiddenelem);
                   11825:                         }
1.1055    raeburn  11826:                     } else {
                   11827:                         $warning = &mt('No new items extracted from archive file.');
                   11828:                     }
                   11829:                 } else {
                   11830:                     $output = $display;
                   11831:                     $error = &mt('An error occurred during extraction from the archive file.');
                   11832:                 }
                   11833:             }
                   11834:         }
                   11835:     }
                   11836:     if ($error) {
                   11837:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   11838:                    $error.'</p>'."\n";
                   11839:     }
                   11840:     if ($warning) {
                   11841:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   11842:     }
                   11843:     return $output;
                   11844: }
                   11845: 
                   11846: sub get_extracted {
1.1056    raeburn  11847:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   11848:         $titles,$wantform) = @_;
1.1055    raeburn  11849:     my $count = 0;
                   11850:     my $depth = 0;
                   11851:     my $datatable;
1.1056    raeburn  11852:     my @hierarchy;
1.1055    raeburn  11853:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  11854:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   11855:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  11856:     foreach my $item (@{$contents}) {
                   11857:         $count ++;
1.1056    raeburn  11858:         @{$dirorder->{$count}} = @hierarchy;
                   11859:         $titles->{$count} = $item;
1.1055    raeburn  11860:         &archive_hierarchy($depth,$count,$parent,$children);
                   11861:         if ($wantform) {
                   11862:             $datatable .= &archive_row($is_dir->{$item},$item,
                   11863:                                        $currdir,$depth,$count);
                   11864:         }
                   11865:         if ($is_dir->{$item}) {
                   11866:             $depth ++;
1.1056    raeburn  11867:             push(@hierarchy,$count);
                   11868:             $parent->{$depth} = $count;
1.1055    raeburn  11869:             $datatable .=
                   11870:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  11871:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   11872:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  11873:             $depth --;
1.1056    raeburn  11874:             pop(@hierarchy);
1.1055    raeburn  11875:         }
                   11876:     }
                   11877:     return ($count,$datatable);
                   11878: }
                   11879: 
                   11880: sub recurse_extracted_archive {
1.1056    raeburn  11881:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   11882:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  11883:     my $result='';
1.1056    raeburn  11884:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   11885:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   11886:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  11887:         return $result;
                   11888:     }
                   11889:     my $dirptr = 16384;
                   11890:     my ($newdirlistref,$newlisterror) =
                   11891:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   11892:     if (ref($newdirlistref) eq 'ARRAY') {
                   11893:         foreach my $dir_line (@{$newdirlistref}) {
                   11894:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   11895:             unless ($item =~ /^\.+$/) {
                   11896:                 $$count ++;
1.1056    raeburn  11897:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   11898:                 $titles->{$$count} = $item;
1.1055    raeburn  11899:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  11900: 
1.1055    raeburn  11901:                 my $is_dir;
                   11902:                 if ($dirptr&$testdir) {
                   11903:                     $is_dir = 1;
                   11904:                 }
                   11905:                 if ($wantform) {
                   11906:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   11907:                 }
                   11908:                 if ($is_dir) {
                   11909:                     $$depth ++;
1.1056    raeburn  11910:                     push(@{$hierarchy},$$count);
                   11911:                     $parent->{$$depth} = $$count;
1.1055    raeburn  11912:                     $result .=
                   11913:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   11914:                                                    $docuname,$depth,$count,
1.1056    raeburn  11915:                                                    $hierarchy,$dirorder,$children,
                   11916:                                                    $parent,$titles,$wantform);
1.1055    raeburn  11917:                     $$depth --;
1.1056    raeburn  11918:                     pop(@{$hierarchy});
1.1055    raeburn  11919:                 }
                   11920:             }
                   11921:         }
                   11922:     }
                   11923:     return $result;
                   11924: }
                   11925: 
                   11926: sub archive_hierarchy {
                   11927:     my ($depth,$count,$parent,$children) =@_;
                   11928:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   11929:         if (exists($parent->{$depth})) {
                   11930:              $children->{$parent->{$depth}} .= $count.':';
                   11931:         }
                   11932:     }
                   11933:     return;
                   11934: }
                   11935: 
                   11936: sub archive_row {
                   11937:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   11938:     my ($name) = ($item =~ m{([^/]+)$});
                   11939:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  11940:                                        'display'    => 'Add as file',
1.1055    raeburn  11941:                                        'dependency' => 'Include as dependency',
                   11942:                                        'discard'    => 'Discard',
                   11943:                                       );
                   11944:     if ($is_dir) {
1.1059    raeburn  11945:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  11946:     }
1.1056    raeburn  11947:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   11948:     my $offset = 0;
1.1055    raeburn  11949:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  11950:         $offset ++;
1.1065    raeburn  11951:         if ($action ne 'display') {
                   11952:             $offset ++;
                   11953:         }  
1.1055    raeburn  11954:         $output .= '<td><span class="LC_nobreak">'.
                   11955:                    '<label><input type="radio" name="archive_'.$count.
                   11956:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   11957:         my $text = $choices{$action};
                   11958:         if ($is_dir) {
                   11959:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   11960:             if ($action eq 'display') {
1.1059    raeburn  11961:                 $text = &mt('Add as folder');
1.1055    raeburn  11962:             }
1.1056    raeburn  11963:         } else {
                   11964:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   11965: 
                   11966:         }
                   11967:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   11968:         if ($action eq 'dependency') {
                   11969:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   11970:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   11971:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   11972:                        '<option value=""></option>'."\n".
                   11973:                        '</select>'."\n".
                   11974:                        '</div>';
1.1059    raeburn  11975:         } elsif ($action eq 'display') {
                   11976:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   11977:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   11978:                        '</div>';
1.1055    raeburn  11979:         }
1.1056    raeburn  11980:         $output .= '</td>';
1.1055    raeburn  11981:     }
                   11982:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   11983:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   11984:     for (my $i=0; $i<$depth; $i++) {
                   11985:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   11986:     }
                   11987:     if ($is_dir) {
                   11988:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   11989:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   11990:     } else {
                   11991:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   11992:     }
                   11993:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   11994:                &end_data_table_row();
                   11995:     return $output;
                   11996: }
                   11997: 
                   11998: sub archive_options_form {
1.1065    raeburn  11999:     my ($form,$display,$count,$hiddenelem) = @_;
                   12000:     my %lt = &Apache::lonlocal::texthash(
                   12001:                perm => 'Permanently remove archive file?',
                   12002:                hows => 'How should each extracted item be incorporated in the course?',
                   12003:                cont => 'Content actions for all',
                   12004:                addf => 'Add as folder/file',
                   12005:                incd => 'Include as dependency for a displayed file',
                   12006:                disc => 'Discard',
                   12007:                no   => 'No',
                   12008:                yes  => 'Yes',
                   12009:                save => 'Save',
                   12010:     );
                   12011:     my $output = <<"END";
                   12012: <form name="$form" method="post" action="">
                   12013: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   12014: <label>
                   12015:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   12016: </label>
                   12017: &nbsp;
                   12018: <label>
                   12019:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   12020: </span>
                   12021: </p>
                   12022: <input type="hidden" name="phase" value="decompress_cleanup" />
                   12023: <br />$lt{'hows'}
                   12024: <div class="LC_columnSection">
                   12025:   <fieldset>
                   12026:     <legend>$lt{'cont'}</legend>
                   12027:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   12028:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   12029:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   12030:   </fieldset>
                   12031: </div>
                   12032: END
                   12033:     return $output.
1.1055    raeburn  12034:            &start_data_table()."\n".
1.1065    raeburn  12035:            $display."\n".
1.1055    raeburn  12036:            &end_data_table()."\n".
                   12037:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   12038:            $hiddenelem.
1.1065    raeburn  12039:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  12040:            '</form>';
                   12041: }
                   12042: 
                   12043: sub archive_javascript {
1.1056    raeburn  12044:     my ($startcount,$numitems,$titles,$children) = @_;
                   12045:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  12046:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  12047:     my $scripttag = <<START;
                   12048: <script type="text/javascript">
                   12049: // <![CDATA[
                   12050: 
                   12051: function checkAll(form,prefix) {
                   12052:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   12053:     for (var i=0; i < form.elements.length; i++) {
                   12054:         var id = form.elements[i].id;
                   12055:         if ((id != '') && (id != undefined)) {
                   12056:             if (idstr.test(id)) {
                   12057:                 if (form.elements[i].type == 'radio') {
                   12058:                     form.elements[i].checked = true;
1.1056    raeburn  12059:                     var nostart = i-$startcount;
1.1059    raeburn  12060:                     var offset = nostart%7;
                   12061:                     var count = (nostart-offset)/7;    
1.1056    raeburn  12062:                     dependencyCheck(form,count,offset);
1.1055    raeburn  12063:                 }
                   12064:             }
                   12065:         }
                   12066:     }
                   12067: }
                   12068: 
                   12069: function propagateCheck(form,count) {
                   12070:     if (count > 0) {
1.1059    raeburn  12071:         var startelement = $startcount + ((count-1) * 7);
                   12072:         for (var j=1; j<6; j++) {
                   12073:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  12074:                 var item = startelement + j; 
                   12075:                 if (form.elements[item].type == 'radio') {
                   12076:                     if (form.elements[item].checked) {
                   12077:                         containerCheck(form,count,j);
                   12078:                         break;
                   12079:                     }
1.1055    raeburn  12080:                 }
                   12081:             }
                   12082:         }
                   12083:     }
                   12084: }
                   12085: 
                   12086: numitems = $numitems
1.1056    raeburn  12087: var titles = new Array(numitems);
                   12088: var parents = new Array(numitems);
1.1055    raeburn  12089: for (var i=0; i<numitems; i++) {
1.1056    raeburn  12090:     parents[i] = new Array;
1.1055    raeburn  12091: }
1.1059    raeburn  12092: var maintitle = '$maintitle';
1.1055    raeburn  12093: 
                   12094: START
                   12095: 
1.1056    raeburn  12096:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   12097:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  12098:         for (my $i=0; $i<@contents; $i ++) {
                   12099:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   12100:         }
                   12101:     }
                   12102: 
1.1056    raeburn  12103:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   12104:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   12105:     }
                   12106: 
1.1055    raeburn  12107:     $scripttag .= <<END;
                   12108: 
                   12109: function containerCheck(form,count,offset) {
                   12110:     if (count > 0) {
1.1056    raeburn  12111:         dependencyCheck(form,count,offset);
1.1059    raeburn  12112:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  12113:         form.elements[item].checked = true;
                   12114:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12115:             if (parents[count].length > 0) {
                   12116:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  12117:                     containerCheck(form,parents[count][j],offset);
                   12118:                 }
                   12119:             }
                   12120:         }
                   12121:     }
                   12122: }
                   12123: 
                   12124: function dependencyCheck(form,count,offset) {
                   12125:     if (count > 0) {
1.1059    raeburn  12126:         var chosen = (offset+$startcount)+7*(count-1);
                   12127:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  12128:         var currtype = form.elements[depitem].type;
                   12129:         if (form.elements[chosen].value == 'dependency') {
                   12130:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   12131:             form.elements[depitem].options.length = 0;
                   12132:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  12133:             for (var i=1; i<=numitems; i++) {
                   12134:                 if (i == count) {
                   12135:                     continue;
                   12136:                 }
1.1059    raeburn  12137:                 var startelement = $startcount + (i-1) * 7;
                   12138:                 for (var j=1; j<6; j++) {
                   12139:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  12140:                         var item = startelement + j;
                   12141:                         if (form.elements[item].type == 'radio') {
                   12142:                             if (form.elements[item].checked) {
                   12143:                                 if (form.elements[item].value == 'display') {
                   12144:                                     var n = form.elements[depitem].options.length;
                   12145:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   12146:                                 }
                   12147:                             }
                   12148:                         }
                   12149:                     }
                   12150:                 }
                   12151:             }
                   12152:         } else {
                   12153:             document.getElementById('arc_depon_'+count).style.display='none';
                   12154:             form.elements[depitem].options.length = 0;
                   12155:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   12156:         }
1.1059    raeburn  12157:         titleCheck(form,count,offset);
1.1056    raeburn  12158:     }
                   12159: }
                   12160: 
                   12161: function propagateSelect(form,count,offset) {
                   12162:     if (count > 0) {
1.1065    raeburn  12163:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  12164:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   12165:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12166:             if (parents[count].length > 0) {
                   12167:                 for (var j=0; j<parents[count].length; j++) {
                   12168:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  12169:                 }
                   12170:             }
                   12171:         }
                   12172:     }
                   12173: }
1.1056    raeburn  12174: 
                   12175: function containerSelect(form,count,offset,picked) {
                   12176:     if (count > 0) {
1.1065    raeburn  12177:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  12178:         if (form.elements[item].type == 'radio') {
                   12179:             if (form.elements[item].value == 'dependency') {
                   12180:                 if (form.elements[item+1].type == 'select-one') {
                   12181:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   12182:                         if (form.elements[item+1].options[i].value == picked) {
                   12183:                             form.elements[item+1].selectedIndex = i;
                   12184:                             break;
                   12185:                         }
                   12186:                     }
                   12187:                 }
                   12188:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12189:                     if (parents[count].length > 0) {
                   12190:                         for (var j=0; j<parents[count].length; j++) {
                   12191:                             containerSelect(form,parents[count][j],offset,picked);
                   12192:                         }
                   12193:                     }
                   12194:                 }
                   12195:             }
                   12196:         }
                   12197:     }
                   12198: }
                   12199: 
1.1059    raeburn  12200: function titleCheck(form,count,offset) {
                   12201:     if (count > 0) {
                   12202:         var chosen = (offset+$startcount)+7*(count-1);
                   12203:         var depitem = $startcount + ((count-1) * 7) + 2;
                   12204:         var currtype = form.elements[depitem].type;
                   12205:         if (form.elements[chosen].value == 'display') {
                   12206:             document.getElementById('arc_title_'+count).style.display='block';
                   12207:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   12208:                 document.getElementById('archive_title_'+count).value=maintitle;
                   12209:             }
                   12210:         } else {
                   12211:             document.getElementById('arc_title_'+count).style.display='none';
                   12212:             if (currtype == 'text') { 
                   12213:                 document.getElementById('archive_title_'+count).value='';
                   12214:             }
                   12215:         }
                   12216:     }
                   12217:     return;
                   12218: }
                   12219: 
1.1055    raeburn  12220: // ]]>
                   12221: </script>
                   12222: END
                   12223:     return $scripttag;
                   12224: }
                   12225: 
                   12226: sub process_extracted_files {
1.1067    raeburn  12227:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  12228:     my $numitems = $env{'form.archive_count'};
                   12229:     return unless ($numitems);
                   12230:     my @ids=&Apache::lonnet::current_machine_ids();
                   12231:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  12232:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  12233:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12234:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12235:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   12236:         $pathtocheck = "$dir_root/$destination";
                   12237:         $dir = $dir_root;
                   12238:         $ishome = 1;
                   12239:     } else {
                   12240:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   12241:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   12242:         $dir = "$dir_root/$docudom/$docuname";    
                   12243:     }
                   12244:     my $currdir = "$dir_root/$destination";
                   12245:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   12246:     if ($env{'form.folderpath'}) {
                   12247:         my @items = split('&',$env{'form.folderpath'});
                   12248:         $folders{'0'} = $items[-2];
1.1099    raeburn  12249:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   12250:             $containers{'0'}='page';
                   12251:         } else {  
                   12252:             $containers{'0'}='sequence';
                   12253:         }
1.1055    raeburn  12254:     }
                   12255:     my @archdirs = &get_env_multiple('form.archive_directory');
                   12256:     if ($numitems) {
                   12257:         for (my $i=1; $i<=$numitems; $i++) {
                   12258:             my $path = $env{'form.archive_content_'.$i};
                   12259:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   12260:                 my $item = $1;
                   12261:                 $toplevelitems{$item} = $i;
                   12262:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   12263:                     $is_dir{$item} = 1;
                   12264:                 }
                   12265:             }
                   12266:         }
                   12267:     }
1.1067    raeburn  12268:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  12269:     if (keys(%toplevelitems) > 0) {
                   12270:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  12271:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   12272:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  12273:     }
1.1066    raeburn  12274:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  12275:     if ($numitems) {
                   12276:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  12277:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  12278:             my $path = $env{'form.archive_content_'.$i};
                   12279:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12280:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   12281:                     if ($prefix ne '' && $path ne '') {
                   12282:                         if (-e $prefix.$path) {
1.1066    raeburn  12283:                             if ((@archdirs > 0) && 
                   12284:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   12285:                                 $todeletedir{$prefix.$path} = 1;
                   12286:                             } else {
                   12287:                                 $todelete{$prefix.$path} = 1;
                   12288:                             }
1.1055    raeburn  12289:                         }
                   12290:                     }
                   12291:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  12292:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  12293:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  12294:                     $docstitle = $env{'form.archive_title_'.$i};
                   12295:                     if ($docstitle eq '') {
                   12296:                         $docstitle = $title;
                   12297:                     }
1.1055    raeburn  12298:                     $outer = 0;
1.1056    raeburn  12299:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12300:                         if (@{$dirorder{$i}} > 0) {
                   12301:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  12302:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   12303:                                     $outer = $item;
                   12304:                                     last;
                   12305:                                 }
                   12306:                             }
                   12307:                         }
                   12308:                     }
                   12309:                     my ($errtext,$fatal) = 
                   12310:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   12311:                                                '/'.$folders{$outer}.'.'.
                   12312:                                                $containers{$outer});
                   12313:                     next if ($fatal);
                   12314:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   12315:                         if ($context eq 'coursedocs') {
1.1056    raeburn  12316:                             $mapinner{$i} = time;
1.1055    raeburn  12317:                             $folders{$i} = 'default_'.$mapinner{$i};
                   12318:                             $containers{$i} = 'sequence';
                   12319:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12320:                                       $folders{$i}.'.'.$containers{$i};
                   12321:                             my $newidx = &LONCAPA::map::getresidx();
                   12322:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12323:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12324:                             push(@LONCAPA::map::order,$newidx);
                   12325:                             my ($outtext,$errtext) =
                   12326:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12327:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  12328:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  12329:                             $newseqid{$i} = $newidx;
1.1067    raeburn  12330:                             unless ($errtext) {
                   12331:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   12332:                             }
1.1055    raeburn  12333:                         }
                   12334:                     } else {
                   12335:                         if ($context eq 'coursedocs') {
                   12336:                             my $newidx=&LONCAPA::map::getresidx();
                   12337:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12338:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   12339:                                       $title;
                   12340:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   12341:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   12342:                             }
                   12343:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12344:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   12345:                             }
                   12346:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12347:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  12348:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  12349:                                 unless ($ishome) {
                   12350:                                     my $fetch = "$newdest{$i}/$title";
                   12351:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   12352:                                     $prompttofetch{$fetch} = 1;
                   12353:                                 }
1.1055    raeburn  12354:                             }
                   12355:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12356:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12357:                             push(@LONCAPA::map::order, $newidx);
                   12358:                             my ($outtext,$errtext)=
                   12359:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12360:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  12361:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  12362:                             unless ($errtext) {
                   12363:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   12364:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   12365:                                 }
                   12366:                             }
1.1055    raeburn  12367:                         }
                   12368:                     }
1.1086    raeburn  12369:                 }
                   12370:             } else {
                   12371:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   12372:             }
                   12373:         }
                   12374:         for (my $i=1; $i<=$numitems; $i++) {
                   12375:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   12376:             my $path = $env{'form.archive_content_'.$i};
                   12377:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12378:                 my ($title) = ($path =~ m{/([^/]+)$});
                   12379:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   12380:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   12381:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12382:                         my ($itemidx,$fullpath,$relpath);
                   12383:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   12384:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  12385:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  12386:                                 if ($dirorder{$i}->[$j] eq $container) {
                   12387:                                     $itemidx = $j;
1.1056    raeburn  12388:                                 }
                   12389:                             }
1.1086    raeburn  12390:                         }
                   12391:                         if ($itemidx eq '') {
                   12392:                             $itemidx =  0;
                   12393:                         } 
                   12394:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   12395:                             if ($mapinner{$referrer{$i}}) {
                   12396:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   12397:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12398:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12399:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12400:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12401:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12402:                                             if (!-e $fullpath) {
                   12403:                                                 mkdir($fullpath,0755);
1.1056    raeburn  12404:                                             }
                   12405:                                         }
1.1086    raeburn  12406:                                     } else {
                   12407:                                         last;
1.1056    raeburn  12408:                                     }
1.1086    raeburn  12409:                                 }
                   12410:                             }
                   12411:                         } elsif ($newdest{$referrer{$i}}) {
                   12412:                             $fullpath = $newdest{$referrer{$i}};
                   12413:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12414:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   12415:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   12416:                                     last;
                   12417:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12418:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12419:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12420:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12421:                                         if (!-e $fullpath) {
                   12422:                                             mkdir($fullpath,0755);
1.1056    raeburn  12423:                                         }
                   12424:                                     }
1.1086    raeburn  12425:                                 } else {
                   12426:                                     last;
1.1056    raeburn  12427:                                 }
1.1055    raeburn  12428:                             }
                   12429:                         }
1.1086    raeburn  12430:                         if ($fullpath ne '') {
                   12431:                             if (-e "$prefix$path") {
                   12432:                                 system("mv $prefix$path $fullpath/$title");
                   12433:                             }
                   12434:                             if (-e "$fullpath/$title") {
                   12435:                                 my $showpath;
                   12436:                                 if ($relpath ne '') {
                   12437:                                     $showpath = "$relpath/$title";
                   12438:                                 } else {
                   12439:                                     $showpath = "/$title";
                   12440:                                 } 
                   12441:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   12442:                             } 
                   12443:                             unless ($ishome) {
                   12444:                                 my $fetch = "$fullpath/$title";
                   12445:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
                   12446:                                 $prompttofetch{$fetch} = 1;
                   12447:                             }
                   12448:                         }
1.1055    raeburn  12449:                     }
1.1086    raeburn  12450:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   12451:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   12452:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  12453:                 }
                   12454:             } else {
                   12455:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   12456:             }
                   12457:         }
                   12458:         if (keys(%todelete)) {
                   12459:             foreach my $key (keys(%todelete)) {
                   12460:                 unlink($key);
1.1066    raeburn  12461:             }
                   12462:         }
                   12463:         if (keys(%todeletedir)) {
                   12464:             foreach my $key (keys(%todeletedir)) {
                   12465:                 rmdir($key);
                   12466:             }
                   12467:         }
                   12468:         foreach my $dir (sort(keys(%is_dir))) {
                   12469:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   12470:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  12471:             }
                   12472:         }
1.1067    raeburn  12473:         if ($result ne '') {
                   12474:             $output .= '<ul>'."\n".
                   12475:                        $result."\n".
                   12476:                        '</ul>';
                   12477:         }
                   12478:         unless ($ishome) {
                   12479:             my $replicationfail;
                   12480:             foreach my $item (keys(%prompttofetch)) {
                   12481:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   12482:                 unless ($fetchresult eq 'ok') {
                   12483:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   12484:                 }
                   12485:             }
                   12486:             if ($replicationfail) {
                   12487:                 $output .= '<p class="LC_error">'.
                   12488:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   12489:                            $replicationfail.
                   12490:                            '</ul></p>';
                   12491:             }
                   12492:         }
1.1055    raeburn  12493:     } else {
                   12494:         $warning = &mt('No items found in archive.');
                   12495:     }
                   12496:     if ($error) {
                   12497:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12498:                    $error.'</p>'."\n";
                   12499:     }
                   12500:     if ($warning) {
                   12501:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12502:     }
                   12503:     return $output;
                   12504: }
                   12505: 
1.1066    raeburn  12506: sub cleanup_empty_dirs {
                   12507:     my ($path) = @_;
                   12508:     if (($path ne '') && (-d $path)) {
                   12509:         if (opendir(my $dirh,$path)) {
                   12510:             my @dircontents = grep(!/^\./,readdir($dirh));
                   12511:             my $numitems = 0;
                   12512:             foreach my $item (@dircontents) {
                   12513:                 if (-d "$path/$item") {
1.1111    raeburn  12514:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  12515:                     if (-e "$path/$item") {
                   12516:                         $numitems ++;
                   12517:                     }
                   12518:                 } else {
                   12519:                     $numitems ++;
                   12520:                 }
                   12521:             }
                   12522:             if ($numitems == 0) {
                   12523:                 rmdir($path);
                   12524:             }
                   12525:             closedir($dirh);
                   12526:         }
                   12527:     }
                   12528:     return;
                   12529: }
                   12530: 
1.41      ng       12531: =pod
1.45      matthew  12532: 
1.1162    raeburn  12533: =item * &get_folder_hierarchy()
1.1068    raeburn  12534: 
                   12535: Provides hierarchy of names of folders/sub-folders containing the current
                   12536: item,
                   12537: 
                   12538: Inputs: 3
                   12539:      - $navmap - navmaps object
                   12540: 
                   12541:      - $map - url for map (either the trigger itself, or map containing
                   12542:                            the resource, which is the trigger).
                   12543: 
                   12544:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   12545: 
                   12546: Outputs: 1 @pathitems - array of folder/subfolder names.
                   12547: 
                   12548: =cut
                   12549: 
                   12550: sub get_folder_hierarchy {
                   12551:     my ($navmap,$map,$showitem) = @_;
                   12552:     my @pathitems;
                   12553:     if (ref($navmap)) {
                   12554:         my $mapres = $navmap->getResourceByUrl($map);
                   12555:         if (ref($mapres)) {
                   12556:             my $pcslist = $mapres->map_hierarchy();
                   12557:             if ($pcslist ne '') {
                   12558:                 my @pcs = split(/,/,$pcslist);
                   12559:                 foreach my $pc (@pcs) {
                   12560:                     if ($pc == 1) {
1.1129    raeburn  12561:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  12562:                     } else {
                   12563:                         my $res = $navmap->getByMapPc($pc);
                   12564:                         if (ref($res)) {
                   12565:                             my $title = $res->compTitle();
                   12566:                             $title =~ s/\W+/_/g;
                   12567:                             if ($title ne '') {
                   12568:                                 push(@pathitems,$title);
                   12569:                             }
                   12570:                         }
                   12571:                     }
                   12572:                 }
                   12573:             }
1.1071    raeburn  12574:             if ($showitem) {
                   12575:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  12576:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  12577:                 } else {
                   12578:                     my $maptitle = $mapres->compTitle();
                   12579:                     $maptitle =~ s/\W+/_/g;
                   12580:                     if ($maptitle ne '') {
                   12581:                         push(@pathitems,$maptitle);
                   12582:                     }
1.1068    raeburn  12583:                 }
                   12584:             }
                   12585:         }
                   12586:     }
                   12587:     return @pathitems;
                   12588: }
                   12589: 
                   12590: =pod
                   12591: 
1.1015    raeburn  12592: =item * &get_turnedin_filepath()
                   12593: 
                   12594: Determines path in a user's portfolio file for storage of files uploaded
                   12595: to a specific essayresponse or dropbox item.
                   12596: 
                   12597: Inputs: 3 required + 1 optional.
                   12598: $symb is symb for resource, $uname and $udom are for current user (required).
                   12599: $caller is optional (can be "submission", if routine is called when storing
                   12600: an upoaded file when "Submit Answer" button was pressed).
                   12601: 
                   12602: Returns array containing $path and $multiresp. 
                   12603: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   12604: than one file upload item.  Callers of routine should append partid as a 
                   12605: subdirectory to $path in cases where $multiresp is 1.
                   12606: 
                   12607: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   12608: 
                   12609: =cut
                   12610: 
                   12611: sub get_turnedin_filepath {
                   12612:     my ($symb,$uname,$udom,$caller) = @_;
                   12613:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   12614:     my $turnindir;
                   12615:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   12616:     $turnindir = $userhash{'turnindir'};
                   12617:     my ($path,$multiresp);
                   12618:     if ($turnindir eq '') {
                   12619:         if ($caller eq 'submission') {
                   12620:             $turnindir = &mt('turned in');
                   12621:             $turnindir =~ s/\W+/_/g;
                   12622:             my %newhash = (
                   12623:                             'turnindir' => $turnindir,
                   12624:                           );
                   12625:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   12626:         }
                   12627:     }
                   12628:     if ($turnindir ne '') {
                   12629:         $path = '/'.$turnindir.'/';
                   12630:         my ($multipart,$turnin,@pathitems);
                   12631:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12632:         if (defined($navmap)) {
                   12633:             my $mapres = $navmap->getResourceByUrl($map);
                   12634:             if (ref($mapres)) {
                   12635:                 my $pcslist = $mapres->map_hierarchy();
                   12636:                 if ($pcslist ne '') {
                   12637:                     foreach my $pc (split(/,/,$pcslist)) {
                   12638:                         my $res = $navmap->getByMapPc($pc);
                   12639:                         if (ref($res)) {
                   12640:                             my $title = $res->compTitle();
                   12641:                             $title =~ s/\W+/_/g;
                   12642:                             if ($title ne '') {
1.1149    raeburn  12643:                                 if (($pc > 1) && (length($title) > 12)) {
                   12644:                                     $title = substr($title,0,12);
                   12645:                                 }
1.1015    raeburn  12646:                                 push(@pathitems,$title);
                   12647:                             }
                   12648:                         }
                   12649:                     }
                   12650:                 }
                   12651:                 my $maptitle = $mapres->compTitle();
                   12652:                 $maptitle =~ s/\W+/_/g;
                   12653:                 if ($maptitle ne '') {
1.1149    raeburn  12654:                     if (length($maptitle) > 12) {
                   12655:                         $maptitle = substr($maptitle,0,12);
                   12656:                     }
1.1015    raeburn  12657:                     push(@pathitems,$maptitle);
                   12658:                 }
                   12659:                 unless ($env{'request.state'} eq 'construct') {
                   12660:                     my $res = $navmap->getBySymb($symb);
                   12661:                     if (ref($res)) {
                   12662:                         my $partlist = $res->parts();
                   12663:                         my $totaluploads = 0;
                   12664:                         if (ref($partlist) eq 'ARRAY') {
                   12665:                             foreach my $part (@{$partlist}) {
                   12666:                                 my @types = $res->responseType($part);
                   12667:                                 my @ids = $res->responseIds($part);
                   12668:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   12669:                                     if ($types[$i] eq 'essay') {
                   12670:                                         my $partid = $part.'_'.$ids[$i];
                   12671:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   12672:                                             $totaluploads ++;
                   12673:                                         }
                   12674:                                     }
                   12675:                                 }
                   12676:                             }
                   12677:                             if ($totaluploads > 1) {
                   12678:                                 $multiresp = 1;
                   12679:                             }
                   12680:                         }
                   12681:                     }
                   12682:                 }
                   12683:             } else {
                   12684:                 return;
                   12685:             }
                   12686:         } else {
                   12687:             return;
                   12688:         }
                   12689:         my $restitle=&Apache::lonnet::gettitle($symb);
                   12690:         $restitle =~ s/\W+/_/g;
                   12691:         if ($restitle eq '') {
                   12692:             $restitle = ($resurl =~ m{/[^/]+$});
                   12693:             if ($restitle eq '') {
                   12694:                 $restitle = time;
                   12695:             }
                   12696:         }
1.1149    raeburn  12697:         if (length($restitle) > 12) {
                   12698:             $restitle = substr($restitle,0,12);
                   12699:         }
1.1015    raeburn  12700:         push(@pathitems,$restitle);
                   12701:         $path .= join('/',@pathitems);
                   12702:     }
                   12703:     return ($path,$multiresp);
                   12704: }
                   12705: 
                   12706: =pod
                   12707: 
1.464     albertel 12708: =back
1.41      ng       12709: 
1.112     bowersj2 12710: =head1 CSV Upload/Handling functions
1.38      albertel 12711: 
1.41      ng       12712: =over 4
                   12713: 
1.648     raeburn  12714: =item * &upfile_store($r)
1.41      ng       12715: 
                   12716: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 12717: needs $env{'form.upfile'}
1.41      ng       12718: returns $datatoken to be put into hidden field
                   12719: 
                   12720: =cut
1.31      albertel 12721: 
                   12722: sub upfile_store {
                   12723:     my $r=shift;
1.258     albertel 12724:     $env{'form.upfile'}=~s/\r/\n/gs;
                   12725:     $env{'form.upfile'}=~s/\f/\n/gs;
                   12726:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   12727:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 12728: 
1.258     albertel 12729:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   12730: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 12731:     {
1.158     raeburn  12732:         my $datafile = $r->dir_config('lonDaemons').
                   12733:                            '/tmp/'.$datatoken.'.tmp';
                   12734:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 12735:             print $fh $env{'form.upfile'};
1.158     raeburn  12736:             close($fh);
                   12737:         }
1.31      albertel 12738:     }
                   12739:     return $datatoken;
                   12740: }
                   12741: 
1.56      matthew  12742: =pod
                   12743: 
1.648     raeburn  12744: =item * &load_tmp_file($r)
1.41      ng       12745: 
                   12746: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 12747: needs $env{'form.datatoken'},
                   12748: sets $env{'form.upfile'} to the contents of the file
1.41      ng       12749: 
                   12750: =cut
1.31      albertel 12751: 
                   12752: sub load_tmp_file {
                   12753:     my $r=shift;
                   12754:     my @studentdata=();
                   12755:     {
1.158     raeburn  12756:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 12757:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  12758:         if ( open(my $fh,"<$studentfile") ) {
                   12759:             @studentdata=<$fh>;
                   12760:             close($fh);
                   12761:         }
1.31      albertel 12762:     }
1.258     albertel 12763:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 12764: }
                   12765: 
1.56      matthew  12766: =pod
                   12767: 
1.648     raeburn  12768: =item * &upfile_record_sep()
1.41      ng       12769: 
                   12770: Separate uploaded file into records
                   12771: returns array of records,
1.258     albertel 12772: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       12773: 
                   12774: =cut
1.31      albertel 12775: 
                   12776: sub upfile_record_sep {
1.258     albertel 12777:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 12778:     } else {
1.248     albertel 12779: 	my @records;
1.258     albertel 12780: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 12781: 	    if ($line=~/^\s*$/) { next; }
                   12782: 	    push(@records,$line);
                   12783: 	}
                   12784: 	return @records;
1.31      albertel 12785:     }
                   12786: }
                   12787: 
1.56      matthew  12788: =pod
                   12789: 
1.648     raeburn  12790: =item * &record_sep($record)
1.41      ng       12791: 
1.258     albertel 12792: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       12793: 
                   12794: =cut
                   12795: 
1.263     www      12796: sub takeleft {
                   12797:     my $index=shift;
                   12798:     return substr('0000'.$index,-4,4);
                   12799: }
                   12800: 
1.31      albertel 12801: sub record_sep {
                   12802:     my $record=shift;
                   12803:     my %components=();
1.258     albertel 12804:     if ($env{'form.upfiletype'} eq 'xml') {
                   12805:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 12806:         my $i=0;
1.356     albertel 12807:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 12808:             $field=~s/^(\"|\')//;
                   12809:             $field=~s/(\"|\')$//;
1.263     www      12810:             $components{&takeleft($i)}=$field;
1.31      albertel 12811:             $i++;
                   12812:         }
1.258     albertel 12813:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 12814:         my $i=0;
1.356     albertel 12815:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 12816:             $field=~s/^(\"|\')//;
                   12817:             $field=~s/(\"|\')$//;
1.263     www      12818:             $components{&takeleft($i)}=$field;
1.31      albertel 12819:             $i++;
                   12820:         }
                   12821:     } else {
1.561     www      12822:         my $separator=',';
1.480     banghart 12823:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      12824:             $separator=';';
1.480     banghart 12825:         }
1.31      albertel 12826:         my $i=0;
1.561     www      12827: # the character we are looking for to indicate the end of a quote or a record 
                   12828:         my $looking_for=$separator;
                   12829: # do not add the characters to the fields
                   12830:         my $ignore=0;
                   12831: # we just encountered a separator (or the beginning of the record)
                   12832:         my $just_found_separator=1;
                   12833: # store the field we are working on here
                   12834:         my $field='';
                   12835: # work our way through all characters in record
                   12836:         foreach my $character ($record=~/(.)/g) {
                   12837:             if ($character eq $looking_for) {
                   12838:                if ($character ne $separator) {
                   12839: # Found the end of a quote, again looking for separator
                   12840:                   $looking_for=$separator;
                   12841:                   $ignore=1;
                   12842:                } else {
                   12843: # Found a separator, store away what we got
                   12844:                   $components{&takeleft($i)}=$field;
                   12845: 	          $i++;
                   12846:                   $just_found_separator=1;
                   12847:                   $ignore=0;
                   12848:                   $field='';
                   12849:                }
                   12850:                next;
                   12851:             }
                   12852: # single or double quotation marks after a separator indicate beginning of a quote
                   12853: # we are now looking for the end of the quote and need to ignore separators
                   12854:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   12855:                $looking_for=$character;
                   12856:                next;
                   12857:             }
                   12858: # ignore would be true after we reached the end of a quote
                   12859:             if ($ignore) { next; }
                   12860:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   12861:             $field.=$character;
                   12862:             $just_found_separator=0; 
1.31      albertel 12863:         }
1.561     www      12864: # catch the very last entry, since we never encountered the separator
                   12865:         $components{&takeleft($i)}=$field;
1.31      albertel 12866:     }
                   12867:     return %components;
                   12868: }
                   12869: 
1.144     matthew  12870: ######################################################
                   12871: ######################################################
                   12872: 
1.56      matthew  12873: =pod
                   12874: 
1.648     raeburn  12875: =item * &upfile_select_html()
1.41      ng       12876: 
1.144     matthew  12877: Return HTML code to select a file from the users machine and specify 
                   12878: the file type.
1.41      ng       12879: 
                   12880: =cut
                   12881: 
1.144     matthew  12882: ######################################################
                   12883: ######################################################
1.31      albertel 12884: sub upfile_select_html {
1.144     matthew  12885:     my %Types = (
                   12886:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 12887:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  12888:                  space => &mt('Space separated'),
                   12889:                  tab   => &mt('Tabulator separated'),
                   12890: #                 xml   => &mt('HTML/XML'),
                   12891:                  );
                   12892:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  12893:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  12894:     foreach my $type (sort(keys(%Types))) {
                   12895:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   12896:     }
                   12897:     $Str .= "</select>\n";
                   12898:     return $Str;
1.31      albertel 12899: }
                   12900: 
1.301     albertel 12901: sub get_samples {
                   12902:     my ($records,$toget) = @_;
                   12903:     my @samples=({});
                   12904:     my $got=0;
                   12905:     foreach my $rec (@$records) {
                   12906: 	my %temp = &record_sep($rec);
                   12907: 	if (! grep(/\S/, values(%temp))) { next; }
                   12908: 	if (%temp) {
                   12909: 	    $samples[$got]=\%temp;
                   12910: 	    $got++;
                   12911: 	    if ($got == $toget) { last; }
                   12912: 	}
                   12913:     }
                   12914:     return \@samples;
                   12915: }
                   12916: 
1.144     matthew  12917: ######################################################
                   12918: ######################################################
                   12919: 
1.56      matthew  12920: =pod
                   12921: 
1.648     raeburn  12922: =item * &csv_print_samples($r,$records)
1.41      ng       12923: 
                   12924: Prints a table of sample values from each column uploaded $r is an
                   12925: Apache Request ref, $records is an arrayref from
                   12926: &Apache::loncommon::upfile_record_sep
                   12927: 
                   12928: =cut
                   12929: 
1.144     matthew  12930: ######################################################
                   12931: ######################################################
1.31      albertel 12932: sub csv_print_samples {
                   12933:     my ($r,$records) = @_;
1.662     bisitz   12934:     my $samples = &get_samples($records,5);
1.301     albertel 12935: 
1.594     raeburn  12936:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   12937:               &start_data_table_header_row());
1.356     albertel 12938:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   12939:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  12940:     $r->print(&end_data_table_header_row());
1.301     albertel 12941:     foreach my $hash (@$samples) {
1.594     raeburn  12942: 	$r->print(&start_data_table_row());
1.356     albertel 12943: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 12944: 	    $r->print('<td>');
1.356     albertel 12945: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 12946: 	    $r->print('</td>');
                   12947: 	}
1.594     raeburn  12948: 	$r->print(&end_data_table_row());
1.31      albertel 12949:     }
1.594     raeburn  12950:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 12951: }
                   12952: 
1.144     matthew  12953: ######################################################
                   12954: ######################################################
                   12955: 
1.56      matthew  12956: =pod
                   12957: 
1.648     raeburn  12958: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       12959: 
                   12960: Prints a table to create associations between values and table columns.
1.144     matthew  12961: 
1.41      ng       12962: $r is an Apache Request ref,
                   12963: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  12964: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       12965: 
                   12966: =cut
                   12967: 
1.144     matthew  12968: ######################################################
                   12969: ######################################################
1.31      albertel 12970: sub csv_print_select_table {
                   12971:     my ($r,$records,$d) = @_;
1.301     albertel 12972:     my $i=0;
                   12973:     my $samples = &get_samples($records,1);
1.144     matthew  12974:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  12975: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  12976:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  12977:               '<th>'.&mt('Column').'</th>'.
                   12978:               &end_data_table_header_row()."\n");
1.356     albertel 12979:     foreach my $array_ref (@$d) {
                   12980: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  12981: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 12982: 
1.875     bisitz   12983: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  12984: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 12985: 	$r->print('<option value="none"></option>');
1.356     albertel 12986: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   12987: 	    $r->print('<option value="'.$sample.'"'.
                   12988:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   12989:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 12990: 	}
1.594     raeburn  12991: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 12992: 	$i++;
                   12993:     }
1.594     raeburn  12994:     $r->print(&end_data_table());
1.31      albertel 12995:     $i--;
                   12996:     return $i;
                   12997: }
1.56      matthew  12998: 
1.144     matthew  12999: ######################################################
                   13000: ######################################################
                   13001: 
1.56      matthew  13002: =pod
1.31      albertel 13003: 
1.648     raeburn  13004: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       13005: 
                   13006: Prints a table of sample values from the upload and can make associate samples to internal names.
                   13007: 
                   13008: $r is an Apache Request ref,
                   13009: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   13010: $d is an array of 2 element arrays (internal name, displayed name)
                   13011: 
                   13012: =cut
                   13013: 
1.144     matthew  13014: ######################################################
                   13015: ######################################################
1.31      albertel 13016: sub csv_samples_select_table {
                   13017:     my ($r,$records,$d) = @_;
                   13018:     my $i=0;
1.144     matthew  13019:     #
1.662     bisitz   13020:     my $max_samples = 5;
                   13021:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  13022:     $r->print(&start_data_table().
                   13023:               &start_data_table_header_row().'<th>'.
                   13024:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   13025:               &end_data_table_header_row());
1.301     albertel 13026: 
                   13027:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  13028: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  13029: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 13030: 	foreach my $option (@$d) {
                   13031: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  13032: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 13033:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  13034:                       $display.'</option>');
1.31      albertel 13035: 	}
                   13036: 	$r->print('</select></td><td>');
1.662     bisitz   13037: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 13038: 	    if (defined($samples->[$line]{$key})) { 
                   13039: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   13040: 	    }
                   13041: 	}
1.594     raeburn  13042: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 13043: 	$i++;
                   13044:     }
1.594     raeburn  13045:     $r->print(&end_data_table());
1.31      albertel 13046:     $i--;
                   13047:     return($i);
1.115     matthew  13048: }
                   13049: 
1.144     matthew  13050: ######################################################
                   13051: ######################################################
                   13052: 
1.115     matthew  13053: =pod
                   13054: 
1.648     raeburn  13055: =item * &clean_excel_name($name)
1.115     matthew  13056: 
                   13057: Returns a replacement for $name which does not contain any illegal characters.
                   13058: 
                   13059: =cut
                   13060: 
1.144     matthew  13061: ######################################################
                   13062: ######################################################
1.115     matthew  13063: sub clean_excel_name {
                   13064:     my ($name) = @_;
                   13065:     $name =~ s/[:\*\?\/\\]//g;
                   13066:     if (length($name) > 31) {
                   13067:         $name = substr($name,0,31);
                   13068:     }
                   13069:     return $name;
1.25      albertel 13070: }
1.84      albertel 13071: 
1.85      albertel 13072: =pod
                   13073: 
1.648     raeburn  13074: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 13075: 
                   13076: Returns either 1 or undef
                   13077: 
                   13078: 1 if the part is to be hidden, undef if it is to be shown
                   13079: 
                   13080: Arguments are:
                   13081: 
                   13082: $id the id of the part to be checked
                   13083: $symb, optional the symb of the resource to check
                   13084: $udom, optional the domain of the user to check for
                   13085: $uname, optional the username of the user to check for
                   13086: 
                   13087: =cut
1.84      albertel 13088: 
                   13089: sub check_if_partid_hidden {
                   13090:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 13091:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 13092: 					 $symb,$udom,$uname);
1.141     albertel 13093:     my $truth=1;
                   13094:     #if the string starts with !, then the list is the list to show not hide
                   13095:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 13096:     my @hiddenlist=split(/,/,$hiddenparts);
                   13097:     foreach my $checkid (@hiddenlist) {
1.141     albertel 13098: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 13099:     }
1.141     albertel 13100:     return !$truth;
1.84      albertel 13101: }
1.127     matthew  13102: 
1.138     matthew  13103: 
                   13104: ############################################################
                   13105: ############################################################
                   13106: 
                   13107: =pod
                   13108: 
1.157     matthew  13109: =back 
                   13110: 
1.138     matthew  13111: =head1 cgi-bin script and graphing routines
                   13112: 
1.157     matthew  13113: =over 4
                   13114: 
1.648     raeburn  13115: =item * &get_cgi_id()
1.138     matthew  13116: 
                   13117: Inputs: none
                   13118: 
                   13119: Returns an id which can be used to pass environment variables
                   13120: to various cgi-bin scripts.  These environment variables will
                   13121: be removed from the users environment after a given time by
                   13122: the routine &Apache::lonnet::transfer_profile_to_env.
                   13123: 
                   13124: =cut
                   13125: 
                   13126: ############################################################
                   13127: ############################################################
1.152     albertel 13128: my $uniq=0;
1.136     matthew  13129: sub get_cgi_id {
1.154     albertel 13130:     $uniq=($uniq+1)%100000;
1.280     albertel 13131:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  13132: }
                   13133: 
1.127     matthew  13134: ############################################################
                   13135: ############################################################
                   13136: 
                   13137: =pod
                   13138: 
1.648     raeburn  13139: =item * &DrawBarGraph()
1.127     matthew  13140: 
1.138     matthew  13141: Facilitates the plotting of data in a (stacked) bar graph.
                   13142: Puts plot definition data into the users environment in order for 
                   13143: graph.png to plot it.  Returns an <img> tag for the plot.
                   13144: The bars on the plot are labeled '1','2',...,'n'.
                   13145: 
                   13146: Inputs:
                   13147: 
                   13148: =over 4
                   13149: 
                   13150: =item $Title: string, the title of the plot
                   13151: 
                   13152: =item $xlabel: string, text describing the X-axis of the plot
                   13153: 
                   13154: =item $ylabel: string, text describing the Y-axis of the plot
                   13155: 
                   13156: =item $Max: scalar, the maximum Y value to use in the plot
                   13157: If $Max is < any data point, the graph will not be rendered.
                   13158: 
1.140     matthew  13159: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  13160: they are plotted.  If undefined, default values will be used.
                   13161: 
1.178     matthew  13162: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   13163: 
1.138     matthew  13164: =item @Values: An array of array references.  Each array reference holds data
                   13165: to be plotted in a stacked bar chart.
                   13166: 
1.239     matthew  13167: =item If the final element of @Values is a hash reference the key/value
                   13168: pairs will be added to the graph definition.
                   13169: 
1.138     matthew  13170: =back
                   13171: 
                   13172: Returns:
                   13173: 
                   13174: An <img> tag which references graph.png and the appropriate identifying
                   13175: information for the plot.
                   13176: 
1.127     matthew  13177: =cut
                   13178: 
                   13179: ############################################################
                   13180: ############################################################
1.134     matthew  13181: sub DrawBarGraph {
1.178     matthew  13182:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  13183:     #
                   13184:     if (! defined($colors)) {
                   13185:         $colors = ['#33ff00', 
                   13186:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   13187:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   13188:                   ]; 
                   13189:     }
1.228     matthew  13190:     my $extra_settings = {};
                   13191:     if (ref($Values[-1]) eq 'HASH') {
                   13192:         $extra_settings = pop(@Values);
                   13193:     }
1.127     matthew  13194:     #
1.136     matthew  13195:     my $identifier = &get_cgi_id();
                   13196:     my $id = 'cgi.'.$identifier;        
1.129     matthew  13197:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  13198:         return '';
                   13199:     }
1.225     matthew  13200:     #
                   13201:     my @Labels;
                   13202:     if (defined($labels)) {
                   13203:         @Labels = @$labels;
                   13204:     } else {
                   13205:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   13206:             push (@Labels,$i+1);
                   13207:         }
                   13208:     }
                   13209:     #
1.129     matthew  13210:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  13211:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  13212:     my %ValuesHash;
                   13213:     my $NumSets=1;
                   13214:     foreach my $array (@Values) {
                   13215:         next if (! ref($array));
1.136     matthew  13216:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  13217:             join(',',@$array);
1.129     matthew  13218:     }
1.127     matthew  13219:     #
1.136     matthew  13220:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  13221:     if ($NumBars < 3) {
                   13222:         $width = 120+$NumBars*32;
1.220     matthew  13223:         $xskip = 1;
1.225     matthew  13224:         $bar_width = 30;
                   13225:     } elsif ($NumBars < 5) {
                   13226:         $width = 120+$NumBars*20;
                   13227:         $xskip = 1;
                   13228:         $bar_width = 20;
1.220     matthew  13229:     } elsif ($NumBars < 10) {
1.136     matthew  13230:         $width = 120+$NumBars*15;
                   13231:         $xskip = 1;
                   13232:         $bar_width = 15;
                   13233:     } elsif ($NumBars <= 25) {
                   13234:         $width = 120+$NumBars*11;
                   13235:         $xskip = 5;
                   13236:         $bar_width = 8;
                   13237:     } elsif ($NumBars <= 50) {
                   13238:         $width = 120+$NumBars*8;
                   13239:         $xskip = 5;
                   13240:         $bar_width = 4;
                   13241:     } else {
                   13242:         $width = 120+$NumBars*8;
                   13243:         $xskip = 5;
                   13244:         $bar_width = 4;
                   13245:     }
                   13246:     #
1.137     matthew  13247:     $Max = 1 if ($Max < 1);
                   13248:     if ( int($Max) < $Max ) {
                   13249:         $Max++;
                   13250:         $Max = int($Max);
                   13251:     }
1.127     matthew  13252:     $Title  = '' if (! defined($Title));
                   13253:     $xlabel = '' if (! defined($xlabel));
                   13254:     $ylabel = '' if (! defined($ylabel));
1.369     www      13255:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   13256:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   13257:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  13258:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  13259:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   13260:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   13261:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   13262:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13263:     $ValuesHash{$id.'.height'}   = $height;
                   13264:     $ValuesHash{$id.'.width'}    = $width;
                   13265:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   13266:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   13267:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  13268:     #
1.228     matthew  13269:     # Deal with other parameters
                   13270:     while (my ($key,$value) = each(%$extra_settings)) {
                   13271:         $ValuesHash{$id.'.'.$key} = $value;
                   13272:     }
                   13273:     #
1.646     raeburn  13274:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  13275:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13276: }
                   13277: 
                   13278: ############################################################
                   13279: ############################################################
                   13280: 
                   13281: =pod
                   13282: 
1.648     raeburn  13283: =item * &DrawXYGraph()
1.137     matthew  13284: 
1.138     matthew  13285: Facilitates the plotting of data in an XY graph.
                   13286: Puts plot definition data into the users environment in order for 
                   13287: graph.png to plot it.  Returns an <img> tag for the plot.
                   13288: 
                   13289: Inputs:
                   13290: 
                   13291: =over 4
                   13292: 
                   13293: =item $Title: string, the title of the plot
                   13294: 
                   13295: =item $xlabel: string, text describing the X-axis of the plot
                   13296: 
                   13297: =item $ylabel: string, text describing the Y-axis of the plot
                   13298: 
                   13299: =item $Max: scalar, the maximum Y value to use in the plot
                   13300: If $Max is < any data point, the graph will not be rendered.
                   13301: 
                   13302: =item $colors: Array ref containing the hex color codes for the data to be 
                   13303: plotted in.  If undefined, default values will be used.
                   13304: 
                   13305: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13306: 
                   13307: =item $Ydata: Array ref containing Array refs.  
1.185     www      13308: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  13309: 
                   13310: =item %Values: hash indicating or overriding any default values which are 
                   13311: passed to graph.png.  
                   13312: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13313: 
                   13314: =back
                   13315: 
                   13316: Returns:
                   13317: 
                   13318: An <img> tag which references graph.png and the appropriate identifying
                   13319: information for the plot.
                   13320: 
1.137     matthew  13321: =cut
                   13322: 
                   13323: ############################################################
                   13324: ############################################################
                   13325: sub DrawXYGraph {
                   13326:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   13327:     #
                   13328:     # Create the identifier for the graph
                   13329:     my $identifier = &get_cgi_id();
                   13330:     my $id = 'cgi.'.$identifier;
                   13331:     #
                   13332:     $Title  = '' if (! defined($Title));
                   13333:     $xlabel = '' if (! defined($xlabel));
                   13334:     $ylabel = '' if (! defined($ylabel));
                   13335:     my %ValuesHash = 
                   13336:         (
1.369     www      13337:          $id.'.title'  => &escape($Title),
                   13338:          $id.'.xlabel' => &escape($xlabel),
                   13339:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  13340:          $id.'.y_max_value'=> $Max,
                   13341:          $id.'.labels'     => join(',',@$Xlabels),
                   13342:          $id.'.PlotType'   => 'XY',
                   13343:          );
                   13344:     #
                   13345:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13346:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13347:     }
                   13348:     #
                   13349:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   13350:         return '';
                   13351:     }
                   13352:     my $NumSets=1;
1.138     matthew  13353:     foreach my $array (@{$Ydata}){
1.137     matthew  13354:         next if (! ref($array));
                   13355:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   13356:     }
1.138     matthew  13357:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  13358:     #
                   13359:     # Deal with other parameters
                   13360:     while (my ($key,$value) = each(%Values)) {
                   13361:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  13362:     }
                   13363:     #
1.646     raeburn  13364:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  13365:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13366: }
                   13367: 
                   13368: ############################################################
                   13369: ############################################################
                   13370: 
                   13371: =pod
                   13372: 
1.648     raeburn  13373: =item * &DrawXYYGraph()
1.138     matthew  13374: 
                   13375: Facilitates the plotting of data in an XY graph with two Y axes.
                   13376: Puts plot definition data into the users environment in order for 
                   13377: graph.png to plot it.  Returns an <img> tag for the plot.
                   13378: 
                   13379: Inputs:
                   13380: 
                   13381: =over 4
                   13382: 
                   13383: =item $Title: string, the title of the plot
                   13384: 
                   13385: =item $xlabel: string, text describing the X-axis of the plot
                   13386: 
                   13387: =item $ylabel: string, text describing the Y-axis of the plot
                   13388: 
                   13389: =item $colors: Array ref containing the hex color codes for the data to be 
                   13390: plotted in.  If undefined, default values will be used.
                   13391: 
                   13392: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13393: 
                   13394: =item $Ydata1: The first data set
                   13395: 
                   13396: =item $Min1: The minimum value of the left Y-axis
                   13397: 
                   13398: =item $Max1: The maximum value of the left Y-axis
                   13399: 
                   13400: =item $Ydata2: The second data set
                   13401: 
                   13402: =item $Min2: The minimum value of the right Y-axis
                   13403: 
                   13404: =item $Max2: The maximum value of the left Y-axis
                   13405: 
                   13406: =item %Values: hash indicating or overriding any default values which are 
                   13407: passed to graph.png.  
                   13408: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13409: 
                   13410: =back
                   13411: 
                   13412: Returns:
                   13413: 
                   13414: An <img> tag which references graph.png and the appropriate identifying
                   13415: information for the plot.
1.136     matthew  13416: 
                   13417: =cut
                   13418: 
                   13419: ############################################################
                   13420: ############################################################
1.137     matthew  13421: sub DrawXYYGraph {
                   13422:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   13423:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  13424:     #
                   13425:     # Create the identifier for the graph
                   13426:     my $identifier = &get_cgi_id();
                   13427:     my $id = 'cgi.'.$identifier;
                   13428:     #
                   13429:     $Title  = '' if (! defined($Title));
                   13430:     $xlabel = '' if (! defined($xlabel));
                   13431:     $ylabel = '' if (! defined($ylabel));
                   13432:     my %ValuesHash = 
                   13433:         (
1.369     www      13434:          $id.'.title'  => &escape($Title),
                   13435:          $id.'.xlabel' => &escape($xlabel),
                   13436:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  13437:          $id.'.labels' => join(',',@$Xlabels),
                   13438:          $id.'.PlotType' => 'XY',
                   13439:          $id.'.NumSets' => 2,
1.137     matthew  13440:          $id.'.two_axes' => 1,
                   13441:          $id.'.y1_max_value' => $Max1,
                   13442:          $id.'.y1_min_value' => $Min1,
                   13443:          $id.'.y2_max_value' => $Max2,
                   13444:          $id.'.y2_min_value' => $Min2,
1.136     matthew  13445:          );
                   13446:     #
1.137     matthew  13447:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13448:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13449:     }
                   13450:     #
                   13451:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   13452:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  13453:         return '';
                   13454:     }
                   13455:     my $NumSets=1;
1.137     matthew  13456:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  13457:         next if (! ref($array));
                   13458:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  13459:     }
                   13460:     #
                   13461:     # Deal with other parameters
                   13462:     while (my ($key,$value) = each(%Values)) {
                   13463:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  13464:     }
                   13465:     #
1.646     raeburn  13466:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 13467:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  13468: }
                   13469: 
                   13470: ############################################################
                   13471: ############################################################
                   13472: 
                   13473: =pod
                   13474: 
1.157     matthew  13475: =back 
                   13476: 
1.139     matthew  13477: =head1 Statistics helper routines?  
                   13478: 
                   13479: Bad place for them but what the hell.
                   13480: 
1.157     matthew  13481: =over 4
                   13482: 
1.648     raeburn  13483: =item * &chartlink()
1.139     matthew  13484: 
                   13485: Returns a link to the chart for a specific student.  
                   13486: 
                   13487: Inputs:
                   13488: 
                   13489: =over 4
                   13490: 
                   13491: =item $linktext: The text of the link
                   13492: 
                   13493: =item $sname: The students username
                   13494: 
                   13495: =item $sdomain: The students domain
                   13496: 
                   13497: =back
                   13498: 
1.157     matthew  13499: =back
                   13500: 
1.139     matthew  13501: =cut
                   13502: 
                   13503: ############################################################
                   13504: ############################################################
                   13505: sub chartlink {
                   13506:     my ($linktext, $sname, $sdomain) = @_;
                   13507:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      13508:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 13509:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  13510:        '">'.$linktext.'</a>';
1.153     matthew  13511: }
                   13512: 
                   13513: #######################################################
                   13514: #######################################################
                   13515: 
                   13516: =pod
                   13517: 
                   13518: =head1 Course Environment Routines
1.157     matthew  13519: 
                   13520: =over 4
1.153     matthew  13521: 
1.648     raeburn  13522: =item * &restore_course_settings()
1.153     matthew  13523: 
1.648     raeburn  13524: =item * &store_course_settings()
1.153     matthew  13525: 
                   13526: Restores/Store indicated form parameters from the course environment.
                   13527: Will not overwrite existing values of the form parameters.
                   13528: 
                   13529: Inputs: 
                   13530: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   13531: 
                   13532: a hash ref describing the data to be stored.  For example:
                   13533:    
                   13534: %Save_Parameters = ('Status' => 'scalar',
                   13535:     'chartoutputmode' => 'scalar',
                   13536:     'chartoutputdata' => 'scalar',
                   13537:     'Section' => 'array',
1.373     raeburn  13538:     'Group' => 'array',
1.153     matthew  13539:     'StudentData' => 'array',
                   13540:     'Maps' => 'array');
                   13541: 
                   13542: Returns: both routines return nothing
                   13543: 
1.631     raeburn  13544: =back
                   13545: 
1.153     matthew  13546: =cut
                   13547: 
                   13548: #######################################################
                   13549: #######################################################
                   13550: sub store_course_settings {
1.496     albertel 13551:     return &store_settings($env{'request.course.id'},@_);
                   13552: }
                   13553: 
                   13554: sub store_settings {
1.153     matthew  13555:     # save to the environment
                   13556:     # appenv the same items, just to be safe
1.300     albertel 13557:     my $udom  = $env{'user.domain'};
                   13558:     my $uname = $env{'user.name'};
1.496     albertel 13559:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13560:     my %SaveHash;
                   13561:     my %AppHash;
                   13562:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 13563:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 13564:         my $envname = 'environment.'.$basename;
1.258     albertel 13565:         if (exists($env{'form.'.$setting})) {
1.153     matthew  13566:             # Save this value away
                   13567:             if ($type eq 'scalar' &&
1.258     albertel 13568:                 (! exists($env{$envname}) || 
                   13569:                  $env{$envname} ne $env{'form.'.$setting})) {
                   13570:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   13571:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  13572:             } elsif ($type eq 'array') {
                   13573:                 my $stored_form;
1.258     albertel 13574:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  13575:                     $stored_form = join(',',
                   13576:                                         map {
1.369     www      13577:                                             &escape($_);
1.258     albertel 13578:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  13579:                 } else {
                   13580:                     $stored_form = 
1.369     www      13581:                         &escape($env{'form.'.$setting});
1.153     matthew  13582:                 }
                   13583:                 # Determine if the array contents are the same.
1.258     albertel 13584:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  13585:                     $SaveHash{$basename} = $stored_form;
                   13586:                     $AppHash{$envname}   = $stored_form;
                   13587:                 }
                   13588:             }
                   13589:         }
                   13590:     }
                   13591:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 13592:                                           $udom,$uname);
1.153     matthew  13593:     if ($put_result !~ /^(ok|delayed)/) {
                   13594:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   13595:                                  'got error:'.$put_result);
                   13596:     }
                   13597:     # Make sure these settings stick around in this session, too
1.646     raeburn  13598:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  13599:     return;
                   13600: }
                   13601: 
                   13602: sub restore_course_settings {
1.499     albertel 13603:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 13604: }
                   13605: 
                   13606: sub restore_settings {
                   13607:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13608:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 13609:         next if (exists($env{'form.'.$setting}));
1.496     albertel 13610:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  13611:             '.'.$setting;
1.258     albertel 13612:         if (exists($env{$envname})) {
1.153     matthew  13613:             if ($type eq 'scalar') {
1.258     albertel 13614:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  13615:             } elsif ($type eq 'array') {
1.258     albertel 13616:                 $env{'form.'.$setting} = [ 
1.153     matthew  13617:                                            map { 
1.369     www      13618:                                                &unescape($_); 
1.258     albertel 13619:                                            } split(',',$env{$envname})
1.153     matthew  13620:                                            ];
                   13621:             }
                   13622:         }
                   13623:     }
1.127     matthew  13624: }
                   13625: 
1.618     raeburn  13626: #######################################################
                   13627: #######################################################
                   13628: 
                   13629: =pod
                   13630: 
                   13631: =head1 Domain E-mail Routines  
                   13632: 
                   13633: =over 4
                   13634: 
1.648     raeburn  13635: =item * &build_recipient_list()
1.618     raeburn  13636: 
1.1144    raeburn  13637: Build recipient lists for following types of e-mail:
1.766     raeburn  13638: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  13639: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   13640: module change checking, student/employee ID conflict checks, as
                   13641: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   13642: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  13643: 
                   13644: Inputs:
1.619     raeburn  13645: defmail (scalar - email address of default recipient), 
1.1144    raeburn  13646: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   13647: requestsmail, updatesmail, or idconflictsmail).
                   13648: 
1.619     raeburn  13649: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  13650: 
1.619     raeburn  13651: origmail (scalar - email address of recipient from loncapa.conf, 
                   13652: i.e., predates configuration by DC via domainprefs.pm 
1.618     raeburn  13653: 
1.655     raeburn  13654: Returns: comma separated list of addresses to which to send e-mail.
                   13655: 
                   13656: =back
1.618     raeburn  13657: 
                   13658: =cut
                   13659: 
                   13660: ############################################################
                   13661: ############################################################
                   13662: sub build_recipient_list {
1.619     raeburn  13663:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  13664:     my @recipients;
                   13665:     my $otheremails;
                   13666:     my %domconfig =
                   13667:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
                   13668:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  13669:         if (exists($domconfig{'contacts'}{$mailing})) {
                   13670:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   13671:                 my @contacts = ('adminemail','supportemail');
                   13672:                 foreach my $item (@contacts) {
                   13673:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   13674:                         my $addr = $domconfig{'contacts'}{$item}; 
                   13675:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   13676:                             push(@recipients,$addr);
                   13677:                         }
1.619     raeburn  13678:                     }
1.766     raeburn  13679:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
1.618     raeburn  13680:                 }
                   13681:             }
1.766     raeburn  13682:         } elsif ($origmail ne '') {
                   13683:             push(@recipients,$origmail);
1.618     raeburn  13684:         }
1.619     raeburn  13685:     } elsif ($origmail ne '') {
                   13686:         push(@recipients,$origmail);
1.618     raeburn  13687:     }
1.688     raeburn  13688:     if (defined($defmail)) {
                   13689:         if ($defmail ne '') {
                   13690:             push(@recipients,$defmail);
                   13691:         }
1.618     raeburn  13692:     }
                   13693:     if ($otheremails) {
1.619     raeburn  13694:         my @others;
                   13695:         if ($otheremails =~ /,/) {
                   13696:             @others = split(/,/,$otheremails);
1.618     raeburn  13697:         } else {
1.619     raeburn  13698:             push(@others,$otheremails);
                   13699:         }
                   13700:         foreach my $addr (@others) {
                   13701:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   13702:                 push(@recipients,$addr);
                   13703:             }
1.618     raeburn  13704:         }
                   13705:     }
1.619     raeburn  13706:     my $recipientlist = join(',',@recipients); 
1.618     raeburn  13707:     return $recipientlist;
                   13708: }
                   13709: 
1.127     matthew  13710: ############################################################
                   13711: ############################################################
1.154     albertel 13712: 
1.655     raeburn  13713: =pod
                   13714: 
                   13715: =head1 Course Catalog Routines
                   13716: 
                   13717: =over 4
                   13718: 
                   13719: =item * &gather_categories()
                   13720: 
                   13721: Converts category definitions - keys of categories hash stored in  
                   13722: coursecategories in configuration.db on the primary library server in a 
                   13723: domain - to an array.  Also generates javascript and idx hash used to 
                   13724: generate Domain Coordinator interface for editing Course Categories.
                   13725: 
                   13726: Inputs:
1.663     raeburn  13727: 
1.655     raeburn  13728: categories (reference to hash of category definitions).
1.663     raeburn  13729: 
1.655     raeburn  13730: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13731:       categories and subcategories).
1.663     raeburn  13732: 
1.655     raeburn  13733: idx (reference to hash of counters used in Domain Coordinator interface for 
                   13734:       editing Course Categories).
1.663     raeburn  13735: 
1.655     raeburn  13736: jsarray (reference to array of categories used to create Javascript arrays for
                   13737:          Domain Coordinator interface for editing Course Categories).
                   13738: 
                   13739: Returns: nothing
                   13740: 
                   13741: Side effects: populates cats, idx and jsarray. 
                   13742: 
                   13743: =cut
                   13744: 
                   13745: sub gather_categories {
                   13746:     my ($categories,$cats,$idx,$jsarray) = @_;
                   13747:     my %counters;
                   13748:     my $num = 0;
                   13749:     foreach my $item (keys(%{$categories})) {
                   13750:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   13751:         if ($container eq '' && $depth == 0) {
                   13752:             $cats->[$depth][$categories->{$item}] = $cat;
                   13753:         } else {
                   13754:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   13755:         }
                   13756:         my ($escitem,$tail) = split(/:/,$item,2);
                   13757:         if ($counters{$tail} eq '') {
                   13758:             $counters{$tail} = $num;
                   13759:             $num ++;
                   13760:         }
                   13761:         if (ref($idx) eq 'HASH') {
                   13762:             $idx->{$item} = $counters{$tail};
                   13763:         }
                   13764:         if (ref($jsarray) eq 'ARRAY') {
                   13765:             push(@{$jsarray->[$counters{$tail}]},$item);
                   13766:         }
                   13767:     }
                   13768:     return;
                   13769: }
                   13770: 
                   13771: =pod
                   13772: 
                   13773: =item * &extract_categories()
                   13774: 
                   13775: Used to generate breadcrumb trails for course categories.
                   13776: 
                   13777: Inputs:
1.663     raeburn  13778: 
1.655     raeburn  13779: categories (reference to hash of category definitions).
1.663     raeburn  13780: 
1.655     raeburn  13781: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13782:       categories and subcategories).
1.663     raeburn  13783: 
1.655     raeburn  13784: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  13785: 
1.655     raeburn  13786: allitems (reference to hash - key is category key 
                   13787:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  13788: 
1.655     raeburn  13789: idx (reference to hash of counters used in Domain Coordinator interface for
                   13790:       editing Course Categories).
1.663     raeburn  13791: 
1.655     raeburn  13792: jsarray (reference to array of categories used to create Javascript arrays for
                   13793:          Domain Coordinator interface for editing Course Categories).
                   13794: 
1.665     raeburn  13795: subcats (reference to hash of arrays containing all subcategories within each 
                   13796:          category, -recursive)
                   13797: 
1.655     raeburn  13798: Returns: nothing
                   13799: 
                   13800: Side effects: populates trails and allitems hash references.
                   13801: 
                   13802: =cut
                   13803: 
                   13804: sub extract_categories {
1.665     raeburn  13805:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  13806:     if (ref($categories) eq 'HASH') {
                   13807:         &gather_categories($categories,$cats,$idx,$jsarray);
                   13808:         if (ref($cats->[0]) eq 'ARRAY') {
                   13809:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   13810:                 my $name = $cats->[0][$i];
                   13811:                 my $item = &escape($name).'::0';
                   13812:                 my $trailstr;
                   13813:                 if ($name eq 'instcode') {
                   13814:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  13815:                 } elsif ($name eq 'communities') {
                   13816:                     $trailstr = &mt('Communities');
1.655     raeburn  13817:                 } else {
                   13818:                     $trailstr = $name;
                   13819:                 }
                   13820:                 if ($allitems->{$item} eq '') {
                   13821:                     push(@{$trails},$trailstr);
                   13822:                     $allitems->{$item} = scalar(@{$trails})-1;
                   13823:                 }
                   13824:                 my @parents = ($name);
                   13825:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   13826:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   13827:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  13828:                         if (ref($subcats) eq 'HASH') {
                   13829:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   13830:                         }
                   13831:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   13832:                     }
                   13833:                 } else {
                   13834:                     if (ref($subcats) eq 'HASH') {
                   13835:                         $subcats->{$item} = [];
1.655     raeburn  13836:                     }
                   13837:                 }
                   13838:             }
                   13839:         }
                   13840:     }
                   13841:     return;
                   13842: }
                   13843: 
                   13844: =pod
                   13845: 
1.1162    raeburn  13846: =item * &recurse_categories()
1.655     raeburn  13847: 
                   13848: Recursively used to generate breadcrumb trails for course categories.
                   13849: 
                   13850: Inputs:
1.663     raeburn  13851: 
1.655     raeburn  13852: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13853:       categories and subcategories).
1.663     raeburn  13854: 
1.655     raeburn  13855: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  13856: 
                   13857: category (current course category, for which breadcrumb trail is being generated).
                   13858: 
                   13859: trails (reference to array of breadcrumb trails for each category).
                   13860: 
1.655     raeburn  13861: allitems (reference to hash - key is category key
                   13862:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  13863: 
1.655     raeburn  13864: parents (array containing containers directories for current category, 
                   13865:          back to top level). 
                   13866: 
                   13867: Returns: nothing
                   13868: 
                   13869: Side effects: populates trails and allitems hash references
                   13870: 
                   13871: =cut
                   13872: 
                   13873: sub recurse_categories {
1.665     raeburn  13874:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  13875:     my $shallower = $depth - 1;
                   13876:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   13877:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   13878:             my $name = $cats->[$depth]{$category}[$k];
                   13879:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   13880:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   13881:             if ($allitems->{$item} eq '') {
                   13882:                 push(@{$trails},$trailstr);
                   13883:                 $allitems->{$item} = scalar(@{$trails})-1;
                   13884:             }
                   13885:             my $deeper = $depth+1;
                   13886:             push(@{$parents},$category);
1.665     raeburn  13887:             if (ref($subcats) eq 'HASH') {
                   13888:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   13889:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   13890:                     my $higher;
                   13891:                     if ($j > 0) {
                   13892:                         $higher = &escape($parents->[$j]).':'.
                   13893:                                   &escape($parents->[$j-1]).':'.$j;
                   13894:                     } else {
                   13895:                         $higher = &escape($parents->[$j]).'::'.$j;
                   13896:                     }
                   13897:                     push(@{$subcats->{$higher}},$subcat);
                   13898:                 }
                   13899:             }
                   13900:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   13901:                                 $subcats);
1.655     raeburn  13902:             pop(@{$parents});
                   13903:         }
                   13904:     } else {
                   13905:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   13906:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   13907:         if ($allitems->{$item} eq '') {
                   13908:             push(@{$trails},$trailstr);
                   13909:             $allitems->{$item} = scalar(@{$trails})-1;
                   13910:         }
                   13911:     }
                   13912:     return;
                   13913: }
                   13914: 
1.663     raeburn  13915: =pod
                   13916: 
1.1162    raeburn  13917: =item * &assign_categories_table()
1.663     raeburn  13918: 
                   13919: Create a datatable for display of hierarchical categories in a domain,
                   13920: with checkboxes to allow a course to be categorized. 
                   13921: 
                   13922: Inputs:
                   13923: 
                   13924: cathash - reference to hash of categories defined for the domain (from
                   13925:           configuration.db)
                   13926: 
                   13927: currcat - scalar with an & separated list of categories assigned to a course. 
                   13928: 
1.919     raeburn  13929: type    - scalar contains course type (Course or Community).
                   13930: 
1.663     raeburn  13931: Returns: $output (markup to be displayed) 
                   13932: 
                   13933: =cut
                   13934: 
                   13935: sub assign_categories_table {
1.919     raeburn  13936:     my ($cathash,$currcat,$type) = @_;
1.663     raeburn  13937:     my $output;
                   13938:     if (ref($cathash) eq 'HASH') {
                   13939:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   13940:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   13941:         $maxdepth = scalar(@cats);
                   13942:         if (@cats > 0) {
                   13943:             my $itemcount = 0;
                   13944:             if (ref($cats[0]) eq 'ARRAY') {
                   13945:                 my @currcategories;
                   13946:                 if ($currcat ne '') {
                   13947:                     @currcategories = split('&',$currcat);
                   13948:                 }
1.919     raeburn  13949:                 my $table;
1.663     raeburn  13950:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   13951:                     my $parent = $cats[0][$i];
1.919     raeburn  13952:                     next if ($parent eq 'instcode');
                   13953:                     if ($type eq 'Community') {
                   13954:                         next unless ($parent eq 'communities');
                   13955:                     } else {
                   13956:                         next if ($parent eq 'communities');
                   13957:                     }
1.663     raeburn  13958:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   13959:                     my $item = &escape($parent).'::0';
                   13960:                     my $checked = '';
                   13961:                     if (@currcategories > 0) {
                   13962:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   13963:                             $checked = ' checked="checked"';
1.663     raeburn  13964:                         }
                   13965:                     }
1.919     raeburn  13966:                     my $parent_title = $parent;
                   13967:                     if ($parent eq 'communities') {
                   13968:                         $parent_title = &mt('Communities');
                   13969:                     }
                   13970:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   13971:                               '<input type="checkbox" name="usecategory" value="'.
                   13972:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
                   13973:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  13974:                     my $depth = 1;
                   13975:                     push(@path,$parent);
1.919     raeburn  13976:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
1.663     raeburn  13977:                     pop(@path);
1.919     raeburn  13978:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  13979:                     $itemcount ++;
                   13980:                 }
1.919     raeburn  13981:                 if ($itemcount) {
                   13982:                     $output = &Apache::loncommon::start_data_table().
                   13983:                               $table.
                   13984:                               &Apache::loncommon::end_data_table();
                   13985:                 }
1.663     raeburn  13986:             }
                   13987:         }
                   13988:     }
                   13989:     return $output;
                   13990: }
                   13991: 
                   13992: =pod
                   13993: 
1.1162    raeburn  13994: =item * &assign_category_rows()
1.663     raeburn  13995: 
                   13996: Create a datatable row for display of nested categories in a domain,
                   13997: with checkboxes to allow a course to be categorized,called recursively.
                   13998: 
                   13999: Inputs:
                   14000: 
                   14001: itemcount - track row number for alternating colors
                   14002: 
                   14003: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   14004:       categories and subcategories.
                   14005: 
                   14006: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   14007: 
                   14008: parent - parent of current category item
                   14009: 
                   14010: path - Array containing all categories back up through the hierarchy from the
                   14011:        current category to the top level.
                   14012: 
                   14013: currcategories - reference to array of current categories assigned to the course
                   14014: 
                   14015: Returns: $output (markup to be displayed).
                   14016: 
                   14017: =cut
                   14018: 
                   14019: sub assign_category_rows {
                   14020:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
                   14021:     my ($text,$name,$item,$chgstr);
                   14022:     if (ref($cats) eq 'ARRAY') {
                   14023:         my $maxdepth = scalar(@{$cats});
                   14024:         if (ref($cats->[$depth]) eq 'HASH') {
                   14025:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   14026:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   14027:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  14028:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  14029:                 for (my $j=0; $j<$numchildren; $j++) {
                   14030:                     $name = $cats->[$depth]{$parent}[$j];
                   14031:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   14032:                     my $deeper = $depth+1;
                   14033:                     my $checked = '';
                   14034:                     if (ref($currcategories) eq 'ARRAY') {
                   14035:                         if (@{$currcategories} > 0) {
                   14036:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   14037:                                 $checked = ' checked="checked"';
1.663     raeburn  14038:                             }
                   14039:                         }
                   14040:                     }
1.664     raeburn  14041:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   14042:                              '<input type="checkbox" name="usecategory" value="'.
1.675     raeburn  14043:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
                   14044:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   14045:                              '</td><td>';
1.663     raeburn  14046:                     if (ref($path) eq 'ARRAY') {
                   14047:                         push(@{$path},$name);
                   14048:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
                   14049:                         pop(@{$path});
                   14050:                     }
                   14051:                     $text .= '</td></tr>';
                   14052:                 }
                   14053:                 $text .= '</table></td>';
                   14054:             }
                   14055:         }
                   14056:     }
                   14057:     return $text;
                   14058: }
                   14059: 
1.1181    raeburn  14060: =pod
                   14061: 
                   14062: =back
                   14063: 
                   14064: =cut
                   14065: 
1.655     raeburn  14066: ############################################################
                   14067: ############################################################
                   14068: 
                   14069: 
1.443     albertel 14070: sub commit_customrole {
1.664     raeburn  14071:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  14072:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 14073:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   14074:                          ($end?', ending '.localtime($end):'').': <b>'.
                   14075:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  14076:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 14077:                  '</b><br />';
                   14078:     return $output;
                   14079: }
                   14080: 
                   14081: sub commit_standardrole {
1.1116    raeburn  14082:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  14083:     my ($output,$logmsg,$linefeed);
                   14084:     if ($context eq 'auto') {
                   14085:         $linefeed = "\n";
                   14086:     } else {
                   14087:         $linefeed = "<br />\n";
                   14088:     }  
1.443     albertel 14089:     if ($three eq 'st') {
1.541     raeburn  14090:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  14091:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  14092:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  14093:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   14094:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 14095:         } else {
1.541     raeburn  14096:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 14097:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14098:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   14099:             if ($context eq 'auto') {
                   14100:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   14101:             } else {
                   14102:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   14103:                &mt('Add to classlist').': <b>ok</b>';
                   14104:             }
                   14105:             $output .= $linefeed;
1.443     albertel 14106:         }
                   14107:     } else {
                   14108:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   14109:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14110:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  14111:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  14112:         if ($context eq 'auto') {
                   14113:             $output .= $result.$linefeed;
                   14114:         } else {
                   14115:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   14116:         }
1.443     albertel 14117:     }
                   14118:     return $output;
                   14119: }
                   14120: 
                   14121: sub commit_studentrole {
1.1116    raeburn  14122:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   14123:         $credits) = @_;
1.626     raeburn  14124:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  14125:     if ($context eq 'auto') {
                   14126:         $linefeed = "\n";
                   14127:     } else {
                   14128:         $linefeed = '<br />'."\n";
                   14129:     }
1.443     albertel 14130:     if (defined($one) && defined($two)) {
                   14131:         my $cid=$one.'_'.$two;
                   14132:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   14133:         my $secchange = 0;
                   14134:         my $expire_role_result;
                   14135:         my $modify_section_result;
1.628     raeburn  14136:         if ($oldsec ne '-1') { 
                   14137:             if ($oldsec ne $sec) {
1.443     albertel 14138:                 $secchange = 1;
1.628     raeburn  14139:                 my $now = time;
1.443     albertel 14140:                 my $uurl='/'.$cid;
                   14141:                 $uurl=~s/\_/\//g;
                   14142:                 if ($oldsec) {
                   14143:                     $uurl.='/'.$oldsec;
                   14144:                 }
1.626     raeburn  14145:                 $oldsecurl = $uurl;
1.628     raeburn  14146:                 $expire_role_result = 
1.652     raeburn  14147:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  14148:                 if ($env{'request.course.sec'} ne '') { 
                   14149:                     if ($expire_role_result eq 'refused') {
                   14150:                         my @roles = ('st');
                   14151:                         my @statuses = ('previous');
                   14152:                         my @roledoms = ($one);
                   14153:                         my $withsec = 1;
                   14154:                         my %roleshash = 
                   14155:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   14156:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   14157:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   14158:                             my ($oldstart,$oldend) = 
                   14159:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   14160:                             if ($oldend > 0 && $oldend <= $now) {
                   14161:                                 $expire_role_result = 'ok';
                   14162:                             }
                   14163:                         }
                   14164:                     }
                   14165:                 }
1.443     albertel 14166:                 $result = $expire_role_result;
                   14167:             }
                   14168:         }
                   14169:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  14170:             $modify_section_result = 
                   14171:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   14172:                                                            undef,undef,undef,$sec,
                   14173:                                                            $end,$start,'','',$cid,
                   14174:                                                            '',$context,$credits);
1.443     albertel 14175:             if ($modify_section_result =~ /^ok/) {
                   14176:                 if ($secchange == 1) {
1.628     raeburn  14177:                     if ($sec eq '') {
                   14178:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   14179:                     } else {
                   14180:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   14181:                     }
1.443     albertel 14182:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  14183:                     if ($sec eq '') {
                   14184:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   14185:                     } else {
                   14186:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14187:                     }
1.443     albertel 14188:                 } else {
1.628     raeburn  14189:                     if ($sec eq '') {
                   14190:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   14191:                     } else {
                   14192:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14193:                     }
1.443     albertel 14194:                 }
                   14195:             } else {
1.1115    raeburn  14196:                 if ($secchange) { 
1.628     raeburn  14197:                     $$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;
                   14198:                 } else {
                   14199:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   14200:                 }
1.443     albertel 14201:             }
                   14202:             $result = $modify_section_result;
                   14203:         } elsif ($secchange == 1) {
1.628     raeburn  14204:             if ($oldsec eq '') {
1.1103    raeburn  14205:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
1.628     raeburn  14206:             } else {
                   14207:                 $$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;
                   14208:             }
1.626     raeburn  14209:             if ($expire_role_result eq 'refused') {
                   14210:                 my $newsecurl = '/'.$cid;
                   14211:                 $newsecurl =~ s/\_/\//g;
                   14212:                 if ($sec ne '') {
                   14213:                     $newsecurl.='/'.$sec;
                   14214:                 }
                   14215:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   14216:                     if ($sec eq '') {
                   14217:                         $$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;
                   14218:                     } else {
                   14219:                         $$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;
                   14220:                     }
                   14221:                 }
                   14222:             }
1.443     albertel 14223:         }
                   14224:     } else {
1.626     raeburn  14225:         $$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 14226:         $result = "error: incomplete course id\n";
                   14227:     }
                   14228:     return $result;
                   14229: }
                   14230: 
1.1108    raeburn  14231: sub show_role_extent {
                   14232:     my ($scope,$context,$role) = @_;
                   14233:     $scope =~ s{^/}{};
                   14234:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   14235:     push(@courseroles,'co');
                   14236:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   14237:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   14238:         $scope =~ s{/}{_};
                   14239:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   14240:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   14241:         my ($audom,$auname) = split(/\//,$scope);
                   14242:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   14243:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   14244:     } else {
                   14245:         $scope =~ s{/$}{};
                   14246:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   14247:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   14248:     }
                   14249: }
                   14250: 
1.443     albertel 14251: ############################################################
                   14252: ############################################################
                   14253: 
1.566     albertel 14254: sub check_clone {
1.578     raeburn  14255:     my ($args,$linefeed) = @_;
1.566     albertel 14256:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   14257:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   14258:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   14259:     my $clonemsg;
                   14260:     my $can_clone = 0;
1.944     raeburn  14261:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  14262:     if ($lctype ne 'community') {
                   14263:         $lctype = 'course';
                   14264:     }
1.566     albertel 14265:     if ($clonehome eq 'no_host') {
1.944     raeburn  14266:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14267:             $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'});
                   14268:         } else {
                   14269:             $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'});
                   14270:         }     
1.566     albertel 14271:     } else {
                   14272: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  14273:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14274:             if ($clonedesc{'type'} ne 'Community') {
                   14275:                  $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'});
                   14276:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14277:             }
                   14278:         }
1.882     raeburn  14279: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
                   14280:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 14281: 	    $can_clone = 1;
                   14282: 	} else {
                   14283: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
                   14284: 						 $args->{'clonedomain'},$args->{'clonecourse'});
                   14285: 	    my @cloners = split(/,/,$clonehash{'cloners'});
1.578     raeburn  14286:             if (grep(/^\*$/,@cloners)) {
                   14287:                 $can_clone = 1;
                   14288:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   14289:                 $can_clone = 1;
                   14290:             } else {
1.908     raeburn  14291:                 my $ccrole = 'cc';
1.944     raeburn  14292:                 if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14293:                     $ccrole = 'co';
                   14294:                 }
1.578     raeburn  14295: 	        my %roleshash =
                   14296: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   14297: 					 $args->{'ccdomain'},
1.908     raeburn  14298:                                          'userroles',['active'],[$ccrole],
1.578     raeburn  14299: 					 [$args->{'clonedomain'}]);
1.908     raeburn  14300: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
1.942     raeburn  14301:                     $can_clone = 1;
                   14302:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
                   14303:                     $can_clone = 1;
                   14304:                 } else {
1.944     raeburn  14305:                     if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14306:                         $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'});
                   14307:                     } else {
                   14308:                         $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'});
                   14309:                     }
1.578     raeburn  14310: 	        }
1.566     albertel 14311: 	    }
1.578     raeburn  14312:         }
1.566     albertel 14313:     }
                   14314:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14315: }
                   14316: 
1.444     albertel 14317: sub construct_course {
1.1166    raeburn  14318:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
1.444     albertel 14319:     my $outcome;
1.541     raeburn  14320:     my $linefeed =  '<br />'."\n";
                   14321:     if ($context eq 'auto') {
                   14322:         $linefeed = "\n";
                   14323:     }
1.566     albertel 14324: 
                   14325: #
                   14326: # Are we cloning?
                   14327: #
                   14328:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14329:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  14330: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 14331: 	if ($context ne 'auto') {
1.578     raeburn  14332:             if ($clonemsg ne '') {
                   14333: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   14334:             }
1.566     albertel 14335: 	}
                   14336: 	$outcome .= $clonemsg.$linefeed;
                   14337: 
                   14338:         if (!$can_clone) {
                   14339: 	    return (0,$outcome);
                   14340: 	}
                   14341:     }
                   14342: 
1.444     albertel 14343: #
                   14344: # Open course
                   14345: #
                   14346:     my $crstype = lc($args->{'crstype'});
                   14347:     my %cenv=();
                   14348:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   14349:                                              $args->{'cdescr'},
                   14350:                                              $args->{'curl'},
                   14351:                                              $args->{'course_home'},
                   14352:                                              $args->{'nonstandard'},
                   14353:                                              $args->{'crscode'},
                   14354:                                              $args->{'ccuname'}.':'.
                   14355:                                              $args->{'ccdomain'},
1.882     raeburn  14356:                                              $args->{'crstype'},
1.885     raeburn  14357:                                              $cnum,$context,$category);
1.444     albertel 14358: 
                   14359:     # Note: The testing routines depend on this being output; see 
                   14360:     # Utils::Course. This needs to at least be output as a comment
                   14361:     # if anyone ever decides to not show this, and Utils::Course::new
                   14362:     # will need to be suitably modified.
1.541     raeburn  14363:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  14364:     if ($$courseid =~ /^error:/) {
                   14365:         return (0,$outcome);
                   14366:     }
                   14367: 
1.444     albertel 14368: #
                   14369: # Check if created correctly
                   14370: #
1.479     albertel 14371:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 14372:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  14373:     if ($crsuhome eq 'no_host') {
                   14374:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   14375:         return (0,$outcome);
                   14376:     }
1.541     raeburn  14377:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 14378: 
1.444     albertel 14379: #
1.566     albertel 14380: # Do the cloning
                   14381: #   
                   14382:     if ($can_clone && $cloneid) {
                   14383: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   14384: 	if ($context ne 'auto') {
                   14385: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   14386: 	}
                   14387: 	$outcome .= $clonemsg.$linefeed;
                   14388: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 14389: # Copy all files
1.637     www      14390: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 14391: # Restore URL
1.566     albertel 14392: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 14393: # Restore title
1.566     albertel 14394: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  14395: # Restore creation date, creator and creation context.
                   14396:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   14397:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   14398:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 14399: # Mark as cloned
1.566     albertel 14400: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      14401: # Need to clone grading mode
                   14402:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   14403:         $cenv{'grading'}=$newenv{'grading'};
                   14404: # Do not clone these environment entries
                   14405:         &Apache::lonnet::del('environment',
                   14406:                   ['default_enrollment_start_date',
                   14407:                    'default_enrollment_end_date',
                   14408:                    'question.email',
                   14409:                    'policy.email',
                   14410:                    'comment.email',
                   14411:                    'pch.users.denied',
1.725     raeburn  14412:                    'plc.users.denied',
                   14413:                    'hidefromcat',
1.1121    raeburn  14414:                    'checkforpriv',
1.1166    raeburn  14415:                    'categories',
                   14416:                    'internal.uniquecode'],
1.638     www      14417:                    $$crsudom,$$crsunum);
1.1170    raeburn  14418:         if ($args->{'textbook'}) {
                   14419:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   14420:         }
1.444     albertel 14421:     }
1.566     albertel 14422: 
1.444     albertel 14423: #
                   14424: # Set environment (will override cloned, if existing)
                   14425: #
                   14426:     my @sections = ();
                   14427:     my @xlists = ();
                   14428:     if ($args->{'crstype'}) {
                   14429:         $cenv{'type'}=$args->{'crstype'};
                   14430:     }
                   14431:     if ($args->{'crsid'}) {
                   14432:         $cenv{'courseid'}=$args->{'crsid'};
                   14433:     }
                   14434:     if ($args->{'crscode'}) {
                   14435:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   14436:     }
                   14437:     if ($args->{'crsquota'} ne '') {
                   14438:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   14439:     } else {
                   14440:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   14441:     }
                   14442:     if ($args->{'ccuname'}) {
                   14443:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   14444:                                         ':'.$args->{'ccdomain'};
                   14445:     } else {
                   14446:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   14447:     }
1.1116    raeburn  14448:     if ($args->{'defaultcredits'}) {
                   14449:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   14450:     }
1.444     albertel 14451:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   14452:     if ($args->{'crssections'}) {
                   14453:         $cenv{'internal.sectionnums'} = '';
                   14454:         if ($args->{'crssections'} =~ m/,/) {
                   14455:             @sections = split/,/,$args->{'crssections'};
                   14456:         } else {
                   14457:             $sections[0] = $args->{'crssections'};
                   14458:         }
                   14459:         if (@sections > 0) {
                   14460:             foreach my $item (@sections) {
                   14461:                 my ($sec,$gp) = split/:/,$item;
                   14462:                 my $class = $args->{'crscode'}.$sec;
                   14463:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   14464:                 $cenv{'internal.sectionnums'} .= $item.',';
                   14465:                 unless ($addcheck eq 'ok') {
                   14466:                     push @badclasses, $class;
                   14467:                 }
                   14468:             }
                   14469:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   14470:         }
                   14471:     }
                   14472: # do not hide course coordinator from staff listing, 
                   14473: # even if privileged
                   14474:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  14475: # add course coordinator's domain to domains to check for privileged users
                   14476: # if different to course domain
                   14477:     if ($$crsudom ne $args->{'ccdomain'}) {
                   14478:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   14479:     }
1.444     albertel 14480: # add crosslistings
                   14481:     if ($args->{'crsxlist'}) {
                   14482:         $cenv{'internal.crosslistings'}='';
                   14483:         if ($args->{'crsxlist'} =~ m/,/) {
                   14484:             @xlists = split/,/,$args->{'crsxlist'};
                   14485:         } else {
                   14486:             $xlists[0] = $args->{'crsxlist'};
                   14487:         }
                   14488:         if (@xlists > 0) {
                   14489:             foreach my $item (@xlists) {
                   14490:                 my ($xl,$gp) = split/:/,$item;
                   14491:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   14492:                 $cenv{'internal.crosslistings'} .= $item.',';
                   14493:                 unless ($addcheck eq 'ok') {
                   14494:                     push @badclasses, $xl;
                   14495:                 }
                   14496:             }
                   14497:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   14498:         }
                   14499:     }
                   14500:     if ($args->{'autoadds'}) {
                   14501:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   14502:     }
                   14503:     if ($args->{'autodrops'}) {
                   14504:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   14505:     }
                   14506: # check for notification of enrollment changes
                   14507:     my @notified = ();
                   14508:     if ($args->{'notify_owner'}) {
                   14509:         if ($args->{'ccuname'} ne '') {
                   14510:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   14511:         }
                   14512:     }
                   14513:     if ($args->{'notify_dc'}) {
                   14514:         if ($uname ne '') { 
1.630     raeburn  14515:             push(@notified,$uname.':'.$udom);
1.444     albertel 14516:         }
                   14517:     }
                   14518:     if (@notified > 0) {
                   14519:         my $notifylist;
                   14520:         if (@notified > 1) {
                   14521:             $notifylist = join(',',@notified);
                   14522:         } else {
                   14523:             $notifylist = $notified[0];
                   14524:         }
                   14525:         $cenv{'internal.notifylist'} = $notifylist;
                   14526:     }
                   14527:     if (@badclasses > 0) {
                   14528:         my %lt=&Apache::lonlocal::texthash(
                   14529:                 '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',
                   14530:                 'dnhr' => 'does not have rights to access enrollment in these classes',
                   14531:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
                   14532:         );
1.541     raeburn  14533:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
                   14534:                            ' ('.$lt{'adby'}.')';
                   14535:         if ($context eq 'auto') {
                   14536:             $outcome .= $badclass_msg.$linefeed;
1.566     albertel 14537:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.541     raeburn  14538:             foreach my $item (@badclasses) {
                   14539:                 if ($context eq 'auto') {
                   14540:                     $outcome .= " - $item\n";
                   14541:                 } else {
                   14542:                     $outcome .= "<li>$item</li>\n";
                   14543:                 }
                   14544:             }
                   14545:             if ($context eq 'auto') {
                   14546:                 $outcome .= $linefeed;
                   14547:             } else {
1.566     albertel 14548:                 $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  14549:             }
                   14550:         } 
1.444     albertel 14551:     }
                   14552:     if ($args->{'no_end_date'}) {
                   14553:         $args->{'endaccess'} = 0;
                   14554:     }
                   14555:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   14556:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   14557:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   14558:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   14559:     if ($args->{'showphotos'}) {
                   14560:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   14561:     }
                   14562:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   14563:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   14564:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   14565:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  14566:             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'); 
                   14567:             if ($context eq 'auto') {
                   14568:                 $outcome .= $krb_msg;
                   14569:             } else {
1.566     albertel 14570:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  14571:             }
                   14572:             $outcome .= $linefeed;
1.444     albertel 14573:         }
                   14574:     }
                   14575:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   14576:        if ($args->{'setpolicy'}) {
                   14577:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   14578:        }
                   14579:        if ($args->{'setcontent'}) {
                   14580:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   14581:        }
                   14582:     }
                   14583:     if ($args->{'reshome'}) {
                   14584: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   14585: 	$cenv{'reshome'}=~s/\/+$/\//;
                   14586:     }
                   14587: #
                   14588: # course has keyed access
                   14589: #
                   14590:     if ($args->{'setkeys'}) {
                   14591:        $cenv{'keyaccess'}='yes';
                   14592:     }
                   14593: # if specified, key authority is not course, but user
                   14594: # only active if keyaccess is yes
                   14595:     if ($args->{'keyauth'}) {
1.487     albertel 14596: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   14597: 	$user = &LONCAPA::clean_username($user);
                   14598: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     14599: 	if ($user ne '' && $domain ne '') {
1.487     albertel 14600: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 14601: 	}
                   14602:     }
                   14603: 
1.1166    raeburn  14604: #
1.1167    raeburn  14605: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  14606: #
                   14607:     if ($args->{'uniquecode'}) {
                   14608:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   14609:         if ($code) {
                   14610:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  14611:             my %crsinfo =
                   14612:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   14613:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   14614:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   14615:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   14616:             } 
1.1166    raeburn  14617:             if (ref($coderef)) {
                   14618:                 $$coderef = $code;
                   14619:             }
                   14620:         }
                   14621:     }
                   14622: 
1.444     albertel 14623:     if ($args->{'disresdis'}) {
                   14624:         $cenv{'pch.roles.denied'}='st';
                   14625:     }
                   14626:     if ($args->{'disablechat'}) {
                   14627:         $cenv{'plc.roles.denied'}='st';
                   14628:     }
                   14629: 
                   14630:     # Record we've not yet viewed the Course Initialization Helper for this 
                   14631:     # course
                   14632:     $cenv{'course.helper.not.run'} = 1;
                   14633:     #
                   14634:     # Use new Randomseed
                   14635:     #
                   14636:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   14637:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   14638:     #
                   14639:     # The encryption code and receipt prefix for this course
                   14640:     #
                   14641:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   14642:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   14643:     #
                   14644:     # By default, use standard grading
                   14645:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   14646: 
1.541     raeburn  14647:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   14648:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 14649: #
                   14650: # Open all assignments
                   14651: #
                   14652:     if ($args->{'openall'}) {
                   14653:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   14654:        my %storecontent = ($storeunder         => time,
                   14655:                            $storeunder.'.type' => 'date_start');
                   14656:        
                   14657:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  14658:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 14659:    }
                   14660: #
                   14661: # Set first page
                   14662: #
                   14663:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   14664: 	    || ($cloneid)) {
1.445     albertel 14665: 	use LONCAPA::map;
1.444     albertel 14666: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 14667: 
                   14668: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   14669:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   14670: 
1.444     albertel 14671:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   14672:         my $title; my $url;
                   14673:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   14674: 	    $title=&mt('Syllabus');
1.444     albertel 14675:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   14676:         } else {
1.963     raeburn  14677:             $title=&mt('Table of Contents');
1.444     albertel 14678:             $url='/adm/navmaps';
                   14679:         }
1.445     albertel 14680: 
                   14681:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   14682: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   14683: 
                   14684: 	if ($errtext) { $fatal=2; }
1.541     raeburn  14685:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 14686:     }
1.566     albertel 14687: 
                   14688:     return (1,$outcome);
1.444     albertel 14689: }
                   14690: 
1.1166    raeburn  14691: sub make_unique_code {
                   14692:     my ($cdom,$cnum) = @_;
                   14693:     # get lock on uniquecodes db
                   14694:     my $lockhash = {
                   14695:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   14696:                                                   ':'.$env{'user.domain'},
                   14697:                    };
                   14698:     my $tries = 0;
                   14699:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   14700:     my ($code,$error);
                   14701:   
                   14702:     while (($gotlock ne 'ok') && ($tries<3)) {
                   14703:         $tries ++;
                   14704:         sleep 1;
                   14705:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   14706:     }
                   14707:     if ($gotlock eq 'ok') {
                   14708:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   14709:         my $gotcode;
                   14710:         my $attempts = 0;
                   14711:         while ((!$gotcode) && ($attempts < 100)) {
                   14712:             $code = &generate_code();
                   14713:             if (!exists($currcodes{$code})) {
                   14714:                 $gotcode = 1;
                   14715:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   14716:                     $error = 'nostore';
                   14717:                 }
                   14718:             }
                   14719:             $attempts ++;
                   14720:         }
                   14721:         my @del_lock = ($cnum."\0".'uniquecodes');
                   14722:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   14723:     } else {
                   14724:         $error = 'nolock';
                   14725:     }
                   14726:     return ($code,$error);
                   14727: }
                   14728: 
                   14729: sub generate_code {
                   14730:     my $code;
                   14731:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   14732:     for (my $i=0; $i<6; $i++) {
                   14733:         my $lettnum = int (rand 2);
                   14734:         my $item = '';
                   14735:         if ($lettnum) {
                   14736:             $item = $letts[int( rand(18) )];
                   14737:         } else {
                   14738:             $item = 1+int( rand(8) );
                   14739:         }
                   14740:         $code .= $item;
                   14741:     }
                   14742:     return $code;
                   14743: }
                   14744: 
1.444     albertel 14745: ############################################################
                   14746: ############################################################
                   14747: 
1.953     droeschl 14748: #SD
                   14749: # only Community and Course, or anything else?
1.378     raeburn  14750: sub course_type {
                   14751:     my ($cid) = @_;
                   14752:     if (!defined($cid)) {
                   14753:         $cid = $env{'request.course.id'};
                   14754:     }
1.404     albertel 14755:     if (defined($env{'course.'.$cid.'.type'})) {
                   14756:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  14757:     } else {
                   14758:         return 'Course';
1.377     raeburn  14759:     }
                   14760: }
1.156     albertel 14761: 
1.406     raeburn  14762: sub group_term {
                   14763:     my $crstype = &course_type();
                   14764:     my %names = (
                   14765:                   'Course' => 'group',
1.865     raeburn  14766:                   'Community' => 'group',
1.406     raeburn  14767:                 );
                   14768:     return $names{$crstype};
                   14769: }
                   14770: 
1.902     raeburn  14771: sub course_types {
1.1165    raeburn  14772:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  14773:     my %typename = (
                   14774:                          official   => 'Official course',
                   14775:                          unofficial => 'Unofficial course',
                   14776:                          community  => 'Community',
1.1165    raeburn  14777:                          textbook   => 'Textbook course',
1.902     raeburn  14778:                    );
                   14779:     return (\@types,\%typename);
                   14780: }
                   14781: 
1.156     albertel 14782: sub icon {
                   14783:     my ($file)=@_;
1.505     albertel 14784:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 14785:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 14786:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 14787:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   14788: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   14789: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   14790: 	            $curfext.".gif") {
                   14791: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   14792: 		$curfext.".gif";
                   14793: 	}
                   14794:     }
1.249     albertel 14795:     return &lonhttpdurl($iconname);
1.154     albertel 14796: } 
1.84      albertel 14797: 
1.575     albertel 14798: sub lonhttpdurl {
1.692     www      14799: #
                   14800: # Had been used for "small fry" static images on separate port 8080.
                   14801: # Modify here if lightweight http functionality desired again.
                   14802: # Currently eliminated due to increasing firewall issues.
                   14803: #
1.575     albertel 14804:     my ($url)=@_;
1.692     www      14805:     return $url;
1.215     albertel 14806: }
                   14807: 
1.213     albertel 14808: sub connection_aborted {
                   14809:     my ($r)=@_;
                   14810:     $r->print(" ");$r->rflush();
                   14811:     my $c = $r->connection;
                   14812:     return $c->aborted();
                   14813: }
                   14814: 
1.221     foxr     14815: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     14816: #    strings as 'strings'.
                   14817: sub escape_single {
1.221     foxr     14818:     my ($input) = @_;
1.223     albertel 14819:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     14820:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   14821:     return $input;
                   14822: }
1.223     albertel 14823: 
1.222     foxr     14824: #  Same as escape_single, but escape's "'s  This 
                   14825: #  can be used for  "strings"
                   14826: sub escape_double {
                   14827:     my ($input) = @_;
                   14828:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   14829:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   14830:     return $input;
                   14831: }
1.223     albertel 14832:  
1.222     foxr     14833: #   Escapes the last element of a full URL.
                   14834: sub escape_url {
                   14835:     my ($url)   = @_;
1.238     raeburn  14836:     my @urlslices = split(/\//, $url,-1);
1.369     www      14837:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  14838:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     14839: }
1.462     albertel 14840: 
1.820     raeburn  14841: sub compare_arrays {
                   14842:     my ($arrayref1,$arrayref2) = @_;
                   14843:     my (@difference,%count);
                   14844:     @difference = ();
                   14845:     %count = ();
                   14846:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   14847:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   14848:         foreach my $element (keys(%count)) {
                   14849:             if ($count{$element} == 1) {
                   14850:                 push(@difference,$element);
                   14851:             }
                   14852:         }
                   14853:     }
                   14854:     return @difference;
                   14855: }
                   14856: 
1.817     bisitz   14857: # -------------------------------------------------------- Initialize user login
1.462     albertel 14858: sub init_user_environment {
1.463     albertel 14859:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 14860:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   14861: 
                   14862:     my $public=($username eq 'public' && $domain eq 'public');
                   14863: 
                   14864: # See if old ID present, if so, remove
                   14865: 
1.1062    raeburn  14866:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 14867:     my $now=time;
                   14868: 
                   14869:     if ($public) {
                   14870: 	my $max_public=100;
                   14871: 	my $oldest;
                   14872: 	my $oldest_time=0;
                   14873: 	for(my $next=1;$next<=$max_public;$next++) {
                   14874: 	    if (-e $lonids."/publicuser_$next.id") {
                   14875: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   14876: 		if ($mtime<$oldest_time || !$oldest_time) {
                   14877: 		    $oldest_time=$mtime;
                   14878: 		    $oldest=$next;
                   14879: 		}
                   14880: 	    } else {
                   14881: 		$cookie="publicuser_$next";
                   14882: 		last;
                   14883: 	    }
                   14884: 	}
                   14885: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   14886:     } else {
1.463     albertel 14887: 	# if this isn't a robot, kill any existing non-robot sessions
                   14888: 	if (!$args->{'robot'}) {
                   14889: 	    opendir(DIR,$lonids);
                   14890: 	    while ($filename=readdir(DIR)) {
                   14891: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   14892: 		    unlink($lonids.'/'.$filename);
                   14893: 		}
1.462     albertel 14894: 	    }
1.463     albertel 14895: 	    closedir(DIR);
1.1204    raeburn  14896: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   14897:             my $namespace = 'nohist_courseeditor';
                   14898:             my $lockingkey = 'paste'."\0".'locked_num';
                   14899:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   14900:                                                 $domain,$username);
                   14901:             if (exists($lockhash{$lockingkey})) {
                   14902:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   14903:                 unless ($delresult eq 'ok') {
                   14904:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   14905:                 }
                   14906:             }
1.462     albertel 14907: 	}
                   14908: # Give them a new cookie
1.463     albertel 14909: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      14910: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 14911: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 14912:     
                   14913: # Initialize roles
                   14914: 
1.1062    raeburn  14915: 	($userroles,$firstaccenv,$timerintenv) = 
                   14916:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 14917:     }
                   14918: # ------------------------------------ Check browser type and MathML capability
                   14919: 
1.1194    raeburn  14920:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   14921:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 14922: 
                   14923: # ------------------------------------------------------------- Get environment
                   14924: 
                   14925:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   14926:     my ($tmp) = keys(%userenv);
                   14927:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   14928:     } else {
                   14929: 	undef(%userenv);
                   14930:     }
                   14931:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   14932: 	$form->{'interface'}=$userenv{'interface'};
                   14933:     }
                   14934:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   14935: 
                   14936: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   14937:     foreach my $option ('interface','localpath','localres') {
                   14938:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 14939:     }
                   14940: # --------------------------------------------------------- Write first profile
                   14941: 
                   14942:     {
                   14943: 	my %initial_env = 
                   14944: 	    ("user.name"          => $username,
                   14945: 	     "user.domain"        => $domain,
                   14946: 	     "user.home"          => $authhost,
                   14947: 	     "browser.type"       => $clientbrowser,
                   14948: 	     "browser.version"    => $clientversion,
                   14949: 	     "browser.mathml"     => $clientmathml,
                   14950: 	     "browser.unicode"    => $clientunicode,
                   14951: 	     "browser.os"         => $clientos,
1.1137    raeburn  14952:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  14953:              "browser.info"       => $clientinfo,
1.1194    raeburn  14954:              "browser.osversion"  => $clientosversion,
1.462     albertel 14955: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   14956: 	     "request.course.fn"  => '',
                   14957: 	     "request.course.uri" => '',
                   14958: 	     "request.course.sec" => '',
                   14959: 	     "request.role"       => 'cm',
                   14960: 	     "request.role.adv"   => $env{'user.adv'},
                   14961: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   14962: 
                   14963:         if ($form->{'localpath'}) {
                   14964: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   14965: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   14966:         }
                   14967: 	
                   14968: 	if ($form->{'interface'}) {
                   14969: 	    $form->{'interface'}=~s/\W//gs;
                   14970: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   14971: 	    $env{'browser.interface'}=$form->{'interface'};
                   14972: 	}
                   14973: 
1.1157    raeburn  14974:         if ($form->{'iptoken'}) {
                   14975:             my $lonhost = $r->dir_config('lonHostID');
                   14976:             $initial_env{"user.noloadbalance"} = $lonhost;
                   14977:             $env{'user.noloadbalance'} = $lonhost;
                   14978:         }
                   14979: 
1.981     raeburn  14980:         my %is_adv = ( is_adv => $env{'user.adv'} );
1.1016    raeburn  14981:         my %domdef;
                   14982:         unless ($domain eq 'public') {
                   14983:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   14984:         }
1.980     raeburn  14985: 
1.1081    raeburn  14986:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
1.724     raeburn  14987:             $userenv{'availabletools.'.$tool} = 
1.980     raeburn  14988:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   14989:                                                   undef,\%userenv,\%domdef,\%is_adv);
1.724     raeburn  14990:         }
                   14991: 
1.1165    raeburn  14992:         foreach my $crstype ('official','unofficial','community','textbook') {
1.765     raeburn  14993:             $userenv{'canrequest.'.$crstype} =
                   14994:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
1.980     raeburn  14995:                                                   'reload','requestcourses',
                   14996:                                                   \%userenv,\%domdef,\%is_adv);
1.765     raeburn  14997:         }
                   14998: 
1.1092    raeburn  14999:         $userenv{'canrequest.author'} =
                   15000:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   15001:                                         'reload','requestauthor',
                   15002:                                         \%userenv,\%domdef,\%is_adv);
                   15003:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   15004:                                              $domain,$username);
                   15005:         my $reqstatus = $reqauthor{'author_status'};
                   15006:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   15007:             if (ref($reqauthor{'author'}) eq 'HASH') {
                   15008:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   15009:                                                   $reqauthor{'author'}{'timestamp'};
                   15010:             }
                   15011:         }
                   15012: 
1.462     albertel 15013: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  15014: 
1.462     albertel 15015: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   15016: 		 &GDBM_WRCREAT(),0640)) {
                   15017: 	    &_add_to_env(\%disk_env,\%initial_env);
                   15018: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   15019: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  15020:             if (ref($firstaccenv) eq 'HASH') {
                   15021:                 &_add_to_env(\%disk_env,$firstaccenv);
                   15022:             }
                   15023:             if (ref($timerintenv) eq 'HASH') {
                   15024:                 &_add_to_env(\%disk_env,$timerintenv);
                   15025:             }
1.463     albertel 15026: 	    if (ref($args->{'extra_env'})) {
                   15027: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   15028: 	    }
1.462     albertel 15029: 	    untie(%disk_env);
                   15030: 	} else {
1.705     tempelho 15031: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   15032: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 15033: 	    return 'error: '.$!;
                   15034: 	}
                   15035:     }
                   15036:     $env{'request.role'}='cm';
                   15037:     $env{'request.role.adv'}=$env{'user.adv'};
                   15038:     $env{'browser.type'}=$clientbrowser;
                   15039: 
                   15040:     return $cookie;
                   15041: 
                   15042: }
                   15043: 
                   15044: sub _add_to_env {
                   15045:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  15046:     if (ref($env_data) eq 'HASH') {
                   15047:         while (my ($key,$value) = each(%$env_data)) {
                   15048: 	    $idf->{$prefix.$key} = $value;
                   15049: 	    $env{$prefix.$key}   = $value;
                   15050:         }
1.462     albertel 15051:     }
                   15052: }
                   15053: 
1.685     tempelho 15054: # --- Get the symbolic name of a problem and the url
                   15055: sub get_symb {
                   15056:     my ($request,$silent) = @_;
1.726     raeburn  15057:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 15058:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   15059:     if ($symb eq '') {
                   15060:         if (!$silent) {
1.1071    raeburn  15061:             if (ref($request)) { 
                   15062:                 $request->print("Unable to handle ambiguous references:$url:.");
                   15063:             }
1.685     tempelho 15064:             return ();
                   15065:         }
                   15066:     }
                   15067:     &Apache::lonenc::check_decrypt(\$symb);
                   15068:     return ($symb);
                   15069: }
                   15070: 
                   15071: # --------------------------------------------------------------Get annotation
                   15072: 
                   15073: sub get_annotation {
                   15074:     my ($symb,$enc) = @_;
                   15075: 
                   15076:     my $key = $symb;
                   15077:     if (!$enc) {
                   15078:         $key =
                   15079:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   15080:     }
                   15081:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   15082:     return $annotation{$key};
                   15083: }
                   15084: 
                   15085: sub clean_symb {
1.731     raeburn  15086:     my ($symb,$delete_enc) = @_;
1.685     tempelho 15087: 
                   15088:     &Apache::lonenc::check_decrypt(\$symb);
                   15089:     my $enc = $env{'request.enc'};
1.731     raeburn  15090:     if ($delete_enc) {
1.730     raeburn  15091:         delete($env{'request.enc'});
                   15092:     }
1.685     tempelho 15093: 
                   15094:     return ($symb,$enc);
                   15095: }
1.462     albertel 15096: 
1.1181    raeburn  15097: ############################################################
                   15098: ############################################################
                   15099: 
                   15100: =pod
                   15101: 
                   15102: =head1 Routines for building display used to search for courses
                   15103: 
                   15104: 
                   15105: =over 4
                   15106: 
                   15107: =item * &build_filters()
                   15108: 
                   15109: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  15110: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   15111: and quotacheck.pl
                   15112: 
1.1181    raeburn  15113: 
                   15114: Inputs:
                   15115: 
                   15116: filterlist - anonymous array of fields to include as potential filters 
                   15117: 
                   15118: crstype - course type
                   15119: 
                   15120: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   15121:               to pop-open a course selector (will contain "extra element"). 
                   15122: 
                   15123: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   15124: 
                   15125: filter - anonymous hash of criteria and their values
                   15126: 
                   15127: action - form action
                   15128: 
                   15129: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   15130: 
1.1182    raeburn  15131: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  15132: 
                   15133: cloneruname - username of owner of new course who wants to clone
                   15134: 
                   15135: clonerudom - domain of owner of new course who wants to clone
                   15136: 
                   15137: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   15138: 
                   15139: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   15140: 
                   15141: codedom - domain
                   15142: 
                   15143: formname - value of form element named "form". 
                   15144: 
                   15145: fixeddom - domain, if fixed.
                   15146: 
                   15147: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   15148: 
                   15149: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   15150: 
                   15151: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   15152: 
                   15153: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   15154: 
                   15155: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   15156: 
                   15157: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   15158: 
                   15159: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   15160: 
1.1182    raeburn  15161: 
1.1181    raeburn  15162: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   15163: 
1.1182    raeburn  15164: 
1.1181    raeburn  15165: Side Effects: None
                   15166: 
                   15167: =cut
                   15168: 
                   15169: # ---------------------------------------------- search for courses based on last activity etc.
                   15170: 
                   15171: sub build_filters {
                   15172:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   15173:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   15174:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   15175:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   15176:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  15177:     my ($list,$jscript);
1.1181    raeburn  15178:     my $onchange = 'javascript:updateFilters(this)';
                   15179:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   15180:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   15181:         $typeselectform,$instcodetitle);
                   15182:     if ($formname eq '') {
                   15183:         $formname = $caller;
                   15184:     }
                   15185:     foreach my $item (@{$filterlist}) {
                   15186:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   15187:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   15188:             if ($item eq 'domainfilter') {
                   15189:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   15190:             } elsif ($item eq 'coursefilter') {
                   15191:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   15192:             } elsif ($item eq 'ownerfilter') {
                   15193:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15194:             } elsif ($item eq 'ownerdomfilter') {
                   15195:                 $filter->{'ownerdomfilter'} =
                   15196:                     &LONCAPA::clean_domain($filter->{$item});
                   15197:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   15198:                                                        'ownerdomfilter',1);
                   15199:             } elsif ($item eq 'personfilter') {
                   15200:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15201:             } elsif ($item eq 'persondomfilter') {
                   15202:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   15203:                                                         'persondomfilter',1);
                   15204:             } else {
                   15205:                 $filter->{$item} =~ s/\W//g;
                   15206:             }
                   15207:             if (!$filter->{$item}) {
                   15208:                 $filter->{$item} = '';
                   15209:             }
                   15210:         }
                   15211:         if ($item eq 'domainfilter') {
                   15212:             my $allow_blank = 1;
                   15213:             if ($formname eq 'portform') {
                   15214:                 $allow_blank=0;
                   15215:             } elsif ($formname eq 'studentform') {
                   15216:                 $allow_blank=0;
                   15217:             }
                   15218:             if ($fixeddom) {
                   15219:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   15220:                                     ' value="'.$codedom.'" />'.
                   15221:                                     &Apache::lonnet::domain($codedom,'description');
                   15222:             } else {
                   15223:                 $domainselectform = &select_dom_form($filter->{$item},
                   15224:                                                      'domainfilter',
                   15225:                                                       $allow_blank,'',$onchange);
                   15226:             }
                   15227:         } else {
                   15228:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   15229:         }
                   15230:     }
                   15231: 
                   15232:     # last course activity filter and selection
                   15233:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   15234: 
                   15235:     # course created filter and selection
                   15236:     if (exists($filter->{'createdfilter'})) {
                   15237:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   15238:     }
                   15239: 
                   15240:     my %lt = &Apache::lonlocal::texthash(
                   15241:                 'cac' => "$crstype Activity",
                   15242:                 'ccr' => "$crstype Created",
                   15243:                 'cde' => "$crstype Title",
                   15244:                 'cdo' => "$crstype Domain",
                   15245:                 'ins' => 'Institutional Code',
                   15246:                 'inc' => 'Institutional Categorization',
                   15247:                 'cow' => "$crstype Owner/Co-owner",
                   15248:                 'cop' => "$crstype Personnel Includes",
                   15249:                 'cog' => 'Type',
                   15250:              );
                   15251: 
                   15252:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15253:         my $typeval = 'Course';
                   15254:         if ($crstype eq 'Community') {
                   15255:             $typeval = 'Community';
                   15256:         }
                   15257:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   15258:     } else {
                   15259:         $typeselectform =  '<select name="type" size="1"';
                   15260:         if ($onchange) {
                   15261:             $typeselectform .= ' onchange="'.$onchange.'"';
                   15262:         }
                   15263:         $typeselectform .= '>'."\n";
                   15264:         foreach my $posstype ('Course','Community') {
                   15265:             $typeselectform.='<option value="'.$posstype.'"'.
                   15266:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   15267:         }
                   15268:         $typeselectform.="</select>";
                   15269:     }
                   15270: 
                   15271:     my ($cloneableonlyform,$cloneabletitle);
                   15272:     if (exists($filter->{'cloneableonly'})) {
                   15273:         my $cloneableon = '';
                   15274:         my $cloneableoff = ' checked="checked"';
                   15275:         if ($filter->{'cloneableonly'}) {
                   15276:             $cloneableon = $cloneableoff;
                   15277:             $cloneableoff = '';
                   15278:         }
                   15279:         $cloneableonlyform = '<span class="LC_nobreak"><label><input type="radio" name="cloneableonly" value="1" '.$cloneableon.'/>&nbsp;'.&mt('Required').'</label>'.('&nbsp;'x3).'<label><input type="radio" name="cloneableonly" value="" '.$cloneableoff.' />&nbsp;'.&mt('No restriction').'</label></span>';
                   15280:         if ($formname eq 'ccrs') {
1.1187    bisitz   15281:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  15282:         } else {
                   15283:             $cloneabletitle = &mt('Cloneable by you');
                   15284:         }
                   15285:     }
                   15286:     my $officialjs;
                   15287:     if ($crstype eq 'Course') {
                   15288:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  15289: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   15290: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   15291:             if ($codedom) { 
1.1181    raeburn  15292:                 $officialjs = 1;
                   15293:                 ($instcodeform,$jscript,$$numtitlesref) =
                   15294:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   15295:                                                                   $officialjs,$codetitlesref);
                   15296:                 if ($jscript) {
1.1182    raeburn  15297:                     $jscript = '<script type="text/javascript">'."\n".
                   15298:                                '// <![CDATA['."\n".
                   15299:                                $jscript."\n".
                   15300:                                '// ]]>'."\n".
                   15301:                                '</script>'."\n";
1.1181    raeburn  15302:                 }
                   15303:             }
                   15304:             if ($instcodeform eq '') {
                   15305:                 $instcodeform =
                   15306:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   15307:                     $list->{'instcodefilter'}.'" />';
                   15308:                 $instcodetitle = $lt{'ins'};
                   15309:             } else {
                   15310:                 $instcodetitle = $lt{'inc'};
                   15311:             }
                   15312:             if ($fixeddom) {
                   15313:                 $instcodetitle .= '<br />('.$codedom.')';
                   15314:             }
                   15315:         }
                   15316:     }
                   15317:     my $output = qq|
                   15318: <form method="post" name="filterpicker" action="$action">
                   15319: <input type="hidden" name="form" value="$formname" />
                   15320: |;
                   15321:     if ($formname eq 'modifycourse') {
                   15322:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   15323:                    '<input type="hidden" name="prevphase" value="'.
                   15324:                    $prevphase.'" />'."\n";
1.1198    musolffc 15325:     } elsif ($formname eq 'quotacheck') {
                   15326:         $output .= qq|
                   15327: <input type="hidden" name="sortby" value="" />
                   15328: <input type="hidden" name="sortorder" value="" />
                   15329: |;
                   15330:     } else {
1.1181    raeburn  15331:         my $name_input;
                   15332:         if ($cnameelement ne '') {
                   15333:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   15334:                           $cnameelement.'" />';
                   15335:         }
                   15336:         $output .= qq|
1.1182    raeburn  15337: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   15338: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  15339: $name_input
                   15340: $roleelement
                   15341: $multelement
                   15342: $typeelement
                   15343: |;
                   15344:         if ($formname eq 'portform') {
                   15345:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   15346:         }
                   15347:     }
                   15348:     if ($fixeddom) {
                   15349:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   15350:     }
                   15351:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   15352:     if ($sincefilterform) {
                   15353:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   15354:                   .$sincefilterform
                   15355:                   .&Apache::lonhtmlcommon::row_closure();
                   15356:     }
                   15357:     if ($createdfilterform) {
                   15358:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   15359:                   .$createdfilterform
                   15360:                   .&Apache::lonhtmlcommon::row_closure();
                   15361:     }
                   15362:     if ($domainselectform) {
                   15363:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   15364:                   .$domainselectform
                   15365:                   .&Apache::lonhtmlcommon::row_closure();
                   15366:     }
                   15367:     if ($typeselectform) {
                   15368:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15369:             $output .= $typeselectform;
                   15370:         } else {
                   15371:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   15372:                       .$typeselectform
                   15373:                       .&Apache::lonhtmlcommon::row_closure();
                   15374:         }
                   15375:     }
                   15376:     if ($instcodeform) {
                   15377:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   15378:                   .$instcodeform
                   15379:                   .&Apache::lonhtmlcommon::row_closure();
                   15380:     }
                   15381:     if (exists($filter->{'ownerfilter'})) {
                   15382:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   15383:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15384:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   15385:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15386:                    $ownerdomselectform.'</td></tr></table>'.
                   15387:                    &Apache::lonhtmlcommon::row_closure();
                   15388:     }
                   15389:     if (exists($filter->{'personfilter'})) {
                   15390:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   15391:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15392:                    '<input type="text" name="personfilter" size="20" value="'.
                   15393:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15394:                    $persondomselectform.'</td></tr></table>'.
                   15395:                    &Apache::lonhtmlcommon::row_closure();
                   15396:     }
                   15397:     if (exists($filter->{'coursefilter'})) {
                   15398:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   15399:                   .'<input type="text" name="coursefilter" size="25" value="'
                   15400:                   .$list->{'coursefilter'}.'" />'
                   15401:                   .&Apache::lonhtmlcommon::row_closure();
                   15402:     }
                   15403:     if ($cloneableonlyform) {
                   15404:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   15405:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   15406:     }
                   15407:     if (exists($filter->{'descriptfilter'})) {
                   15408:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   15409:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   15410:                   .$list->{'descriptfilter'}.'" />'
                   15411:                   .&Apache::lonhtmlcommon::row_closure(1);
                   15412:     }
                   15413:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   15414:                '<input type="hidden" name="updater" value="" />'."\n".
                   15415:                '<input type="submit" name="gosearch" value="'.
                   15416:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   15417:     return $jscript.$clonewarning.$output;
                   15418: }
                   15419: 
                   15420: =pod 
                   15421: 
                   15422: =item * &timebased_select_form()
                   15423: 
1.1182    raeburn  15424: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  15425: filter e.g., Course Activity, Course Created, when searching for courses
                   15426: or communities
                   15427: 
                   15428: Inputs:
                   15429: 
                   15430: item - name of form element (sincefilter or createdfilter)
                   15431: 
                   15432: filter - anonymous hash of criteria and their values
                   15433: 
                   15434: Returns: HTML for a select box contained a blank, then six time selections,
                   15435:          with value set in incoming form variables currently selected. 
                   15436: 
                   15437: Side Effects: None
                   15438: 
                   15439: =cut
                   15440: 
                   15441: sub timebased_select_form {
                   15442:     my ($item,$filter) = @_;
                   15443:     if (ref($filter) eq 'HASH') {
                   15444:         $filter->{$item} =~ s/[^\d-]//g;
                   15445:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   15446:         return &select_form(
                   15447:                             $filter->{$item},
                   15448:                             $item,
                   15449:                             {      '-1' => '',
                   15450:                                 '86400' => &mt('today'),
                   15451:                                '604800' => &mt('last week'),
                   15452:                               '2592000' => &mt('last month'),
                   15453:                               '7776000' => &mt('last three months'),
                   15454:                              '15552000' => &mt('last six months'),
                   15455:                              '31104000' => &mt('last year'),
                   15456:                     'select_form_order' =>
                   15457:                            ['-1','86400','604800','2592000','7776000',
                   15458:                             '15552000','31104000']});
                   15459:     }
                   15460: }
                   15461: 
                   15462: =pod
                   15463: 
                   15464: =item * &js_changer()
                   15465: 
                   15466: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  15467: when course type or domain is changed, and also to hide 'Searching ...' on
                   15468: page load completion for page showing search result.
1.1181    raeburn  15469: 
                   15470: Inputs: None
                   15471: 
1.1183    raeburn  15472: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  15473: 
                   15474: Side Effects: None
                   15475: 
                   15476: =cut
                   15477: 
                   15478: sub js_changer {
                   15479:     return <<ENDJS;
                   15480: <script type="text/javascript">
                   15481: // <![CDATA[
                   15482: function updateFilters(caller) {
                   15483:     if (typeof(caller) != "undefined") {
                   15484:         document.filterpicker.updater.value = caller.name;
                   15485:     }
                   15486:     document.filterpicker.submit();
                   15487: }
1.1183    raeburn  15488: 
                   15489: function hideSearching() {
                   15490:     if (document.getElementById('searching')) {
                   15491:         document.getElementById('searching').style.display = 'none';
                   15492:     }
                   15493:     return;
                   15494: }
                   15495: 
1.1181    raeburn  15496: // ]]>
                   15497: </script>
                   15498: 
                   15499: ENDJS
                   15500: }
                   15501: 
                   15502: =pod
                   15503: 
1.1182    raeburn  15504: =item * &search_courses()
                   15505: 
                   15506: Process selected filters form course search form and pass to lonnet::courseiddump
                   15507: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   15508: 
                   15509: Inputs:
                   15510: 
                   15511: dom - domain being searched 
                   15512: 
                   15513: type - course type ('Course' or 'Community' or '.' if any).
                   15514: 
                   15515: filter - anonymous hash of criteria and their values
                   15516: 
                   15517: numtitles - for institutional codes - number of categories
                   15518: 
                   15519: cloneruname - optional username of new course owner
                   15520: 
                   15521: clonerudom - optional domain of new course owner
                   15522: 
                   15523: domcloner - Optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
                   15524:             (used when DC is using course creation form)
                   15525: 
                   15526: codetitles - reference to array of titles of components in institutional codes (official courses).
                   15527: 
                   15528: 
                   15529: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   15530: 
                   15531: 
                   15532: Side Effects: None
                   15533: 
                   15534: =cut
                   15535: 
                   15536: 
                   15537: sub search_courses {
                   15538:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles) = @_;
                   15539:     my (%courses,%showcourses,$cloner);
                   15540:     if (($filter->{'ownerfilter'} ne '') ||
                   15541:         ($filter->{'ownerdomfilter'} ne '')) {
                   15542:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   15543:                                        $filter->{'ownerdomfilter'};
                   15544:     }
                   15545:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   15546:         if (!$filter->{$item}) {
                   15547:             $filter->{$item}='.';
                   15548:         }
                   15549:     }
                   15550:     my $now = time;
                   15551:     my $timefilter =
                   15552:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   15553:     my ($createdbefore,$createdafter);
                   15554:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   15555:         $createdbefore = $now;
                   15556:         $createdafter = $now-$filter->{'createdfilter'};
                   15557:     }
                   15558:     my ($instcodefilter,$regexpok);
                   15559:     if ($numtitles) {
                   15560:         if ($env{'form.official'} eq 'on') {
                   15561:             $instcodefilter =
                   15562:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   15563:             $regexpok = 1;
                   15564:         } elsif ($env{'form.official'} eq 'off') {
                   15565:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   15566:             unless ($instcodefilter eq '') {
                   15567:                 $regexpok = -1;
                   15568:             }
                   15569:         }
                   15570:     } else {
                   15571:         $instcodefilter = $filter->{'instcodefilter'};
                   15572:     }
                   15573:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   15574:     if ($type eq '') { $type = '.'; }
                   15575: 
                   15576:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   15577:         $cloner = $cloneruname.':'.$clonerudom;
                   15578:     }
                   15579:     %courses = &Apache::lonnet::courseiddump($dom,
                   15580:                                              $filter->{'descriptfilter'},
                   15581:                                              $timefilter,
                   15582:                                              $instcodefilter,
                   15583:                                              $filter->{'combownerfilter'},
                   15584:                                              $filter->{'coursefilter'},
                   15585:                                              undef,undef,$type,$regexpok,undef,undef,
                   15586:                                              undef,undef,$cloner,$env{'form.cc_clone'},
                   15587:                                              $filter->{'cloneableonly'},
                   15588:                                              $createdbefore,$createdafter,undef,
                   15589:                                              $domcloner);
                   15590:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   15591:         my $ccrole;
                   15592:         if ($type eq 'Community') {
                   15593:             $ccrole = 'co';
                   15594:         } else {
                   15595:             $ccrole = 'cc';
                   15596:         }
                   15597:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   15598:                                                      $filter->{'persondomfilter'},
                   15599:                                                      'userroles',undef,
                   15600:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   15601:                                                      $dom);
                   15602:         foreach my $role (keys(%rolehash)) {
                   15603:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   15604:             my $cid = $cdom.'_'.$cnum;
                   15605:             if (exists($courses{$cid})) {
                   15606:                 if (ref($courses{$cid}) eq 'HASH') {
                   15607:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   15608:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
                   15609:                             push (@{$courses{$cid}{roles}},$courserole);
                   15610:                         }
                   15611:                     } else {
                   15612:                         $courses{$cid}{roles} = [$courserole];
                   15613:                     }
                   15614:                     $showcourses{$cid} = $courses{$cid};
                   15615:                 }
                   15616:             }
                   15617:         }
                   15618:         %courses = %showcourses;
                   15619:     }
                   15620:     return %courses;
                   15621: }
                   15622: 
                   15623: =pod
                   15624: 
1.1181    raeburn  15625: =back
                   15626: 
                   15627: =cut
                   15628: 
                   15629: 
1.1083    raeburn  15630: sub update_content_constraints {
                   15631:     my ($cdom,$cnum,$chome,$cid) = @_;
                   15632:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   15633:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   15634:     my %checkresponsetypes;
                   15635:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   15636:         my ($item,$name,$value) = split(/:/,$key);
                   15637:         if ($item eq 'resourcetag') {
                   15638:             if ($name eq 'responsetype') {
                   15639:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   15640:             }
                   15641:         }
                   15642:     }
                   15643:     my $navmap = Apache::lonnavmaps::navmap->new();
                   15644:     if (defined($navmap)) {
                   15645:         my %allresponses;
                   15646:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   15647:             my %responses = $res->responseTypes();
                   15648:             foreach my $key (keys(%responses)) {
                   15649:                 next unless(exists($checkresponsetypes{$key}));
                   15650:                 $allresponses{$key} += $responses{$key};
                   15651:             }
                   15652:         }
                   15653:         foreach my $key (keys(%allresponses)) {
                   15654:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   15655:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   15656:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   15657:             }
                   15658:         }
                   15659:         undef($navmap);
                   15660:     }
                   15661:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   15662:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   15663:     }
                   15664:     return;
                   15665: }
                   15666: 
1.1110    raeburn  15667: sub allmaps_incourse {
                   15668:     my ($cdom,$cnum,$chome,$cid) = @_;
                   15669:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   15670:         $cid = $env{'request.course.id'};
                   15671:         $cdom = $env{'course.'.$cid.'.domain'};
                   15672:         $cnum = $env{'course.'.$cid.'.num'};
                   15673:         $chome = $env{'course.'.$cid.'.home'};
                   15674:     }
                   15675:     my %allmaps = ();
                   15676:     my $lastchange =
                   15677:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   15678:     if ($lastchange > $env{'request.course.tied'}) {
                   15679:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   15680:         unless ($ferr) {
                   15681:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   15682:         }
                   15683:     }
                   15684:     my $navmap = Apache::lonnavmaps::navmap->new();
                   15685:     if (defined($navmap)) {
                   15686:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   15687:             $allmaps{$res->src()} = 1;
                   15688:         }
                   15689:     }
                   15690:     return \%allmaps;
                   15691: }
                   15692: 
1.1083    raeburn  15693: sub parse_supplemental_title {
                   15694:     my ($title) = @_;
                   15695: 
                   15696:     my ($foldertitle,$renametitle);
                   15697:     if ($title =~ /&amp;&amp;&amp;/) {
                   15698:         $title = &HTML::Entites::decode($title);
                   15699:     }
                   15700:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   15701:         $renametitle=$4;
                   15702:         my ($time,$uname,$udom) = ($1,$2,$3);
                   15703:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   15704:         my $name =  &plainname($uname,$udom);
                   15705:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   15706:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   15707:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   15708:             $name.': <br />'.$foldertitle;
                   15709:     }
                   15710:     if (wantarray) {
                   15711:         return ($title,$foldertitle,$renametitle);
                   15712:     }
                   15713:     return $title;
                   15714: }
                   15715: 
1.1143    raeburn  15716: sub recurse_supplemental {
                   15717:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   15718:     if ($suppmap) {
                   15719:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   15720:         if ($fatal) {
                   15721:             $errors ++;
                   15722:         } else {
                   15723:             if ($#LONCAPA::map::resources > 0) {
                   15724:                 foreach my $res (@LONCAPA::map::resources) {
                   15725:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   15726:                     if (($src ne '') && ($status eq 'res')) {
1.1146    raeburn  15727:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   15728:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1143    raeburn  15729:                         } else {
                   15730:                             $numfiles ++;
                   15731:                         }
                   15732:                     }
                   15733:                 }
                   15734:             }
                   15735:         }
                   15736:     }
                   15737:     return ($numfiles,$errors);
                   15738: }
                   15739: 
1.1101    raeburn  15740: sub symb_to_docspath {
                   15741:     my ($symb) = @_;
                   15742:     return unless ($symb);
                   15743:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   15744:     if ($resurl=~/\.(sequence|page)$/) {
                   15745:         $mapurl=$resurl;
                   15746:     } elsif ($resurl eq 'adm/navmaps') {
                   15747:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   15748:     }
                   15749:     my $mapresobj;
                   15750:     my $navmap = Apache::lonnavmaps::navmap->new();
                   15751:     if (ref($navmap)) {
                   15752:         $mapresobj = $navmap->getResourceByUrl($mapurl);
                   15753:     }
                   15754:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   15755:     my $type=$2;
                   15756:     my $path;
                   15757:     if (ref($mapresobj)) {
                   15758:         my $pcslist = $mapresobj->map_hierarchy();
                   15759:         if ($pcslist ne '') {
                   15760:             foreach my $pc (split(/,/,$pcslist)) {
                   15761:                 next if ($pc <= 1);
                   15762:                 my $res = $navmap->getByMapPc($pc);
                   15763:                 if (ref($res)) {
                   15764:                     my $thisurl = $res->src();
                   15765:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   15766:                     my $thistitle = $res->title();
                   15767:                     $path .= '&'.
                   15768:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  15769:                              &escape($thistitle).
1.1101    raeburn  15770:                              ':'.$res->randompick().
                   15771:                              ':'.$res->randomout().
                   15772:                              ':'.$res->encrypted().
                   15773:                              ':'.$res->randomorder().
                   15774:                              ':'.$res->is_page();
                   15775:                 }
                   15776:             }
                   15777:         }
                   15778:         $path =~ s/^\&//;
                   15779:         my $maptitle = $mapresobj->title();
                   15780:         if ($mapurl eq 'default') {
1.1129    raeburn  15781:             $maptitle = 'Main Content';
1.1101    raeburn  15782:         }
                   15783:         $path .= (($path ne '')? '&' : '').
                   15784:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  15785:                  &escape($maptitle).
1.1101    raeburn  15786:                  ':'.$mapresobj->randompick().
                   15787:                  ':'.$mapresobj->randomout().
                   15788:                  ':'.$mapresobj->encrypted().
                   15789:                  ':'.$mapresobj->randomorder().
                   15790:                  ':'.$mapresobj->is_page();
                   15791:     } else {
                   15792:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   15793:         my $ispage = (($type eq 'page')? 1 : '');
                   15794:         if ($mapurl eq 'default') {
1.1129    raeburn  15795:             $maptitle = 'Main Content';
1.1101    raeburn  15796:         }
                   15797:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  15798:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  15799:     }
                   15800:     unless ($mapurl eq 'default') {
                   15801:         $path = 'default&'.
1.1146    raeburn  15802:                 &escape('Main Content').
1.1101    raeburn  15803:                 ':::::&'.$path;
                   15804:     }
                   15805:     return $path;
                   15806: }
                   15807: 
1.1094    raeburn  15808: sub captcha_display {
                   15809:     my ($context,$lonhost) = @_;
                   15810:     my ($output,$error);
                   15811:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  15812:     if ($captcha eq 'original') {
1.1094    raeburn  15813:         $output = &create_captcha();
                   15814:         unless ($output) {
1.1172    raeburn  15815:             $error = 'captcha';
1.1094    raeburn  15816:         }
                   15817:     } elsif ($captcha eq 'recaptcha') {
                   15818:         $output = &create_recaptcha($pubkey);
                   15819:         unless ($output) {
1.1172    raeburn  15820:             $error = 'recaptcha';
1.1094    raeburn  15821:         }
                   15822:     }
1.1176    raeburn  15823:     return ($output,$error,$captcha);
1.1094    raeburn  15824: }
                   15825: 
                   15826: sub captcha_response {
                   15827:     my ($context,$lonhost) = @_;
                   15828:     my ($captcha_chk,$captcha_error);
                   15829:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  15830:     if ($captcha eq 'original') {
1.1094    raeburn  15831:         ($captcha_chk,$captcha_error) = &check_captcha();
                   15832:     } elsif ($captcha eq 'recaptcha') {
                   15833:         $captcha_chk = &check_recaptcha($privkey);
                   15834:     } else {
                   15835:         $captcha_chk = 1;
                   15836:     }
                   15837:     return ($captcha_chk,$captcha_error);
                   15838: }
                   15839: 
                   15840: sub get_captcha_config {
                   15841:     my ($context,$lonhost) = @_;
1.1095    raeburn  15842:     my ($captcha,$pubkey,$privkey,$hashtocheck);
1.1094    raeburn  15843:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   15844:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   15845:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  15846:     if ($context eq 'usercreation') {
                   15847:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   15848:         if (ref($domconfig{$context}) eq 'HASH') {
                   15849:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   15850:             if (ref($hashtocheck) eq 'HASH') {
                   15851:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   15852:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   15853:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   15854:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   15855:                     }
                   15856:                     if ($privkey && $pubkey) {
                   15857:                         $captcha = 'recaptcha';
                   15858:                     } else {
                   15859:                         $captcha = 'original';
                   15860:                     }
                   15861:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   15862:                     $captcha = 'original';
                   15863:                 }
1.1094    raeburn  15864:             }
1.1095    raeburn  15865:         } else {
                   15866:             $captcha = 'captcha';
                   15867:         }
                   15868:     } elsif ($context eq 'login') {
                   15869:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   15870:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   15871:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   15872:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  15873:             if ($privkey && $pubkey) {
                   15874:                 $captcha = 'recaptcha';
1.1095    raeburn  15875:             } else {
                   15876:                 $captcha = 'original';
1.1094    raeburn  15877:             }
1.1095    raeburn  15878:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   15879:             $captcha = 'original';
1.1094    raeburn  15880:         }
                   15881:     }
                   15882:     return ($captcha,$pubkey,$privkey);
                   15883: }
                   15884: 
                   15885: sub create_captcha {
                   15886:     my %captcha_params = &captcha_settings();
                   15887:     my ($output,$maxtries,$tries) = ('',10,0);
                   15888:     while ($tries < $maxtries) {
                   15889:         $tries ++;
                   15890:         my $captcha = Authen::Captcha->new (
                   15891:                                            output_folder => $captcha_params{'output_dir'},
                   15892:                                            data_folder   => $captcha_params{'db_dir'},
                   15893:                                           );
                   15894:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   15895: 
                   15896:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   15897:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   15898:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1176    raeburn  15899:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   15900:                       '<br />'.
                   15901:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  15902:             last;
                   15903:         }
                   15904:     }
                   15905:     return $output;
                   15906: }
                   15907: 
                   15908: sub captcha_settings {
                   15909:     my %captcha_params = (
                   15910:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   15911:                            www_output_dir => "/captchaspool",
                   15912:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   15913:                            numchars       => '5',
                   15914:                          );
                   15915:     return %captcha_params;
                   15916: }
                   15917: 
                   15918: sub check_captcha {
                   15919:     my ($captcha_chk,$captcha_error);
                   15920:     my $code = $env{'form.code'};
                   15921:     my $md5sum = $env{'form.crypt'};
                   15922:     my %captcha_params = &captcha_settings();
                   15923:     my $captcha = Authen::Captcha->new(
                   15924:                       output_folder => $captcha_params{'output_dir'},
                   15925:                       data_folder   => $captcha_params{'db_dir'},
                   15926:                   );
1.1109    raeburn  15927:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  15928:     my %captcha_hash = (
                   15929:                         0       => 'Code not checked (file error)',
                   15930:                        -1      => 'Failed: code expired',
                   15931:                        -2      => 'Failed: invalid code (not in database)',
                   15932:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   15933:     );
                   15934:     if ($captcha_chk != 1) {
                   15935:         $captcha_error = $captcha_hash{$captcha_chk}
                   15936:     }
                   15937:     return ($captcha_chk,$captcha_error);
                   15938: }
                   15939: 
                   15940: sub create_recaptcha {
                   15941:     my ($pubkey) = @_;
1.1153    raeburn  15942:     my $use_ssl;
                   15943:     if ($ENV{'SERVER_PORT'} == 443) {
                   15944:         $use_ssl = 1;
                   15945:     }
1.1094    raeburn  15946:     my $captcha = Captcha::reCAPTCHA->new;
                   15947:     return $captcha->get_options_setter({theme => 'white'})."\n".
1.1153    raeburn  15948:            $captcha->get_html($pubkey,undef,$use_ssl).
1.1094    raeburn  15949:            &mt('If either word is hard to read, [_1] will replace them.',
1.1133    raeburn  15950:                '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
1.1094    raeburn  15951:            '<br /><br />';
                   15952: }
                   15953: 
                   15954: sub check_recaptcha {
                   15955:     my ($privkey) = @_;
                   15956:     my $captcha_chk;
                   15957:     my $captcha = Captcha::reCAPTCHA->new;
                   15958:     my $captcha_result =
                   15959:         $captcha->check_answer(
                   15960:                                 $privkey,
                   15961:                                 $ENV{'REMOTE_ADDR'},
                   15962:                                 $env{'form.recaptcha_challenge_field'},
                   15963:                                 $env{'form.recaptcha_response_field'},
                   15964:                               );
                   15965:     if ($captcha_result->{is_valid}) {
                   15966:         $captcha_chk = 1;
                   15967:     }
                   15968:     return $captcha_chk;
                   15969: }
                   15970: 
1.1174    raeburn  15971: sub emailusername_info {
1.1177    raeburn  15972:     my @fields = ('firstname','lastname','institution','web','location','officialemail');
1.1174    raeburn  15973:     my %titles = &Apache::lonlocal::texthash (
                   15974:                      lastname      => 'Last Name',
                   15975:                      firstname     => 'First Name',
                   15976:                      institution   => 'School/college/university',
                   15977:                      location      => "School's city, state/province, country",
                   15978:                      web           => "School's web address",
                   15979:                      officialemail => 'E-mail address at institution (if different)',
                   15980:                  );
                   15981:     return (\@fields,\%titles);
                   15982: }
                   15983: 
1.1161    raeburn  15984: sub cleanup_html {
                   15985:     my ($incoming) = @_;
                   15986:     my $outgoing;
                   15987:     if ($incoming ne '') {
                   15988:         $outgoing = $incoming;
                   15989:         $outgoing =~ s/;/&#059;/g;
                   15990:         $outgoing =~ s/\#/&#035;/g;
                   15991:         $outgoing =~ s/\&/&#038;/g;
                   15992:         $outgoing =~ s/</&#060;/g;
                   15993:         $outgoing =~ s/>/&#062;/g;
                   15994:         $outgoing =~ s/\(/&#040/g;
                   15995:         $outgoing =~ s/\)/&#041;/g;
                   15996:         $outgoing =~ s/"/&#034;/g;
                   15997:         $outgoing =~ s/'/&#039;/g;
                   15998:         $outgoing =~ s/\$/&#036;/g;
                   15999:         $outgoing =~ s{/}{&#047;}g;
                   16000:         $outgoing =~ s/=/&#061;/g;
                   16001:         $outgoing =~ s/\\/&#092;/g
                   16002:     }
                   16003:     return $outgoing;
                   16004: }
                   16005: 
1.1190    musolffc 16006: # Checks for critical messages and returns a redirect url if one exists.
                   16007: # $interval indicates how often to check for messages.
                   16008: sub critical_redirect {
                   16009:     my ($interval) = @_;
                   16010:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
                   16011:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   16012:                                         $env{'user.name'});
                   16013:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  16014:         my $redirecturl;
1.1190    musolffc 16015:         if ($what[0]) {
                   16016: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   16017: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  16018: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   16019:                 return (1, $url);
1.1190    musolffc 16020:             }
1.1191    raeburn  16021:         }
                   16022:     } 
                   16023:     return ();
1.1190    musolffc 16024: }
                   16025: 
1.1174    raeburn  16026: # Use:
                   16027: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   16028: #
                   16029: ##################################################
                   16030: #          password associated functions         #
                   16031: ##################################################
                   16032: sub des_keys {
                   16033:     # Make a new key for DES encryption.
                   16034:     # Each key has two parts which are returned separately.
                   16035:     # Please note:  Each key must be passed through the &hex function
                   16036:     # before it is output to the web browser.  The hex versions cannot
                   16037:     # be used to decrypt.
                   16038:     my @hexstr=('0','1','2','3','4','5','6','7',
                   16039:                 '8','9','a','b','c','d','e','f');
                   16040:     my $lkey='';
                   16041:     for (0..7) {
                   16042:         $lkey.=$hexstr[rand(15)];
                   16043:     }
                   16044:     my $ukey='';
                   16045:     for (0..7) {
                   16046:         $ukey.=$hexstr[rand(15)];
                   16047:     }
                   16048:     return ($lkey,$ukey);
                   16049: }
                   16050: 
                   16051: sub des_decrypt {
                   16052:     my ($key,$cyphertext) = @_;
                   16053:     my $keybin=pack("H16",$key);
                   16054:     my $cypher;
                   16055:     if ($Crypt::DES::VERSION>=2.03) {
                   16056:         $cypher=new Crypt::DES $keybin;
                   16057:     } else {
                   16058:         $cypher=new DES $keybin;
                   16059:     }
                   16060:     my $plaintext=
                   16061:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,0,16))));
                   16062:     $plaintext.=
                   16063:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,16,16))));
                   16064:     $plaintext=substr($plaintext,1,ord(substr($plaintext,0,1)) );
                   16065:     return $plaintext;
                   16066: }
                   16067: 
1.112     bowersj2 16068: 1;
                   16069: __END__;
1.41      ng       16070: 

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