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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1372  ! raeburn     4: # $Id: loncommon.pm,v 1.1371 2021/11/24 04:25:01 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.1280    raeburn    74: use LONCAPA::LWPReq;
1.1328    raeburn    75: use HTTP::Request;
1.657     raeburn    76: use DateTime::TimeZone;
1.1241    raeburn    77: use DateTime::Locale;
1.1220    raeburn    78: use Encode();
1.1091    foxr       79: use Text::Aspell;
1.1094    raeburn    80: use Authen::Captcha;
                     81: use Captcha::reCAPTCHA;
1.1234    raeburn    82: use JSON::DWIW;
1.1174    raeburn    83: use Crypt::DES;
                     84: use DynaLoader; # for Crypt::DES version
1.1223    musolffc   85: use MIME::Lite;
                     86: use MIME::Types;
1.1292    raeburn    87: use File::Copy();
1.1300    raeburn    88: use File::Path();
1.1309    raeburn    89: use String::CRC32();
                     90: use Short::URL();
1.117     www        91: 
1.517     raeburn    92: # ---------------------------------------------- Designs
                     93: use vars qw(%defaultdesign);
                     94: 
1.22      www        95: my $readit;
                     96: 
1.517     raeburn    97: 
1.157     matthew    98: ##
                     99: ## Global Variables
                    100: ##
1.46      matthew   101: 
1.643     foxr      102: 
                    103: # ----------------------------------------------- SSI with retries:
                    104: #
                    105: 
                    106: =pod
                    107: 
1.648     raeburn   108: =head1 Server Side include with retries:
1.643     foxr      109: 
                    110: =over 4
                    111: 
1.648     raeburn   112: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      113: 
                    114: Performs an ssi with some number of retries.  Retries continue either
                    115: until the result is ok or until the retry count supplied by the
                    116: caller is exhausted.  
                    117: 
                    118: Inputs:
1.648     raeburn   119: 
                    120: =over 4
                    121: 
1.643     foxr      122: resource   - Identifies the resource to insert.
1.648     raeburn   123: 
1.643     foxr      124: retries    - Count of the number of retries allowed.
1.648     raeburn   125: 
1.643     foxr      126: form       - Hash that identifies the rendering options.
                    127: 
1.648     raeburn   128: =back
                    129: 
                    130: Returns:
                    131: 
                    132: =over 4
                    133: 
1.643     foxr      134: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   135: 
1.643     foxr      136: response   - The response from the last attempt (which may or may not have been successful.
                    137: 
1.648     raeburn   138: =back
                    139: 
                    140: =back
                    141: 
1.643     foxr      142: =cut
                    143: 
                    144: sub ssi_with_retries {
                    145:     my ($resource, $retries, %form) = @_;
                    146: 
                    147: 
                    148:     my $ok = 0;			# True if we got a good response.
                    149:     my $content;
                    150:     my $response;
                    151: 
                    152:     # Try to get the ssi done. within the retries count:
                    153: 
                    154:     do {
                    155: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    156: 	$ok      = $response->is_success;
1.650     www       157:         if (!$ok) {
                    158:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    159:         }
1.643     foxr      160: 	$retries--;
                    161:     } while (!$ok && ($retries > 0));
                    162: 
                    163:     if (!$ok) {
                    164: 	$content = '';		# On error return an empty content.
                    165:     }
                    166:     return ($content, $response);
                    167: 
                    168: }
                    169: 
                    170: 
                    171: 
1.20      www       172: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  173: my %language;
1.124     www       174: my %supported_language;
1.1088    foxr      175: my %supported_codes;
1.1048    foxr      176: my %latex_language;		# For choosing hyphenation in <transl..>
                    177: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  178: my %cprtag;
1.192     taceyjo1  179: my %scprtag;
1.351     www       180: my %fe; my %fd; my %fm;
1.41      ng        181: my %category_extensions;
1.12      harris41  182: 
1.46      matthew   183: # ---------------------------------------------- Thesaurus variables
1.144     matthew   184: #
                    185: # %Keywords:
                    186: #      A hash used by &keyword to determine if a word is considered a keyword.
                    187: # $thesaurus_db_file 
                    188: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   189: 
                    190: my %Keywords;
                    191: my $thesaurus_db_file;
                    192: 
1.144     matthew   193: #
                    194: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    195: # thesaurus.tab, and filecategories.tab.
                    196: #
1.18      www       197: BEGIN {
1.46      matthew   198:     # Variable initialization
                    199:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    200:     #
1.22      www       201:     unless ($readit) {
1.12      harris41  202: # ------------------------------------------------------------------- languages
                    203:     {
1.158     raeburn   204:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    205:                                    '/language.tab';
1.1317    raeburn   206:         if ( open(my $fh,'<',$langtabfile) ) {
1.356     albertel  207:             while (my $line = <$fh>) {
                    208:                 next if ($line=~/^\#/);
                    209:                 chomp($line);
1.1088    foxr      210:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   211:                 $language{$key}=$val.' - '.$enc;
                    212:                 if ($sup) {
                    213:                     $supported_language{$key}=$sup;
1.1088    foxr      214: 		    $supported_codes{$key}   = $code;
1.158     raeburn   215:                 }
1.1048    foxr      216: 		if ($latex) {
                    217: 		    $latex_language_bykey{$key} = $latex;
1.1088    foxr      218: 		    $latex_language{$code} = $latex;
1.1048    foxr      219: 		}
1.158     raeburn   220:             }
                    221:             close($fh);
                    222:         }
1.12      harris41  223:     }
                    224: # ------------------------------------------------------------------ copyrights
                    225:     {
1.158     raeburn   226:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    227:                                   '/copyright.tab';
1.1317    raeburn   228:         if ( open (my $fh,'<',$copyrightfile) ) {
1.356     albertel  229:             while (my $line = <$fh>) {
                    230:                 next if ($line=~/^\#/);
                    231:                 chomp($line);
                    232:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   233:                 $cprtag{$key}=$val;
                    234:             }
                    235:             close($fh);
                    236:         }
1.12      harris41  237:     }
1.351     www       238: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  239:     {
                    240:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    241:                                   '/source_copyright.tab';
1.1317    raeburn   242:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
1.356     albertel  243:             while (my $line = <$fh>) {
                    244:                 next if ($line =~ /^\#/);
                    245:                 chomp($line);
                    246:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  247:                 $scprtag{$key}=$val;
                    248:             }
                    249:             close($fh);
                    250:         }
                    251:     }
1.63      www       252: 
1.517     raeburn   253: # -------------------------------------------------------------- default domain designs
1.63      www       254:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   255:     my $designfile = $designdir.'/default.tab';
1.1317    raeburn   256:     if ( open (my $fh,'<',$designfile) ) {
1.517     raeburn   257:         while (my $line = <$fh>) {
                    258:             next if ($line =~ /^\#/);
                    259:             chomp($line);
                    260:             my ($key,$val)=(split(/\=/,$line));
                    261:             if ($val) { $defaultdesign{$key}=$val; }
                    262:         }
                    263:         close($fh);
1.63      www       264:     }
                    265: 
1.15      harris41  266: # ------------------------------------------------------------- file categories
                    267:     {
1.158     raeburn   268:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    269:                                   '/filecategories.tab';
1.1317    raeburn   270:         if ( open (my $fh,'<',$categoryfile) ) {
1.356     albertel  271: 	    while (my $line = <$fh>) {
                    272: 		next if ($line =~ /^\#/);
                    273: 		chomp($line);
                    274:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1263    raeburn   275:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   276:             }
                    277:             close($fh);
                    278:         }
                    279: 
1.15      harris41  280:     }
1.12      harris41  281: # ------------------------------------------------------------------ file types
                    282:     {
1.158     raeburn   283:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    284:                '/filetypes.tab';
1.1317    raeburn   285:         if ( open (my $fh,'<',$typesfile) ) {
1.356     albertel  286:             while (my $line = <$fh>) {
                    287: 		next if ($line =~ /^\#/);
                    288: 		chomp($line);
                    289:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   290:                 if ($descr ne '') {
                    291:                     $fe{$ending}=lc($emb);
                    292:                     $fd{$ending}=$descr;
1.351     www       293:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   294:                 }
                    295:             }
                    296:             close($fh);
                    297:         }
1.12      harris41  298:     }
1.22      www       299:     &Apache::lonnet::logthis(
1.705     tempelho  300:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       301:     $readit=1;
1.46      matthew   302:     }  # end of unless($readit) 
1.32      matthew   303:     
                    304: }
1.112     bowersj2  305: 
1.42      matthew   306: ###############################################################
                    307: ##           HTML and Javascript Helper Functions            ##
                    308: ###############################################################
                    309: 
                    310: =pod 
                    311: 
1.112     bowersj2  312: =head1 HTML and Javascript Functions
1.42      matthew   313: 
1.112     bowersj2  314: =over 4
                    315: 
1.648     raeburn   316: =item * &browser_and_searcher_javascript()
1.112     bowersj2  317: 
                    318: X<browsing, javascript>X<searching, javascript>Returns a string
                    319: containing javascript with two functions, C<openbrowser> and
                    320: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    321: tags.
1.42      matthew   322: 
1.648     raeburn   323: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   324: 
                    325: inputs: formname, elementname, only, omit
                    326: 
                    327: formname and elementname indicate the name of the html form and name of
                    328: the element that the results of the browsing selection are to be placed in. 
                    329: 
                    330: Specifying 'only' will restrict the browser to displaying only files
1.185     www       331: with the given extension.  Can be a comma separated list.
1.42      matthew   332: 
                    333: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       334: with the given extension.  Can be a comma separated list.
1.42      matthew   335: 
1.648     raeburn   336: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   337: 
                    338: Inputs: formname, elementname
                    339: 
                    340: formname and elementname specify the name of the html form and the name
                    341: of the element the selection from the search results will be placed in.
1.542     raeburn   342: 
1.42      matthew   343: =cut
                    344: 
                    345: sub browser_and_searcher_javascript {
1.199     albertel  346:     my ($mode)=@_;
                    347:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  348:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   349:     return <<END;
1.219     albertel  350: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   351:     var editbrowser = null;
1.135     albertel  352:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       353:         var url = '$resurl/?';
1.42      matthew   354:         if (editbrowser == null) {
                    355:             url += 'launch=1&';
                    356:         }
                    357:         url += 'catalogmode=interactive&';
1.199     albertel  358:         url += 'mode=$mode&';
1.611     albertel  359:         url += 'inhibitmenu=yes&';
1.42      matthew   360:         url += 'form=' + formname + '&';
                    361:         if (only != null) {
                    362:             url += 'only=' + only + '&';
1.217     albertel  363:         } else {
                    364:             url += 'only=&';
                    365: 	}
1.42      matthew   366:         if (omit != null) {
                    367:             url += 'omit=' + omit + '&';
1.217     albertel  368:         } else {
                    369:             url += 'omit=&';
                    370: 	}
1.135     albertel  371:         if (titleelement != null) {
                    372:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  373:         } else {
                    374: 	    url += 'titleelement=&';
                    375: 	}
1.42      matthew   376:         url += 'element=' + elementname + '';
                    377:         var title = 'Browser';
1.435     albertel  378:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   379:         options += ',width=700,height=600';
                    380:         editbrowser = open(url,title,options,'1');
                    381:         editbrowser.focus();
                    382:     }
                    383:     var editsearcher;
1.135     albertel  384:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   385:         var url = '/adm/searchcat?';
                    386:         if (editsearcher == null) {
                    387:             url += 'launch=1&';
                    388:         }
                    389:         url += 'catalogmode=interactive&';
1.199     albertel  390:         url += 'mode=$mode&';
1.42      matthew   391:         url += 'form=' + formname + '&';
1.135     albertel  392:         if (titleelement != null) {
                    393:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  394:         } else {
                    395: 	    url += 'titleelement=&';
                    396: 	}
1.42      matthew   397:         url += 'element=' + elementname + '';
                    398:         var title = 'Search';
1.435     albertel  399:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   400:         options += ',width=700,height=600';
                    401:         editsearcher = open(url,title,options,'1');
                    402:         editsearcher.focus();
                    403:     }
1.219     albertel  404: // END LON-CAPA Internal -->
1.42      matthew   405: END
1.170     www       406: }
                    407: 
                    408: sub lastresurl {
1.258     albertel  409:     if ($env{'environment.lastresurl'}) {
                    410: 	return $env{'environment.lastresurl'}
1.170     www       411:     } else {
                    412: 	return '/res';
                    413:     }
                    414: }
                    415: 
                    416: sub storeresurl {
                    417:     my $resurl=&Apache::lonnet::clutter(shift);
                    418:     unless ($resurl=~/^\/res/) { return 0; }
                    419:     $resurl=~s/\/$//;
                    420:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   421:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       422:     return 1;
1.42      matthew   423: }
                    424: 
1.74      www       425: sub studentbrowser_javascript {
1.111     www       426:    unless (
1.258     albertel  427:             (($env{'request.course.id'}) && 
1.302     albertel  428:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    429: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    430: 					  '/'.$env{'request.course.sec'})
                    431: 	      ))
1.258     albertel  432:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       433:           ) { return ''; }  
1.74      www       434:    return (<<'ENDSTDBRW');
1.776     bisitz    435: <script type="text/javascript" language="Javascript">
1.824     bisitz    436: // <![CDATA[
1.74      www       437:     var stdeditbrowser;
1.1337    raeburn   438:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
1.74      www       439:         var url = '/adm/pickstudent?';
                    440:         var filter;
1.558     albertel  441: 	if (!ignorefilter) {
                    442: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    443: 	}
1.74      www       444:         if (filter != null) {
                    445:            if (filter != '') {
                    446:                url += 'filter='+filter+'&';
                    447: 	   }
                    448:         }
                    449:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       450:                                     '&udomelement='+udom+
                    451:                                     '&clicker='+clicker;
1.111     www       452: 	if (roleflag) { url+="&roles=1"; }
1.1337    raeburn   453:         if (courseadv == 'condition') {
                    454:             if (document.getElementById('courseadv')) {
                    455:                 courseadv = document.getElementById('courseadv').value;
                    456:             }
                    457:         }
                    458:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
1.102     www       459:         var title = 'Student_Browser';
1.74      www       460:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    461:         options += ',width=700,height=600';
                    462:         stdeditbrowser = open(url,title,options,'1');
                    463:         stdeditbrowser.focus();
                    464:     }
1.824     bisitz    465: // ]]>
1.74      www       466: </script>
                    467: ENDSTDBRW
                    468: }
1.42      matthew   469: 
1.1003    www       470: sub resourcebrowser_javascript {
                    471:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       472:    return (<<'ENDRESBRW');
1.1003    www       473: <script type="text/javascript" language="Javascript">
                    474: // <![CDATA[
                    475:     var reseditbrowser;
1.1004    www       476:     function openresbrowser(formname,reslink) {
1.1005    www       477:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       478:         var title = 'Resource_Browser';
                    479:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       480:         options += ',width=700,height=500';
1.1004    www       481:         reseditbrowser = open(url,title,options,'1');
                    482:         reseditbrowser.focus();
1.1003    www       483:     }
                    484: // ]]>
                    485: </script>
1.1004    www       486: ENDRESBRW
1.1003    www       487: }
                    488: 
1.74      www       489: sub selectstudent_link {
1.1337    raeburn   490:    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
1.999     www       491:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    492:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    493:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  494:    if ($env{'request.course.id'}) {  
1.302     albertel  495:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    496: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    497: 					'/'.$env{'request.course.sec'})) {
1.111     www       498: 	   return '';
                    499:        }
1.999     www       500:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.1337    raeburn   501:        if ($courseadv eq 'only') {
                    502:            $callargs .= ",'',1,'$courseadv'";
                    503:        } elsif ($courseadv eq 'none') {
                    504:            $callargs .= ",'','','$courseadv'";
                    505:        } elsif ($courseadv eq 'condition') {
                    506:            $callargs .= ",'','','$courseadv'";
1.793     raeburn   507:        }
                    508:        return '<span class="LC_nobreak">'.
                    509:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    510:               &mt('Select User').'</a></span>';
1.74      www       511:    }
1.258     albertel  512:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       513:        $callargs .= ",'',1"; 
1.793     raeburn   514:        return '<span class="LC_nobreak">'.
                    515:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    516:               &mt('Select User').'</a></span>';
1.111     www       517:    }
                    518:    return '';
1.91      www       519: }
                    520: 
1.1004    www       521: sub selectresource_link {
                    522:    my ($form,$reslink,$arg)=@_;
                    523:    
                    524:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    525:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    526:    unless ($env{'request.course.id'}) { return $arg; }
                    527:    return '<span class="LC_nobreak">'.
                    528:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    529:               $arg.'</a></span>';
                    530: }
                    531: 
                    532: 
                    533: 
1.653     raeburn   534: sub authorbrowser_javascript {
                    535:     return <<"ENDAUTHORBRW";
1.776     bisitz    536: <script type="text/javascript" language="JavaScript">
1.824     bisitz    537: // <![CDATA[
1.653     raeburn   538: var stdeditbrowser;
                    539: 
                    540: function openauthorbrowser(formname,udom) {
                    541:     var url = '/adm/pickauthor?';
                    542:     url += 'form='+formname+'&roledom='+udom;
                    543:     var title = 'Author_Browser';
                    544:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    545:     options += ',width=700,height=600';
                    546:     stdeditbrowser = open(url,title,options,'1');
                    547:     stdeditbrowser.focus();
                    548: }
                    549: 
1.824     bisitz    550: // ]]>
1.653     raeburn   551: </script>
                    552: ENDAUTHORBRW
                    553: }
                    554: 
1.91      www       555: sub coursebrowser_javascript {
1.1116    raeburn   556:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1221    raeburn   557:         $credits_element,$instcode) = @_;
1.932     raeburn   558:     my $wintitle = 'Course_Browser';
1.931     raeburn   559:     if ($crstype eq 'Community') {
1.932     raeburn   560:         $wintitle = 'Community_Browser';
1.909     raeburn   561:     }
1.876     raeburn   562:     my $id_functions = &javascript_index_functions();
                    563:     my $output = '
1.776     bisitz    564: <script type="text/javascript" language="JavaScript">
1.824     bisitz    565: // <![CDATA[
1.468     raeburn   566:     var stdeditbrowser;'."\n";
1.876     raeburn   567: 
                    568:     $output .= <<"ENDSTDBRW";
1.909     raeburn   569:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       570:         var url = '/adm/pickcourse?';
1.895     raeburn   571:         var formid = getFormIdByName(formname);
1.876     raeburn   572:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  573:         if (domainfilter != null) {
                    574:            if (domainfilter != '') {
                    575:                url += 'domainfilter='+domainfilter+'&';
                    576: 	   }
                    577:         }
1.91      www       578:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  579: 	                            '&cdomelement='+udom+
                    580:                                     '&cnameelement='+desc;
1.468     raeburn   581:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   582:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   583:                 url += '&roleelement='+extra_element;
                    584:                 if (domainfilter == null || domainfilter == '') {
                    585:                     url += '&domainfilter='+extra_element;
                    586:                 }
1.234     raeburn   587:             }
1.468     raeburn   588:             else {
                    589:                 if (formname == 'portform') {
                    590:                     url += '&setroles='+extra_element;
1.800     raeburn   591:                 } else {
                    592:                     if (formname == 'rules') {
                    593:                         url += '&fixeddom='+extra_element; 
                    594:                     }
1.468     raeburn   595:                 }
                    596:             }     
1.230     raeburn   597:         }
1.909     raeburn   598:         if (type != null && type != '') {
                    599:             url += '&type='+type;
                    600:         }
                    601:         if (type_elem != null && type_elem != '') {
                    602:             url += '&typeelement='+type_elem;
                    603:         }
1.872     raeburn   604:         if (formname == 'ccrs') {
                    605:             var ownername = document.forms[formid].ccuname.value;
                    606:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1238    raeburn   607:             url += '&cloner='+ownername+':'+ownerdom;
                    608:             if (type == 'Course') {
                    609:                 url += '&crscode='+document.forms[formid].crscode.value;
                    610:             }
1.1221    raeburn   611:         }
                    612:         if (formname == 'requestcrs') {
                    613:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   614:         }
1.293     raeburn   615:         if (multflag !=null && multflag != '') {
                    616:             url += '&multiple='+multflag;
                    617:         }
1.909     raeburn   618:         var title = '$wintitle';
1.91      www       619:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    620:         options += ',width=700,height=600';
                    621:         stdeditbrowser = open(url,title,options,'1');
                    622:         stdeditbrowser.focus();
                    623:     }
1.876     raeburn   624: $id_functions
                    625: ENDSTDBRW
1.1116    raeburn   626:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    627:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    628:                                       $credits_element);
1.876     raeburn   629:     }
                    630:     $output .= '
                    631: // ]]>
                    632: </script>';
                    633:     return $output;
                    634: }
                    635: 
                    636: sub javascript_index_functions {
                    637:     return <<"ENDJS";
                    638: 
                    639: function getFormIdByName(formname) {
                    640:     for (var i=0;i<document.forms.length;i++) {
                    641:         if (document.forms[i].name == formname) {
                    642:             return i;
                    643:         }
                    644:     }
                    645:     return -1;
                    646: }
                    647: 
                    648: function getIndexByName(formid,item) {
                    649:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    650:         if (document.forms[formid].elements[i].name == item) {
                    651:             return i;
                    652:         }
                    653:     }
                    654:     return -1;
                    655: }
1.468     raeburn   656: 
1.876     raeburn   657: function getDomainFromSelectbox(formname,udom) {
                    658:     var userdom;
                    659:     var formid = getFormIdByName(formname);
                    660:     if (formid > -1) {
                    661:         var domid = getIndexByName(formid,udom);
                    662:         if (domid > -1) {
                    663:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    664:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    665:             }
                    666:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    667:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   668:             }
                    669:         }
                    670:     }
1.876     raeburn   671:     return userdom;
                    672: }
                    673: 
                    674: ENDJS
1.468     raeburn   675: 
1.876     raeburn   676: }
                    677: 
1.1017    raeburn   678: sub javascript_array_indexof {
1.1018    raeburn   679:     return <<ENDJS;
1.1017    raeburn   680: <script type="text/javascript" language="JavaScript">
                    681: // <![CDATA[
                    682: 
                    683: if (!Array.prototype.indexOf) {
                    684:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    685:         "use strict";
                    686:         if (this === void 0 || this === null) {
                    687:             throw new TypeError();
                    688:         }
                    689:         var t = Object(this);
                    690:         var len = t.length >>> 0;
                    691:         if (len === 0) {
                    692:             return -1;
                    693:         }
                    694:         var n = 0;
                    695:         if (arguments.length > 0) {
                    696:             n = Number(arguments[1]);
1.1088    foxr      697:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   698:                 n = 0;
                    699:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    700:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    701:             }
                    702:         }
                    703:         if (n >= len) {
                    704:             return -1;
                    705:         }
                    706:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    707:         for (; k < len; k++) {
                    708:             if (k in t && t[k] === searchElement) {
                    709:                 return k;
                    710:             }
                    711:         }
                    712:         return -1;
                    713:     }
                    714: }
                    715: 
                    716: // ]]>
                    717: </script>
                    718: 
                    719: ENDJS
                    720: 
                    721: }
                    722: 
1.876     raeburn   723: sub userbrowser_javascript {
                    724:     my $id_functions = &javascript_index_functions();
                    725:     return <<"ENDUSERBRW";
                    726: 
1.888     raeburn   727: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   728:     var url = '/adm/pickuser?';
                    729:     var userdom = getDomainFromSelectbox(formname,udom);
                    730:     if (userdom != null) {
                    731:        if (userdom != '') {
                    732:            url += 'srchdom='+userdom+'&';
                    733:        }
                    734:     }
                    735:     url += 'form=' + formname + '&unameelement='+uname+
                    736:                                 '&udomelement='+udom+
                    737:                                 '&ulastelement='+ulast+
                    738:                                 '&ufirstelement='+ufirst+
                    739:                                 '&uemailelement='+uemail+
1.881     raeburn   740:                                 '&hideudomelement='+hideudom+
                    741:                                 '&coursedom='+crsdom;
1.888     raeburn   742:     if ((caller != null) && (caller != undefined)) {
                    743:         url += '&caller='+caller;
                    744:     }
1.876     raeburn   745:     var title = 'User_Browser';
                    746:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    747:     options += ',width=700,height=600';
                    748:     var stdeditbrowser = open(url,title,options,'1');
                    749:     stdeditbrowser.focus();
                    750: }
                    751: 
1.888     raeburn   752: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   753:     var formid = getFormIdByName(formname);
                    754:     if (formid > -1) {
1.888     raeburn   755:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   756:         var domid = getIndexByName(formid,udom);
                    757:         var hidedomid = getIndexByName(formid,origdom);
                    758:         if (hidedomid > -1) {
                    759:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   760:             var unameval = document.forms[formid].elements[unameid].value;
                    761:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    762:                 if (domid > -1) {
                    763:                     var slct = document.forms[formid].elements[domid];
                    764:                     if (slct.type == 'select-one') {
                    765:                         var i;
                    766:                         for (i=0;i<slct.length;i++) {
                    767:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    768:                         }
                    769:                     }
                    770:                     if (slct.type == 'hidden') {
                    771:                         slct.value = fixeddom;
1.876     raeburn   772:                     }
                    773:                 }
1.468     raeburn   774:             }
                    775:         }
                    776:     }
1.876     raeburn   777:     return;
                    778: }
                    779: 
                    780: $id_functions
                    781: ENDUSERBRW
1.468     raeburn   782: }
                    783: 
                    784: sub setsec_javascript {
1.1116    raeburn   785:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   786:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    787:         $communityrolestr);
                    788:     if ($role_element ne '') {
                    789:         my @allroles = ('st','ta','ep','in','ad');
                    790:         foreach my $crstype ('Course','Community') {
                    791:             if ($crstype eq 'Community') {
                    792:                 foreach my $role (@allroles) {
                    793:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    794:                 }
                    795:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    796:             } else {
                    797:                 foreach my $role (@allroles) {
                    798:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    799:                 }
                    800:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    801:             }
                    802:         }
                    803:         $rolestr = '"'.join('","',@allroles).'"';
                    804:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    805:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    806:     }
1.468     raeburn   807:     my $setsections = qq|
                    808: function setSect(sectionlist) {
1.629     raeburn   809:     var sectionsArray = new Array();
                    810:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    811:         sectionsArray = sectionlist.split(",");
                    812:     }
1.468     raeburn   813:     var numSections = sectionsArray.length;
                    814:     document.$formname.$sec_element.length = 0;
                    815:     if (numSections == 0) {
                    816:         document.$formname.$sec_element.multiple=false;
                    817:         document.$formname.$sec_element.size=1;
                    818:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    819:     } else {
                    820:         if (numSections == 1) {
                    821:             document.$formname.$sec_element.multiple=false;
                    822:             document.$formname.$sec_element.size=1;
                    823:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    824:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    825:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    826:         } else {
                    827:             for (var i=0; i<numSections; i++) {
                    828:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    829:             }
                    830:             document.$formname.$sec_element.multiple=true
                    831:             if (numSections < 3) {
                    832:                 document.$formname.$sec_element.size=numSections;
                    833:             } else {
                    834:                 document.$formname.$sec_element.size=3;
                    835:             }
                    836:             document.$formname.$sec_element.options[0].selected = false
                    837:         }
                    838:     }
1.91      www       839: }
1.905     raeburn   840: 
                    841: function setRole(crstype) {
1.468     raeburn   842: |;
1.905     raeburn   843:     if ($role_element eq '') {
                    844:         $setsections .= '    return;
                    845: }
                    846: ';
                    847:     } else {
                    848:         $setsections .= qq|
                    849:     var elementLength = document.$formname.$role_element.length;
                    850:     var allroles = Array($rolestr);
                    851:     var courserolenames = Array($courserolestr);
                    852:     var communityrolenames = Array($communityrolestr);
                    853:     if (elementLength != undefined) {
                    854:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    855:             if (crstype == 'Course') {
                    856:                 return;
                    857:             } else {
                    858:                 allroles[5] = 'co';
                    859:                 for (var i=0; i<6; i++) {
                    860:                     document.$formname.$role_element.options[i].value = allroles[i];
                    861:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    862:                 }
                    863:             }
                    864:         } else {
                    865:             if (crstype == 'Community') {
                    866:                 return;
                    867:             } else {
                    868:                 allroles[5] = 'cc';
                    869:                 for (var i=0; i<6; i++) {
                    870:                     document.$formname.$role_element.options[i].value = allroles[i];
                    871:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    872:                 }
                    873:             }
                    874:         }
                    875:     }
                    876:     return;
                    877: }
                    878: |;
                    879:     }
1.1116    raeburn   880:     if ($credits_element) {
                    881:         $setsections .= qq|
                    882: function setCredits(defaultcredits) {
                    883:     document.$formname.$credits_element.value = defaultcredits;
                    884:     return;
                    885: }
                    886: |;
                    887:     }
1.468     raeburn   888:     return $setsections;
                    889: }
                    890: 
1.91      www       891: sub selectcourse_link {
1.909     raeburn   892:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    893:        $typeelement) = @_;
                    894:    my $type = $selecttype;
1.871     raeburn   895:    my $linktext = &mt('Select Course');
                    896:    if ($selecttype eq 'Community') {
1.909     raeburn   897:        $linktext = &mt('Select Community');
1.1239    raeburn   898:    } elsif ($selecttype eq 'Placement') {
                    899:        $linktext = &mt('Select Placement Test'); 
1.906     raeburn   900:    } elsif ($selecttype eq 'Course/Community') {
                    901:        $linktext = &mt('Select Course/Community');
1.909     raeburn   902:        $type = '';
1.1019    raeburn   903:    } elsif ($selecttype eq 'Select') {
                    904:        $linktext = &mt('Select');
                    905:        $type = '';
1.871     raeburn   906:    }
1.787     bisitz    907:    return '<span class="LC_nobreak">'
                    908:          ."<a href='"
                    909:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    910:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   911:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   912:          ."'>".$linktext.'</a>'
1.787     bisitz    913:          .'</span>';
1.74      www       914: }
1.42      matthew   915: 
1.653     raeburn   916: sub selectauthor_link {
                    917:    my ($form,$udom)=@_;
                    918:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    919:           &mt('Select Author').'</a>';
                    920: }
                    921: 
1.876     raeburn   922: sub selectuser_link {
1.881     raeburn   923:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   924:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   925:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   926:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   927:            ');">'.$linktext.'</a>';
1.876     raeburn   928: }
                    929: 
1.273     raeburn   930: sub check_uncheck_jscript {
                    931:     my $jscript = <<"ENDSCRT";
                    932: function checkAll(field) {
                    933:     if (field.length > 0) {
                    934:         for (i = 0; i < field.length; i++) {
1.1093    raeburn   935:             if (!field[i].disabled) { 
                    936:                 field[i].checked = true;
                    937:             }
1.273     raeburn   938:         }
                    939:     } else {
1.1093    raeburn   940:         if (!field.disabled) { 
                    941:             field.checked = true;
                    942:         }
1.273     raeburn   943:     }
                    944: }
                    945:  
                    946: function uncheckAll(field) {
                    947:     if (field.length > 0) {
                    948:         for (i = 0; i < field.length; i++) {
                    949:             field[i].checked = false ;
1.543     albertel  950:         }
                    951:     } else {
1.273     raeburn   952:         field.checked = false ;
                    953:     }
                    954: }
                    955: ENDSCRT
                    956:     return $jscript;
                    957: }
                    958: 
1.656     www       959: sub select_timezone {
1.1256    raeburn   960:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    961:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.659     raeburn   962:    if ($includeempty) {
                    963:        $output .= '<option value=""';
                    964:        if (($selected eq '') || ($selected eq 'local')) {
                    965:            $output .= ' selected="selected" ';
                    966:        }
                    967:        $output .= '> </option>';
                    968:    }
1.657     raeburn   969:    my @timezones = DateTime::TimeZone->all_names;
                    970:    foreach my $tzone (@timezones) {
                    971:        $output.= '<option value="'.$tzone.'"';
                    972:        if ($tzone eq $selected) {
                    973:            $output.=' selected="selected"';
                    974:        }
                    975:        $output.=">$tzone</option>\n";
1.656     www       976:    }
                    977:    $output.="</select>";
                    978:    return $output;
                    979: }
1.273     raeburn   980: 
1.687     raeburn   981: sub select_datelocale {
1.1256    raeburn   982:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    983:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   984:     if ($includeempty) {
                    985:         $output .= '<option value=""';
                    986:         if ($selected eq '') {
                    987:             $output .= ' selected="selected" ';
                    988:         }
                    989:         $output .= '> </option>';
                    990:     }
1.1241    raeburn   991:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   992:     my (@possibles,%locale_names);
1.1241    raeburn   993:     my @locales = DateTime::Locale->ids();
                    994:     foreach my $id (@locales) {
                    995:         if ($id ne '') {
                    996:             my ($en_terr,$native_terr);
                    997:             my $loc = DateTime::Locale->load($id);
                    998:             if (ref($loc)) {
                    999:                 $en_terr = $loc->name();
                   1000:                 $native_terr = $loc->native_name();
1.687     raeburn  1001:                 if (grep(/^en$/,@languages) || !@languages) {
                   1002:                     if ($en_terr ne '') {
                   1003:                         $locale_names{$id} = '('.$en_terr.')';
                   1004:                     } elsif ($native_terr ne '') {
                   1005:                         $locale_names{$id} = $native_terr;
                   1006:                     }
                   1007:                 } else {
                   1008:                     if ($native_terr ne '') {
                   1009:                         $locale_names{$id} = $native_terr.' ';
                   1010:                     } elsif ($en_terr ne '') {
                   1011:                         $locale_names{$id} = '('.$en_terr.')';
                   1012:                     }
                   1013:                 }
1.1220    raeburn  1014:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1241    raeburn  1015:                 push(@possibles,$id);
                   1016:             } 
1.687     raeburn  1017:         }
                   1018:     }
                   1019:     foreach my $item (sort(@possibles)) {
                   1020:         $output.= '<option value="'.$item.'"';
                   1021:         if ($item eq $selected) {
                   1022:             $output.=' selected="selected"';
                   1023:         }
                   1024:         $output.=">$item";
                   1025:         if ($locale_names{$item} ne '') {
1.1220    raeburn  1026:             $output.='  '.$locale_names{$item};
1.687     raeburn  1027:         }
                   1028:         $output.="</option>\n";
                   1029:     }
                   1030:     $output.="</select>";
                   1031:     return $output;
                   1032: }
                   1033: 
1.792     raeburn  1034: sub select_language {
1.1256    raeburn  1035:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1036:     my %langchoices;
                   1037:     if ($includeempty) {
1.1117    raeburn  1038:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1039:     }
                   1040:     foreach my $id (&languageids()) {
                   1041:         my $code = &supportedlanguagecode($id);
                   1042:         if ($code) {
                   1043:             $langchoices{$code} = &plainlanguagedescription($id);
                   1044:         }
                   1045:     }
1.1117    raeburn  1046:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1256    raeburn  1047:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1048: }
                   1049: 
1.42      matthew  1050: =pod
1.36      matthew  1051: 
1.1088    foxr     1052: 
                   1053: =item * &list_languages()
                   1054: 
                   1055: Returns an array reference that is suitable for use in language prompters.
                   1056: Each array element is itself a two element array.  The first element
                   1057: is the language code.  The second element a descsriptiuon of the 
                   1058: language itself.  This is suitable for use in e.g.
                   1059: &Apache::edit::select_arg (once dereferenced that is).
                   1060: 
                   1061: =cut 
                   1062: 
                   1063: sub list_languages {
                   1064:     my @lang_choices;
                   1065: 
                   1066:     foreach my $id (&languageids()) {
                   1067: 	my $code = &supportedlanguagecode($id);
                   1068: 	if ($code) {
                   1069: 	    my $selector    = $supported_codes{$id};
                   1070: 	    my $description = &plainlanguagedescription($id);
1.1263    raeburn  1071: 	    push(@lang_choices, [$selector, $description]);
1.1088    foxr     1072: 	}
                   1073:     }
                   1074:     return \@lang_choices;
                   1075: }
                   1076: 
                   1077: =pod
                   1078: 
1.648     raeburn  1079: =item * &linked_select_forms(...)
1.36      matthew  1080: 
                   1081: linked_select_forms returns a string containing a <script></script> block
                   1082: and html for two <select> menus.  The select menus will be linked in that
                   1083: changing the value of the first menu will result in new values being placed
                   1084: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1085: order unless a defined order is provided.
1.36      matthew  1086: 
                   1087: linked_select_forms takes the following ordered inputs:
                   1088: 
                   1089: =over 4
                   1090: 
1.112     bowersj2 1091: =item * $formname, the name of the <form> tag
1.36      matthew  1092: 
1.112     bowersj2 1093: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1094: 
1.112     bowersj2 1095: =item * $firstdefault, the default value for the first menu
1.36      matthew  1096: 
1.112     bowersj2 1097: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1098: 
1.112     bowersj2 1099: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1100: 
1.112     bowersj2 1101: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1102: 
1.609     raeburn  1103: =item * $menuorder, the order of values in the first menu
                   1104: 
1.1115    raeburn  1105: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1106:         event for the first <select> tag
                   1107: 
                   1108: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1109:         event for the second <select> tag
                   1110: 
1.1245    raeburn  1111: =item * $suffix, to differentiate separate uses of select2data javascript
                   1112:         objects in a page.
                   1113: 
1.41      ng       1114: =back 
                   1115: 
1.36      matthew  1116: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1117: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1118: values for the first select menu.  The text that coincides with the 
1.41      ng       1119: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1120: and text for the second menu are given in the hash pointed to by 
                   1121: $menu{$choice1}->{'select2'}.  
                   1122: 
1.112     bowersj2 1123:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1124:                        default => "B3",
                   1125:                        select2 => { 
                   1126:                            B1 => "Choice B1",
                   1127:                            B2 => "Choice B2",
                   1128:                            B3 => "Choice B3",
                   1129:                            B4 => "Choice B4"
1.609     raeburn  1130:                            },
                   1131:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1132:                    },
                   1133:                A2 => { text =>"Choice A2" ,
                   1134:                        default => "C2",
                   1135:                        select2 => { 
                   1136:                            C1 => "Choice C1",
                   1137:                            C2 => "Choice C2",
                   1138:                            C3 => "Choice C3"
1.609     raeburn  1139:                            },
                   1140:                        order => ['C2','C1','C3'],
1.112     bowersj2 1141:                    },
                   1142:                A3 => { text =>"Choice A3" ,
                   1143:                        default => "D6",
                   1144:                        select2 => { 
                   1145:                            D1 => "Choice D1",
                   1146:                            D2 => "Choice D2",
                   1147:                            D3 => "Choice D3",
                   1148:                            D4 => "Choice D4",
                   1149:                            D5 => "Choice D5",
                   1150:                            D6 => "Choice D6",
                   1151:                            D7 => "Choice D7"
1.609     raeburn  1152:                            },
                   1153:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1154:                    }
                   1155:                );
1.36      matthew  1156: 
                   1157: =cut
                   1158: 
                   1159: sub linked_select_forms {
                   1160:     my ($formname,
                   1161:         $middletext,
                   1162:         $firstdefault,
                   1163:         $firstselectname,
                   1164:         $secondselectname, 
1.609     raeburn  1165:         $hashref,
                   1166:         $menuorder,
1.1115    raeburn  1167:         $onchangefirst,
1.1245    raeburn  1168:         $onchangesecond,
                   1169:         $suffix
1.36      matthew  1170:         ) = @_;
                   1171:     my $second = "document.$formname.$secondselectname";
                   1172:     my $first = "document.$formname.$firstselectname";
                   1173:     # output the javascript to do the changing
                   1174:     my $result = '';
1.776     bisitz   1175:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1176:     $result.="// <![CDATA[\n";
1.1245    raeburn  1177:     $result.="var select2data${suffix} = new Object();\n";
1.36      matthew  1178:     $" = '","';
                   1179:     my $debug = '';
                   1180:     foreach my $s1 (sort(keys(%$hashref))) {
1.1245    raeburn  1181:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
                   1182:         $result.="select2data${suffix}['d_$s1'].def = new String('".
1.36      matthew  1183:             $hashref->{$s1}->{'default'}."');\n";
1.1245    raeburn  1184:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
1.36      matthew  1185:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1186:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1187:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1188:         }
1.36      matthew  1189:         $result.="\"@s2values\");\n";
1.1245    raeburn  1190:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
1.36      matthew  1191:         my @s2texts;
                   1192:         foreach my $value (@s2values) {
1.1263    raeburn  1193:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1194:         }
                   1195:         $result.="\"@s2texts\");\n";
                   1196:     }
                   1197:     $"=' ';
                   1198:     $result.= <<"END";
                   1199: 
1.1245    raeburn  1200: function select1${suffix}_changed() {
1.36      matthew  1201:     // Determine new choice
1.1245    raeburn  1202:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
1.36      matthew  1203:     // update select2
1.1245    raeburn  1204:     var values     = select2data${suffix}[newvalue].values;
                   1205:     var texts      = select2data${suffix}[newvalue].texts;
                   1206:     var select2def = select2data${suffix}[newvalue].def;
1.36      matthew  1207:     var i;
                   1208:     // out with the old
1.1245    raeburn  1209:     $second.options.length = 0;
                   1210:     // in with the new
1.36      matthew  1211:     for (i=0;i<values.length; i++) {
                   1212:         $second.options[i] = new Option(values[i]);
1.143     matthew  1213:         $second.options[i].value = values[i];
1.36      matthew  1214:         $second.options[i].text = texts[i];
                   1215:         if (values[i] == select2def) {
                   1216:             $second.options[i].selected = true;
                   1217:         }
                   1218:     }
                   1219: }
1.824     bisitz   1220: // ]]>
1.36      matthew  1221: </script>
                   1222: END
                   1223:     # output the initial values for the selection lists
1.1245    raeburn  1224:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
1.609     raeburn  1225:     my @order = sort(keys(%{$hashref}));
                   1226:     if (ref($menuorder) eq 'ARRAY') {
                   1227:         @order = @{$menuorder};
                   1228:     }
                   1229:     foreach my $value (@order) {
1.36      matthew  1230:         $result.="    <option value=\"$value\" ";
1.253     albertel 1231:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1232:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1233:     }
                   1234:     $result .= "</select>\n";
                   1235:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1236:     $result .= $middletext;
1.1115    raeburn  1237:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1238:     if ($onchangesecond) {
                   1239:         $result .= ' onchange="'.$onchangesecond.'"';
                   1240:     }
                   1241:     $result .= ">\n";
1.36      matthew  1242:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1243:     
                   1244:     my @secondorder = sort(keys(%select2));
                   1245:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1246:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1247:     }
                   1248:     foreach my $value (@secondorder) {
1.36      matthew  1249:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1250:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1251:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1252:     }
                   1253:     $result .= "</select>\n";
                   1254:     #    return $debug;
                   1255:     return $result;
                   1256: }   #  end of sub linked_select_forms {
                   1257: 
1.45      matthew  1258: =pod
1.44      bowersj2 1259: 
1.973     raeburn  1260: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1261: 
1.112     bowersj2 1262: Returns a string corresponding to an HTML link to the given help
                   1263: $topic, where $topic corresponds to the name of a .tex file in
                   1264: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1265: spaces. 
                   1266: 
                   1267: $text will optionally be linked to the same topic, allowing you to
                   1268: link text in addition to the graphic. If you do not want to link
                   1269: text, but wish to specify one of the later parameters, pass an
                   1270: empty string. 
                   1271: 
                   1272: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1273: the link will not open a new window. If false, the link will open
                   1274: a new window using Javascript. (Default is false.) 
                   1275: 
                   1276: $width and $height are optional numerical parameters that will
                   1277: override the width and height of the popped up window, which may
1.973     raeburn  1278: be useful for certain help topics with big pictures included.
                   1279: 
                   1280: $imgid is the id of the img tag used for the help icon. This may be
                   1281: used in a javascript call to switch the image src.  See 
                   1282: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1283: 
                   1284: =cut
                   1285: 
                   1286: sub help_open_topic {
1.973     raeburn  1287:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1288:     $text = "" if (not defined $text);
1.44      bowersj2 1289:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1290:     $width = 500 if (not defined $width);
1.44      bowersj2 1291:     $height = 400 if (not defined $height);
                   1292:     my $filename = $topic;
                   1293:     $filename =~ s/ /_/g;
                   1294: 
1.48      bowersj2 1295:     my $template = "";
                   1296:     my $link;
1.572     banghart 1297:     
1.159     www      1298:     $topic=~s/\W/\_/g;
1.44      bowersj2 1299: 
1.572     banghart 1300:     if (!$stayOnPage) {
1.1033    www      1301: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1302:     } elsif ($stayOnPage eq 'popup') {
                   1303:         $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 1304:     } else {
1.48      bowersj2 1305: 	$link = "/adm/help/${filename}.hlp";
                   1306:     }
                   1307: 
                   1308:     # Add the text
1.1314    raeburn  1309:     my $target = ' target="_top"';
                   1310:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
                   1311:         $target = '';
                   1312:     }
1.755     neumanie 1313:     if ($text ne "") {	
1.763     bisitz   1314: 	$template.='<span class="LC_help_open_topic">'
1.1314    raeburn  1315:                   .'<a'.$target.' href="'.$link.'">'
1.763     bisitz   1316:                   .$text.'</a>';
1.48      bowersj2 1317:     }
                   1318: 
1.763     bisitz   1319:     # (Always) Add the graphic
1.179     matthew  1320:     my $title = &mt('Online Help');
1.667     raeburn  1321:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1322:     if ($imgid ne '') {
                   1323:         $imgid = ' id="'.$imgid.'"';
                   1324:     }
1.1314    raeburn  1325:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
1.763     bisitz   1326:               .'<img src="'.$helpicon.'" border="0"'
                   1327:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1328:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1329:               .' /></a>';
                   1330:     if ($text ne "") {	
                   1331:         $template.='</span>';
                   1332:     }
1.44      bowersj2 1333:     return $template;
                   1334: 
1.106     bowersj2 1335: }
                   1336: 
                   1337: # This is a quicky function for Latex cheatsheet editing, since it 
                   1338: # appears in at least four places
                   1339: sub helpLatexCheatsheet {
1.1037    www      1340:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1341:     my $out;
1.106     bowersj2 1342:     my $addOther = '';
1.732     raeburn  1343:     if ($topic) {
1.1037    www      1344: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1345:     }
                   1346:     $out = '<span>' # Start cheatsheet
                   1347: 	  .$addOther
                   1348:           .'<span>'
1.1037    www      1349: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1350: 	  .'</span> <span>'
1.1037    www      1351: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1352: 	  .'</span>';
1.732     raeburn  1353:     unless ($not_author) {
1.1186    kruse    1354:         $out .= '<span>'
                   1355:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
                   1356:                .'</span> <span>'
                   1357:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1.763     bisitz   1358: 	       .'</span>';
1.732     raeburn  1359:     }
1.763     bisitz   1360:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1361:     return $out;
1.172     www      1362: }
                   1363: 
1.430     albertel 1364: sub general_help {
                   1365:     my $helptopic='Student_Intro';
                   1366:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1367: 	$helptopic='Authoring_Intro';
1.907     raeburn  1368:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1369: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1370:     } elsif ($env{'request.role'}=~/^dc/) {
                   1371:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1372:     }
                   1373:     return $helptopic;
                   1374: }
                   1375: 
                   1376: sub update_help_link {
                   1377:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1378:     my $origurl = $ENV{'REQUEST_URI'};
                   1379:     $origurl=~s|^/~|/priv/|;
                   1380:     my $timestamp = time;
                   1381:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1382:         $$datum = &escape($$datum);
                   1383:     }
                   1384: 
                   1385:     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";
                   1386:     my $output .= <<"ENDOUTPUT";
                   1387: <script type="text/javascript">
1.824     bisitz   1388: // <![CDATA[
1.430     albertel 1389: banner_link = '$banner_link';
1.824     bisitz   1390: // ]]>
1.430     albertel 1391: </script>
                   1392: ENDOUTPUT
                   1393:     return $output;
                   1394: }
                   1395: 
                   1396: # now just updates the help link and generates a blue icon
1.193     raeburn  1397: sub help_open_menu {
1.430     albertel 1398:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1399: 	= @_;    
1.949     droeschl 1400:     $stayOnPage = 1;
1.430     albertel 1401:     my $output;
                   1402:     if ($component_help) {
                   1403: 	if (!$text) {
                   1404: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1405: 				       $width,$height);
                   1406: 	} else {
                   1407: 	    my $help_text;
                   1408: 	    $help_text=&unescape($topic);
                   1409: 	    $output='<table><tr><td>'.
                   1410: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1411: 				 $width,$height).'</td></tr></table>';
                   1412: 	}
                   1413:     }
                   1414:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1415:     return $output.$banner_link;
                   1416: }
                   1417: 
                   1418: sub top_nav_help {
1.1369    raeburn  1419:     my ($text,$linkattr) = @_;
1.436     albertel 1420:     $text = &mt($text);
1.949     droeschl 1421:     my $stay_on_page = 1;
                   1422: 
1.1168    raeburn  1423:     my ($link,$banner_link);
                   1424:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1425:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1426: 	                         : "javascript:helpMenu('open')";
                   1427:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1428:     }
1.201     raeburn  1429:     my $title = &mt('Get help');
1.1168    raeburn  1430:     if ($link) {
                   1431:         return <<"END";
1.436     albertel 1432: $banner_link
1.1369    raeburn  1433: <a href="$link" title="$title" $linkattr>$text</a>
1.436     albertel 1434: END
1.1168    raeburn  1435:     } else {
                   1436:         return '&nbsp;'.$text.'&nbsp;';
                   1437:     }
1.436     albertel 1438: }
                   1439: 
                   1440: sub help_menu_js {
1.1154    raeburn  1441:     my ($httphost) = @_;
1.949     droeschl 1442:     my $stayOnPage = 1;
1.436     albertel 1443:     my $width = 620;
                   1444:     my $height = 600;
1.430     albertel 1445:     my $helptopic=&general_help();
1.1154    raeburn  1446:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1447:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1448:     my $start_page =
                   1449:         &Apache::loncommon::start_page('Help Menu', undef,
                   1450: 				       {'frameset'    => 1,
                   1451: 					'js_ready'    => 1,
1.1154    raeburn  1452:                                         'use_absolute' => $httphost,
1.331     albertel 1453: 					'add_entries' => {
1.1168    raeburn  1454: 					    'border' => '0', 
1.579     raeburn  1455: 					    'rows'   => "110,*",},});
1.331     albertel 1456:     my $end_page =
                   1457:         &Apache::loncommon::end_page({'frameset' => 1,
                   1458: 				      'js_ready' => 1,});
                   1459: 
1.436     albertel 1460:     my $template .= <<"ENDTEMPLATE";
                   1461: <script type="text/javascript">
1.877     bisitz   1462: // <![CDATA[
1.253     albertel 1463: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1464: var banner_link = '';
1.243     raeburn  1465: function helpMenu(target) {
                   1466:     var caller = this;
                   1467:     if (target == 'open') {
                   1468:         var newWindow = null;
                   1469:         try {
1.262     albertel 1470:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1471:         }
                   1472:         catch(error) {
                   1473:             writeHelp(caller);
                   1474:             return;
                   1475:         }
                   1476:         if (newWindow) {
                   1477:             caller = newWindow;
                   1478:         }
1.193     raeburn  1479:     }
1.243     raeburn  1480:     writeHelp(caller);
                   1481:     return;
                   1482: }
                   1483: function writeHelp(caller) {
1.1168    raeburn  1484:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1485:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1486:     caller.document.close();
                   1487:     caller.focus();
1.193     raeburn  1488: }
1.877     bisitz   1489: // END LON-CAPA Internal -->
1.253     albertel 1490: // ]]>
1.436     albertel 1491: </script>
1.193     raeburn  1492: ENDTEMPLATE
                   1493:     return $template;
                   1494: }
                   1495: 
1.172     www      1496: sub help_open_bug {
                   1497:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1498:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1499:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1500:     $text = "" if (not defined $text);
                   1501: 	$stayOnPage=1;
1.184     albertel 1502:     $width = 600 if (not defined $width);
                   1503:     $height = 600 if (not defined $height);
1.172     www      1504: 
                   1505:     $topic=~s/\W+/\+/g;
                   1506:     my $link='';
                   1507:     my $template='';
1.379     albertel 1508:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1509: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1510:     if (!$stayOnPage)
                   1511:     {
                   1512: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1513:     }
                   1514:     else
                   1515:     {
                   1516: 	$link = $url;
                   1517:     }
1.1314    raeburn  1518: 
                   1519:     my $target = ' target="_top"';
                   1520:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
                   1521:         $target = '';
                   1522:     }
1.172     www      1523:     # Add the text
                   1524:     if ($text ne "")
                   1525:     {
                   1526: 	$template .= 
                   1527:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.1314    raeburn  1528:   "<td bgcolor='#FF5555'><a".$target." href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1529:     }
                   1530: 
                   1531:     # Add the graphic
1.179     matthew  1532:     my $title = &mt('Report a Bug');
1.215     albertel 1533:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1534:     $template .= <<"ENDTEMPLATE";
1.1314    raeburn  1535:  <a$target href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1536: ENDTEMPLATE
                   1537:     if ($text ne '') { $template.='</td></tr></table>' };
                   1538:     return $template;
                   1539: 
                   1540: }
                   1541: 
                   1542: sub help_open_faq {
                   1543:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1544:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1545:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1546:     $text = "" if (not defined $text);
                   1547: 	$stayOnPage=1;
                   1548:     $width = 350 if (not defined $width);
                   1549:     $height = 400 if (not defined $height);
                   1550: 
                   1551:     $topic=~s/\W+/\+/g;
                   1552:     my $link='';
                   1553:     my $template='';
                   1554:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1555:     if (!$stayOnPage)
                   1556:     {
                   1557: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1558:     }
                   1559:     else
                   1560:     {
                   1561: 	$link = $url;
                   1562:     }
                   1563: 
                   1564:     # Add the text
                   1565:     if ($text ne "")
                   1566:     {
                   1567: 	$template .= 
1.173     www      1568:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1569:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1570:     }
                   1571: 
                   1572:     # Add the graphic
1.179     matthew  1573:     my $title = &mt('View the FAQ');
1.215     albertel 1574:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1575:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1576:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1577: ENDTEMPLATE
                   1578:     if ($text ne '') { $template.='</td></tr></table>' };
                   1579:     return $template;
                   1580: 
1.44      bowersj2 1581: }
1.37      matthew  1582: 
1.180     matthew  1583: ###############################################################
                   1584: ###############################################################
                   1585: 
1.45      matthew  1586: =pod
                   1587: 
1.648     raeburn  1588: =item * &change_content_javascript():
1.256     matthew  1589: 
                   1590: This and the next function allow you to create small sections of an
                   1591: otherwise static HTML page that you can update on the fly with
                   1592: Javascript, even in Netscape 4.
                   1593: 
                   1594: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1595: must be written to the HTML page once. It will prove the Javascript
                   1596: function "change(name, content)". Calling the change function with the
                   1597: name of the section 
                   1598: you want to update, matching the name passed to C<changable_area>, and
                   1599: the new content you want to put in there, will put the content into
                   1600: that area.
                   1601: 
                   1602: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1603: to contain room for the original contents. You need to "make space"
                   1604: for whatever changes you wish to make, and be B<sure> to check your
                   1605: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1606: it's adequate for updating a one-line status display, but little more.
                   1607: This script will set the space to 100% width, so you only need to
                   1608: worry about height in Netscape 4.
                   1609: 
                   1610: Modern browsers are much less limiting, and if you can commit to the
                   1611: user not using Netscape 4, this feature may be used freely with
                   1612: pretty much any HTML.
                   1613: 
                   1614: =cut
                   1615: 
                   1616: sub change_content_javascript {
                   1617:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1618:     if ($env{'browser.type'} eq 'netscape' &&
                   1619: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1620: 	return (<<NETSCAPE4);
                   1621: 	function change(name, content) {
                   1622: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1623: 	    doc.open();
                   1624: 	    doc.write(content);
                   1625: 	    doc.close();
                   1626: 	}
                   1627: NETSCAPE4
                   1628:     } else {
                   1629: 	# Otherwise, we need to use semi-standards-compliant code
                   1630: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1631: 	# is really scary, and every useful browser supports it
                   1632: 	return (<<DOMBASED);
                   1633: 	function change(name, content) {
                   1634: 	    element = document.getElementById(name);
                   1635: 	    element.innerHTML = content;
                   1636: 	}
                   1637: DOMBASED
                   1638:     }
                   1639: }
                   1640: 
                   1641: =pod
                   1642: 
1.648     raeburn  1643: =item * &changable_area($name,$origContent):
1.256     matthew  1644: 
                   1645: This provides a "changable area" that can be modified on the fly via
                   1646: the Javascript code provided in C<change_content_javascript>. $name is
                   1647: the name you will use to reference the area later; do not repeat the
                   1648: same name on a given HTML page more then once. $origContent is what
                   1649: the area will originally contain, which can be left blank.
                   1650: 
                   1651: =cut
                   1652: 
                   1653: sub changable_area {
                   1654:     my ($name, $origContent) = @_;
                   1655: 
1.258     albertel 1656:     if ($env{'browser.type'} eq 'netscape' &&
                   1657: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1658: 	# If this is netscape 4, we need to use the Layer tag
                   1659: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1660:     } else {
                   1661: 	return "<span id='$name'>$origContent</span>";
                   1662:     }
                   1663: }
                   1664: 
                   1665: =pod
                   1666: 
1.648     raeburn  1667: =item * &viewport_geometry_js 
1.590     raeburn  1668: 
                   1669: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1670: 
                   1671: =cut
                   1672: 
                   1673: 
                   1674: sub viewport_geometry_js { 
                   1675:     return <<"GEOMETRY";
                   1676: var Geometry = {};
                   1677: function init_geometry() {
                   1678:     if (Geometry.init) { return };
                   1679:     Geometry.init=1;
                   1680:     if (window.innerHeight) {
                   1681:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1682:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1683:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1684:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1685:     }
                   1686:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1687:         Geometry.getViewportHeight =
                   1688:             function() { return document.documentElement.clientHeight; };
                   1689:         Geometry.getViewportWidth =
                   1690:             function() { return document.documentElement.clientWidth; };
                   1691: 
                   1692:         Geometry.getHorizontalScroll =
                   1693:             function() { return document.documentElement.scrollLeft; };
                   1694:         Geometry.getVerticalScroll =
                   1695:             function() { return document.documentElement.scrollTop; };
                   1696:     }
                   1697:     else if (document.body.clientHeight) {
                   1698:         Geometry.getViewportHeight =
                   1699:             function() { return document.body.clientHeight; };
                   1700:         Geometry.getViewportWidth =
                   1701:             function() { return document.body.clientWidth; };
                   1702:         Geometry.getHorizontalScroll =
                   1703:             function() { return document.body.scrollLeft; };
                   1704:         Geometry.getVerticalScroll =
                   1705:             function() { return document.body.scrollTop; };
                   1706:     }
                   1707: }
                   1708: 
                   1709: GEOMETRY
                   1710: }
                   1711: 
                   1712: =pod
                   1713: 
1.648     raeburn  1714: =item * &viewport_size_js()
1.590     raeburn  1715: 
                   1716: 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. 
                   1717: 
                   1718: =cut
                   1719: 
                   1720: sub viewport_size_js {
                   1721:     my $geometry = &viewport_geometry_js();
                   1722:     return <<"DIMS";
                   1723: 
                   1724: $geometry
                   1725: 
                   1726: function getViewportDims(width,height) {
                   1727:     init_geometry();
                   1728:     width.value = Geometry.getViewportWidth();
                   1729:     height.value = Geometry.getViewportHeight();
                   1730:     return;
                   1731: }
                   1732: 
                   1733: DIMS
                   1734: }
                   1735: 
                   1736: =pod
                   1737: 
1.648     raeburn  1738: =item * &resize_textarea_js()
1.565     albertel 1739: 
                   1740: emits the needed javascript to resize a textarea to be as big as possible
                   1741: 
                   1742: creates a function resize_textrea that takes two IDs first should be
                   1743: the id of the element to resize, second should be the id of a div that
                   1744: surrounds everything that comes after the textarea, this routine needs
                   1745: to be attached to the <body> for the onload and onresize events.
                   1746: 
1.648     raeburn  1747: =back
1.565     albertel 1748: 
                   1749: =cut
                   1750: 
                   1751: sub resize_textarea_js {
1.590     raeburn  1752:     my $geometry = &viewport_geometry_js();
1.565     albertel 1753:     return <<"RESIZE";
                   1754:     <script type="text/javascript">
1.824     bisitz   1755: // <![CDATA[
1.590     raeburn  1756: $geometry
1.565     albertel 1757: 
1.588     albertel 1758: function getX(element) {
                   1759:     var x = 0;
                   1760:     while (element) {
                   1761: 	x += element.offsetLeft;
                   1762: 	element = element.offsetParent;
                   1763:     }
                   1764:     return x;
                   1765: }
                   1766: function getY(element) {
                   1767:     var y = 0;
                   1768:     while (element) {
                   1769: 	y += element.offsetTop;
                   1770: 	element = element.offsetParent;
                   1771:     }
                   1772:     return y;
                   1773: }
                   1774: 
                   1775: 
1.565     albertel 1776: function resize_textarea(textarea_id,bottom_id) {
                   1777:     init_geometry();
                   1778:     var textarea        = document.getElementById(textarea_id);
                   1779:     //alert(textarea);
                   1780: 
1.588     albertel 1781:     var textarea_top    = getY(textarea);
1.565     albertel 1782:     var textarea_height = textarea.offsetHeight;
                   1783:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1784:     var bottom_top      = getY(bottom);
1.565     albertel 1785:     var bottom_height   = bottom.offsetHeight;
                   1786:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1787:     var fudge           = 23;
1.565     albertel 1788:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1789:     if (new_height < 300) {
                   1790: 	new_height = 300;
                   1791:     }
                   1792:     textarea.style.height=new_height+'px';
                   1793: }
1.824     bisitz   1794: // ]]>
1.565     albertel 1795: </script>
                   1796: RESIZE
                   1797: 
                   1798: }
                   1799: 
1.1205    golterma 1800: sub colorfuleditor_js {
1.1248    raeburn  1801:     my $browse_or_search;
                   1802:     my $respath;
                   1803:     my ($cnum,$cdom) = &crsauthor_url();
                   1804:     if ($cnum) {
                   1805:         $respath = "/res/$cdom/$cnum/";
                   1806:         my %js_lt = &Apache::lonlocal::texthash(
                   1807:             sunm => 'Sub-directory name',
                   1808:             save => 'Save page to make this permanent',
                   1809:         );
                   1810:         &js_escape(\%js_lt);
                   1811:         $browse_or_search = <<"END";
                   1812: 
                   1813:     function toggleChooser(form,element,titleid,only,search) {
                   1814:         var disp = 'none';
                   1815:         if (document.getElementById('chooser_'+element)) {
                   1816:             var curr = document.getElementById('chooser_'+element).style.display;
                   1817:             if (curr == 'none') {
                   1818:                 disp='inline';
                   1819:                 if (form.elements['chooser_'+element].length) {
                   1820:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
                   1821:                         form.elements['chooser_'+element][i].checked = false;
                   1822:                     }
                   1823:                 }
                   1824:                 toggleResImport(form,element);
                   1825:             }
                   1826:             document.getElementById('chooser_'+element).style.display = disp;
                   1827:         }
                   1828:     }
                   1829: 
                   1830:     function toggleCrsFile(form,element,numdirs) {
                   1831:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1832:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1833:             if (curr == 'none') {
                   1834:                 if (numdirs) {
                   1835:                     form.elements['coursepath_'+element].selectedIndex = 0;
                   1836:                     if (numdirs > 1) {
                   1837:                         window['select1'+element+'_changed']();
                   1838:                     }
                   1839:                 }
                   1840:             } 
                   1841:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
                   1842:             
                   1843:         }
                   1844:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1845:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
                   1846:             if (document.getElementById('uploadcrsres_'+element)) {
                   1847:                 document.getElementById('uploadcrsres_'+element).value = '';
                   1848:             }
                   1849:         }
                   1850:         return;
                   1851:     }
                   1852: 
                   1853:     function toggleCrsUpload(form,element,numcrsdirs) {
                   1854:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1855:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
                   1856:         }
                   1857:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1858:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
                   1859:             if (curr == 'none') {
                   1860:                 if (numcrsdirs) {
                   1861:                    form.elements['crsauthorpath_'+element].selectedIndex = 0;
                   1862:                    form.elements['newsubdir_'+element][0].checked = true;
                   1863:                    toggleNewsubdir(form,element);
                   1864:                 }
                   1865:             }
                   1866:             document.getElementById('chooser_'+element+'_upload').style.display = 'block';
                   1867:         }
                   1868:         return;
                   1869:     }
                   1870: 
                   1871:     function toggleResImport(form,element) {
                   1872:         var choices = new Array('crsres','upload');
                   1873:         for (var i=0; i<choices.length; i++) {
                   1874:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
                   1875:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
                   1876:             }
                   1877:         }
                   1878:     }
                   1879: 
                   1880:     function toggleNewsubdir(form,element) {
                   1881:         var newsub = form.elements['newsubdir_'+element];
                   1882:         if (newsub) {
                   1883:             if (newsub.length) {
                   1884:                 for (var j=0; j<newsub.length; j++) {
                   1885:                     if (newsub[j].checked) {
                   1886:                         if (document.getElementById('newsubdirname_'+element)) {
                   1887:                             if (newsub[j].value == '1') {
                   1888:                                 document.getElementById('newsubdirname_'+element).type = "text";
                   1889:                                 if (document.getElementById('newsubdir_'+element)) {
                   1890:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
                   1891:                                 }
                   1892:                             } else {
                   1893:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
                   1894:                                 document.getElementById('newsubdirname_'+element).value = "";
                   1895:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
                   1896:                             }
                   1897:                         }
                   1898:                         break; 
                   1899:                     }
                   1900:                 }
                   1901:             }
                   1902:         }
                   1903:     }
                   1904: 
                   1905:     function updateCrsFile(form,element) {
                   1906:         var directory = form.elements['coursepath_'+element];
                   1907:         var filename = form.elements['coursefile_'+element];
                   1908:         var path = directory.options[directory.selectedIndex].value;
                   1909:         var file = filename.options[filename.selectedIndex].value;
                   1910:         form.elements[element].value = '$respath';
                   1911:         if (path == '/') {
                   1912:             form.elements[element].value += file;
                   1913:         } else {
                   1914:             form.elements[element].value += path+'/'+file;
                   1915:         }
                   1916:         unClean();
                   1917:         if (document.getElementById('previewimg_'+element)) {
                   1918:             document.getElementById('previewimg_'+element).src = form.elements[element].value;
                   1919:             var newsrc = document.getElementById('previewimg_'+element).src; 
                   1920:         }
                   1921:         if (document.getElementById('showimg_'+element)) {
                   1922:             document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
                   1923:         }
                   1924:         toggleChooser(form,element);
                   1925:         return;
                   1926:     }
                   1927: 
                   1928:     function uploadDone(suffix,name) {
                   1929:         if (name) {
                   1930: 	    document.forms["lonhomework"].elements[suffix].value = name;
                   1931:             unClean();
                   1932:             toggleChooser(document.forms["lonhomework"],suffix);
                   1933:         }
                   1934:     }
                   1935: 
                   1936: \$(document).ready(function(){
                   1937: 
                   1938:     \$(document).delegate('form :submit', 'click', function( event ) {
                   1939:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
                   1940:             var buttonId = this.id;
                   1941:             var suffix = buttonId.toString();
                   1942:             suffix = suffix.replace(/^crsupload_/,'');
                   1943:             event.preventDefault();
                   1944:             document.lonhomework.target = 'crsupload_target_'+suffix;
                   1945:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
                   1946:             \$(this.form).submit();
                   1947:             document.lonhomework.target = '';
                   1948:             if (document.getElementById('crsuploadto_'+suffix)) {
                   1949:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
                   1950:             }
                   1951:             return false;
                   1952:         }
                   1953:     });
                   1954: });
                   1955: END
                   1956:     }
1.1205    golterma 1957:     return <<"COLORFULEDIT"
                   1958: <script type="text/javascript">
                   1959: // <![CDATA[>
                   1960:     function fold_box(curDepth, lastresource){
                   1961: 
                   1962:     // we need a list because there can be several blocks you need to fold in one tag
                   1963:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1964:     // but there is only one folding button per tag
                   1965:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1966: 
                   1967:         if(block.item(0).style.display == 'none'){
                   1968: 
                   1969:             foldbutton.value = '@{[&mt("Hide")]}';
                   1970:             for (i = 0; i < block.length; i++){
                   1971:                 block.item(i).style.display = '';
                   1972:             }
                   1973:         }else{
                   1974: 
                   1975:             foldbutton.value = '@{[&mt("Show")]}';
                   1976:             for (i = 0; i < block.length; i++){
                   1977:                 // block.item(i).style.visibility = 'collapse';
                   1978:                 block.item(i).style.display = 'none';
                   1979:             }
                   1980:         };
                   1981:         saveState(lastresource);
                   1982:     }
                   1983: 
                   1984:     function saveState (lastresource) {
                   1985: 
                   1986:         var tag_list = getTagList();
                   1987:         if(tag_list != null){
                   1988:             var timestamp = new Date().getTime();
                   1989:             var key = lastresource;
                   1990: 
                   1991:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1992:             // starting with timestamp
                   1993:             var value = timestamp+';';
                   1994: 
                   1995:             // building the list of key-value pairs
                   1996:             for(var i = 0; i < tag_list.length; i++){
                   1997:                 value += tag_list[i]+',';
                   1998:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1999:             }
                   2000: 
                   2001:             // only iterate whole storage if nothing to override
                   2002:             if(localStorage.getItem(key) == null){        
                   2003: 
                   2004:                 // prevent storage from growing large
                   2005:                 if(localStorage.length > 50){
                   2006:                     var regex_getTimestamp = /^(?:\d)+;/;
                   2007:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   2008:                     var oldest_key;
                   2009:                     
                   2010:                     for(var i = 1; i < localStorage.length; i++){
                   2011:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   2012:                             oldest_key = localStorage.key(i);
                   2013:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   2014:                         }
                   2015:                     }
                   2016:                     localStorage.removeItem(oldest_key);
                   2017:                 }
                   2018:             }
                   2019:             localStorage.setItem(key,value);
                   2020:         }
                   2021:     }
                   2022: 
                   2023:     // restore folding status of blocks (on page load)
                   2024:     function restoreState (lastresource) {
                   2025:         if(localStorage.getItem(lastresource) != null){
                   2026:             var key = lastresource;
                   2027:             var value = localStorage.getItem(key);
                   2028:             var regex_delTimestamp = /^\d+;/;
                   2029: 
                   2030:             value.replace(regex_delTimestamp, '');
                   2031: 
                   2032:             var valueArr = value.split(';');
                   2033:             var pairs;
                   2034:             var elements;
                   2035:             for (var i = 0; i < valueArr.length; i++){
                   2036:                 pairs = valueArr[i].split(',');
                   2037:                 elements = document.getElementsByName(pairs[0]);
                   2038: 
                   2039:                 for (var j = 0; j < elements.length; j++){  
                   2040:                     elements[j].style.display = pairs[1];
                   2041:                     if (pairs[1] == "none"){
                   2042:                         var regex_id = /([_\\d]+)\$/;
                   2043:                         regex_id.exec(pairs[0]);
                   2044:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   2045:                     }
                   2046:                 }
                   2047:             }
                   2048:         }
                   2049:     }
                   2050: 
                   2051:     function getTagList () {
                   2052:         
                   2053:         var stringToSearch = document.lonhomework.innerHTML;
                   2054: 
                   2055:         var ret = new Array();
                   2056:         var regex_findBlock = /(foldblock_.*?)"/g;
                   2057:         var tag_list = stringToSearch.match(regex_findBlock);
                   2058: 
                   2059:         if(tag_list != null){
                   2060:             for(var i = 0; i < tag_list.length; i++){            
                   2061:                 ret.push(tag_list[i].replace(/"/, ''));
                   2062:             }
                   2063:         }
                   2064:         return ret;
                   2065:     }
                   2066: 
                   2067:     function saveScrollPosition (resource) {
                   2068:         var tag_list = getTagList();
                   2069: 
                   2070:         // we dont always want to jump to the first block
                   2071:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   2072:         if(\$(window).scrollTop() > 170){
                   2073:             if(tag_list != null){
                   2074:                 var result;
                   2075:                 for(var i = 0; i < tag_list.length; i++){
                   2076:                     if(isElementInViewport(tag_list[i])){
                   2077:                         result += tag_list[i]+';';
                   2078:                     }
                   2079:                 }
                   2080:                 sessionStorage.setItem('anchor_'+resource, result);
                   2081:             }
                   2082:         } else {
                   2083:             // we dont need to save zero, just delete the item to leave everything tidy
                   2084:             sessionStorage.removeItem('anchor_'+resource);
                   2085:         }
                   2086:     }
                   2087: 
                   2088:     function restoreScrollPosition(resource){
                   2089: 
                   2090:         var elem = sessionStorage.getItem('anchor_'+resource);
                   2091:         if(elem != null){
                   2092:             var tag_list = elem.split(';');
                   2093:             var elem_list;
                   2094: 
                   2095:             for(var i = 0; i < tag_list.length; i++){
                   2096:                 elem_list = document.getElementsByName(tag_list[i]);
                   2097:                 
                   2098:                 if(elem_list.length > 0){
                   2099:                     elem = elem_list[0];
                   2100:                     break;
                   2101:                 }
                   2102:             }
                   2103:             elem.scrollIntoView();
                   2104:         }
                   2105:     }
                   2106: 
                   2107:     function isElementInViewport(el) {
                   2108: 
                   2109:         // change to last element instead of first
                   2110:         var elem = document.getElementsByName(el);
                   2111:         var rect = elem[0].getBoundingClientRect();
                   2112: 
                   2113:         return (
                   2114:             rect.top >= 0 &&
                   2115:             rect.left >= 0 &&
                   2116:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   2117:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   2118:         );
                   2119:     }
                   2120:     
                   2121:     function autosize(depth){
                   2122:         var cmInst = window['cm'+depth];
                   2123:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   2124: 
                   2125:         // is fixed size, switching to dynamic
                   2126:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   2127:             cmInst.setSize("","auto");
                   2128:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   2129:             sessionStorage.setItem("autosized_"+depth, "yes");
                   2130: 
                   2131:         // is dynamic size, switching to fixed
                   2132:         } else {
                   2133:             cmInst.setSize("","300px");
                   2134:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   2135:             sessionStorage.removeItem("autosized_"+depth);
                   2136:         }
                   2137:     }
                   2138: 
1.1248    raeburn  2139: $browse_or_search
1.1205    golterma 2140: 
                   2141: // ]]>
                   2142: </script>
                   2143: COLORFULEDIT
                   2144: }
                   2145: 
                   2146: sub xmleditor_js {
                   2147:     return <<XMLEDIT
                   2148: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   2149: <script type="text/javascript">
                   2150: // <![CDATA[>
                   2151: 
                   2152:     function saveScrollPosition (resource) {
                   2153: 
                   2154:         var scrollPos = \$(window).scrollTop();
                   2155:         sessionStorage.setItem(resource,scrollPos);
                   2156:     }
                   2157: 
                   2158:     function restoreScrollPosition(resource){
                   2159: 
                   2160:         var scrollPos = sessionStorage.getItem(resource);
                   2161:         \$(window).scrollTop(scrollPos);
                   2162:     }
                   2163: 
                   2164:     // unless internet explorer
                   2165:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   2166: 
                   2167:         \$(document).ready(function() {
                   2168:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   2169:         });
                   2170:     }
                   2171: 
                   2172:     // inserts text at cursor position into codemirror (xml editor only)
                   2173:     function insertText(text){
                   2174:         cm.focus();
                   2175:         var curPos = cm.getCursor();
                   2176:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   2177:     }
                   2178: // ]]>
                   2179: </script>
                   2180: XMLEDIT
                   2181: }
                   2182: 
                   2183: sub insert_folding_button {
                   2184:     my $curDepth = $Apache::lonxml::curdepth;
                   2185:     my $lastresource = $env{'request.ambiguous'};
                   2186: 
                   2187:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   2188:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2189: }
                   2190: 
1.1248    raeburn  2191: sub crsauthor_url {
                   2192:     my ($url) = @_;
                   2193:     if ($url eq '') {
                   2194:         $url = $ENV{'REQUEST_URI'};
                   2195:     }
                   2196:     my ($cnum,$cdom);
                   2197:     if ($env{'request.course.id'}) {
                   2198:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
                   2199:         if ($audom ne '' && $auname ne '') {
                   2200:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
                   2201:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
                   2202:                 $cnum = $auname;
                   2203:                 $cdom = $audom;
                   2204:             }
                   2205:         }
                   2206:     }
                   2207:     return ($cnum,$cdom);
                   2208: }
                   2209: 
                   2210: sub import_crsauthor_form {
1.1265    raeburn  2211:     my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
1.1248    raeburn  2212:     return (0) unless ($env{'request.course.id'});
                   2213:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2214:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2215:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   2216:     return (0) unless (($cnum ne '') && ($cdom ne ''));
                   2217:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
                   2218:     my @ids=&Apache::lonnet::current_machine_ids();
                   2219:     my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
                   2220:     
                   2221:     if (grep(/^\Q$crshome\E$/,@ids)) {
                   2222:         $is_home = 1;
                   2223:     }
                   2224:     $relpath = "/priv/$cdom/$cnum";
                   2225:     &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
                   2226:     my %lt = &Apache::lonlocal::texthash (
                   2227:         fnam => 'Filename',
                   2228:         dire => 'Directory',
                   2229:     );
                   2230:     my $numdirs = scalar(keys(%files));
                   2231:     my (%possexts,$singledir,@singledirfiles);
                   2232:     if ($only) {
                   2233:         map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
                   2234:     }
                   2235:     my (%nonemptydirs,$possdirs);
                   2236:     if ($numdirs > 1) {
                   2237:         my @order;
                   2238:         foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
                   2239:             if (ref($files{$key}) eq 'HASH') {
                   2240:                 my $shown = $key;
                   2241:                 if ($key eq '') {
                   2242:                     $shown = '/';
                   2243:                 }
                   2244:                 my @ordered = ();
                   2245:                 foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
1.1315    raeburn  2246:                     next if ($file =~ /\.rights$/);
1.1248    raeburn  2247:                     if ($only) {
                   2248:                         my ($ext) = ($file =~ /\.([^.]+)$/);
                   2249:                         unless ($possexts{lc($ext)}) {
                   2250:                             next;
                   2251:                         }
                   2252:                     }
                   2253:                     $selimport_menus{$key}->{'select2'}->{$file} = $file;
                   2254:                     push(@ordered,$file);
                   2255:                 }
                   2256:                 if (@ordered) {
                   2257:                     push(@order,$key);
                   2258:                     $nonemptydirs{$key} = 1;
                   2259:                     $selimport_menus{$key}->{'text'} = $shown;
                   2260:                     $selimport_menus{$key}->{'default'} = '';
                   2261:                     $selimport_menus{$key}->{'select2'}->{''} = '';
                   2262:                     $selimport_menus{$key}->{'order'} = \@ordered;
                   2263:                 }
                   2264:             }
                   2265:         }
                   2266:         $possdirs = scalar(keys(%nonemptydirs));
                   2267:         if ($possdirs > 1) {
                   2268:             my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
                   2269:             $output = $lt{'dire'}.
                   2270:                       &linked_select_forms($form,'<br />'.
                   2271:                                            $lt{'fnam'},'',
                   2272:                                            $firstselectname,$secondselectname,
                   2273:                                            \%selimport_menus,\@order,
                   2274:                                            $onchangefirst,'',$suffix).'<br />';
                   2275:         } elsif ($possdirs == 1) {
                   2276:             $singledir = (keys(%nonemptydirs))[0];
                   2277:             if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
                   2278:                 @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
                   2279:             }
                   2280:             delete($selimport_menus{$singledir});
                   2281:         }
                   2282:     } elsif ($numdirs == 1) {
                   2283:         $singledir = (keys(%files))[0];
                   2284:         foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
                   2285:             if ($only) {
                   2286:                 my ($ext) = ($file =~ /\.([^.]+)$/);
                   2287:                 unless ($possexts{lc($ext)}) {
                   2288:                     next;
                   2289:                 }
1.1315    raeburn  2290:             } else {
                   2291:                 next if ($file =~ /\.rights$/);
1.1248    raeburn  2292:             }
                   2293:             push(@singledirfiles,$file);
                   2294:         }
                   2295:         if (@singledirfiles) {
1.1315    raeburn  2296:             $possdirs = 1;
1.1248    raeburn  2297:         }
                   2298:     }
                   2299:     if (($possdirs == 1) && (@singledirfiles)) {
                   2300:         my $showdir = $singledir;
                   2301:         if ($singledir eq '') {
                   2302:             $showdir = '/';
                   2303:         }
                   2304:         $output = $lt{'dire'}.
                   2305:                   '<select name="'.$firstselectname.'">'.
                   2306:                   '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
                   2307:                   '</select><br />'.
                   2308:                   $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
                   2309:                   '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
                   2310:         foreach my $file (@singledirfiles) {
                   2311:             $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
                   2312:         }
                   2313:         $output .= '</select><br />'."\n";
                   2314:     }
                   2315:     return ($possdirs,$output);
                   2316: }
                   2317: 
1.565     albertel 2318: =pod
                   2319: 
1.256     matthew  2320: =head1 Excel and CSV file utility routines
                   2321: 
                   2322: =cut
                   2323: 
                   2324: ###############################################################
                   2325: ###############################################################
                   2326: 
                   2327: =pod
                   2328: 
1.1162    raeburn  2329: =over 4
                   2330: 
1.648     raeburn  2331: =item * &csv_translate($text) 
1.37      matthew  2332: 
1.185     www      2333: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2334: format.
                   2335: 
                   2336: =cut
                   2337: 
1.180     matthew  2338: ###############################################################
                   2339: ###############################################################
1.37      matthew  2340: sub csv_translate {
                   2341:     my $text = shift;
                   2342:     $text =~ s/\"/\"\"/g;
1.209     albertel 2343:     $text =~ s/\n/ /g;
1.37      matthew  2344:     return $text;
                   2345: }
1.180     matthew  2346: 
                   2347: ###############################################################
                   2348: ###############################################################
                   2349: 
                   2350: =pod
                   2351: 
1.648     raeburn  2352: =item * &define_excel_formats()
1.180     matthew  2353: 
                   2354: Define some commonly used Excel cell formats.
                   2355: 
                   2356: Currently supported formats:
                   2357: 
                   2358: =over 4
                   2359: 
                   2360: =item header
                   2361: 
                   2362: =item bold
                   2363: 
                   2364: =item h1
                   2365: 
                   2366: =item h2
                   2367: 
                   2368: =item h3
                   2369: 
1.256     matthew  2370: =item h4
                   2371: 
                   2372: =item i
                   2373: 
1.180     matthew  2374: =item date
                   2375: 
                   2376: =back
                   2377: 
                   2378: Inputs: $workbook
                   2379: 
                   2380: Returns: $format, a hash reference.
                   2381: 
1.1057    foxr     2382: 
1.180     matthew  2383: =cut
                   2384: 
                   2385: ###############################################################
                   2386: ###############################################################
                   2387: sub define_excel_formats {
                   2388:     my ($workbook) = @_;
                   2389:     my $format;
                   2390:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2391:                                                 bottom    => 1,
                   2392:                                                 align     => 'center');
                   2393:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2394:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2395:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2396:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2397:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2398:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2399:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2400:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2401:     return $format;
                   2402: }
                   2403: 
                   2404: ###############################################################
                   2405: ###############################################################
1.113     bowersj2 2406: 
                   2407: =pod
                   2408: 
1.648     raeburn  2409: =item * &create_workbook()
1.255     matthew  2410: 
                   2411: Create an Excel worksheet.  If it fails, output message on the
                   2412: request object and return undefs.
                   2413: 
                   2414: Inputs: Apache request object
                   2415: 
                   2416: Returns (undef) on failure, 
                   2417:     Excel worksheet object, scalar with filename, and formats 
                   2418:     from &Apache::loncommon::define_excel_formats on success
                   2419: 
                   2420: =cut
                   2421: 
                   2422: ###############################################################
                   2423: ###############################################################
                   2424: sub create_workbook {
                   2425:     my ($r) = @_;
                   2426:         #
                   2427:     # Create the excel spreadsheet
                   2428:     my $filename = '/prtspool/'.
1.258     albertel 2429:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2430:         time.'_'.rand(1000000000).'.xls';
                   2431:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2432:     if (! defined($workbook)) {
                   2433:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2434:         $r->print(
                   2435:             '<p class="LC_error">'
                   2436:            .&mt('Problems occurred in creating the new Excel file.')
                   2437:            .' '.&mt('This error has been logged.')
                   2438:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2439:            .'</p>'
                   2440:         );
1.255     matthew  2441:         return (undef);
                   2442:     }
                   2443:     #
1.1014    foxr     2444:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2445:     #
                   2446:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2447:     return ($workbook,$filename,$format);
                   2448: }
                   2449: 
                   2450: ###############################################################
                   2451: ###############################################################
                   2452: 
                   2453: =pod
                   2454: 
1.648     raeburn  2455: =item * &create_text_file()
1.113     bowersj2 2456: 
1.542     raeburn  2457: Create a file to write to and eventually make available to the user.
1.256     matthew  2458: If file creation fails, outputs an error message on the request object and 
                   2459: return undefs.
1.113     bowersj2 2460: 
1.256     matthew  2461: Inputs: Apache request object, and file suffix
1.113     bowersj2 2462: 
1.256     matthew  2463: Returns (undef) on failure, 
                   2464:     Filehandle and filename on success.
1.113     bowersj2 2465: 
                   2466: =cut
                   2467: 
1.256     matthew  2468: ###############################################################
                   2469: ###############################################################
                   2470: sub create_text_file {
                   2471:     my ($r,$suffix) = @_;
                   2472:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2473:     my $fh;
                   2474:     my $filename = '/prtspool/'.
1.258     albertel 2475:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2476:         time.'_'.rand(1000000000).'.'.$suffix;
                   2477:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2478:     if (! defined($fh)) {
                   2479:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2480:         $r->print(
                   2481:             '<p class="LC_error">'
                   2482:            .&mt('Problems occurred in creating the output file.')
                   2483:            .' '.&mt('This error has been logged.')
                   2484:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2485:            .'</p>'
                   2486:         );
1.113     bowersj2 2487:     }
1.256     matthew  2488:     return ($fh,$filename)
1.113     bowersj2 2489: }
                   2490: 
                   2491: 
1.256     matthew  2492: =pod 
1.113     bowersj2 2493: 
                   2494: =back
                   2495: 
                   2496: =cut
1.37      matthew  2497: 
                   2498: ###############################################################
1.33      matthew  2499: ##        Home server <option> list generating code          ##
                   2500: ###############################################################
1.35      matthew  2501: 
1.169     www      2502: # ------------------------------------------
                   2503: 
                   2504: sub domain_select {
1.1289    raeburn  2505:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
                   2506:     my @possdoms;
                   2507:     if (ref($incdoms) eq 'ARRAY') {
                   2508:         @possdoms = @{$incdoms};
                   2509:     } else {
                   2510:         @possdoms = &Apache::lonnet::all_domains();
                   2511:     }
                   2512: 
1.169     www      2513:     my %domains=map { 
1.514     albertel 2514: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.1289    raeburn  2515:     } @possdoms;
                   2516: 
                   2517:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
                   2518:         foreach my $dom (@{$excdoms}) {
                   2519:             delete($domains{$dom});
                   2520:         }
                   2521:     }
                   2522: 
1.169     www      2523:     if ($multiple) {
                   2524: 	$domains{''}=&mt('Any domain');
1.550     albertel 2525: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2526: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2527:     } else {
1.550     albertel 2528: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2529: 	return &select_form($name,$value,\%domains);
1.169     www      2530:     }
                   2531: }
                   2532: 
1.282     albertel 2533: #-------------------------------------------
                   2534: 
                   2535: =pod
                   2536: 
1.519     raeburn  2537: =head1 Routines for form select boxes
                   2538: 
                   2539: =over 4
                   2540: 
1.648     raeburn  2541: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2542: 
                   2543: Returns a string containing a <select> element int multiple mode
                   2544: 
                   2545: 
                   2546: Args:
                   2547:   $name - name of the <select> element
1.506     raeburn  2548:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2549:   $size - number of rows long the select element is
1.283     albertel 2550:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2551:           (shown text should already have been &mt())
1.506     raeburn  2552:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2553: 
1.282     albertel 2554: =cut
                   2555: 
                   2556: #-------------------------------------------
1.169     www      2557: sub multiple_select_form {
1.284     albertel 2558:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2559:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2560:     my $output='';
1.191     matthew  2561:     if (! defined($size)) {
                   2562:         $size = 4;
1.283     albertel 2563:         if (scalar(keys(%$hash))<4) {
                   2564:             $size = scalar(keys(%$hash));
1.191     matthew  2565:         }
                   2566:     }
1.734     bisitz   2567:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2568:     my @order;
1.506     raeburn  2569:     if (ref($order) eq 'ARRAY')  {
                   2570:         @order = @{$order};
                   2571:     } else {
                   2572:         @order = sort(keys(%$hash));
1.501     banghart 2573:     }
                   2574:     if (exists($$hash{'select_form_order'})) {
                   2575:         @order = @{$$hash{'select_form_order'}};
                   2576:     }
                   2577:         
1.284     albertel 2578:     foreach my $key (@order) {
1.356     albertel 2579:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2580:         $output.='selected="selected" ' if ($selected{$key});
                   2581:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2582:     }
                   2583:     $output.="</select>\n";
                   2584:     return $output;
                   2585: }
                   2586: 
1.88      www      2587: #-------------------------------------------
                   2588: 
                   2589: =pod
                   2590: 
1.1254    raeburn  2591: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2592: 
                   2593: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2594: allow a user to select options from a ref to a hash containing:
                   2595: option_name => displayed text. An optional $onchange can include
1.1254    raeburn  2596: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2597: An optional arg -- $readonly -- if true will cause the select form
                   2598: to be disabled, e.g., for the case where an instructor has a section-
                   2599: specific role, and is viewing/modifying parameters. 
1.970     raeburn  2600: 
1.88      www      2601: See lonrights.pm for an example invocation and use.
                   2602: 
                   2603: =cut
                   2604: 
                   2605: #-------------------------------------------
                   2606: sub select_form {
1.1228    raeburn  2607:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2608:     return unless (ref($hashref) eq 'HASH');
                   2609:     if ($onchange) {
                   2610:         $onchange = ' onchange="'.$onchange.'"';
                   2611:     }
1.1228    raeburn  2612:     my $disabled;
                   2613:     if ($readonly) {
                   2614:         $disabled = ' disabled="disabled"';
                   2615:     }
                   2616:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2617:     my @keys;
1.970     raeburn  2618:     if (exists($hashref->{'select_form_order'})) {
                   2619: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2620:     } else {
1.970     raeburn  2621: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2622:     }
1.356     albertel 2623:     foreach my $key (@keys) {
                   2624:         $selectform.=
                   2625: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2626:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2627:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2628:     }
                   2629:     $selectform.="</select>";
                   2630:     return $selectform;
                   2631: }
                   2632: 
1.475     www      2633: # For display filters
                   2634: 
                   2635: sub display_filter {
1.1074    raeburn  2636:     my ($context) = @_;
1.475     www      2637:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2638:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2639:     my $phraseinput = 'hidden';
                   2640:     my $includeinput = 'hidden';
                   2641:     my ($checked,$includetypestext);
                   2642:     if ($env{'form.displayfilter'} eq 'containing') {
                   2643:         $phraseinput = 'text'; 
                   2644:         if ($context eq 'parmslog') {
                   2645:             $includeinput = 'checkbox';
                   2646:             if ($env{'form.includetypes'}) {
                   2647:                 $checked = ' checked="checked"';
                   2648:             }
                   2649:             $includetypestext = &mt('Include parameter types');
                   2650:         }
                   2651:     } else {
                   2652:         $includetypestext = '&nbsp;';
                   2653:     }
                   2654:     my ($additional,$secondid,$thirdid);
                   2655:     if ($context eq 'parmslog') {
                   2656:         $additional = 
                   2657:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2658:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2659:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2660:             '</label>';
                   2661:         $secondid = 'includetypes';
                   2662:         $thirdid = 'includetypestext';
                   2663:     }
                   2664:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2665:                                                     '$secondid','$thirdid')";
                   2666:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2667: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2668: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2669: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2670:            &mt('Filter: [_1]',
1.477     www      2671: 	   &select_form($env{'form.displayfilter'},
                   2672: 			'displayfilter',
1.970     raeburn  2673: 			{'currentfolder' => 'Current folder/page',
1.477     www      2674: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2675: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2676: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2677:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2678:                          '" />'.$additional;
                   2679: }
                   2680: 
                   2681: sub display_filter_js {
                   2682:     my $includetext = &mt('Include parameter types');
                   2683:     return <<"ENDJS";
                   2684:   
                   2685: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2686:     var firstType = 'hidden';
                   2687:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2688:         firstType = 'text';
                   2689:     }
                   2690:     firstObject = document.getElementById(firstid);
                   2691:     if (typeof(firstObject) == 'object') {
                   2692:         if (firstObject.type != firstType) {
                   2693:             changeInputType(firstObject,firstType);
                   2694:         }
                   2695:     }
                   2696:     if (context == 'parmslog') {
                   2697:         var secondType = 'hidden';
                   2698:         if (firstType == 'text') {
                   2699:             secondType = 'checkbox';
                   2700:         }
                   2701:         secondObject = document.getElementById(secondid);  
                   2702:         if (typeof(secondObject) == 'object') {
                   2703:             if (secondObject.type != secondType) {
                   2704:                 changeInputType(secondObject,secondType);
                   2705:             }
                   2706:         }
                   2707:         var textItem = document.getElementById(thirdid);
                   2708:         var currtext = textItem.innerHTML;
                   2709:         var newtext;
                   2710:         if (firstType == 'text') {
                   2711:             newtext = '$includetext';
                   2712:         } else {
                   2713:             newtext = '&nbsp;';
                   2714:         }
                   2715:         if (currtext != newtext) {
                   2716:             textItem.innerHTML = newtext;
                   2717:         }
                   2718:     }
                   2719:     return;
                   2720: }
                   2721: 
                   2722: function changeInputType(oldObject,newType) {
                   2723:     var newObject = document.createElement('input');
                   2724:     newObject.type = newType;
                   2725:     if (oldObject.size) {
                   2726:         newObject.size = oldObject.size;
                   2727:     }
                   2728:     if (oldObject.value) {
                   2729:         newObject.value = oldObject.value;
                   2730:     }
                   2731:     if (oldObject.name) {
                   2732:         newObject.name = oldObject.name;
                   2733:     }
                   2734:     if (oldObject.id) {
                   2735:         newObject.id = oldObject.id;
                   2736:     }
                   2737:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2738:     return;
                   2739: }
                   2740: 
                   2741: ENDJS
1.475     www      2742: }
                   2743: 
1.167     www      2744: sub gradeleveldescription {
                   2745:     my $gradelevel=shift;
                   2746:     my %gradelevels=(0 => 'Not specified',
                   2747: 		     1 => 'Grade 1',
                   2748: 		     2 => 'Grade 2',
                   2749: 		     3 => 'Grade 3',
                   2750: 		     4 => 'Grade 4',
                   2751: 		     5 => 'Grade 5',
                   2752: 		     6 => 'Grade 6',
                   2753: 		     7 => 'Grade 7',
                   2754: 		     8 => 'Grade 8',
                   2755: 		     9 => 'Grade 9',
                   2756: 		     10 => 'Grade 10',
                   2757: 		     11 => 'Grade 11',
                   2758: 		     12 => 'Grade 12',
                   2759: 		     13 => 'Grade 13',
                   2760: 		     14 => '100 Level',
                   2761: 		     15 => '200 Level',
                   2762: 		     16 => '300 Level',
                   2763: 		     17 => '400 Level',
                   2764: 		     18 => 'Graduate Level');
                   2765:     return &mt($gradelevels{$gradelevel});
                   2766: }
                   2767: 
1.163     www      2768: sub select_level_form {
                   2769:     my ($deflevel,$name)=@_;
                   2770:     unless ($deflevel) { $deflevel=0; }
1.167     www      2771:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2772:     for (my $i=0; $i<=18; $i++) {
                   2773:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2774:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2775:                 ">".&gradeleveldescription($i)."</option>\n";
                   2776:     }
                   2777:     $selectform.="</select>";
                   2778:     return $selectform;
1.163     www      2779: }
1.167     www      2780: 
1.35      matthew  2781: #-------------------------------------------
                   2782: 
1.45      matthew  2783: =pod
                   2784: 
1.1256    raeburn  2785: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2786: 
                   2787: Returns a string containing a <select name='$name' size='1'> form to 
                   2788: allow a user to select the domain to preform an operation in.  
                   2789: See loncreateuser.pm for an example invocation and use.
                   2790: 
1.90      www      2791: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2792: selected");
                   2793: 
1.743     raeburn  2794: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2795: 
1.910     raeburn  2796: 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.
                   2797: 
1.1121    raeburn  2798: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2799: 
                   2800: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  2801: 
1.1256    raeburn  2802: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
                   2803: 
1.35      matthew  2804: =cut
                   2805: 
                   2806: #-------------------------------------------
1.34      matthew  2807: sub select_dom_form {
1.1256    raeburn  2808:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2809:     if ($onchange) {
1.874     raeburn  2810:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2811:     }
1.1256    raeburn  2812:     if ($disabled) {
                   2813:         $disabled = ' disabled="disabled"';
                   2814:     }
1.1121    raeburn  2815:     my (@domains,%exclude);
1.910     raeburn  2816:     if (ref($incdoms) eq 'ARRAY') {
                   2817:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2818:     } else {
                   2819:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2820:     }
1.90      www      2821:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  2822:     if (ref($excdoms) eq 'ARRAY') {
                   2823:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   2824:     }
1.1256    raeburn  2825:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2826:     foreach my $dom (@domains) {
1.1121    raeburn  2827:         next if ($exclude{$dom});
1.356     albertel 2828:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2829:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2830:         if ($showdomdesc) {
                   2831:             if ($dom ne '') {
                   2832:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2833:                 if ($domdesc ne '') {
                   2834:                     $selectdomain .= ' ('.$domdesc.')';
                   2835:                 }
                   2836:             } 
                   2837:         }
                   2838:         $selectdomain .= "</option>\n";
1.34      matthew  2839:     }
                   2840:     $selectdomain.="</select>";
                   2841:     return $selectdomain;
                   2842: }
                   2843: 
1.35      matthew  2844: #-------------------------------------------
                   2845: 
1.45      matthew  2846: =pod
                   2847: 
1.648     raeburn  2848: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2849: 
1.586     raeburn  2850: input: 4 arguments (two required, two optional) - 
                   2851:     $domain - domain of new user
                   2852:     $name - name of form element
                   2853:     $default - Value of 'default' causes a default item to be first 
                   2854:                             option, and selected by default. 
                   2855:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2856:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2857: output: returns 2 items: 
1.586     raeburn  2858: (a) form element which contains either:
                   2859:    (i) <select name="$name">
                   2860:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2861:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2862:        </select>
                   2863:        form item if there are multiple library servers in $domain, or
                   2864:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2865:        if there is only one library server in $domain.
                   2866: 
                   2867: (b) number of library servers found.
                   2868: 
                   2869: See loncreateuser.pm for example of use.
1.35      matthew  2870: 
                   2871: =cut
                   2872: 
                   2873: #-------------------------------------------
1.586     raeburn  2874: sub home_server_form_item {
                   2875:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2876:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2877:     my $result;
                   2878:     my $numlib = keys(%servers);
                   2879:     if ($numlib > 1) {
                   2880:         $result .= '<select name="'.$name.'" />'."\n";
                   2881:         if ($default) {
1.804     bisitz   2882:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2883:                        '</option>'."\n";
                   2884:         }
                   2885:         foreach my $hostid (sort(keys(%servers))) {
                   2886:             $result.= '<option value="'.$hostid.'">'.
                   2887: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2888:         }
                   2889:         $result .= '</select>'."\n";
                   2890:     } elsif ($numlib == 1) {
                   2891:         my $hostid;
                   2892:         foreach my $item (keys(%servers)) {
                   2893:             $hostid = $item;
                   2894:         }
                   2895:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2896:                    $hostid.'" />';
                   2897:                    if (!$hide) {
                   2898:                        $result .= $hostid.' '.$servers{$hostid};
                   2899:                    }
                   2900:                    $result .= "\n";
                   2901:     } elsif ($default) {
                   2902:         $result .= '<input type="hidden" name="'.$name.
                   2903:                    '" value="default" />';
                   2904:                    if (!$hide) {
                   2905:                        $result .= &mt('default');
                   2906:                    }
                   2907:                    $result .= "\n";
1.33      matthew  2908:     }
1.586     raeburn  2909:     return ($result,$numlib);
1.33      matthew  2910: }
1.112     bowersj2 2911: 
                   2912: =pod
                   2913: 
1.534     albertel 2914: =back 
                   2915: 
1.112     bowersj2 2916: =cut
1.87      matthew  2917: 
                   2918: ###############################################################
1.112     bowersj2 2919: ##                  Decoding User Agent                      ##
1.87      matthew  2920: ###############################################################
                   2921: 
                   2922: =pod
                   2923: 
1.112     bowersj2 2924: =head1 Decoding the User Agent
                   2925: 
                   2926: =over 4
                   2927: 
                   2928: =item * &decode_user_agent()
1.87      matthew  2929: 
                   2930: Inputs: $r
                   2931: 
                   2932: Outputs:
                   2933: 
                   2934: =over 4
                   2935: 
1.112     bowersj2 2936: =item * $httpbrowser
1.87      matthew  2937: 
1.112     bowersj2 2938: =item * $clientbrowser
1.87      matthew  2939: 
1.112     bowersj2 2940: =item * $clientversion
1.87      matthew  2941: 
1.112     bowersj2 2942: =item * $clientmathml
1.87      matthew  2943: 
1.112     bowersj2 2944: =item * $clientunicode
1.87      matthew  2945: 
1.112     bowersj2 2946: =item * $clientos
1.87      matthew  2947: 
1.1137    raeburn  2948: =item * $clientmobile
                   2949: 
1.1141    raeburn  2950: =item * $clientinfo
                   2951: 
1.1194    raeburn  2952: =item * $clientosversion
                   2953: 
1.87      matthew  2954: =back
                   2955: 
1.157     matthew  2956: =back 
                   2957: 
1.87      matthew  2958: =cut
                   2959: 
                   2960: ###############################################################
                   2961: ###############################################################
                   2962: sub decode_user_agent {
1.247     albertel 2963:     my ($r)=@_;
1.87      matthew  2964:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2965:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2966:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2967:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2968:     my $clientbrowser='unknown';
                   2969:     my $clientversion='0';
                   2970:     my $clientmathml='';
                   2971:     my $clientunicode='0';
1.1137    raeburn  2972:     my $clientmobile=0;
1.1194    raeburn  2973:     my $clientosversion='';
1.87      matthew  2974:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  2975:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2976: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2977: 	    $clientbrowser=$bname;
                   2978:             $httpbrowser=~/$vreg/i;
                   2979: 	    $clientversion=$1;
                   2980:             $clientmathml=($clientversion>=$minv);
                   2981:             $clientunicode=($clientversion>=$univ);
                   2982: 	}
                   2983:     }
                   2984:     my $clientos='unknown';
1.1141    raeburn  2985:     my $clientinfo;
1.87      matthew  2986:     if (($httpbrowser=~/linux/i) ||
                   2987:         ($httpbrowser=~/unix/i) ||
                   2988:         ($httpbrowser=~/ux/i) ||
                   2989:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2990:     if (($httpbrowser=~/vax/i) ||
                   2991:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2992:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2993:     if (($httpbrowser=~/mac/i) ||
                   2994:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  2995:     if ($httpbrowser=~/win/i) {
                   2996:         $clientos='win';
                   2997:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2998:             $clientosversion = $1;
                   2999:         }
                   3000:     }
1.87      matthew  3001:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  3002:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   3003:         $clientmobile=lc($1);
                   3004:     }
1.1141    raeburn  3005:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   3006:         $clientinfo = 'firefox-'.$1;
                   3007:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   3008:         $clientinfo = 'chromeframe-'.$1;
                   3009:     }
1.87      matthew  3010:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  3011:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   3012:             $clientosversion);
1.87      matthew  3013: }
                   3014: 
1.32      matthew  3015: ###############################################################
                   3016: ##    Authentication changing form generation subroutines    ##
                   3017: ###############################################################
                   3018: ##
                   3019: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   3020: ## hash, and have reasonable default values.
                   3021: ##
                   3022: ##    formname = the name given in the <form> tag.
1.35      matthew  3023: #-------------------------------------------
                   3024: 
1.45      matthew  3025: =pod
                   3026: 
1.112     bowersj2 3027: =head1 Authentication Routines
                   3028: 
                   3029: =over 4
                   3030: 
1.648     raeburn  3031: =item * &authform_xxxxxx()
1.35      matthew  3032: 
                   3033: The authform_xxxxxx subroutines provide javascript and html forms which 
                   3034: handle some of the conveniences required for authentication forms.  
                   3035: This is not an optimal method, but it works.  
                   3036: 
                   3037: =over 4
                   3038: 
1.112     bowersj2 3039: =item * authform_header
1.35      matthew  3040: 
1.112     bowersj2 3041: =item * authform_authorwarning
1.35      matthew  3042: 
1.112     bowersj2 3043: =item * authform_nochange
1.35      matthew  3044: 
1.112     bowersj2 3045: =item * authform_kerberos
1.35      matthew  3046: 
1.112     bowersj2 3047: =item * authform_internal
1.35      matthew  3048: 
1.112     bowersj2 3049: =item * authform_filesystem
1.35      matthew  3050: 
1.1310    raeburn  3051: =item * authform_lti
                   3052: 
1.35      matthew  3053: =back
                   3054: 
1.648     raeburn  3055: See loncreateuser.pm for invocation and use examples.
1.157     matthew  3056: 
1.35      matthew  3057: =cut
                   3058: 
                   3059: #-------------------------------------------
1.32      matthew  3060: sub authform_header{  
                   3061:     my %in = (
                   3062:         formname => 'cu',
1.80      albertel 3063:         kerb_def_dom => '',
1.32      matthew  3064:         @_,
                   3065:     );
                   3066:     $in{'formname'} = 'document.' . $in{'formname'};
                   3067:     my $result='';
1.80      albertel 3068: 
                   3069: #---------------------------------------------- Code for upper case translation
                   3070:     my $Javascript_toUpperCase;
                   3071:     unless ($in{kerb_def_dom}) {
                   3072:         $Javascript_toUpperCase =<<"END";
                   3073:         switch (choice) {
                   3074:            case 'krb': currentform.elements[choicearg].value =
                   3075:                currentform.elements[choicearg].value.toUpperCase();
                   3076:                break;
                   3077:            default:
                   3078:         }
                   3079: END
                   3080:     } else {
                   3081:         $Javascript_toUpperCase = "";
                   3082:     }
                   3083: 
1.165     raeburn  3084:     my $radioval = "'nochange'";
1.591     raeburn  3085:     if (defined($in{'curr_authtype'})) {
                   3086:         if ($in{'curr_authtype'} ne '') {
                   3087:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   3088:         }
1.174     matthew  3089:     }
1.165     raeburn  3090:     my $argfield = 'null';
1.591     raeburn  3091:     if (defined($in{'mode'})) {
1.165     raeburn  3092:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  3093:             if (defined($in{'curr_autharg'})) {
                   3094:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  3095:                     $argfield = "'$in{'curr_autharg'}'";
                   3096:                 }
                   3097:             }
                   3098:         }
                   3099:     }
                   3100: 
1.32      matthew  3101:     $result.=<<"END";
                   3102: var current = new Object();
1.165     raeburn  3103: current.radiovalue = $radioval;
                   3104: current.argfield = $argfield;
1.32      matthew  3105: 
                   3106: function changed_radio(choice,currentform) {
                   3107:     var choicearg = choice + 'arg';
                   3108:     // If a radio button in changed, we need to change the argfield
                   3109:     if (current.radiovalue != choice) {
                   3110:         current.radiovalue = choice;
                   3111:         if (current.argfield != null) {
                   3112:             currentform.elements[current.argfield].value = '';
                   3113:         }
                   3114:         if (choice == 'nochange') {
                   3115:             current.argfield = null;
                   3116:         } else {
                   3117:             current.argfield = choicearg;
                   3118:             switch(choice) {
                   3119:                 case 'krb': 
                   3120:                     currentform.elements[current.argfield].value = 
                   3121:                         "$in{'kerb_def_dom'}";
                   3122:                 break;
                   3123:               default:
                   3124:                 break;
                   3125:             }
                   3126:         }
                   3127:     }
                   3128:     return;
                   3129: }
1.22      www      3130: 
1.32      matthew  3131: function changed_text(choice,currentform) {
                   3132:     var choicearg = choice + 'arg';
                   3133:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 3134:         $Javascript_toUpperCase
1.32      matthew  3135:         // clear old field
                   3136:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   3137:             currentform.elements[current.argfield].value = '';
                   3138:         }
                   3139:         current.argfield = choicearg;
                   3140:     }
                   3141:     set_auth_radio_buttons(choice,currentform);
                   3142:     return;
1.20      www      3143: }
1.32      matthew  3144: 
                   3145: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  3146:     var numauthchoices = currentform.login.length;
                   3147:     if (typeof numauthchoices  == "undefined") {
                   3148:         return;
                   3149:     } 
1.32      matthew  3150:     var i=0;
1.986     raeburn  3151:     while (i < numauthchoices) {
1.32      matthew  3152:         if (currentform.login[i].value == newvalue) { break; }
                   3153:         i++;
                   3154:     }
1.986     raeburn  3155:     if (i == numauthchoices) {
1.32      matthew  3156:         return;
                   3157:     }
                   3158:     current.radiovalue = newvalue;
                   3159:     currentform.login[i].checked = true;
                   3160:     return;
                   3161: }
                   3162: END
                   3163:     return $result;
                   3164: }
                   3165: 
1.1106    raeburn  3166: sub authform_authorwarning {
1.32      matthew  3167:     my $result='';
1.144     matthew  3168:     $result='<i>'.
                   3169:         &mt('As a general rule, only authors or co-authors should be '.
                   3170:             'filesystem authenticated '.
                   3171:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  3172:     return $result;
                   3173: }
                   3174: 
1.1106    raeburn  3175: sub authform_nochange {
1.32      matthew  3176:     my %in = (
                   3177:               formname => 'document.cu',
                   3178:               kerb_def_dom => 'MSU.EDU',
                   3179:               @_,
                   3180:           );
1.1106    raeburn  3181:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  3182:     my $result;
1.1104    raeburn  3183:     if (!$authnum) {
1.1105    raeburn  3184:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  3185:     } else {
                   3186:         $result = '<label>'.&mt('[_1] Do not change login data',
                   3187:                   '<input type="radio" name="login" value="nochange" '.
                   3188:                   'checked="checked" onclick="'.
1.281     albertel 3189:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   3190: 	    '</label>';
1.586     raeburn  3191:     }
1.32      matthew  3192:     return $result;
                   3193: }
                   3194: 
1.591     raeburn  3195: sub authform_kerberos {
1.32      matthew  3196:     my %in = (
                   3197:               formname => 'document.cu',
                   3198:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 3199:               kerb_def_auth => 'krb4',
1.32      matthew  3200:               @_,
                   3201:               );
1.586     raeburn  3202:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1259    raeburn  3203:         $autharg,$jscall,$disabled);
1.1106    raeburn  3204:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 3205:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   3206:        $check5 = ' checked="checked"';
1.80      albertel 3207:     } else {
1.772     bisitz   3208:        $check4 = ' checked="checked"';
1.80      albertel 3209:     }
1.1259    raeburn  3210:     if ($in{'readonly'}) {
                   3211:         $disabled = ' disabled="disabled"';
                   3212:     }
1.165     raeburn  3213:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  3214:     if (defined($in{'curr_authtype'})) {
                   3215:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   3216:             $krbcheck = ' checked="checked"';
1.623     raeburn  3217:             if (defined($in{'mode'})) {
                   3218:                 if ($in{'mode'} eq 'modifyuser') {
                   3219:                     $krbcheck = '';
                   3220:                 }
                   3221:             }
1.591     raeburn  3222:             if (defined($in{'curr_kerb_ver'})) {
                   3223:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   3224:                     $check5 = ' checked="checked"';
1.591     raeburn  3225:                     $check4 = '';
                   3226:                 } else {
1.772     bisitz   3227:                     $check4 = ' checked="checked"';
1.591     raeburn  3228:                     $check5 = '';
                   3229:                 }
1.586     raeburn  3230:             }
1.591     raeburn  3231:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  3232:                 $krbarg = $in{'curr_autharg'};
                   3233:             }
1.586     raeburn  3234:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  3235:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3236:                     $result = 
                   3237:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   3238:         $in{'curr_autharg'},$krbver);
                   3239:                 } else {
                   3240:                     $result =
                   3241:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   3242:                 }
                   3243:                 return $result; 
                   3244:             }
                   3245:         }
                   3246:     } else {
                   3247:         if ($authnum == 1) {
1.784     bisitz   3248:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  3249:         }
                   3250:     }
1.586     raeburn  3251:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   3252:         return;
1.587     raeburn  3253:     } elsif ($authtype eq '') {
1.591     raeburn  3254:         if (defined($in{'mode'})) {
1.587     raeburn  3255:             if ($in{'mode'} eq 'modifycourse') {
                   3256:                 if ($authnum == 1) {
1.1259    raeburn  3257:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  3258:                 }
                   3259:             }
                   3260:         }
1.586     raeburn  3261:     }
                   3262:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   3263:     if ($authtype eq '') {
                   3264:         $authtype = '<input type="radio" name="login" value="krb" '.
                   3265:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1259    raeburn  3266:                     $krbcheck.$disabled.' />';
1.586     raeburn  3267:     }
                   3268:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  3269:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  3270:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  3271:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  3272:          $in{'curr_authtype'} eq 'krb4')) {
                   3273:         $result .= &mt
1.144     matthew  3274:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 3275:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  3276:          '<label>'.$authtype,
1.281     albertel 3277:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  3278:              'value="'.$krbarg.'" '.
1.1259    raeburn  3279:              'onchange="'.$jscall.'"'.$disabled.' />',
                   3280:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   3281:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 3282: 	 '</label>');
1.586     raeburn  3283:     } elsif ($can_assign{'krb4'}) {
                   3284:         $result .= &mt
                   3285:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3286:          '[_3] Version 4 [_4]',
                   3287:          '<label>'.$authtype,
                   3288:          '</label><input type="text" size="10" name="krbarg" '.
                   3289:              'value="'.$krbarg.'" '.
1.1259    raeburn  3290:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3291:          '<label><input type="hidden" name="krbver" value="4" />',
                   3292:          '</label>');
                   3293:     } elsif ($can_assign{'krb5'}) {
                   3294:         $result .= &mt
                   3295:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3296:          '[_3] Version 5 [_4]',
                   3297:          '<label>'.$authtype,
                   3298:          '</label><input type="text" size="10" name="krbarg" '.
                   3299:              'value="'.$krbarg.'" '.
1.1259    raeburn  3300:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3301:          '<label><input type="hidden" name="krbver" value="5" />',
                   3302:          '</label>');
                   3303:     }
1.32      matthew  3304:     return $result;
                   3305: }
                   3306: 
1.1106    raeburn  3307: sub authform_internal {
1.586     raeburn  3308:     my %in = (
1.32      matthew  3309:                 formname => 'document.cu',
                   3310:                 kerb_def_dom => 'MSU.EDU',
                   3311:                 @_,
                   3312:                 );
1.1259    raeburn  3313:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3314:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3315:     if ($in{'readonly'}) {
                   3316:         $disabled = ' disabled="disabled"';
                   3317:     }
1.591     raeburn  3318:     if (defined($in{'curr_authtype'})) {
                   3319:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3320:             if ($can_assign{'int'}) {
1.772     bisitz   3321:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3322:                 if (defined($in{'mode'})) {
                   3323:                     if ($in{'mode'} eq 'modifyuser') {
                   3324:                         $intcheck = '';
                   3325:                     }
                   3326:                 }
1.591     raeburn  3327:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3328:                     $intarg = $in{'curr_autharg'};
                   3329:                 }
                   3330:             } else {
                   3331:                 $result = &mt('Currently internally authenticated.');
                   3332:                 return $result;
1.165     raeburn  3333:             }
                   3334:         }
1.586     raeburn  3335:     } else {
                   3336:         if ($authnum == 1) {
1.784     bisitz   3337:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3338:         }
                   3339:     }
                   3340:     if (!$can_assign{'int'}) {
                   3341:         return;
1.587     raeburn  3342:     } elsif ($authtype eq '') {
1.591     raeburn  3343:         if (defined($in{'mode'})) {
1.587     raeburn  3344:             if ($in{'mode'} eq 'modifycourse') {
                   3345:                 if ($authnum == 1) {
1.1259    raeburn  3346:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3347:                 }
                   3348:             }
                   3349:         }
1.165     raeburn  3350:     }
1.586     raeburn  3351:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3352:     if ($authtype eq '') {
                   3353:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1259    raeburn  3354:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3355:     }
1.605     bisitz   3356:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1259    raeburn  3357:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3358:     $result = &mt
1.144     matthew  3359:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3360:          '<label>'.$authtype,'</label>'.$autharg);
1.1259    raeburn  3361:     $result.='<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.intarg.type='."'text'".' } else { this.form.intarg.type='."'password'".' }"'.$disabled.' />'.&mt('Visible input').'</label>';
1.32      matthew  3362:     return $result;
                   3363: }
                   3364: 
1.1104    raeburn  3365: sub authform_local {
1.32      matthew  3366:     my %in = (
                   3367:               formname => 'document.cu',
                   3368:               kerb_def_dom => 'MSU.EDU',
                   3369:               @_,
                   3370:               );
1.1259    raeburn  3371:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3372:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3373:     if ($in{'readonly'}) {
                   3374:         $disabled = ' disabled="disabled"';
                   3375:     } 
1.591     raeburn  3376:     if (defined($in{'curr_authtype'})) {
                   3377:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3378:             if ($can_assign{'loc'}) {
1.772     bisitz   3379:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3380:                 if (defined($in{'mode'})) {
                   3381:                     if ($in{'mode'} eq 'modifyuser') {
                   3382:                         $loccheck = '';
                   3383:                     }
                   3384:                 }
1.591     raeburn  3385:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3386:                     $locarg = $in{'curr_autharg'};
                   3387:                 }
                   3388:             } else {
                   3389:                 $result = &mt('Currently using local (institutional) authentication.');
                   3390:                 return $result;
1.165     raeburn  3391:             }
                   3392:         }
1.586     raeburn  3393:     } else {
                   3394:         if ($authnum == 1) {
1.784     bisitz   3395:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3396:         }
                   3397:     }
                   3398:     if (!$can_assign{'loc'}) {
                   3399:         return;
1.587     raeburn  3400:     } elsif ($authtype eq '') {
1.591     raeburn  3401:         if (defined($in{'mode'})) {
1.587     raeburn  3402:             if ($in{'mode'} eq 'modifycourse') {
                   3403:                 if ($authnum == 1) {
1.1259    raeburn  3404:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3405:                 }
                   3406:             }
                   3407:         }
1.165     raeburn  3408:     }
1.586     raeburn  3409:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3410:     if ($authtype eq '') {
                   3411:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3412:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3413:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3414:     }
                   3415:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1259    raeburn  3416:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3417:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3418:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3419:     return $result;
                   3420: }
                   3421: 
1.1106    raeburn  3422: sub authform_filesystem {
1.32      matthew  3423:     my %in = (
                   3424:               formname => 'document.cu',
                   3425:               kerb_def_dom => 'MSU.EDU',
                   3426:               @_,
                   3427:               );
1.1259    raeburn  3428:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3429:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3430:     if ($in{'readonly'}) {
                   3431:         $disabled = ' disabled="disabled"';
                   3432:     }
1.591     raeburn  3433:     if (defined($in{'curr_authtype'})) {
                   3434:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3435:             if ($can_assign{'fsys'}) {
1.772     bisitz   3436:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3437:                 if (defined($in{'mode'})) {
                   3438:                     if ($in{'mode'} eq 'modifyuser') {
                   3439:                         $fsyscheck = '';
                   3440:                     }
                   3441:                 }
1.586     raeburn  3442:             } else {
                   3443:                 $result = &mt('Currently Filesystem Authenticated.');
                   3444:                 return $result;
1.1259    raeburn  3445:             }
1.586     raeburn  3446:         }
                   3447:     } else {
                   3448:         if ($authnum == 1) {
1.784     bisitz   3449:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3450:         }
                   3451:     }
                   3452:     if (!$can_assign{'fsys'}) {
                   3453:         return;
1.587     raeburn  3454:     } elsif ($authtype eq '') {
1.591     raeburn  3455:         if (defined($in{'mode'})) {
1.587     raeburn  3456:             if ($in{'mode'} eq 'modifycourse') {
                   3457:                 if ($authnum == 1) {
1.1259    raeburn  3458:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3459:                 }
                   3460:             }
                   3461:         }
1.586     raeburn  3462:     }
                   3463:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3464:     if ($authtype eq '') {
                   3465:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3466:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3467:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3468:     }
1.1310    raeburn  3469:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
1.1259    raeburn  3470:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3471:     $result = &mt
1.144     matthew  3472:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.1310    raeburn  3473:          '<label>'.$authtype,'</label>'.$autharg);
                   3474:     return $result;
                   3475: }
                   3476: 
                   3477: sub authform_lti {
                   3478:     my %in = (
                   3479:               formname => 'document.cu',
                   3480:               kerb_def_dom => 'MSU.EDU',
                   3481:               @_,
                   3482:               );
                   3483:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
                   3484:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
                   3485:     if ($in{'readonly'}) {
                   3486:         $disabled = ' disabled="disabled"';
                   3487:     }
                   3488:     if (defined($in{'curr_authtype'})) {
                   3489:         if ($in{'curr_authtype'} eq 'lti') {
                   3490:             if ($can_assign{'lti'}) {
                   3491:                 $lticheck = 'checked="checked" ';
                   3492:                 if (defined($in{'mode'})) {
                   3493:                     if ($in{'mode'} eq 'modifyuser') {
                   3494:                         $lticheck = '';
                   3495:                     }
                   3496:                 }
                   3497:             } else {
                   3498:                 $result = &mt('Currently LTI Authenticated.');
                   3499:                 return $result;
                   3500:             }
                   3501:         }
                   3502:     } else {
                   3503:         if ($authnum == 1) {
                   3504:             $authtype = '<input type="hidden" name="login" value="lti" />';
                   3505:         }
                   3506:     }
                   3507:     if (!$can_assign{'lti'}) {
                   3508:         return;
                   3509:     } elsif ($authtype eq '') {
                   3510:         if (defined($in{'mode'})) {
                   3511:             if ($in{'mode'} eq 'modifycourse') {
                   3512:                 if ($authnum == 1) {
                   3513:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
                   3514:                 }
                   3515:             }
                   3516:         }
                   3517:     }
                   3518:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
                   3519:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
                   3520:         $authtype = '<input type="radio" name="login" value="lti" '.
                   3521:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
                   3522:                     $jscall.'"'.$disabled.' />';
                   3523:     }
                   3524:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
                   3525:     if ($authtype) {
                   3526:         $result = &mt('[_1] LTI Authenticated',
                   3527:                       '<label>'.$authtype.'</label>'.$autharg);
                   3528:     } else {
                   3529:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
                   3530:                   $autharg;
                   3531:     }
1.32      matthew  3532:     return $result;
                   3533: }
                   3534: 
1.586     raeburn  3535: sub get_assignable_auth {
                   3536:     my ($dom) = @_;
                   3537:     if ($dom eq '') {
                   3538:         $dom = $env{'request.role.domain'};
                   3539:     }
                   3540:     my %can_assign = (
                   3541:                           krb4 => 1,
                   3542:                           krb5 => 1,
                   3543:                           int  => 1,
                   3544:                           loc  => 1,
1.1310    raeburn  3545:                           lti  => 1,
1.586     raeburn  3546:                      );
                   3547:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3548:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3549:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3550:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3551:             my $context;
                   3552:             if ($env{'request.role'} =~ /^au/) {
                   3553:                 $context = 'author';
1.1259    raeburn  3554:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3555:                 $context = 'domain';
                   3556:             } elsif ($env{'request.course.id'}) {
                   3557:                 $context = 'course';
                   3558:             }
                   3559:             if ($context) {
                   3560:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3561:                    %can_assign = %{$authhash->{$context}}; 
                   3562:                 }
                   3563:             }
                   3564:         }
                   3565:     }
                   3566:     my $authnum = 0;
                   3567:     foreach my $key (keys(%can_assign)) {
                   3568:         if ($can_assign{$key}) {
                   3569:             $authnum ++;
                   3570:         }
                   3571:     }
                   3572:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3573:         $authnum --;
                   3574:     }
                   3575:     return ($authnum,%can_assign);
                   3576: }
                   3577: 
1.1331    raeburn  3578: sub check_passwd_rules {
                   3579:     my ($domain,$plainpass) = @_;
                   3580:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3581:     my ($min,$max,@chars,@brokerule,$warning);
1.1333    raeburn  3582:     $min = $Apache::lonnet::passwdmin;
1.1331    raeburn  3583:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3584:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1333    raeburn  3585:             if ($passwdconf{'min'} > $min) {
                   3586:                 $min = $passwdconf{'min'};
                   3587:             }
1.1331    raeburn  3588:         }
                   3589:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3590:             $max = $passwdconf{'max'};
                   3591:         }
                   3592:         @chars = @{$passwdconf{'chars'}};
                   3593:     }
                   3594:     if (($min) && (length($plainpass) < $min)) {
                   3595:         push(@brokerule,'min');
                   3596:     }
                   3597:     if (($max) && (length($plainpass) > $max)) {
                   3598:         push(@brokerule,'max');
                   3599:     }
                   3600:     if (@chars) {
                   3601:         my %rules;
                   3602:         map { $rules{$_} = 1; } @chars;
                   3603:         if ($rules{'uc'}) {
                   3604:             unless ($plainpass =~ /[A-Z]/) {
                   3605:                 push(@brokerule,'uc');
                   3606:             }
                   3607:         }
                   3608:         if ($rules{'lc'}) {
1.1332    raeburn  3609:             unless ($plainpass =~ /[a-z]/) {
1.1331    raeburn  3610:                 push(@brokerule,'lc');
                   3611:             }
                   3612:         }
                   3613:         if ($rules{'num'}) {
                   3614:             unless ($plainpass =~ /\d/) {
                   3615:                 push(@brokerule,'num');
                   3616:             }
                   3617:         }
                   3618:         if ($rules{'spec'}) {
                   3619:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3620:                 push(@brokerule,'spec');
                   3621:             }
                   3622:         }
                   3623:     }
                   3624:     if (@brokerule) {
                   3625:         my %rulenames = &Apache::lonlocal::texthash(
                   3626:             uc   => 'At least one upper case letter',
                   3627:             lc   => 'At least one lower case letter',
                   3628:             num  => 'At least one number',
                   3629:             spec => 'At least one non-alphanumeric',
                   3630:         );
                   3631:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3632:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3633:         $rulenames{'num'} .= ': 0123456789';
                   3634:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3635:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3636:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3637:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1336    raeburn  3638:         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1331    raeburn  3639:             if (grep(/^$rule$/,@brokerule)) {
                   3640:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3641:             }
                   3642:         }
                   3643:         $warning .= '</ul>';
                   3644:     }
1.1332    raeburn  3645:     if (wantarray) {
                   3646:         return @brokerule;
                   3647:     }
1.1331    raeburn  3648:     return $warning;
                   3649: }
                   3650: 
1.80      albertel 3651: ###############################################################
                   3652: ##    Get Kerberos Defaults for Domain                 ##
                   3653: ###############################################################
                   3654: ##
                   3655: ## Returns default kerberos version and an associated argument
                   3656: ## as listed in file domain.tab. If not listed, provides
                   3657: ## appropriate default domain and kerberos version.
                   3658: ##
                   3659: #-------------------------------------------
                   3660: 
                   3661: =pod
                   3662: 
1.648     raeburn  3663: =item * &get_kerberos_defaults()
1.80      albertel 3664: 
                   3665: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3666: version and domain. If not found, it defaults to version 4 and the 
                   3667: domain of the server.
1.80      albertel 3668: 
1.648     raeburn  3669: =over 4
                   3670: 
1.80      albertel 3671: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3672: 
1.648     raeburn  3673: =back
                   3674: 
                   3675: =back
                   3676: 
1.80      albertel 3677: =cut
                   3678: 
                   3679: #-------------------------------------------
                   3680: sub get_kerberos_defaults {
                   3681:     my $domain=shift;
1.641     raeburn  3682:     my ($krbdef,$krbdefdom);
                   3683:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3684:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3685:         $krbdef = $domdefaults{'auth_def'};
                   3686:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3687:     } else {
1.80      albertel 3688:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3689:         my $krbdefdom=$1;
                   3690:         $krbdefdom=~tr/a-z/A-Z/;
                   3691:         $krbdef = "krb4";
                   3692:     }
                   3693:     return ($krbdef,$krbdefdom);
                   3694: }
1.112     bowersj2 3695: 
1.32      matthew  3696: 
1.46      matthew  3697: ###############################################################
                   3698: ##                Thesaurus Functions                        ##
                   3699: ###############################################################
1.20      www      3700: 
1.46      matthew  3701: =pod
1.20      www      3702: 
1.112     bowersj2 3703: =head1 Thesaurus Functions
                   3704: 
                   3705: =over 4
                   3706: 
1.648     raeburn  3707: =item * &initialize_keywords()
1.46      matthew  3708: 
                   3709: Initializes the package variable %Keywords if it is empty.  Uses the
                   3710: package variable $thesaurus_db_file.
                   3711: 
                   3712: =cut
                   3713: 
                   3714: ###################################################
                   3715: 
                   3716: sub initialize_keywords {
                   3717:     return 1 if (scalar keys(%Keywords));
                   3718:     # If we are here, %Keywords is empty, so fill it up
                   3719:     #   Make sure the file we need exists...
                   3720:     if (! -e $thesaurus_db_file) {
                   3721:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3722:                                  " failed because it does not exist");
                   3723:         return 0;
                   3724:     }
                   3725:     #   Set up the hash as a database
                   3726:     my %thesaurus_db;
                   3727:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3728:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3729:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3730:                                  $thesaurus_db_file);
                   3731:         return 0;
                   3732:     } 
                   3733:     #  Get the average number of appearances of a word.
                   3734:     my $avecount = $thesaurus_db{'average.count'};
                   3735:     #  Put keywords (those that appear > average) into %Keywords
                   3736:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3737:         my ($count,undef) = split /:/,$data;
                   3738:         $Keywords{$word}++ if ($count > $avecount);
                   3739:     }
                   3740:     untie %thesaurus_db;
                   3741:     # Remove special values from %Keywords.
1.356     albertel 3742:     foreach my $value ('total.count','average.count') {
                   3743:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3744:   }
1.46      matthew  3745:     return 1;
                   3746: }
                   3747: 
                   3748: ###################################################
                   3749: 
                   3750: =pod
                   3751: 
1.648     raeburn  3752: =item * &keyword($word)
1.46      matthew  3753: 
                   3754: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3755: than the average number of times in the thesaurus database.  Calls 
                   3756: &initialize_keywords
                   3757: 
                   3758: =cut
                   3759: 
                   3760: ###################################################
1.20      www      3761: 
                   3762: sub keyword {
1.46      matthew  3763:     return if (!&initialize_keywords());
                   3764:     my $word=lc(shift());
                   3765:     $word=~s/\W//g;
                   3766:     return exists($Keywords{$word});
1.20      www      3767: }
1.46      matthew  3768: 
                   3769: ###############################################################
                   3770: 
                   3771: =pod 
1.20      www      3772: 
1.648     raeburn  3773: =item * &get_related_words()
1.46      matthew  3774: 
1.160     matthew  3775: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3776: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3777: will be returned.  The order of the words returned is determined by the
                   3778: database which holds them.
                   3779: 
                   3780: Uses global $thesaurus_db_file.
                   3781: 
1.1057    foxr     3782: 
1.46      matthew  3783: =cut
                   3784: 
                   3785: ###############################################################
                   3786: sub get_related_words {
                   3787:     my $keyword = shift;
                   3788:     my %thesaurus_db;
                   3789:     if (! -e $thesaurus_db_file) {
                   3790:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3791:                                  "failed because the file does not exist");
                   3792:         return ();
                   3793:     }
                   3794:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3795:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3796:         return ();
                   3797:     } 
                   3798:     my @Words=();
1.429     www      3799:     my $count=0;
1.46      matthew  3800:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3801: 	# The first element is the number of times
                   3802: 	# the word appears.  We do not need it now.
1.429     www      3803: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3804: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3805: 	my $threshold=$mostfrequentcount/10;
                   3806:         foreach my $possibleword (@RelatedWords) {
                   3807:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3808:             if ($wordcount>$threshold) {
                   3809: 		push(@Words,$word);
                   3810:                 $count++;
                   3811:                 if ($count>10) { last; }
                   3812: 	    }
1.20      www      3813:         }
                   3814:     }
1.46      matthew  3815:     untie %thesaurus_db;
                   3816:     return @Words;
1.14      harris41 3817: }
1.1090    foxr     3818: ###############################################################
                   3819: #
                   3820: #  Spell checking
                   3821: #
                   3822: 
                   3823: =pod
                   3824: 
1.1142    raeburn  3825: =back
                   3826: 
1.1090    foxr     3827: =head1 Spell checking
                   3828: 
                   3829: =over 4
                   3830: 
                   3831: =item * &check_spelling($wordlist $language)
                   3832: 
                   3833: Takes a string containing words and feeds it to an external
                   3834: spellcheck program via a pipeline. Returns a string containing
                   3835: them mis-spelled words.
                   3836: 
                   3837: Parameters:
                   3838: 
                   3839: =over 4
                   3840: 
                   3841: =item - $wordlist
                   3842: 
                   3843: String that will be fed into the spellcheck program.
                   3844: 
                   3845: =item - $language
                   3846: 
                   3847: Language string that specifies the language for which the spell
                   3848: check will be performed.
                   3849: 
                   3850: =back
                   3851: 
                   3852: =back
                   3853: 
                   3854: Note: This sub assumes that aspell is installed.
                   3855: 
                   3856: 
                   3857: =cut
                   3858: 
1.46      matthew  3859: 
1.1090    foxr     3860: sub check_spelling {
                   3861:     my ($wordlist, $language) = @_;
1.1091    foxr     3862:     my @misspellings;
                   3863:     
                   3864:     # Generate the speller and set the langauge.
                   3865:     # if explicitly selected:
1.1090    foxr     3866: 
1.1091    foxr     3867:     my $speller = Text::Aspell->new;
1.1090    foxr     3868:     if ($language) {
1.1091    foxr     3869: 	$speller->set_option('lang', $language);
1.1090    foxr     3870:     }
                   3871: 
1.1091    foxr     3872:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     3873: 
1.1091    foxr     3874:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     3875: 
1.1091    foxr     3876:     foreach my $word (@words) {
                   3877: 	if(! $speller->check($word)) {
                   3878: 	    push(@misspellings, $word);
1.1090    foxr     3879: 	}
                   3880:     }
1.1091    foxr     3881:     return join(' ', @misspellings);
                   3882:     
1.1090    foxr     3883: }
                   3884: 
1.61      www      3885: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3886: =pod
                   3887: 
1.112     bowersj2 3888: =head1 User Name Functions
                   3889: 
                   3890: =over 4
                   3891: 
1.648     raeburn  3892: =item * &plainname($uname,$udom,$first)
1.81      albertel 3893: 
1.112     bowersj2 3894: Takes a users logon name and returns it as a string in
1.226     albertel 3895: "first middle last generation" form 
                   3896: if $first is set to 'lastname' then it returns it as
                   3897: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3898: 
                   3899: =cut
1.61      www      3900: 
1.295     www      3901: 
1.81      albertel 3902: ###############################################################
1.61      www      3903: sub plainname {
1.226     albertel 3904:     my ($uname,$udom,$first)=@_;
1.537     albertel 3905:     return if (!defined($uname) || !defined($udom));
1.295     www      3906:     my %names=&getnames($uname,$udom);
1.226     albertel 3907:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3908: 					  $names{'middlename'},
                   3909: 					  $names{'lastname'},
                   3910: 					  $names{'generation'},$first);
                   3911:     $name=~s/^\s+//;
1.62      www      3912:     $name=~s/\s+$//;
                   3913:     $name=~s/\s+/ /g;
1.353     albertel 3914:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3915:     return $name;
1.61      www      3916: }
1.66      www      3917: 
                   3918: # -------------------------------------------------------------------- Nickname
1.81      albertel 3919: =pod
                   3920: 
1.648     raeburn  3921: =item * &nickname($uname,$udom)
1.81      albertel 3922: 
                   3923: Gets a users name and returns it as a string as
                   3924: 
                   3925: "&quot;nickname&quot;"
1.66      www      3926: 
1.81      albertel 3927: if the user has a nickname or
                   3928: 
                   3929: "first middle last generation"
                   3930: 
                   3931: if the user does not
                   3932: 
                   3933: =cut
1.66      www      3934: 
                   3935: sub nickname {
                   3936:     my ($uname,$udom)=@_;
1.537     albertel 3937:     return if (!defined($uname) || !defined($udom));
1.295     www      3938:     my %names=&getnames($uname,$udom);
1.68      albertel 3939:     my $name=$names{'nickname'};
1.66      www      3940:     if ($name) {
                   3941:        $name='&quot;'.$name.'&quot;'; 
                   3942:     } else {
                   3943:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3944: 	     $names{'lastname'}.' '.$names{'generation'};
                   3945:        $name=~s/\s+$//;
                   3946:        $name=~s/\s+/ /g;
                   3947:     }
                   3948:     return $name;
                   3949: }
                   3950: 
1.295     www      3951: sub getnames {
                   3952:     my ($uname,$udom)=@_;
1.537     albertel 3953:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3954:     if ($udom eq 'public' && $uname eq 'public') {
                   3955: 	return ('lastname' => &mt('Public'));
                   3956:     }
1.295     www      3957:     my $id=$uname.':'.$udom;
                   3958:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3959:     if ($cached) {
                   3960: 	return %{$names};
                   3961:     } else {
                   3962: 	my %loadnames=&Apache::lonnet::get('environment',
                   3963:                     ['firstname','middlename','lastname','generation','nickname'],
                   3964: 					 $udom,$uname);
                   3965: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3966: 	return %loadnames;
                   3967:     }
                   3968: }
1.61      www      3969: 
1.542     raeburn  3970: # -------------------------------------------------------------------- getemails
1.648     raeburn  3971: 
1.542     raeburn  3972: =pod
                   3973: 
1.648     raeburn  3974: =item * &getemails($uname,$udom)
1.542     raeburn  3975: 
                   3976: Gets a user's email information and returns it as a hash with keys:
                   3977: notification, critnotification, permanentemail
                   3978: 
                   3979: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3980: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3981:  
1.648     raeburn  3982: 
1.542     raeburn  3983: =cut
                   3984: 
1.648     raeburn  3985: 
1.466     albertel 3986: sub getemails {
                   3987:     my ($uname,$udom)=@_;
                   3988:     if ($udom eq 'public' && $uname eq 'public') {
                   3989: 	return;
                   3990:     }
1.467     www      3991:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3992:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3993:     my $id=$uname.':'.$udom;
                   3994:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3995:     if ($cached) {
                   3996: 	return %{$names};
                   3997:     } else {
                   3998: 	my %loadnames=&Apache::lonnet::get('environment',
                   3999:                     			   ['notification','critnotification',
                   4000: 					    'permanentemail'],
                   4001: 					   $udom,$uname);
                   4002: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   4003: 	return %loadnames;
                   4004:     }
                   4005: }
                   4006: 
1.551     albertel 4007: sub flush_email_cache {
                   4008:     my ($uname,$udom)=@_;
                   4009:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4010:     if (!$uname) { $uname=$env{'user.name'};   }
                   4011:     return if ($udom eq 'public' && $uname eq 'public');
                   4012:     my $id=$uname.':'.$udom;
                   4013:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   4014: }
                   4015: 
1.728     raeburn  4016: # -------------------------------------------------------------------- getlangs
                   4017: 
                   4018: =pod
                   4019: 
                   4020: =item * &getlangs($uname,$udom)
                   4021: 
                   4022: Gets a user's language preference and returns it as a hash with key:
                   4023: language.
                   4024: 
                   4025: =cut
                   4026: 
                   4027: 
                   4028: sub getlangs {
                   4029:     my ($uname,$udom) = @_;
                   4030:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4031:     if (!$uname) { $uname=$env{'user.name'};   }
                   4032:     my $id=$uname.':'.$udom;
                   4033:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   4034:     if ($cached) {
                   4035:         return %{$langs};
                   4036:     } else {
                   4037:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   4038:                                            $udom,$uname);
                   4039:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   4040:         return %loadlangs;
                   4041:     }
                   4042: }
                   4043: 
                   4044: sub flush_langs_cache {
                   4045:     my ($uname,$udom)=@_;
                   4046:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4047:     if (!$uname) { $uname=$env{'user.name'};   }
                   4048:     return if ($udom eq 'public' && $uname eq 'public');
                   4049:     my $id=$uname.':'.$udom;
                   4050:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   4051: }
                   4052: 
1.61      www      4053: # ------------------------------------------------------------------ Screenname
1.81      albertel 4054: 
                   4055: =pod
                   4056: 
1.648     raeburn  4057: =item * &screenname($uname,$udom)
1.81      albertel 4058: 
                   4059: Gets a users screenname and returns it as a string
                   4060: 
                   4061: =cut
1.61      www      4062: 
                   4063: sub screenname {
                   4064:     my ($uname,$udom)=@_;
1.258     albertel 4065:     if ($uname eq $env{'user.name'} &&
                   4066: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 4067:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 4068:     return $names{'screenname'};
1.62      www      4069: }
                   4070: 
1.212     albertel 4071: 
1.802     bisitz   4072: # ------------------------------------------------------------- Confirm Wrapper
                   4073: =pod
                   4074: 
1.1142    raeburn  4075: =item * &confirmwrapper($message)
1.802     bisitz   4076: 
                   4077: Wrap messages about completion of operation in box
                   4078: 
                   4079: =cut
                   4080: 
                   4081: sub confirmwrapper {
                   4082:     my ($message)=@_;
                   4083:     if ($message) {
                   4084:         return "\n".'<div class="LC_confirm_box">'."\n"
                   4085:                .$message."\n"
                   4086:                .'</div>'."\n";
                   4087:     } else {
                   4088:         return $message;
                   4089:     }
                   4090: }
                   4091: 
1.62      www      4092: # ------------------------------------------------------------- Message Wrapper
                   4093: 
                   4094: sub messagewrapper {
1.369     www      4095:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      4096:     return 
1.441     albertel 4097:         '<a href="/adm/email?compose=individual&amp;'.
                   4098:         'recname='.$username.'&amp;recdom='.$domain.
                   4099: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  4100:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      4101: }
1.802     bisitz   4102: 
1.74      www      4103: # --------------------------------------------------------------- Notes Wrapper
                   4104: 
                   4105: sub noteswrapper {
                   4106:     my ($link,$un,$do)=@_;
                   4107:     return 
1.896     amueller 4108: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      4109: }
1.802     bisitz   4110: 
1.62      www      4111: # ------------------------------------------------------------- Aboutme Wrapper
                   4112: 
                   4113: sub aboutmewrapper {
1.1070    raeburn  4114:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  4115:     if (!defined($username)  && !defined($domain)) {
                   4116:         return;
                   4117:     }
1.1096    raeburn  4118:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  4119: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      4120: }
                   4121: 
                   4122: # ------------------------------------------------------------ Syllabus Wrapper
                   4123: 
                   4124: sub syllabuswrapper {
1.707     bisitz   4125:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  4126:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      4127: }
1.14      harris41 4128: 
1.802     bisitz   4129: # -----------------------------------------------------------------------------
                   4130: 
1.208     matthew  4131: sub track_student_link {
1.887     raeburn  4132:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 4133:     my $link ="/adm/trackstudent?";
1.208     matthew  4134:     my $title = 'View recent activity';
                   4135:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4136:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 4137:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  4138:         $title .= ' of this student';
1.268     albertel 4139:     } 
1.208     matthew  4140:     if (defined($target) && $target !~ /^\s*$/) {
                   4141:         $target = qq{target="$target"};
                   4142:     } else {
                   4143:         $target = '';
                   4144:     }
1.268     albertel 4145:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  4146:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 4147:     $title = &mt($title);
                   4148:     $linktext = &mt($linktext);
1.448     albertel 4149:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   4150: 	&help_open_topic('View_recent_activity');
1.208     matthew  4151: }
                   4152: 
1.781     raeburn  4153: sub slot_reservations_link {
                   4154:     my ($linktext,$sname,$sdom,$target) = @_;
                   4155:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   4156:     my $title = 'View slot reservation history';
                   4157:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4158:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   4159:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   4160:         $title .= ' of this student';
                   4161:     }
                   4162:     if (defined($target) && $target !~ /^\s*$/) {
                   4163:         $target = qq{target="$target"};
                   4164:     } else {
                   4165:         $target = '';
                   4166:     }
                   4167:     $title = &mt($title);
                   4168:     $linktext = &mt($linktext);
                   4169:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   4170: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   4171: 
                   4172: }
                   4173: 
1.508     www      4174: # ===================================================== Display a student photo
                   4175: 
                   4176: 
1.509     albertel 4177: sub student_image_tag {
1.508     www      4178:     my ($domain,$user)=@_;
                   4179:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   4180:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   4181: 	return '<img src="'.$imgsrc.'" align="right" />';
                   4182:     } else {
                   4183: 	return '';
                   4184:     }
                   4185: }
                   4186: 
1.112     bowersj2 4187: =pod
                   4188: 
                   4189: =back
                   4190: 
                   4191: =head1 Access .tab File Data
                   4192: 
                   4193: =over 4
                   4194: 
1.648     raeburn  4195: =item * &languageids() 
1.112     bowersj2 4196: 
                   4197: returns list of all language ids
                   4198: 
                   4199: =cut
                   4200: 
1.14      harris41 4201: sub languageids {
1.16      harris41 4202:     return sort(keys(%language));
1.14      harris41 4203: }
                   4204: 
1.112     bowersj2 4205: =pod
                   4206: 
1.648     raeburn  4207: =item * &languagedescription() 
1.112     bowersj2 4208: 
                   4209: returns description of a specified language id
                   4210: 
                   4211: =cut
                   4212: 
1.14      harris41 4213: sub languagedescription {
1.125     www      4214:     my $code=shift;
                   4215:     return  ($supported_language{$code}?'* ':'').
                   4216:             $language{$code}.
1.126     www      4217: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4218: }
                   4219: 
1.1048    foxr     4220: =pod
                   4221: 
                   4222: =item * &plainlanguagedescription
                   4223: 
                   4224: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4225: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4226: 
                   4227: =cut
                   4228: 
1.145     www      4229: sub plainlanguagedescription {
                   4230:     my $code=shift;
                   4231:     return $language{$code};
                   4232: }
                   4233: 
1.1048    foxr     4234: =pod
                   4235: 
                   4236: =item * &supportedlanguagecode
                   4237: 
                   4238: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4239: code.
                   4240: 
                   4241: =cut
                   4242: 
1.145     www      4243: sub supportedlanguagecode {
                   4244:     my $code=shift;
                   4245:     return $supported_language{$code};
1.97      www      4246: }
                   4247: 
1.112     bowersj2 4248: =pod
                   4249: 
1.1048    foxr     4250: =item * &latexlanguage()
                   4251: 
                   4252: Given a language key code returns the correspondnig language to use
                   4253: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4254: is no supported hyphenation for the language code.
                   4255: 
                   4256: =cut
                   4257: 
                   4258: sub latexlanguage {
                   4259:     my $code = shift;
                   4260:     return $latex_language{$code};
                   4261: }
                   4262: 
                   4263: =pod
                   4264: 
                   4265: =item * &latexhyphenation()
                   4266: 
                   4267: Same as above but what's supplied is the language as it might be stored
                   4268: in the metadata.
                   4269: 
                   4270: =cut
                   4271: 
                   4272: sub latexhyphenation {
                   4273:     my $key = shift;
                   4274:     return $latex_language_bykey{$key};
                   4275: }
                   4276: 
                   4277: =pod
                   4278: 
1.648     raeburn  4279: =item * &copyrightids() 
1.112     bowersj2 4280: 
                   4281: returns list of all copyrights
                   4282: 
                   4283: =cut
                   4284: 
                   4285: sub copyrightids {
                   4286:     return sort(keys(%cprtag));
                   4287: }
                   4288: 
                   4289: =pod
                   4290: 
1.648     raeburn  4291: =item * &copyrightdescription() 
1.112     bowersj2 4292: 
                   4293: returns description of a specified copyright id
                   4294: 
                   4295: =cut
                   4296: 
                   4297: sub copyrightdescription {
1.166     www      4298:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4299: }
1.197     matthew  4300: 
                   4301: =pod
                   4302: 
1.648     raeburn  4303: =item * &source_copyrightids() 
1.192     taceyjo1 4304: 
                   4305: returns list of all source copyrights
                   4306: 
                   4307: =cut
                   4308: 
                   4309: sub source_copyrightids {
                   4310:     return sort(keys(%scprtag));
                   4311: }
                   4312: 
                   4313: =pod
                   4314: 
1.648     raeburn  4315: =item * &source_copyrightdescription() 
1.192     taceyjo1 4316: 
                   4317: returns description of a specified source copyright id
                   4318: 
                   4319: =cut
                   4320: 
                   4321: sub source_copyrightdescription {
                   4322:     return &mt($scprtag{shift(@_)});
                   4323: }
1.112     bowersj2 4324: 
                   4325: =pod
                   4326: 
1.648     raeburn  4327: =item * &filecategories() 
1.112     bowersj2 4328: 
                   4329: returns list of all file categories
                   4330: 
                   4331: =cut
                   4332: 
                   4333: sub filecategories {
                   4334:     return sort(keys(%category_extensions));
                   4335: }
                   4336: 
                   4337: =pod
                   4338: 
1.648     raeburn  4339: =item * &filecategorytypes() 
1.112     bowersj2 4340: 
                   4341: returns list of file types belonging to a given file
                   4342: category
                   4343: 
                   4344: =cut
                   4345: 
                   4346: sub filecategorytypes {
1.356     albertel 4347:     my ($cat) = @_;
1.1248    raeburn  4348:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
                   4349:         return @{$category_extensions{lc($cat)}};
                   4350:     } else {
                   4351:         return ();
                   4352:     }
1.112     bowersj2 4353: }
                   4354: 
                   4355: =pod
                   4356: 
1.648     raeburn  4357: =item * &fileembstyle() 
1.112     bowersj2 4358: 
                   4359: returns embedding style for a specified file type
                   4360: 
                   4361: =cut
                   4362: 
                   4363: sub fileembstyle {
                   4364:     return $fe{lc(shift(@_))};
1.169     www      4365: }
                   4366: 
1.351     www      4367: sub filemimetype {
                   4368:     return $fm{lc(shift(@_))};
                   4369: }
                   4370: 
1.169     www      4371: 
                   4372: sub filecategoryselect {
                   4373:     my ($name,$value)=@_;
1.189     matthew  4374:     return &select_form($value,$name,
1.970     raeburn  4375:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4376: }
                   4377: 
                   4378: =pod
                   4379: 
1.648     raeburn  4380: =item * &filedescription() 
1.112     bowersj2 4381: 
                   4382: returns description for a specified file type
                   4383: 
                   4384: =cut
                   4385: 
                   4386: sub filedescription {
1.188     matthew  4387:     my $file_description = $fd{lc(shift())};
                   4388:     $file_description =~ s:([\[\]]):~$1:g;
                   4389:     return &mt($file_description);
1.112     bowersj2 4390: }
                   4391: 
                   4392: =pod
                   4393: 
1.648     raeburn  4394: =item * &filedescriptionex() 
1.112     bowersj2 4395: 
                   4396: returns description for a specified file type with
                   4397: extra formatting
                   4398: 
                   4399: =cut
                   4400: 
                   4401: sub filedescriptionex {
                   4402:     my $ex=shift;
1.188     matthew  4403:     my $file_description = $fd{lc($ex)};
                   4404:     $file_description =~ s:([\[\]]):~$1:g;
                   4405:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4406: }
                   4407: 
                   4408: # End of .tab access
                   4409: =pod
                   4410: 
                   4411: =back
                   4412: 
                   4413: =cut
                   4414: 
                   4415: # ------------------------------------------------------------------ File Types
                   4416: sub fileextensions {
                   4417:     return sort(keys(%fe));
                   4418: }
                   4419: 
1.97      www      4420: # ----------------------------------------------------------- Display Languages
                   4421: # returns a hash with all desired display languages
                   4422: #
                   4423: 
                   4424: sub display_languages {
                   4425:     my %languages=();
1.695     raeburn  4426:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4427: 	$languages{$lang}=1;
1.97      www      4428:     }
                   4429:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4430:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4431: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4432: 	    $languages{$lang}=1;
1.97      www      4433:         }
                   4434:     }
                   4435:     return %languages;
1.14      harris41 4436: }
                   4437: 
1.582     albertel 4438: sub languages {
                   4439:     my ($possible_langs) = @_;
1.695     raeburn  4440:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4441:     if (!ref($possible_langs)) {
                   4442: 	if( wantarray ) {
                   4443: 	    return @preferred_langs;
                   4444: 	} else {
                   4445: 	    return $preferred_langs[0];
                   4446: 	}
                   4447:     }
                   4448:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4449:     my @preferred_possibilities;
                   4450:     foreach my $preferred_lang (@preferred_langs) {
                   4451: 	if (exists($possibilities{$preferred_lang})) {
                   4452: 	    push(@preferred_possibilities, $preferred_lang);
                   4453: 	}
                   4454:     }
                   4455:     if( wantarray ) {
                   4456: 	return @preferred_possibilities;
                   4457:     }
                   4458:     return $preferred_possibilities[0];
                   4459: }
                   4460: 
1.742     raeburn  4461: sub user_lang {
                   4462:     my ($touname,$toudom,$fromcid) = @_;
                   4463:     my @userlangs;
                   4464:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4465:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4466:                     $env{'course.'.$fromcid.'.languages'}));
                   4467:     } else {
                   4468:         my %langhash = &getlangs($touname,$toudom);
                   4469:         if ($langhash{'languages'} ne '') {
                   4470:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4471:         } else {
                   4472:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4473:             if ($domdefs{'lang_def'} ne '') {
                   4474:                 @userlangs = ($domdefs{'lang_def'});
                   4475:             }
                   4476:         }
                   4477:     }
                   4478:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4479:     my $user_lh = Apache::localize->get_handle(@languages);
                   4480:     return $user_lh;
                   4481: }
                   4482: 
                   4483: 
1.112     bowersj2 4484: ###############################################################
                   4485: ##               Student Answer Attempts                     ##
                   4486: ###############################################################
                   4487: 
                   4488: =pod
                   4489: 
                   4490: =head1 Alternate Problem Views
                   4491: 
                   4492: =over 4
                   4493: 
1.648     raeburn  4494: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  4495:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4496: 
                   4497: Return string with previous attempt on problem. Arguments:
                   4498: 
                   4499: =over 4
                   4500: 
                   4501: =item * $symb: Problem, including path
                   4502: 
                   4503: =item * $username: username of the desired student
                   4504: 
                   4505: =item * $domain: domain of the desired student
1.14      harris41 4506: 
1.112     bowersj2 4507: =item * $course: Course ID
1.14      harris41 4508: 
1.112     bowersj2 4509: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4510:     something
1.14      harris41 4511: 
1.112     bowersj2 4512: =item * $regexp: if string matches this regexp, the string will be
                   4513:     sent to $gradesub
1.14      harris41 4514: 
1.112     bowersj2 4515: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4516: 
1.1199    raeburn  4517: =item * $usec: section of the desired student
                   4518: 
                   4519: =item * $identifier: counter for student (multiple students one problem) or 
                   4520:     problem (one student; whole sequence).
                   4521: 
1.112     bowersj2 4522: =back
1.14      harris41 4523: 
1.112     bowersj2 4524: The output string is a table containing all desired attempts, if any.
1.16      harris41 4525: 
1.112     bowersj2 4526: =cut
1.1       albertel 4527: 
                   4528: sub get_previous_attempt {
1.1199    raeburn  4529:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4530:   my $prevattempts='';
1.43      ng       4531:   no strict 'refs';
1.1       albertel 4532:   if ($symb) {
1.3       albertel 4533:     my (%returnhash)=
                   4534:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4535:     if ($returnhash{'version'}) {
                   4536:       my %lasthash=();
                   4537:       my $version;
                   4538:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  4539:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4540:             if ($key =~ /\.rawrndseed$/) {
                   4541:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4542:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4543:             } else {
                   4544:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4545:             }
1.19      harris41 4546:         }
1.1       albertel 4547:       }
1.596     albertel 4548:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4549:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  4550:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4551:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4552:       foreach my $key (sort(keys(%lasthash))) {
                   4553: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4554: 	if ($#parts > 0) {
1.31      albertel 4555: 	  my $data=$parts[-1];
1.989     raeburn  4556:           next if ($data eq 'foilorder');
1.31      albertel 4557: 	  pop(@parts);
1.1010    www      4558:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4559:           if ($data eq 'type') {
                   4560:               unless ($showsurv) {
                   4561:                   my $id = join(',',@parts);
                   4562:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4563:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4564:                       $lasthidden{$ign.'.'.$id} = 1;
                   4565:                   }
1.945     raeburn  4566:               }
1.1199    raeburn  4567:               if ($identifier ne '') {
                   4568:                   my $id = join(',',@parts);
                   4569:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4570:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4571:                       $hidestatus{$ign.'.'.$id} = 1;
                   4572:                   }
                   4573:               }
                   4574:           } elsif ($data eq 'regrader') {
                   4575:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  4576:                   my $id = join(',',@parts);
                   4577:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  4578:               }
1.1010    www      4579:           } 
1.31      albertel 4580: 	} else {
1.41      ng       4581: 	  if ($#parts == 0) {
                   4582: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4583: 	  } else {
                   4584: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4585: 	  }
1.31      albertel 4586: 	}
1.16      harris41 4587:       }
1.596     albertel 4588:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4589:       if ($getattempt eq '') {
1.1199    raeburn  4590:         my (%solved,%resets,%probstatus);
1.1200    raeburn  4591:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4592:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4593:                 foreach my $id (keys(%regraded)) {
                   4594:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4595:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4596:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4597:                         push(@{$resets{$id}},$version);
1.1199    raeburn  4598:                     }
                   4599:                 }
                   4600:             }
1.1200    raeburn  4601:         }
                   4602: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  4603:             my (@hidden,@unsolved);
1.945     raeburn  4604:             if (%typeparts) {
                   4605:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  4606:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   4607:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4608:                         push(@hidden,$id);
1.1199    raeburn  4609:                     } elsif ($identifier ne '') {
                   4610:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4611:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4612:                                 ($hidestatus{$id})) {
1.1200    raeburn  4613:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  4614:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4615:                                 push(@{$solved{$id}},$version);
                   4616:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4617:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4618:                                 my $skip;
                   4619:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4620:                                     foreach my $reset (@{$resets{$id}}) {
                   4621:                                         if ($reset > $solved{$id}[-1]) {
                   4622:                                             $skip=1;
                   4623:                                             last;
                   4624:                                         }
                   4625:                                     }
                   4626:                                 }
                   4627:                                 unless ($skip) {
                   4628:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4629:                                     push(@unsolved,$partslist);
                   4630:                                 }
                   4631:                             }
                   4632:                         }
1.945     raeburn  4633:                     }
                   4634:                 }
                   4635:             }
                   4636:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  4637:                            '<td>'.&mt('Transaction [_1]',$version);
                   4638:             if (@unsolved) {
                   4639:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4640:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4641:                                  &mt('Hide').'</label></span>';
                   4642:             }
                   4643:             $prevattempts .= '</td>';
1.945     raeburn  4644:             if (@hidden) {
                   4645:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4646:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4647:                     my $hide;
                   4648:                     foreach my $id (@hidden) {
                   4649:                         if ($key =~ /^\Q$id\E/) {
                   4650:                             $hide = 1;
                   4651:                             last;
                   4652:                         }
                   4653:                     }
                   4654:                     if ($hide) {
                   4655:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4656:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4657:                             my $value = &format_previous_attempt_value($key,
                   4658:                                              $returnhash{$version.':'.$key});
1.1173    kruse    4659:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4660:                         } else {
                   4661:                             $prevattempts.='<td>&nbsp;</td>';
                   4662:                         }
                   4663:                     } else {
                   4664:                         if ($key =~ /\./) {
1.1212    raeburn  4665:                             my $value = $returnhash{$version.':'.$key};
                   4666:                             if ($key =~ /\.rndseed$/) {
                   4667:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4668:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4669:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4670:                                 }
                   4671:                             }
                   4672:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4673:                                            '&nbsp;</td>';
1.945     raeburn  4674:                         } else {
                   4675:                             $prevattempts.='<td>&nbsp;</td>';
                   4676:                         }
                   4677:                     }
                   4678:                 }
                   4679:             } else {
                   4680: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4681:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  4682:                     my $value = $returnhash{$version.':'.$key};
                   4683:                     if ($key =~ /\.rndseed$/) {
                   4684:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4685:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4686:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4687:                         }
                   4688:                     }
                   4689:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4690:                                    '&nbsp;</td>';
1.945     raeburn  4691: 	        }
                   4692:             }
                   4693: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4694: 	 }
1.1       albertel 4695:       }
1.945     raeburn  4696:       my @currhidden = keys(%lasthidden);
1.596     albertel 4697:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4698:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4699:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4700:           if (%typeparts) {
                   4701:               my $hidden;
                   4702:               foreach my $id (@currhidden) {
                   4703:                   if ($key =~ /^\Q$id\E/) {
                   4704:                       $hidden = 1;
                   4705:                       last;
                   4706:                   }
                   4707:               }
                   4708:               if ($hidden) {
                   4709:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4710:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4711:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4712:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4713:                           $value = &$gradesub($value);
                   4714:                       }
1.1173    kruse    4715:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  4716:                   } else {
                   4717:                       $prevattempts.='<td>&nbsp;</td>';
                   4718:                   }
                   4719:               } else {
                   4720:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4721:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4722:                       $value = &$gradesub($value);
                   4723:                   }
1.1173    kruse    4724:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4725:               }
                   4726:           } else {
                   4727: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4728: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4729:                   $value = &$gradesub($value);
                   4730:               }
1.1173    kruse    4731: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4732:           }
1.16      harris41 4733:       }
1.596     albertel 4734:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4735:     } else {
1.1305    raeburn  4736:       my $msg;
                   4737:       if ($symb =~ /ext\.tool$/) {
                   4738:           $msg = &mt('No grade passed back.');
                   4739:       } else {
                   4740:           $msg = &mt('Nothing submitted - no attempts.');
                   4741:       }
1.596     albertel 4742:       $prevattempts=
                   4743: 	  &start_data_table().&start_data_table_row().
1.1305    raeburn  4744: 	  '<td>'.$msg.'</td>'.
1.596     albertel 4745: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4746:     }
                   4747:   } else {
1.596     albertel 4748:     $prevattempts=
                   4749: 	  &start_data_table().&start_data_table_row().
                   4750: 	  '<td>'.&mt('No data.').'</td>'.
                   4751: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4752:   }
1.10      albertel 4753: }
                   4754: 
1.581     albertel 4755: sub format_previous_attempt_value {
                   4756:     my ($key,$value) = @_;
1.1011    www      4757:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    4758:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 4759:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    4760:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  4761:     } elsif ($key =~ /answerstring$/) {
                   4762:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    4763:         my @answer = %answers;
                   4764:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  4765:         my @anskeys = sort(keys(%answers));
                   4766:         if (@anskeys == 1) {
                   4767:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4768:             if ($answer =~ m{\0}) {
                   4769:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4770:             }
                   4771:             my $tag_internal_answer_name = 'INTERNAL';
                   4772:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4773:                 $value = $answer; 
                   4774:             } else {
                   4775:                 $value = $anskeys[0].'='.$answer;
                   4776:             }
                   4777:         } else {
                   4778:             foreach my $ans (@anskeys) {
                   4779:                 my $answer = $answers{$ans};
1.1001    raeburn  4780:                 if ($answer =~ m{\0}) {
                   4781:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4782:                 }
                   4783:                 $value .=  $ans.'='.$answer.'<br />';;
                   4784:             } 
                   4785:         }
1.581     albertel 4786:     } else {
1.1173    kruse    4787:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 4788:     }
                   4789:     return $value;
                   4790: }
                   4791: 
                   4792: 
1.107     albertel 4793: sub relative_to_absolute {
                   4794:     my ($url,$output)=@_;
                   4795:     my $parser=HTML::TokeParser->new(\$output);
                   4796:     my $token;
                   4797:     my $thisdir=$url;
                   4798:     my @rlinks=();
                   4799:     while ($token=$parser->get_token) {
                   4800: 	if ($token->[0] eq 'S') {
                   4801: 	    if ($token->[1] eq 'a') {
                   4802: 		if ($token->[2]->{'href'}) {
                   4803: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4804: 		}
                   4805: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4806: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4807: 	    } elsif ($token->[1] eq 'base') {
                   4808: 		$thisdir=$token->[2]->{'href'};
                   4809: 	    }
                   4810: 	}
                   4811:     }
                   4812:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4813:     foreach my $link (@rlinks) {
1.726     raeburn  4814: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4815: 		($link=~/^\//) ||
                   4816: 		($link=~/^javascript:/i) ||
                   4817: 		($link=~/^mailto:/i) ||
                   4818: 		($link=~/^\#/)) {
                   4819: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4820: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4821: 	}
                   4822:     }
                   4823: # -------------------------------------------------- Deal with Applet codebases
                   4824:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4825:     return $output;
                   4826: }
                   4827: 
1.112     bowersj2 4828: =pod
                   4829: 
1.648     raeburn  4830: =item * &get_student_view()
1.112     bowersj2 4831: 
                   4832: show a snapshot of what student was looking at
                   4833: 
                   4834: =cut
                   4835: 
1.10      albertel 4836: sub get_student_view {
1.186     albertel 4837:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4838:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4839:   my (%form);
1.10      albertel 4840:   my @elements=('symb','courseid','domain','username');
                   4841:   foreach my $element (@elements) {
1.186     albertel 4842:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4843:   }
1.186     albertel 4844:   if (defined($moreenv)) {
                   4845:       %form=(%form,%{$moreenv});
                   4846:   }
1.236     albertel 4847:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4848:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.1306    raeburn  4849:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
                   4850:       $feedurl =~ s{^/adm/wrapper}{};
                   4851:   }
1.650     www      4852:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4853:   $userview=~s/\<body[^\>]*\>//gi;
                   4854:   $userview=~s/\<\/body\>//gi;
                   4855:   $userview=~s/\<html\>//gi;
                   4856:   $userview=~s/\<\/html\>//gi;
                   4857:   $userview=~s/\<head\>//gi;
                   4858:   $userview=~s/\<\/head\>//gi;
                   4859:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4860:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4861:   if (wantarray) {
                   4862:      return ($userview,$response);
                   4863:   } else {
                   4864:      return $userview;
                   4865:   }
                   4866: }
                   4867: 
                   4868: sub get_student_view_with_retries {
                   4869:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4870: 
                   4871:     my $ok = 0;                 # True if we got a good response.
                   4872:     my $content;
                   4873:     my $response;
                   4874: 
                   4875:     # Try to get the student_view done. within the retries count:
                   4876:     
                   4877:     do {
                   4878:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4879:          $ok      = $response->is_success;
                   4880:          if (!$ok) {
                   4881:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4882:          }
                   4883:          $retries--;
                   4884:     } while (!$ok && ($retries > 0));
                   4885:     
                   4886:     if (!$ok) {
                   4887:        $content = '';          # On error return an empty content.
                   4888:     }
1.651     www      4889:     if (wantarray) {
                   4890:        return ($content, $response);
                   4891:     } else {
                   4892:        return $content;
                   4893:     }
1.11      albertel 4894: }
                   4895: 
1.1349    raeburn  4896: sub css_links {
                   4897:     my ($currsymb,$level) = @_;
                   4898:     my ($links,@symbs,%cssrefs,%httpref);
                   4899:     if ($level eq 'map') {
                   4900:         my $navmap = Apache::lonnavmaps::navmap->new();
                   4901:         if (ref($navmap)) {
                   4902:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
                   4903:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
                   4904:             foreach my $res (@resources) {
                   4905:                 if (ref($res) && $res->symb()) {
                   4906:                     push(@symbs,$res->symb());
                   4907:                 }
                   4908:             }
                   4909:         }
                   4910:     } else {
                   4911:         @symbs = ($currsymb);
                   4912:     }
                   4913:     foreach my $symb (@symbs) {
                   4914:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
                   4915:         if ($css_href =~ /\S/) {
                   4916:             unless ($css_href =~ m{https?://}) {
                   4917:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
                   4918:                 my $proburl =  &Apache::lonnet::clutter($url);
                   4919:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
                   4920:                 unless ($css_href =~ m{^/}) {
                   4921:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
                   4922:                 }
                   4923:                 if ($css_href =~ m{^/(res|uploaded)/}) {
                   4924:                     unless (($httpref{'httpref.'.$css_href}) ||
                   4925:                             (&Apache::lonnet::is_on_map($css_href))) {
                   4926:                         my $thisurl = $proburl;
                   4927:                         if ($env{'httpref.'.$proburl}) {
                   4928:                             $thisurl = $env{'httpref.'.$proburl};
                   4929:                         }
                   4930:                         $httpref{'httpref.'.$css_href} = $thisurl;
                   4931:                     }
                   4932:                 }
                   4933:             }
                   4934:             $cssrefs{$css_href} = 1;
                   4935:         }
                   4936:     }
                   4937:     if (keys(%httpref)) {
                   4938:         &Apache::lonnet::appenv(\%httpref);
                   4939:     }
                   4940:     if (keys(%cssrefs)) {
                   4941:         foreach my $css_href (keys(%cssrefs)) {
                   4942:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
                   4943:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
                   4944:         }
                   4945:     }
                   4946:     return $links;
                   4947: }
                   4948: 
1.112     bowersj2 4949: =pod
                   4950: 
1.648     raeburn  4951: =item * &get_student_answers() 
1.112     bowersj2 4952: 
                   4953: show a snapshot of how student was answering problem
                   4954: 
                   4955: =cut
                   4956: 
1.11      albertel 4957: sub get_student_answers {
1.100     sakharuk 4958:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4959:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4960:   my (%moreenv);
1.11      albertel 4961:   my @elements=('symb','courseid','domain','username');
                   4962:   foreach my $element (@elements) {
1.186     albertel 4963:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4964:   }
1.186     albertel 4965:   $moreenv{'grade_target'}='answer';
                   4966:   %moreenv=(%form,%moreenv);
1.497     raeburn  4967:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4968:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4969:   return $userview;
1.1       albertel 4970: }
1.116     albertel 4971: 
                   4972: =pod
                   4973: 
                   4974: =item * &submlink()
                   4975: 
1.242     albertel 4976: Inputs: $text $uname $udom $symb $target
1.116     albertel 4977: 
                   4978: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4979: 
                   4980: =cut
                   4981: 
                   4982: ###############################################
                   4983: sub submlink {
1.242     albertel 4984:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4985:     if (!($uname && $udom)) {
                   4986: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4987: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4988: 	if (!$symb) { $symb=$cursymb; }
                   4989:     }
1.254     matthew  4990:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4991:     $symb=&escape($symb);
1.960     bisitz   4992:     if ($target) { $target=" target=\"$target\""; }
                   4993:     return
                   4994:         '<a href="/adm/grades?command=submission'.
                   4995:         '&amp;symb='.$symb.
                   4996:         '&amp;student='.$uname.
                   4997:         '&amp;userdom='.$udom.'"'.
                   4998:         $target.'>'.$text.'</a>';
1.242     albertel 4999: }
                   5000: ##############################################
                   5001: 
                   5002: =pod
                   5003: 
                   5004: =item * &pgrdlink()
                   5005: 
                   5006: Inputs: $text $uname $udom $symb $target
                   5007: 
                   5008: Returns: A link to grades.pm such as to see the PGRD view of a student
                   5009: 
                   5010: =cut
                   5011: 
                   5012: ###############################################
                   5013: sub pgrdlink {
                   5014:     my $link=&submlink(@_);
                   5015:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   5016:     return $link;
                   5017: }
                   5018: ##############################################
                   5019: 
                   5020: =pod
                   5021: 
                   5022: =item * &pprmlink()
                   5023: 
                   5024: Inputs: $text $uname $udom $symb $target
                   5025: 
                   5026: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 5027: student and a specific resource
1.242     albertel 5028: 
                   5029: =cut
                   5030: 
                   5031: ###############################################
                   5032: sub pprmlink {
                   5033:     my ($text,$uname,$udom,$symb,$target)=@_;
                   5034:     if (!($uname && $udom)) {
                   5035: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5036: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 5037: 	if (!$symb) { $symb=$cursymb; }
                   5038:     }
1.254     matthew  5039:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5040:     $symb=&escape($symb);
1.242     albertel 5041:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 5042:     return '<a href="/adm/parmset?command=set&amp;'.
                   5043: 	'symb='.$symb.'&amp;uname='.$uname.
                   5044: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 5045: }
                   5046: ##############################################
1.37      matthew  5047: 
1.112     bowersj2 5048: =pod
                   5049: 
                   5050: =back
                   5051: 
                   5052: =cut
                   5053: 
1.37      matthew  5054: ###############################################
1.51      www      5055: 
                   5056: 
                   5057: sub timehash {
1.687     raeburn  5058:     my ($thistime) = @_;
                   5059:     my $timezone = &Apache::lonlocal::gettimezone();
                   5060:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   5061:                      ->set_time_zone($timezone);
                   5062:     my $wday = $dt->day_of_week();
                   5063:     if ($wday == 7) { $wday = 0; }
                   5064:     return ( 'second' => $dt->second(),
                   5065:              'minute' => $dt->minute(),
                   5066:              'hour'   => $dt->hour(),
                   5067:              'day'     => $dt->day_of_month(),
                   5068:              'month'   => $dt->month(),
                   5069:              'year'    => $dt->year(),
                   5070:              'weekday' => $wday,
                   5071:              'dayyear' => $dt->day_of_year(),
                   5072:              'dlsav'   => $dt->is_dst() );
1.51      www      5073: }
                   5074: 
1.370     www      5075: sub utc_string {
                   5076:     my ($date)=@_;
1.371     www      5077:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      5078: }
                   5079: 
1.51      www      5080: sub maketime {
                   5081:     my %th=@_;
1.687     raeburn  5082:     my ($epoch_time,$timezone,$dt);
                   5083:     $timezone = &Apache::lonlocal::gettimezone();
                   5084:     eval {
                   5085:         $dt = DateTime->new( year   => $th{'year'},
                   5086:                              month  => $th{'month'},
                   5087:                              day    => $th{'day'},
                   5088:                              hour   => $th{'hour'},
                   5089:                              minute => $th{'minute'},
                   5090:                              second => $th{'second'},
                   5091:                              time_zone => $timezone,
                   5092:                          );
                   5093:     };
                   5094:     if (!$@) {
                   5095:         $epoch_time = $dt->epoch;
                   5096:         if ($epoch_time) {
                   5097:             return $epoch_time;
                   5098:         }
                   5099:     }
1.51      www      5100:     return POSIX::mktime(
                   5101:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      5102:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      5103: }
                   5104: 
                   5105: #########################################
1.51      www      5106: 
                   5107: sub findallcourses {
1.482     raeburn  5108:     my ($roles,$uname,$udom) = @_;
1.355     albertel 5109:     my %roles;
                   5110:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 5111:     my %courses;
1.51      www      5112:     my $now=time;
1.482     raeburn  5113:     if (!defined($uname)) {
                   5114:         $uname = $env{'user.name'};
                   5115:     }
                   5116:     if (!defined($udom)) {
                   5117:         $udom = $env{'user.domain'};
                   5118:     }
                   5119:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  5120:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  5121:         if (!%roles) {
                   5122:             %roles = (
                   5123:                        cc => 1,
1.907     raeburn  5124:                        co => 1,
1.482     raeburn  5125:                        in => 1,
                   5126:                        ep => 1,
                   5127:                        ta => 1,
                   5128:                        cr => 1,
                   5129:                        st => 1,
                   5130:              );
                   5131:         }
                   5132:         foreach my $entry (keys(%roleshash)) {
                   5133:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   5134:             if ($trole =~ /^cr/) { 
                   5135:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   5136:             } else {
                   5137:                 next if (!exists($roles{$trole}));
                   5138:             }
                   5139:             if ($tend) {
                   5140:                 next if ($tend < $now);
                   5141:             }
                   5142:             if ($tstart) {
                   5143:                 next if ($tstart > $now);
                   5144:             }
1.1058    raeburn  5145:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  5146:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  5147:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  5148:             if ($secpart eq '') {
                   5149:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   5150:                 $sec = 'none';
1.1058    raeburn  5151:                 $value .= $cnum.'/';
1.482     raeburn  5152:             } else {
                   5153:                 $cnum = $cnumpart;
                   5154:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  5155:                 $value .= $cnum.'/'.$sec;
                   5156:             }
                   5157:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5158:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5159:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5160:                 }
                   5161:             } else {
                   5162:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  5163:             }
1.482     raeburn  5164:         }
                   5165:     } else {
                   5166:         foreach my $key (keys(%env)) {
1.483     albertel 5167: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   5168:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  5169: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   5170: 	        next if ($role eq 'ca' || $role eq 'aa');
                   5171: 	        next if (%roles && !exists($roles{$role}));
                   5172: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   5173:                 my $active=1;
                   5174:                 if ($starttime) {
                   5175: 		    if ($now<$starttime) { $active=0; }
                   5176:                 }
                   5177:                 if ($endtime) {
                   5178:                     if ($now>$endtime) { $active=0; }
                   5179:                 }
                   5180:                 if ($active) {
1.1058    raeburn  5181:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  5182:                     if ($sec eq '') {
                   5183:                         $sec = 'none';
1.1058    raeburn  5184:                     } else {
                   5185:                         $value .= $sec;
                   5186:                     }
                   5187:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5188:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5189:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5190:                         }
                   5191:                     } else {
                   5192:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  5193:                     }
1.474     raeburn  5194:                 }
                   5195:             }
1.51      www      5196:         }
                   5197:     }
1.474     raeburn  5198:     return %courses;
1.51      www      5199: }
1.37      matthew  5200: 
1.54      www      5201: ###############################################
1.474     raeburn  5202: 
                   5203: sub blockcheck {
1.1372  ! raeburn  5204:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
        !          5205:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
        !          5206:         my ($has_evb,$check_ipaccess);
        !          5207:         my $dom = $env{'user.domain'};
        !          5208:         if ($env{'request.course.id'}) {
        !          5209:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
        !          5210:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
        !          5211:             my $checkrole = "cm./$cdom/$cnum";
        !          5212:             my $sec = $env{'request.course.sec'};
        !          5213:             if ($sec ne '') {
        !          5214:                 $checkrole .= "/$sec";
        !          5215:             }
        !          5216:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
        !          5217:                 ($env{'request.role'} !~ /^st/)) {
        !          5218:                 $has_evb = 1;
        !          5219:             }
        !          5220:             unless ($has_evb) {
        !          5221:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
        !          5222:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
        !          5223:                     if ($udom eq $cdom) {
        !          5224:                         $check_ipaccess = 1;
        !          5225:                     }
        !          5226:                 }
        !          5227:             }
        !          5228:         }
        !          5229:         unless ($has_evb || $check_ipaccess) {
        !          5230:             my @machinedoms = &Apache::lonnet::current_machine_domains();
        !          5231:             if (($dom eq 'public') && ($activity eq 'port')) {
        !          5232:                 $dom = $udom;
        !          5233:             }
        !          5234:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
        !          5235:                 $check_ipaccess = 1;
        !          5236:             } else {
        !          5237:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
        !          5238:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
        !          5239:                 my $prim = &Apache::lonnet::domain($dom,'primary');
        !          5240:                 my $intdom = &Apache::lonnet::internet_dom($prim);
        !          5241:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
        !          5242:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
        !          5243:                         $check_ipaccess = 1;
        !          5244:                     }
        !          5245:                 }
        !          5246:             }
        !          5247:         }
        !          5248:         if ($check_ipaccess) {
        !          5249:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
        !          5250:             unless (defined($cached)) {
        !          5251:                 my %domconfig =
        !          5252:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
        !          5253:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
        !          5254:             }
        !          5255:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
        !          5256:                 foreach my $id (keys(%{$ipaccessref})) {
        !          5257:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
        !          5258:                         my $range = $ipaccessref->{$id}->{'ip'};
        !          5259:                         if ($range) {
        !          5260:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
        !          5261:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
        !          5262:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
        !          5263:                                         return ('','','',$id,$dom);
        !          5264:                                         last;
        !          5265:                                     }
        !          5266:                                 }
        !          5267:                             }
        !          5268:                         }
        !          5269:                     }
        !          5270:                 }
        !          5271:             }
        !          5272:         }
        !          5273:     }
1.1189    raeburn  5274:     if (defined($udom) && defined($uname)) {
                   5275:         # If uname and udom are for a course, check for blocks in the course.
                   5276:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5277:             my ($startblock,$endblock,$triggerblock) =
1.1347    raeburn  5278:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1189    raeburn  5279:             return ($startblock,$endblock,$triggerblock);
                   5280:         }
                   5281:     } else {
1.490     raeburn  5282:         $udom = $env{'user.domain'};
                   5283:         $uname = $env{'user.name'};
                   5284:     }
                   5285: 
1.502     raeburn  5286:     my $startblock = 0;
                   5287:     my $endblock = 0;
1.1062    raeburn  5288:     my $triggerblock = '';
1.482     raeburn  5289:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  5290: 
1.490     raeburn  5291:     # If uname is for a user, and activity is course-specific, i.e.,
                   5292:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5293: 
1.490     raeburn  5294:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1282    raeburn  5295:          $activity eq 'groups' || $activity eq 'printout' ||
1.1346    raeburn  5296:          $activity eq 'search' || $activity eq 'reinit' ||
                   5297:          $activity eq 'alert') &&
1.1189    raeburn  5298:         ($env{'request.course.id'})) {
1.490     raeburn  5299:         foreach my $key (keys(%live_courses)) {
                   5300:             if ($key ne $env{'request.course.id'}) {
                   5301:                 delete($live_courses{$key});
                   5302:             }
                   5303:         }
                   5304:     }
                   5305: 
                   5306:     my $otheruser = 0;
                   5307:     my %own_courses;
                   5308:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5309:         # Resource belongs to user other than current user.
                   5310:         $otheruser = 1;
                   5311:         # Gather courses for current user
                   5312:         %own_courses = 
                   5313:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5314:     }
                   5315: 
                   5316:     # Gather active course roles - course coordinator, instructor, 
                   5317:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5318: 
                   5319:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5320:         my ($cdom,$cnum);
                   5321:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5322:             $cdom = $env{'course.'.$course.'.domain'};
                   5323:             $cnum = $env{'course.'.$course.'.num'};
                   5324:         } else {
1.490     raeburn  5325:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5326:         }
                   5327:         my $no_ownblock = 0;
                   5328:         my $no_userblock = 0;
1.533     raeburn  5329:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5330:             # Check if current user has 'evb' priv for this
                   5331:             if (defined($own_courses{$course})) {
                   5332:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5333:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5334:                     if ($sec ne 'none') {
                   5335:                         $checkrole .= '/'.$sec;
                   5336:                     }
                   5337:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5338:                         $no_ownblock = 1;
                   5339:                         last;
                   5340:                     }
                   5341:                 }
                   5342:             }
                   5343:             # if they have 'evb' priv and are currently not playing student
                   5344:             next if (($no_ownblock) &&
                   5345:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5346:         }
1.474     raeburn  5347:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5348:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5349:             if ($sec ne 'none') {
1.482     raeburn  5350:                 $checkrole .= '/'.$sec;
1.474     raeburn  5351:             }
1.490     raeburn  5352:             if ($otheruser) {
                   5353:                 # Resource belongs to user other than current user.
                   5354:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5355:                 my (%allroles,%userroles);
                   5356:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5357:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5358:                         my ($trole,$tdom,$tnum,$tsec);
                   5359:                         if ($entry =~ /^cr/) {
                   5360:                             ($trole,$tdom,$tnum,$tsec) = 
                   5361:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5362:                         } else {
                   5363:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5364:                         }
                   5365:                         my ($spec,$area,$trest);
                   5366:                         $area = '/'.$tdom.'/'.$tnum;
                   5367:                         $trest = $tnum;
                   5368:                         if ($tsec ne '') {
                   5369:                             $area .= '/'.$tsec;
                   5370:                             $trest .= '/'.$tsec;
                   5371:                         }
                   5372:                         $spec = $trole.'.'.$area;
                   5373:                         if ($trole =~ /^cr/) {
                   5374:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5375:                                                               $tdom,$spec,$trest,$area);
                   5376:                         } else {
                   5377:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5378:                                                                 $tdom,$spec,$trest,$area);
                   5379:                         }
                   5380:                     }
1.1276    raeburn  5381:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5382:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5383:                         if ($1) {
                   5384:                             $no_userblock = 1;
                   5385:                             last;
                   5386:                         }
1.486     raeburn  5387:                     }
                   5388:                 }
1.490     raeburn  5389:             } else {
                   5390:                 # Resource belongs to current user
                   5391:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5392:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5393:                     $no_ownblock = 1;
                   5394:                     last;
                   5395:                 }
1.474     raeburn  5396:             }
                   5397:         }
                   5398:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5399:         next if (($no_ownblock) &&
1.491     albertel 5400:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5401:         next if ($no_userblock);
1.474     raeburn  5402: 
1.1303    raeburn  5403:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5404:         # of specified user, unless user has 'evb' privilege.
1.1284    raeburn  5405: 
1.1062    raeburn  5406:         my ($start,$end,$trigger) = 
1.1347    raeburn  5407:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  5408:         if (($start != 0) && 
                   5409:             (($startblock == 0) || ($startblock > $start))) {
                   5410:             $startblock = $start;
1.1062    raeburn  5411:             if ($trigger ne '') {
                   5412:                 $triggerblock = $trigger;
                   5413:             }
1.502     raeburn  5414:         }
                   5415:         if (($end != 0)  &&
                   5416:             (($endblock == 0) || ($endblock < $end))) {
                   5417:             $endblock = $end;
1.1062    raeburn  5418:             if ($trigger ne '') {
                   5419:                 $triggerblock = $trigger;
                   5420:             }
1.502     raeburn  5421:         }
1.490     raeburn  5422:     }
1.1062    raeburn  5423:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5424: }
                   5425: 
                   5426: sub get_blocks {
1.1347    raeburn  5427:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  5428:     my $startblock = 0;
                   5429:     my $endblock = 0;
1.1062    raeburn  5430:     my $triggerblock = '';
1.490     raeburn  5431:     my $course = $cdom.'_'.$cnum;
                   5432:     $setters->{$course} = {};
                   5433:     $setters->{$course}{'staff'} = [];
                   5434:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5435:     $setters->{$course}{'triggers'} = [];
                   5436:     my (@blockers,%triggered);
                   5437:     my $now = time;
                   5438:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5439:     if ($activity eq 'docs') {
1.1348    raeburn  5440:         my ($blocked,$nosymbcache,$noenccheck);
1.1347    raeburn  5441:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   5442:             $blocked = 1;
                   5443:             $nosymbcache = 1;
1.1348    raeburn  5444:             $noenccheck = 1;
1.1347    raeburn  5445:         }
1.1348    raeburn  5446:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
1.1062    raeburn  5447:         foreach my $block (@blockers) {
                   5448:             if ($block =~ /^firstaccess____(.+)$/) {
                   5449:                 my $item = $1;
                   5450:                 my $type = 'map';
                   5451:                 my $timersymb = $item;
                   5452:                 if ($item eq 'course') {
                   5453:                     $type = 'course';
                   5454:                 } elsif ($item =~ /___\d+___/) {
                   5455:                     $type = 'resource';
                   5456:                 } else {
                   5457:                     $timersymb = &Apache::lonnet::symbread($item);
                   5458:                 }
                   5459:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5460:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5461:                 $triggered{$block} = {
                   5462:                                        start => $start,
                   5463:                                        end   => $end,
                   5464:                                        type  => $type,
                   5465:                                      };
                   5466:             }
                   5467:         }
                   5468:     } else {
                   5469:         foreach my $block (keys(%commblocks)) {
                   5470:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5471:                 my ($start,$end) = ($1,$2);
                   5472:                 if ($start <= time && $end >= time) {
                   5473:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5474:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5475:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5476:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5477:                                     push(@blockers,$block);
                   5478:                                 }
                   5479:                             }
                   5480:                         }
                   5481:                     }
                   5482:                 }
                   5483:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5484:                 my $item = $1;
                   5485:                 my $timersymb = $item; 
                   5486:                 my $type = 'map';
                   5487:                 if ($item eq 'course') {
                   5488:                     $type = 'course';
                   5489:                 } elsif ($item =~ /___\d+___/) {
                   5490:                     $type = 'resource';
                   5491:                 } else {
                   5492:                     $timersymb = &Apache::lonnet::symbread($item);
                   5493:                 }
                   5494:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5495:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5496:                 if ($start && $end) {
                   5497:                     if (($start <= time) && ($end >= time)) {
1.1281    raeburn  5498:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5499:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5500:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5501:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5502:                                         push(@blockers,$block);
                   5503:                                         $triggered{$block} = {
                   5504:                                                                start => $start,
                   5505:                                                                end   => $end,
                   5506:                                                                type  => $type,
                   5507:                                                              };
                   5508:                                     }
                   5509:                                 }
                   5510:                             }
1.1062    raeburn  5511:                         }
                   5512:                     }
1.490     raeburn  5513:                 }
1.1062    raeburn  5514:             }
                   5515:         }
                   5516:     }
                   5517:     foreach my $blocker (@blockers) {
                   5518:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5519:             &parse_block_record($commblocks{$blocker});
                   5520:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5521:         my ($start,$end,$triggertype);
                   5522:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5523:             ($start,$end) = ($1,$2);
                   5524:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5525:             $start = $triggered{$blocker}{'start'};
                   5526:             $end = $triggered{$blocker}{'end'};
                   5527:             $triggertype = $triggered{$blocker}{'type'};
                   5528:         }
                   5529:         if ($start) {
                   5530:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5531:             if ($triggertype) {
                   5532:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5533:             } else {
                   5534:                 push(@{$$setters{$course}{'triggers'}},0);
                   5535:             }
                   5536:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5537:                 $startblock = $start;
                   5538:                 if ($triggertype) {
                   5539:                     $triggerblock = $blocker;
1.474     raeburn  5540:                 }
                   5541:             }
1.1062    raeburn  5542:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5543:                $endblock = $end;
                   5544:                if ($triggertype) {
                   5545:                    $triggerblock = $blocker;
                   5546:                }
                   5547:             }
1.474     raeburn  5548:         }
                   5549:     }
1.1062    raeburn  5550:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5551: }
                   5552: 
                   5553: sub parse_block_record {
                   5554:     my ($record) = @_;
                   5555:     my ($setuname,$setudom,$title,$blocks);
                   5556:     if (ref($record) eq 'HASH') {
                   5557:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5558:         $title = &unescape($record->{'event'});
                   5559:         $blocks = $record->{'blocks'};
                   5560:     } else {
                   5561:         my @data = split(/:/,$record,3);
                   5562:         if (scalar(@data) eq 2) {
                   5563:             $title = $data[1];
                   5564:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5565:         } else {
                   5566:             ($setuname,$setudom,$title) = @data;
                   5567:         }
                   5568:         $blocks = { 'com' => 'on' };
                   5569:     }
                   5570:     return ($setuname,$setudom,$title,$blocks);
                   5571: }
                   5572: 
1.854     kalberla 5573: sub blocking_status {
1.1372  ! raeburn  5574:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  5575:     my %setters;
1.890     droeschl 5576: 
1.1061    raeburn  5577: # check for active blocking
1.1372  ! raeburn  5578:     if ($clientip eq '') {
        !          5579:         $clientip = &Apache::lonnet::get_requestor_ip();
        !          5580:     }
        !          5581:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
        !          5582:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  5583:     my $blocked = 0;
1.1372  ! raeburn  5584:     if (($startblock && $endblock) || ($by_ip)) {
1.1062    raeburn  5585:         $blocked = 1;
                   5586:     }
1.890     droeschl 5587: 
1.1061    raeburn  5588: # caller just wants to know whether a block is active
                   5589:     if (!wantarray) { return $blocked; }
                   5590: 
                   5591: # build a link to a popup window containing the details
                   5592:     my $querystring  = "?activity=$activity";
1.1351    raeburn  5593: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
                   5594:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
1.1232    raeburn  5595:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   5596:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5597:     } elsif ($activity eq 'docs') {
1.1347    raeburn  5598:         my $showurl = &Apache::lonenc::check_encrypt($url);
                   5599:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   5600:         if ($symb) {
                   5601:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   5602:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   5603:         }
1.1062    raeburn  5604:     }
1.1061    raeburn  5605: 
                   5606:     my $output .= <<'END_MYBLOCK';
                   5607: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5608:     var options = "width=" + w + ",height=" + h + ",";
                   5609:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5610:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5611:     var newWin = window.open(url, wdwName, options);
                   5612:     newWin.focus();
                   5613: }
1.890     droeschl 5614: END_MYBLOCK
1.854     kalberla 5615: 
1.1061    raeburn  5616:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5617:   
1.1061    raeburn  5618:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5619:     my $text = &mt('Communication Blocked');
1.1217    raeburn  5620:     my $class = 'LC_comblock';
1.1062    raeburn  5621:     if ($activity eq 'docs') {
                   5622:         $text = &mt('Content Access Blocked');
1.1217    raeburn  5623:         $class = '';
1.1063    raeburn  5624:     } elsif ($activity eq 'printout') {
                   5625:         $text = &mt('Printing Blocked');
1.1232    raeburn  5626:     } elsif ($activity eq 'passwd') {
                   5627:         $text = &mt('Password Changing Blocked');
1.1345    raeburn  5628:     } elsif ($activity eq 'grades') {
                   5629:         $text = &mt('Gradebook Blocked');
1.1346    raeburn  5630:     } elsif ($activity eq 'search') {
                   5631:         $text = &mt('Search Blocked');
1.1282    raeburn  5632:     } elsif ($activity eq 'alert') {
                   5633:         $text = &mt('Checking Critical Messages Blocked');
                   5634:     } elsif ($activity eq 'reinit') {
                   5635:         $text = &mt('Checking Course Update Blocked');
1.1351    raeburn  5636:     } elsif ($activity eq 'about') {
                   5637:         $text = &mt('Access to User Information Pages Blocked');
1.1062    raeburn  5638:     }
1.1061    raeburn  5639:     $output .= <<"END_BLOCK";
1.1217    raeburn  5640: <div class='$class'>
1.869     kalberla 5641:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5642:   title='$text'>
                   5643:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5644:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5645:   title='$text'>$text</a>
1.867     kalberla 5646: </div>
                   5647: 
                   5648: END_BLOCK
1.474     raeburn  5649: 
1.1061    raeburn  5650:     return ($blocked, $output);
1.854     kalberla 5651: }
1.490     raeburn  5652: 
1.60      matthew  5653: ###############################################
                   5654: 
1.682     raeburn  5655: sub check_ip_acc {
1.1201    raeburn  5656:     my ($acc,$clientip)=@_;
1.682     raeburn  5657:     &Apache::lonxml::debug("acc is $acc");
                   5658:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5659:         return 1;
                   5660:     }
1.1339    raeburn  5661:     my ($ip,$allowed);
                   5662:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   5663:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   5664:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   5665:     } else {
1.1350    raeburn  5666:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
                   5667:         $ip = $remote_ip || $env{'request.host'} || $clientip;
1.1339    raeburn  5668:     }
1.682     raeburn  5669: 
                   5670:     my $name;
1.1219    raeburn  5671:     my %access = (
                   5672:                      allowfrom => 1,
                   5673:                      denyfrom  => 0,
                   5674:                  );
                   5675:     my @allows;
                   5676:     my @denies;
                   5677:     foreach my $item (split(',',$acc)) {
                   5678:         $item =~ s/^\s*//;
                   5679:         $item =~ s/\s*$//;
                   5680:         my $pattern;
                   5681:         if ($item =~ /^\!(.+)$/) {
                   5682:             push(@denies,$1);
                   5683:         } else {
                   5684:             push(@allows,$item);
                   5685:         }
                   5686:    }
                   5687:    my $numdenies = scalar(@denies);
                   5688:    my $numallows = scalar(@allows);
                   5689:    my $count = 0;
                   5690:    foreach my $pattern (@denies,@allows) {
                   5691:         $count ++; 
                   5692:         my $acctype = 'allowfrom';
                   5693:         if ($count <= $numdenies) {
                   5694:             $acctype = 'denyfrom';
                   5695:         }
1.682     raeburn  5696:         if ($pattern =~ /\*$/) {
                   5697:             #35.8.*
                   5698:             $pattern=~s/\*//;
1.1219    raeburn  5699:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5700:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5701:             #35.8.3.[34-56]
                   5702:             my $low=$2;
                   5703:             my $high=$3;
                   5704:             $pattern=$1;
                   5705:             if ($ip =~ /^\Q$pattern\E/) {
                   5706:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  5707:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5708:             }
                   5709:         } elsif ($pattern =~ /^\*/) {
                   5710:             #*.msu.edu
                   5711:             $pattern=~s/\*//;
                   5712:             if (!defined($name)) {
                   5713:                 use Socket;
                   5714:                 my $netaddr=inet_aton($ip);
                   5715:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5716:             }
1.1219    raeburn  5717:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5718:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5719:             #127.0.0.1
1.1219    raeburn  5720:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5721:         } else {
                   5722:             #some.name.com
                   5723:             if (!defined($name)) {
                   5724:                 use Socket;
                   5725:                 my $netaddr=inet_aton($ip);
                   5726:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5727:             }
1.1219    raeburn  5728:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5729:         }
                   5730:         if ($allowed =~ /^(0|1)$/) { last; }
                   5731:     }
                   5732:     if ($allowed eq '') {
                   5733:         if ($numdenies && !$numallows) {
                   5734:             $allowed = 1;
                   5735:         } else {
                   5736:             $allowed = 0;
1.682     raeburn  5737:         }
                   5738:     }
                   5739:     return $allowed;
                   5740: }
                   5741: 
                   5742: ###############################################
                   5743: 
1.60      matthew  5744: =pod
                   5745: 
1.112     bowersj2 5746: =head1 Domain Template Functions
                   5747: 
                   5748: =over 4
                   5749: 
                   5750: =item * &determinedomain()
1.60      matthew  5751: 
                   5752: Inputs: $domain (usually will be undef)
                   5753: 
1.63      www      5754: Returns: Determines which domain should be used for designs
1.60      matthew  5755: 
                   5756: =cut
1.54      www      5757: 
1.60      matthew  5758: ###############################################
1.63      www      5759: sub determinedomain {
                   5760:     my $domain=shift;
1.531     albertel 5761:     if (! $domain) {
1.60      matthew  5762:         # Determine domain if we have not been given one
1.893     raeburn  5763:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5764:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5765:         if ($env{'request.role.domain'}) { 
                   5766:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5767:         }
                   5768:     }
1.63      www      5769:     return $domain;
                   5770: }
                   5771: ###############################################
1.517     raeburn  5772: 
1.518     albertel 5773: sub devalidate_domconfig_cache {
                   5774:     my ($udom)=@_;
                   5775:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5776: }
                   5777: 
                   5778: # ---------------------- Get domain configuration for a domain
                   5779: sub get_domainconf {
                   5780:     my ($udom) = @_;
                   5781:     my $cachetime=1800;
                   5782:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5783:     if (defined($cached)) { return %{$result}; }
                   5784: 
                   5785:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5786: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5787:     my (%designhash,%legacy);
1.518     albertel 5788:     if (keys(%domconfig) > 0) {
                   5789:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5790:             if (keys(%{$domconfig{'login'}})) {
                   5791:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5792:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  5793:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5794:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5795:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5796:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5797:                                         if ($key eq 'loginvia') {
                   5798:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5799:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5800:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5801:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5802: 
                   5803:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5804:                                                 } else {
                   5805:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5806:                                                 }
1.948     raeburn  5807:                                             }
1.1208    raeburn  5808:                                         } elsif ($key eq 'headtag') {
                   5809:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5810:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5811:                                             }
1.946     raeburn  5812:                                         }
1.1208    raeburn  5813:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5814:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5815:                                         }
1.946     raeburn  5816:                                     }
                   5817:                                 }
                   5818:                             }
1.1366    raeburn  5819:                         } elsif ($key eq 'saml') {
                   5820:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5821:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
                   5822:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
                   5823:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
                   5824:                                         foreach my $item ('text','img','alt','url','title','notsso') {
                   5825:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
                   5826:                                         }
                   5827:                                     }
                   5828:                                 }
                   5829:                             }
1.946     raeburn  5830:                         } else {
                   5831:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5832:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5833:                                     $domconfig{'login'}{$key}{$img};
                   5834:                             }
1.699     raeburn  5835:                         }
                   5836:                     } else {
                   5837:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5838:                     }
1.632     raeburn  5839:                 }
                   5840:             } else {
                   5841:                 $legacy{'login'} = 1;
1.518     albertel 5842:             }
1.632     raeburn  5843:         } else {
                   5844:             $legacy{'login'} = 1;
1.518     albertel 5845:         }
                   5846:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5847:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5848:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5849:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5850:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5851:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5852:                         }
1.518     albertel 5853:                     }
                   5854:                 }
1.632     raeburn  5855:             } else {
                   5856:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5857:             }
1.632     raeburn  5858:         } else {
                   5859:             $legacy{'rolecolors'} = 1;
1.518     albertel 5860:         }
1.948     raeburn  5861:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5862:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5863:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5864:             }
                   5865:         }
1.632     raeburn  5866:         if (keys(%legacy) > 0) {
                   5867:             my %legacyhash = &get_legacy_domconf($udom);
                   5868:             foreach my $item (keys(%legacyhash)) {
                   5869:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5870:                     if ($legacy{'login'}) { 
                   5871:                         $designhash{$item} = $legacyhash{$item};
                   5872:                     }
                   5873:                 } else {
                   5874:                     if ($legacy{'rolecolors'}) {
                   5875:                         $designhash{$item} = $legacyhash{$item};
                   5876:                     }
1.518     albertel 5877:                 }
                   5878:             }
                   5879:         }
1.632     raeburn  5880:     } else {
                   5881:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5882:     }
                   5883:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5884: 				  $cachetime);
                   5885:     return %designhash;
                   5886: }
                   5887: 
1.632     raeburn  5888: sub get_legacy_domconf {
                   5889:     my ($udom) = @_;
                   5890:     my %legacyhash;
                   5891:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5892:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5893:     if (-e $designfile) {
1.1317    raeburn  5894:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  5895:             while (my $line = <$fh>) {
                   5896:                 next if ($line =~ /^\#/);
                   5897:                 chomp($line);
                   5898:                 my ($key,$val)=(split(/\=/,$line));
                   5899:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5900:             }
                   5901:             close($fh);
                   5902:         }
                   5903:     }
1.1026    raeburn  5904:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5905:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5906:     }
                   5907:     return %legacyhash;
                   5908: }
                   5909: 
1.63      www      5910: =pod
                   5911: 
1.112     bowersj2 5912: =item * &domainlogo()
1.63      www      5913: 
                   5914: Inputs: $domain (usually will be undef)
                   5915: 
                   5916: Returns: A link to a domain logo, if the domain logo exists.
                   5917: If the domain logo does not exist, a description of the domain.
                   5918: 
                   5919: =cut
1.112     bowersj2 5920: 
1.63      www      5921: ###############################################
                   5922: sub domainlogo {
1.517     raeburn  5923:     my $domain = &determinedomain(shift);
1.518     albertel 5924:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5925:     # See if there is a logo
                   5926:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5927:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5928:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5929: 	    if ($imgsrc =~ m{^/res/}) {
                   5930: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5931: 		&Apache::lonnet::repcopy($local_name);
                   5932: 	    }
                   5933: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5934:         } 
                   5935:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5936:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5937:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5938:     } else {
1.60      matthew  5939:         return '';
1.59      www      5940:     }
                   5941: }
1.63      www      5942: ##############################################
                   5943: 
                   5944: =pod
                   5945: 
1.112     bowersj2 5946: =item * &designparm()
1.63      www      5947: 
                   5948: Inputs: $which parameter; $domain (usually will be undef)
                   5949: 
                   5950: Returns: value of designparamter $which
                   5951: 
                   5952: =cut
1.112     bowersj2 5953: 
1.397     albertel 5954: 
1.400     albertel 5955: ##############################################
1.397     albertel 5956: sub designparm {
                   5957:     my ($which,$domain)=@_;
                   5958:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5959:         return $env{'environment.color.'.$which};
1.96      www      5960:     }
1.63      www      5961:     $domain=&determinedomain($domain);
1.1016    raeburn  5962:     my %domdesign;
                   5963:     unless ($domain eq 'public') {
                   5964:         %domdesign = &get_domainconf($domain);
                   5965:     }
1.520     raeburn  5966:     my $output;
1.517     raeburn  5967:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5968:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5969:     } else {
1.520     raeburn  5970:         $output = $defaultdesign{$which};
                   5971:     }
                   5972:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5973:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5974:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5975:             if ($output =~ m{^/res/}) {
                   5976:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5977:                 &Apache::lonnet::repcopy($local_name);
                   5978:             }
1.520     raeburn  5979:             $output = &lonhttpdurl($output);
                   5980:         }
1.63      www      5981:     }
1.520     raeburn  5982:     return $output;
1.63      www      5983: }
1.59      www      5984: 
1.822     bisitz   5985: ##############################################
                   5986: =pod
                   5987: 
1.832     bisitz   5988: =item * &authorspace()
                   5989: 
1.1028    raeburn  5990: Inputs: $url (usually will be undef).
1.832     bisitz   5991: 
1.1132    raeburn  5992: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5993:          directory being viewed (or for which action is being taken). 
                   5994:          If $url is provided, and begins /priv/<domain>/<uname>
                   5995:          the path will be that portion of the $context argument.
                   5996:          Otherwise the path will be for the author space of the current
                   5997:          user when the current role is author, or for that of the 
                   5998:          co-author/assistant co-author space when the current role 
                   5999:          is co-author or assistant co-author.
1.832     bisitz   6000: 
                   6001: =cut
                   6002: 
                   6003: sub authorspace {
1.1028    raeburn  6004:     my ($url) = @_;
                   6005:     if ($url ne '') {
                   6006:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   6007:            return $1;
                   6008:         }
                   6009:     }
1.832     bisitz   6010:     my $caname = '';
1.1024    www      6011:     my $cadom = '';
1.1028    raeburn  6012:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      6013:         ($cadom,$caname) =
1.832     bisitz   6014:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  6015:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   6016:         $caname = $env{'user.name'};
1.1024    www      6017:         $cadom = $env{'user.domain'};
1.832     bisitz   6018:     }
1.1028    raeburn  6019:     if (($caname ne '') && ($cadom ne '')) {
                   6020:         return "/priv/$cadom/$caname/";
                   6021:     }
                   6022:     return;
1.832     bisitz   6023: }
                   6024: 
                   6025: ##############################################
                   6026: =pod
                   6027: 
1.822     bisitz   6028: =item * &head_subbox()
                   6029: 
                   6030: Inputs: $content (contains HTML code with page functions, etc.)
                   6031: 
                   6032: Returns: HTML div with $content
                   6033:          To be included in page header
                   6034: 
                   6035: =cut
                   6036: 
                   6037: sub head_subbox {
                   6038:     my ($content)=@_;
                   6039:     my $output =
1.993     raeburn  6040:         '<div class="LC_head_subbox">'
1.822     bisitz   6041:        .$content
                   6042:        .'</div>'
                   6043: }
                   6044: 
                   6045: ##############################################
                   6046: =pod
                   6047: 
                   6048: =item * &CSTR_pageheader()
                   6049: 
1.1026    raeburn  6050: Input: (optional) filename from which breadcrumb trail is built.
                   6051:        In most cases no input as needed, as $env{'request.filename'}
                   6052:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   6053: 
                   6054: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  6055:          To be included on Authoring Space pages
1.822     bisitz   6056: 
                   6057: =cut
                   6058: 
                   6059: sub CSTR_pageheader {
1.1026    raeburn  6060:     my ($trailfile) = @_;
                   6061:     if ($trailfile eq '') {
                   6062:         $trailfile = $env{'request.filename'};
                   6063:     }
                   6064: 
                   6065: # this is for resources; directories have customtitle, and crumbs
                   6066: # and select recent are created in lonpubdir.pm
                   6067: 
                   6068:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      6069:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  6070:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  6071:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   6072:     $formaction =~ s{/+}{/}g;
1.822     bisitz   6073: 
                   6074:     my $parentpath = '';
                   6075:     my $lastitem = '';
                   6076:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   6077:         $parentpath = $1;
                   6078:         $lastitem = $2;
                   6079:     } else {
                   6080:         $lastitem = $thisdisfn;
                   6081:     }
1.921     bisitz   6082: 
1.1246    raeburn  6083:     my ($crsauthor,$title);
                   6084:     if (($env{'request.course.id'}) &&
                   6085:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  6086:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  6087:         $crsauthor = 1;
                   6088:         $title = &mt('Course Authoring Space');
                   6089:     } else {
                   6090:         $title = &mt('Authoring Space');
                   6091:     }
                   6092: 
1.1314    raeburn  6093:     my ($target,$crumbtarget) = (' target="_top"','_top'); #FIXME lonpubdir: target="_parent"
1.1313    raeburn  6094:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
1.1314    raeburn  6095:         $target = '';
                   6096:         $crumbtarget = '';
1.1313    raeburn  6097:     }
                   6098: 
1.921     bisitz   6099:     my $output =
1.822     bisitz   6100:          '<div>'
                   6101:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  6102:         .'<b>'.$title.'</b> '
1.1314    raeburn  6103:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   6104:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   6105: 
                   6106:     if ($lastitem) {
                   6107:         $output .=
                   6108:              '<span class="LC_filename">'
                   6109:             .$lastitem
                   6110:             .'</span>';
                   6111:     }
1.1245    raeburn  6112: 
1.1246    raeburn  6113:     if ($crsauthor) {
                   6114:         $output .= '</form>'.&Apache::lonmenu::constspaceform();
                   6115:     } else {
                   6116:         $output .=
                   6117:              '<br />'
1.1314    raeburn  6118:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.1246    raeburn  6119:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   6120:             .'</form>'
                   6121:             .&Apache::lonmenu::constspaceform();
                   6122:     }
                   6123:     $output .= '</div>';
1.921     bisitz   6124: 
                   6125:     return $output;
1.822     bisitz   6126: }
                   6127: 
1.60      matthew  6128: ###############################################
                   6129: ###############################################
                   6130: 
                   6131: =pod
                   6132: 
1.112     bowersj2 6133: =back
                   6134: 
1.549     albertel 6135: =head1 HTML Helpers
1.112     bowersj2 6136: 
                   6137: =over 4
                   6138: 
                   6139: =item * &bodytag()
1.60      matthew  6140: 
                   6141: Returns a uniform header for LON-CAPA web pages.
                   6142: 
                   6143: Inputs: 
                   6144: 
1.112     bowersj2 6145: =over 4
                   6146: 
                   6147: =item * $title, A title to be displayed on the page.
                   6148: 
                   6149: =item * $function, the current role (can be undef).
                   6150: 
                   6151: =item * $addentries, extra parameters for the <body> tag.
                   6152: 
                   6153: =item * $bodyonly, if defined, only return the <body> tag.
                   6154: 
                   6155: =item * $domain, if defined, force a given domain.
                   6156: 
                   6157: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      6158:             text interface only)
1.60      matthew  6159: 
1.814     bisitz   6160: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   6161:                      navigational links
1.317     albertel 6162: 
1.338     albertel 6163: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   6164: 
1.460     albertel 6165: =item * $args, optional argument valid values are
                   6166:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1274    raeburn  6167:             use_absolute     -> for external resource or syllabus, this will
                   6168:                                 contain https://<hostname> if server uses
                   6169:                                 https (as per hosts.tab), but request is for http
                   6170:             hostname         -> hostname, from $r->hostname().
1.460     albertel 6171: 
1.1096    raeburn  6172: =item * $advtoolsref, optional argument, ref to an array containing
                   6173:             inlineremote items to be added in "Functions" menu below
                   6174:             breadcrumbs.
                   6175: 
1.1316    raeburn  6176: =item * $ltiscope, optional argument, will be one of: resource, map or
                   6177:             course, if LON-CAPA is in LTI Provider context. Value is
                   6178:             the scope of use, i.e., launch was for access to a single, a map
                   6179:             or the entire course.
                   6180: 
                   6181: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   6182:             context, this will contain the URL for the landing item in
                   6183:             the course, after launch from an LTI Consumer
                   6184: 
1.1318    raeburn  6185: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   6186:             context, this will contain a reference to hash of items
                   6187:             to be included in the page header and/or inline menu.
                   6188: 
1.112     bowersj2 6189: =back
                   6190: 
1.60      matthew  6191: Returns: A uniform header for LON-CAPA web pages.  
                   6192: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   6193: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   6194: other decorations will be returned.
                   6195: 
                   6196: =cut
                   6197: 
1.54      www      6198: sub bodytag {
1.831     bisitz   6199:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1359    raeburn  6200:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
                   6201:         $ltimenu,$menucoll,$menuref)=@_;
1.339     albertel 6202: 
1.954     raeburn  6203:     my $public;
                   6204:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   6205:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   6206:         $public = 1;
                   6207:     }
1.460     albertel 6208:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  6209:     my $httphost = $args->{'use_absolute'};
1.1274    raeburn  6210:     my $hostname = $args->{'hostname'};
1.339     albertel 6211: 
1.183     matthew  6212:     $function = &get_users_function() if (!$function);
1.339     albertel 6213:     my $img =    &designparm($function.'.img',$domain);
                   6214:     my $font =   &designparm($function.'.font',$domain);
                   6215:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   6216: 
1.803     bisitz   6217:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 6218: 		   'bgcolor' => $pgbg,
1.339     albertel 6219: 		   'text'    => $font,
                   6220:                    'alink'   => &designparm($function.'.alink',$domain),
                   6221: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   6222: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 6223:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 6224: 
1.63      www      6225:  # role and realm
1.1178    raeburn  6226:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   6227:     if ($realm) {
                   6228:         $realm = '/'.$realm;
                   6229:     }
1.1357    raeburn  6230:     if ($role eq 'ca') {
1.479     albertel 6231:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 6232:         $realm = &plainname($rname,$rdom);
1.378     raeburn  6233:     } 
1.55      www      6234: # realm
1.1357    raeburn  6235:     my ($cid,$sec);
1.258     albertel 6236:     if ($env{'request.course.id'}) {
1.1357    raeburn  6237:         $cid = $env{'request.course.id'};
                   6238:         if ($env{'request.course.sec'}) {
                   6239:             $sec = $env{'request.course.sec'};
                   6240:         }
                   6241:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
                   6242:         if (&Apache::lonnet::is_course($1,$2)) {
                   6243:             $cid = $1.'_'.$2;
                   6244:             $sec = $3;
                   6245:         }
                   6246:     }
                   6247:     if ($cid) {
1.378     raeburn  6248:         if ($env{'request.role'} !~ /^cr/) {
                   6249:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  6250:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269    raeburn  6251:             if ($env{'request.role.desc'}) {
                   6252:                 $role = $env{'request.role.desc'};
                   6253:             } else {
                   6254:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6255:             }
1.1257    raeburn  6256:         } else {
                   6257:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  6258:         }
1.1357    raeburn  6259:         if ($sec) {
                   6260:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
1.898     raeburn  6261:         }   
1.1357    raeburn  6262: 	$realm = $env{'course.'.$cid.'.description'};
1.378     raeburn  6263:     } else {
                   6264:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6265:     }
1.433     albertel 6266: 
1.359     albertel 6267:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 6268: 
1.438     albertel 6269:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6270: 
1.101     www      6271: # construct main body tag
1.359     albertel 6272:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  6273: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6274: 
1.1131    raeburn  6275:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6276: 
1.1130    raeburn  6277:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6278:         return $bodytag;
1.1130    raeburn  6279:     }
1.359     albertel 6280: 
1.954     raeburn  6281:     if ($public) {
1.433     albertel 6282: 	undef($role);
                   6283:     }
1.1318    raeburn  6284: 
1.1359    raeburn  6285:     my $showcrstitle = 1;
1.1357    raeburn  6286:     if (($cid) && ($env{'request.lti.login'})) {
1.1318    raeburn  6287:         if (ref($ltimenu) eq 'HASH') {
                   6288:             unless ($ltimenu->{'role'}) {
                   6289:                 undef($role);
                   6290:             }
                   6291:             unless ($ltimenu->{'coursetitle'}) {
                   6292:                 $realm='&nbsp;';
1.1359    raeburn  6293:                 $showcrstitle = 0;
                   6294:             }
                   6295:         }
                   6296:     } elsif (($cid) && ($menucoll)) {
                   6297:         if (ref($menuref) eq 'HASH') {
                   6298:             unless ($menuref->{'role'}) {
                   6299:                 undef($role);
                   6300:             }
                   6301:             unless ($menuref->{'crs'}) {
                   6302:                 $realm='&nbsp;';
                   6303:                 $showcrstitle = 0;
1.1318    raeburn  6304:             }
                   6305:         }
                   6306:     }
                   6307: 
1.762     bisitz   6308:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6309:     #
                   6310:     # Extra info if you are the DC
                   6311:     my $dc_info = '';
1.1359    raeburn  6312:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
1.1357    raeburn  6313:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
1.917     raeburn  6314:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6315:         $dc_info =~ s/\s+$//;
1.359     albertel 6316:     }
                   6317: 
1.1237    raeburn  6318:     my $crstype;
1.1357    raeburn  6319:     if ($cid) {
                   6320:         $crstype = $env{'course.'.$cid.'.type'};
1.1237    raeburn  6321:     } elsif ($args->{'crstype'}) {
                   6322:         $crstype = $args->{'crstype'};
                   6323:     }
                   6324:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   6325:         undef($role);
                   6326:     } else {
1.1242    raeburn  6327:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  6328:     }
1.853     droeschl 6329: 
1.903     droeschl 6330:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   6331: 
                   6332:         #    if ($env{'request.state'} eq 'construct') {
                   6333:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   6334:         #    }
                   6335: 
1.1130    raeburn  6336:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  6337:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 6338: 
1.1318    raeburn  6339:         unless ($args->{'no_primary_menu'}) {
1.1369    raeburn  6340:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
                   6341:                                                               $args->{'links_disabled'});
1.359     albertel 6342: 
1.1318    raeburn  6343:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   6344:                 if ($dc_info) {
                   6345:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   6346:                 }
                   6347:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
                   6348:                                <em>$realm</em> $dc_info</div>|;
                   6349:                 return $bodytag;
                   6350:             }
1.894     droeschl 6351: 
1.1318    raeburn  6352:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   6353:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   6354:             }
1.916     droeschl 6355: 
1.1318    raeburn  6356:             $bodytag .= $right;
1.852     droeschl 6357: 
1.1318    raeburn  6358:             if ($dc_info) {
                   6359:                 $dc_info = &dc_courseid_toggle($dc_info);
                   6360:             }
                   6361:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.917     raeburn  6362:         }
1.916     droeschl 6363: 
1.1169    raeburn  6364:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  6365:         if ($args->{'no_secondary_menu'}) {
                   6366:             return $bodytag;
                   6367:         }
1.1169    raeburn  6368:         #don't show menus for public users
1.954     raeburn  6369:         if (!$public){
1.1318    raeburn  6370:             unless ($args->{'no_inline_menu'}) {
                   6371:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
1.1359    raeburn  6372:                                                             $args->{'no_primary_menu'},
1.1369    raeburn  6373:                                                             $menucoll,$menuref,
                   6374:                                                             $args->{'links_disabled'});
1.1318    raeburn  6375:             }
1.903     droeschl 6376:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  6377:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   6378:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 6379:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1316    raeburn  6380:                                 $args->{'bread_crumbs'},'','',$hostname,$ltiscope,$ltiuri);
1.1096    raeburn  6381:             } elsif ($forcereg) {
                   6382:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1258    raeburn  6383:                                                             $args->{'group'},
1.1274    raeburn  6384:                                                             $args->{'hide_buttons'},
1.1316    raeburn  6385:                                                             $hostname,$ltiscope,$ltiuri);
1.1096    raeburn  6386:             } else {
                   6387:                 $bodytag .= 
                   6388:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6389:                                                         $forcereg,$args->{'group'},
                   6390:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  6391:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  6392:             }
1.903     droeschl 6393:         }else{
                   6394:             # this is to seperate menu from content when there's no secondary
                   6395:             # menu. Especially needed for public accessible ressources.
                   6396:             $bodytag .= '<hr style="clear:both" />';
                   6397:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  6398:         }
1.903     droeschl 6399: 
1.235     raeburn  6400:         return $bodytag;
1.182     matthew  6401: }
                   6402: 
1.917     raeburn  6403: sub dc_courseid_toggle {
                   6404:     my ($dc_info) = @_;
1.980     raeburn  6405:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  6406:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  6407:            &mt('(More ...)').'</a></span>'.
                   6408:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   6409: }
                   6410: 
1.330     albertel 6411: sub make_attr_string {
                   6412:     my ($register,$attr_ref) = @_;
                   6413: 
                   6414:     if ($attr_ref && !ref($attr_ref)) {
                   6415: 	die("addentries Must be a hash ref ".
                   6416: 	    join(':',caller(1))." ".
                   6417: 	    join(':',caller(0))." ");
                   6418:     }
                   6419: 
                   6420:     if ($register) {
1.339     albertel 6421: 	my ($on_load,$on_unload);
                   6422: 	foreach my $key (keys(%{$attr_ref})) {
                   6423: 	    if      (lc($key) eq 'onload') {
                   6424: 		$on_load.=$attr_ref->{$key}.';';
                   6425: 		delete($attr_ref->{$key});
                   6426: 
                   6427: 	    } elsif (lc($key) eq 'onunload') {
                   6428: 		$on_unload.=$attr_ref->{$key}.';';
                   6429: 		delete($attr_ref->{$key});
                   6430: 	    }
                   6431: 	}
1.953     droeschl 6432: 	$attr_ref->{'onload'}  = $on_load;
                   6433: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 6434:     }
1.339     albertel 6435: 
1.330     albertel 6436:     my $attr_string;
1.1159    raeburn  6437:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6438: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6439:     }
                   6440:     return $attr_string;
                   6441: }
                   6442: 
                   6443: 
1.182     matthew  6444: ###############################################
1.251     albertel 6445: ###############################################
                   6446: 
                   6447: =pod
                   6448: 
                   6449: =item * &endbodytag()
                   6450: 
                   6451: Returns a uniform footer for LON-CAPA web pages.
                   6452: 
1.635     raeburn  6453: Inputs: 1 - optional reference to an args hash
                   6454: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6455: a 'Continue' link is not displayed if the page contains an
                   6456: internal redirect in the <head></head> section,
                   6457: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6458: 
                   6459: =cut
                   6460: 
                   6461: sub endbodytag {
1.635     raeburn  6462:     my ($args) = @_;
1.1080    raeburn  6463:     my $endbodytag;
                   6464:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6465:         $endbodytag='</body>';
                   6466:     }
1.315     albertel 6467:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6468:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   6469: 	    $endbodytag=
                   6470: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   6471: 	        &mt('Continue').'</a>'.
                   6472: 	        $endbodytag;
                   6473:         }
1.315     albertel 6474:     }
1.251     albertel 6475:     return $endbodytag;
                   6476: }
                   6477: 
1.352     albertel 6478: =pod
                   6479: 
                   6480: =item * &standard_css()
                   6481: 
                   6482: Returns a style sheet
                   6483: 
                   6484: Inputs: (all optional)
                   6485:             domain         -> force to color decorate a page for a specific
                   6486:                                domain
                   6487:             function       -> force usage of a specific rolish color scheme
                   6488:             bgcolor        -> override the default page bgcolor
                   6489: 
                   6490: =cut
                   6491: 
1.343     albertel 6492: sub standard_css {
1.345     albertel 6493:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6494:     $function  = &get_users_function() if (!$function);
                   6495:     my $img    = &designparm($function.'.img',   $domain);
                   6496:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6497:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6498:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6499: #second colour for later usage
1.345     albertel 6500:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6501:     my $pgbg_or_bgcolor =
                   6502: 	         $bgcolor ||
1.352     albertel 6503: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6504:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6505:     my $alink  = &designparm($function.'.alink', $domain);
                   6506:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6507:     my $link   = &designparm($function.'.link',  $domain);
                   6508: 
1.602     albertel 6509:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6510:     my $mono                 = 'monospace';
1.850     bisitz   6511:     my $data_table_head      = $sidebg;
                   6512:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6513:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6514:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6515:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6516:     my $mail_new             = '#FFBB77';
                   6517:     my $mail_new_hover       = '#DD9955';
                   6518:     my $mail_read            = '#BBBB77';
                   6519:     my $mail_read_hover      = '#999944';
                   6520:     my $mail_replied         = '#AAAA88';
                   6521:     my $mail_replied_hover   = '#888855';
                   6522:     my $mail_other           = '#99BBBB';
                   6523:     my $mail_other_hover     = '#669999';
1.391     albertel 6524:     my $table_header         = '#DDDDDD';
1.489     raeburn  6525:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6526:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6527:     my $button_hover         = '#BF2317';
1.392     albertel 6528: 
1.608     albertel 6529:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6530:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6531:                                              : '0 3px 0 4px';
1.448     albertel 6532: 
1.523     albertel 6533: 
1.343     albertel 6534:     return <<END;
1.947     droeschl 6535: 
                   6536: /* needed for iframe to allow 100% height in FF */
                   6537: body, html { 
                   6538:     margin: 0;
                   6539:     padding: 0 0.5%;
                   6540:     height: 99%; /* to avoid scrollbars */
                   6541: }
                   6542: 
1.795     www      6543: body {
1.911     bisitz   6544:   font-family: $sans;
                   6545:   line-height:130%;
                   6546:   font-size:0.83em;
                   6547:   color:$font;
1.795     www      6548: }
                   6549: 
1.959     onken    6550: a:focus,
                   6551: a:focus img {
1.795     www      6552:   color: red;
                   6553: }
1.698     harmsja  6554: 
1.911     bisitz   6555: form, .inline {
                   6556:   display: inline;
1.795     www      6557: }
1.721     harmsja  6558: 
1.795     www      6559: .LC_right {
1.911     bisitz   6560:   text-align:right;
1.795     www      6561: }
                   6562: 
                   6563: .LC_middle {
1.911     bisitz   6564:   vertical-align:middle;
1.795     www      6565: }
1.721     harmsja  6566: 
1.1130    raeburn  6567: .LC_floatleft {
                   6568:   float: left;
                   6569: }
                   6570: 
                   6571: .LC_floatright {
                   6572:   float: right;
                   6573: }
                   6574: 
1.911     bisitz   6575: .LC_400Box {
                   6576:   width:400px;
                   6577: }
1.721     harmsja  6578: 
1.947     droeschl 6579: .LC_iframecontainer {
                   6580:     width: 98%;
                   6581:     margin: 0;
                   6582:     position: fixed;
                   6583:     top: 8.5em;
                   6584:     bottom: 0;
                   6585: }
                   6586: 
                   6587: .LC_iframecontainer iframe{
                   6588:     border: none;
                   6589:     width: 100%;
                   6590:     height: 100%;
                   6591: }
                   6592: 
1.778     bisitz   6593: .LC_filename {
                   6594:   font-family: $mono;
                   6595:   white-space:pre;
1.921     bisitz   6596:   font-size: 120%;
1.778     bisitz   6597: }
                   6598: 
                   6599: .LC_fileicon {
                   6600:   border: none;
                   6601:   height: 1.3em;
                   6602:   vertical-align: text-bottom;
                   6603:   margin-right: 0.3em;
                   6604:   text-decoration:none;
                   6605: }
                   6606: 
1.1008    www      6607: .LC_setting {
                   6608:   text-decoration:underline;
                   6609: }
                   6610: 
1.350     albertel 6611: .LC_error {
                   6612:   color: red;
                   6613: }
1.795     www      6614: 
1.1097    bisitz   6615: .LC_warning {
                   6616:   color: darkorange;
                   6617: }
                   6618: 
1.457     albertel 6619: .LC_diff_removed {
1.733     bisitz   6620:   color: red;
1.394     albertel 6621: }
1.532     albertel 6622: 
                   6623: .LC_info,
1.457     albertel 6624: .LC_success,
                   6625: .LC_diff_added {
1.350     albertel 6626:   color: green;
                   6627: }
1.795     www      6628: 
1.802     bisitz   6629: div.LC_confirm_box {
                   6630:   background-color: #FAFAFA;
                   6631:   border: 1px solid $lg_border_color;
                   6632:   margin-right: 0;
                   6633:   padding: 5px;
                   6634: }
                   6635: 
                   6636: div.LC_confirm_box .LC_error img,
                   6637: div.LC_confirm_box .LC_success img {
                   6638:   vertical-align: middle;
                   6639: }
                   6640: 
1.1242    raeburn  6641: .LC_maxwidth {
                   6642:   max-width: 100%;
                   6643:   height: auto;
                   6644: }
                   6645: 
1.1243    raeburn  6646: .LC_textsize_mobile {
                   6647:   \@media only screen and (max-device-width: 480px) {
                   6648:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6649:   }
                   6650: }
                   6651: 
1.440     albertel 6652: .LC_icon {
1.771     droeschl 6653:   border: none;
1.790     droeschl 6654:   vertical-align: middle;
1.771     droeschl 6655: }
                   6656: 
1.543     albertel 6657: .LC_docs_spacer {
                   6658:   width: 25px;
                   6659:   height: 1px;
1.771     droeschl 6660:   border: none;
1.543     albertel 6661: }
1.346     albertel 6662: 
1.532     albertel 6663: .LC_internal_info {
1.735     bisitz   6664:   color: #999999;
1.532     albertel 6665: }
                   6666: 
1.794     www      6667: .LC_discussion {
1.1050    www      6668:   background: $data_table_dark;
1.911     bisitz   6669:   border: 1px solid black;
                   6670:   margin: 2px;
1.794     www      6671: }
                   6672: 
                   6673: .LC_disc_action_left {
1.1050    www      6674:   background: $sidebg;
1.911     bisitz   6675:   text-align: left;
1.1050    www      6676:   padding: 4px;
                   6677:   margin: 2px;
1.794     www      6678: }
                   6679: 
                   6680: .LC_disc_action_right {
1.1050    www      6681:   background: $sidebg;
1.911     bisitz   6682:   text-align: right;
1.1050    www      6683:   padding: 4px;
                   6684:   margin: 2px;
1.794     www      6685: }
                   6686: 
                   6687: .LC_disc_new_item {
1.911     bisitz   6688:   background: white;
                   6689:   border: 2px solid red;
1.1050    www      6690:   margin: 4px;
                   6691:   padding: 4px;
1.794     www      6692: }
                   6693: 
                   6694: .LC_disc_old_item {
1.911     bisitz   6695:   background: white;
1.1050    www      6696:   margin: 4px;
                   6697:   padding: 4px;
1.794     www      6698: }
                   6699: 
1.458     albertel 6700: table.LC_pastsubmission {
                   6701:   border: 1px solid black;
                   6702:   margin: 2px;
                   6703: }
                   6704: 
1.924     bisitz   6705: table#LC_menubuttons {
1.345     albertel 6706:   width: 100%;
                   6707:   background: $pgbg;
1.392     albertel 6708:   border: 2px;
1.402     albertel 6709:   border-collapse: separate;
1.803     bisitz   6710:   padding: 0;
1.345     albertel 6711: }
1.392     albertel 6712: 
1.801     tempelho 6713: table#LC_title_bar a {
                   6714:   color: $fontmenu;
                   6715: }
1.836     bisitz   6716: 
1.807     droeschl 6717: table#LC_title_bar {
1.819     tempelho 6718:   clear: both;
1.836     bisitz   6719:   display: none;
1.807     droeschl 6720: }
                   6721: 
1.795     www      6722: table#LC_title_bar,
1.933     droeschl 6723: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6724: table#LC_title_bar.LC_with_remote {
1.359     albertel 6725:   width: 100%;
1.392     albertel 6726:   border-color: $pgbg;
                   6727:   border-style: solid;
                   6728:   border-width: $border;
1.379     albertel 6729:   background: $pgbg;
1.801     tempelho 6730:   color: $fontmenu;
1.392     albertel 6731:   border-collapse: collapse;
1.803     bisitz   6732:   padding: 0;
1.819     tempelho 6733:   margin: 0;
1.359     albertel 6734: }
1.795     www      6735: 
1.933     droeschl 6736: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6737:     margin: 0;
                   6738:     padding: 0;
1.933     droeschl 6739:     position: relative;
                   6740:     list-style: none;
1.913     droeschl 6741: }
1.933     droeschl 6742: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6743:     display: inline;
                   6744: }
1.933     droeschl 6745: 
                   6746: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6747:     padding: 0;
1.933     droeschl 6748:     margin: 0;
                   6749:     float: left;
1.913     droeschl 6750: }
1.933     droeschl 6751: .LC_breadcrumb_tools_tools {
                   6752:     padding: 0;
                   6753:     margin: 0;
1.913     droeschl 6754:     float: right;
                   6755: }
                   6756: 
1.1240    raeburn  6757: .LC_placement_prog {
                   6758:     padding-right: 20px;
                   6759:     font-weight: bold;
                   6760:     font-size: 90%;
                   6761: }
                   6762: 
1.359     albertel 6763: table#LC_title_bar td {
                   6764:   background: $tabbg;
                   6765: }
1.795     www      6766: 
1.911     bisitz   6767: table#LC_menubuttons img {
1.803     bisitz   6768:   border: none;
1.346     albertel 6769: }
1.795     www      6770: 
1.842     droeschl 6771: .LC_breadcrumbs_component {
1.911     bisitz   6772:   float: right;
                   6773:   margin: 0 1em;
1.357     albertel 6774: }
1.842     droeschl 6775: .LC_breadcrumbs_component img {
1.911     bisitz   6776:   vertical-align: middle;
1.777     tempelho 6777: }
1.795     www      6778: 
1.1243    raeburn  6779: .LC_breadcrumbs_hoverable {
                   6780:   background: $sidebg;
                   6781: }
                   6782: 
1.383     albertel 6783: td.LC_table_cell_checkbox {
                   6784:   text-align: center;
                   6785: }
1.795     www      6786: 
                   6787: .LC_fontsize_small {
1.911     bisitz   6788:   font-size: 70%;
1.705     tempelho 6789: }
                   6790: 
1.844     bisitz   6791: #LC_breadcrumbs {
1.911     bisitz   6792:   clear:both;
                   6793:   background: $sidebg;
                   6794:   border-bottom: 1px solid $lg_border_color;
                   6795:   line-height: 2.5em;
1.933     droeschl 6796:   overflow: hidden;
1.911     bisitz   6797:   margin: 0;
                   6798:   padding: 0;
1.995     raeburn  6799:   text-align: left;
1.819     tempelho 6800: }
1.862     bisitz   6801: 
1.1098    bisitz   6802: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6803:   clear:both;
                   6804:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6805:   border: 1px solid $sidebg;
1.1098    bisitz   6806:   margin: 0 0 10px 0;
1.966     bisitz   6807:   padding: 3px;
1.995     raeburn  6808:   text-align: left;
1.822     bisitz   6809: }
                   6810: 
1.795     www      6811: .LC_fontsize_medium {
1.911     bisitz   6812:   font-size: 85%;
1.705     tempelho 6813: }
                   6814: 
1.795     www      6815: .LC_fontsize_large {
1.911     bisitz   6816:   font-size: 120%;
1.705     tempelho 6817: }
                   6818: 
1.346     albertel 6819: .LC_menubuttons_inline_text {
                   6820:   color: $font;
1.698     harmsja  6821:   font-size: 90%;
1.701     harmsja  6822:   padding-left:3px;
1.346     albertel 6823: }
                   6824: 
1.934     droeschl 6825: .LC_menubuttons_inline_text img{
                   6826:   vertical-align: middle;
                   6827: }
                   6828: 
1.1051    www      6829: li.LC_menubuttons_inline_text img {
1.951     onken    6830:   cursor:pointer;
1.1002    droeschl 6831:   text-decoration: none;
1.951     onken    6832: }
                   6833: 
1.526     www      6834: .LC_menubuttons_link {
                   6835:   text-decoration: none;
                   6836: }
1.795     www      6837: 
1.522     albertel 6838: .LC_menubuttons_category {
1.521     www      6839:   color: $font;
1.526     www      6840:   background: $pgbg;
1.521     www      6841:   font-size: larger;
                   6842:   font-weight: bold;
                   6843: }
                   6844: 
1.346     albertel 6845: td.LC_menubuttons_text {
1.911     bisitz   6846:   color: $font;
1.346     albertel 6847: }
1.706     harmsja  6848: 
1.346     albertel 6849: .LC_current_location {
                   6850:   background: $tabbg;
                   6851: }
1.795     www      6852: 
1.1286    raeburn  6853: td.LC_zero_height {
                   6854:   line-height: 0; 
                   6855:   cellpadding: 0;
                   6856: }
                   6857: 
1.938     bisitz   6858: table.LC_data_table {
1.347     albertel 6859:   border: 1px solid #000000;
1.402     albertel 6860:   border-collapse: separate;
1.426     albertel 6861:   border-spacing: 1px;
1.610     albertel 6862:   background: $pgbg;
1.347     albertel 6863: }
1.795     www      6864: 
1.422     albertel 6865: .LC_data_table_dense {
                   6866:   font-size: small;
                   6867: }
1.795     www      6868: 
1.507     raeburn  6869: table.LC_nested_outer {
                   6870:   border: 1px solid #000000;
1.589     raeburn  6871:   border-collapse: collapse;
1.803     bisitz   6872:   border-spacing: 0;
1.507     raeburn  6873:   width: 100%;
                   6874: }
1.795     www      6875: 
1.879     raeburn  6876: table.LC_innerpickbox,
1.507     raeburn  6877: table.LC_nested {
1.803     bisitz   6878:   border: none;
1.589     raeburn  6879:   border-collapse: collapse;
1.803     bisitz   6880:   border-spacing: 0;
1.507     raeburn  6881:   width: 100%;
                   6882: }
1.795     www      6883: 
1.911     bisitz   6884: table.LC_data_table tr th,
                   6885: table.LC_calendar tr th,
1.879     raeburn  6886: table.LC_prior_tries tr th,
                   6887: table.LC_innerpickbox tr th {
1.349     albertel 6888:   font-weight: bold;
                   6889:   background-color: $data_table_head;
1.801     tempelho 6890:   color:$fontmenu;
1.701     harmsja  6891:   font-size:90%;
1.347     albertel 6892: }
1.795     www      6893: 
1.879     raeburn  6894: table.LC_innerpickbox tr th,
                   6895: table.LC_innerpickbox tr td {
                   6896:   vertical-align: top;
                   6897: }
                   6898: 
1.711     raeburn  6899: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6900:   background-color: #CCCCCC;
1.711     raeburn  6901:   font-weight: bold;
                   6902:   text-align: left;
                   6903: }
1.795     www      6904: 
1.912     bisitz   6905: table.LC_data_table tr.LC_odd_row > td {
                   6906:   background-color: $data_table_light;
                   6907:   padding: 2px;
                   6908:   vertical-align: top;
                   6909: }
                   6910: 
1.809     bisitz   6911: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6912:   background-color: $data_table_light;
1.912     bisitz   6913:   vertical-align: top;
                   6914: }
                   6915: 
                   6916: table.LC_data_table tr.LC_even_row > td {
                   6917:   background-color: $data_table_dark;
1.425     albertel 6918:   padding: 2px;
1.900     bisitz   6919:   vertical-align: top;
1.347     albertel 6920: }
1.795     www      6921: 
1.809     bisitz   6922: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6923:   background-color: $data_table_dark;
1.900     bisitz   6924:   vertical-align: top;
1.347     albertel 6925: }
1.795     www      6926: 
1.425     albertel 6927: table.LC_data_table tr.LC_data_table_highlight td {
                   6928:   background-color: $data_table_darker;
                   6929: }
1.795     www      6930: 
1.639     raeburn  6931: table.LC_data_table tr td.LC_leftcol_header {
                   6932:   background-color: $data_table_head;
                   6933:   font-weight: bold;
                   6934: }
1.795     www      6935: 
1.451     albertel 6936: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6937: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6938:   font-weight: bold;
                   6939:   font-style: italic;
                   6940:   text-align: center;
                   6941:   padding: 8px;
1.347     albertel 6942: }
1.795     www      6943: 
1.1114    raeburn  6944: table.LC_data_table tr.LC_empty_row td,
                   6945: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6946:   background-color: $sidebg;
                   6947: }
                   6948: 
                   6949: table.LC_nested tr.LC_empty_row td {
                   6950:   background-color: #FFFFFF;
                   6951: }
                   6952: 
1.890     droeschl 6953: table.LC_caption {
                   6954: }
                   6955: 
1.507     raeburn  6956: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6957:   padding: 4ex
                   6958: }
1.795     www      6959: 
1.507     raeburn  6960: table.LC_nested_outer tr th {
                   6961:   font-weight: bold;
1.801     tempelho 6962:   color:$fontmenu;
1.507     raeburn  6963:   background-color: $data_table_head;
1.701     harmsja  6964:   font-size: small;
1.507     raeburn  6965:   border-bottom: 1px solid #000000;
                   6966: }
1.795     www      6967: 
1.507     raeburn  6968: table.LC_nested_outer tr td.LC_subheader {
                   6969:   background-color: $data_table_head;
                   6970:   font-weight: bold;
                   6971:   font-size: small;
                   6972:   border-bottom: 1px solid #000000;
                   6973:   text-align: right;
1.451     albertel 6974: }
1.795     www      6975: 
1.507     raeburn  6976: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6977:   background-color: #CCCCCC;
1.451     albertel 6978:   font-weight: bold;
                   6979:   font-size: small;
1.507     raeburn  6980:   text-align: center;
                   6981: }
1.795     www      6982: 
1.589     raeburn  6983: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6984: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6985:   text-align: left;
1.451     albertel 6986: }
1.795     www      6987: 
1.507     raeburn  6988: table.LC_nested td {
1.735     bisitz   6989:   background-color: #FFFFFF;
1.451     albertel 6990:   font-size: small;
1.507     raeburn  6991: }
1.795     www      6992: 
1.507     raeburn  6993: table.LC_nested_outer tr th.LC_right_item,
                   6994: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6995: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6996: table.LC_nested tr td.LC_right_item {
1.451     albertel 6997:   text-align: right;
                   6998: }
                   6999: 
1.507     raeburn  7000: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   7001:   background-color: #EEEEEE;
1.451     albertel 7002: }
                   7003: 
1.473     raeburn  7004: table.LC_createuser {
                   7005: }
                   7006: 
                   7007: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  7008:   font-size: small;
1.473     raeburn  7009: }
                   7010: 
                   7011: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   7012:   background-color: #CCCCCC;
1.473     raeburn  7013:   font-weight: bold;
                   7014:   text-align: center;
                   7015: }
                   7016: 
1.349     albertel 7017: table.LC_calendar {
                   7018:   border: 1px solid #000000;
                   7019:   border-collapse: collapse;
1.917     raeburn  7020:   width: 98%;
1.349     albertel 7021: }
1.795     www      7022: 
1.349     albertel 7023: table.LC_calendar_pickdate {
                   7024:   font-size: xx-small;
                   7025: }
1.795     www      7026: 
1.349     albertel 7027: table.LC_calendar tr td {
                   7028:   border: 1px solid #000000;
                   7029:   vertical-align: top;
1.917     raeburn  7030:   width: 14%;
1.349     albertel 7031: }
1.795     www      7032: 
1.349     albertel 7033: table.LC_calendar tr td.LC_calendar_day_empty {
                   7034:   background-color: $data_table_dark;
                   7035: }
1.795     www      7036: 
1.779     bisitz   7037: table.LC_calendar tr td.LC_calendar_day_current {
                   7038:   background-color: $data_table_highlight;
1.777     tempelho 7039: }
1.795     www      7040: 
1.938     bisitz   7041: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 7042:   background-color: $mail_new;
                   7043: }
1.795     www      7044: 
1.938     bisitz   7045: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 7046:   background-color: $mail_new_hover;
                   7047: }
1.795     www      7048: 
1.938     bisitz   7049: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 7050:   background-color: $mail_read;
                   7051: }
1.795     www      7052: 
1.938     bisitz   7053: /*
                   7054: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 7055:   background-color: $mail_read_hover;
                   7056: }
1.938     bisitz   7057: */
1.795     www      7058: 
1.938     bisitz   7059: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 7060:   background-color: $mail_replied;
                   7061: }
1.795     www      7062: 
1.938     bisitz   7063: /*
                   7064: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 7065:   background-color: $mail_replied_hover;
                   7066: }
1.938     bisitz   7067: */
1.795     www      7068: 
1.938     bisitz   7069: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 7070:   background-color: $mail_other;
                   7071: }
1.795     www      7072: 
1.938     bisitz   7073: /*
                   7074: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 7075:   background-color: $mail_other_hover;
                   7076: }
1.938     bisitz   7077: */
1.494     raeburn  7078: 
1.777     tempelho 7079: table.LC_data_table tr > td.LC_browser_file,
                   7080: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   7081:   background: #AAEE77;
1.389     albertel 7082: }
1.795     www      7083: 
1.777     tempelho 7084: table.LC_data_table tr > td.LC_browser_file_locked,
                   7085: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 7086:   background: #FFAA99;
1.387     albertel 7087: }
1.795     www      7088: 
1.777     tempelho 7089: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   7090:   background: #888888;
1.779     bisitz   7091: }
1.795     www      7092: 
1.777     tempelho 7093: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   7094: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   7095:   background: #F8F866;
1.777     tempelho 7096: }
1.795     www      7097: 
1.696     bisitz   7098: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   7099:   background: #E0E8FF;
1.387     albertel 7100: }
1.696     bisitz   7101: 
1.707     bisitz   7102: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   7103:   /* background: #77FF77; */
1.707     bisitz   7104: }
1.795     www      7105: 
1.707     bisitz   7106: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   7107:   border-right: 8px solid #FFFF77;
1.707     bisitz   7108: }
1.795     www      7109: 
1.707     bisitz   7110: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   7111:   border-right: 8px solid #FFAA77;
1.707     bisitz   7112: }
1.795     www      7113: 
1.707     bisitz   7114: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   7115:   border-right: 8px solid #FF7777;
1.707     bisitz   7116: }
1.795     www      7117: 
1.707     bisitz   7118: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   7119:   border-right: 8px solid #AAFF77;
1.707     bisitz   7120: }
1.795     www      7121: 
1.707     bisitz   7122: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   7123:   border-right: 8px solid #11CC55;
1.707     bisitz   7124: }
                   7125: 
1.388     albertel 7126: span.LC_current_location {
1.701     harmsja  7127:   font-size:larger;
1.388     albertel 7128:   background: $pgbg;
                   7129: }
1.387     albertel 7130: 
1.1029    www      7131: span.LC_current_nav_location {
                   7132:   font-weight:bold;
                   7133:   background: $sidebg;
                   7134: }
                   7135: 
1.395     albertel 7136: span.LC_parm_menu_item {
                   7137:   font-size: larger;
                   7138: }
1.795     www      7139: 
1.395     albertel 7140: span.LC_parm_scope_all {
                   7141:   color: red;
                   7142: }
1.795     www      7143: 
1.395     albertel 7144: span.LC_parm_scope_folder {
                   7145:   color: green;
                   7146: }
1.795     www      7147: 
1.395     albertel 7148: span.LC_parm_scope_resource {
                   7149:   color: orange;
                   7150: }
1.795     www      7151: 
1.395     albertel 7152: span.LC_parm_part {
                   7153:   color: blue;
                   7154: }
1.795     www      7155: 
1.911     bisitz   7156: span.LC_parm_folder,
                   7157: span.LC_parm_symb {
1.395     albertel 7158:   font-size: x-small;
                   7159:   font-family: $mono;
                   7160:   color: #AAAAAA;
                   7161: }
                   7162: 
1.977     bisitz   7163: ul.LC_parm_parmlist li {
                   7164:   display: inline-block;
                   7165:   padding: 0.3em 0.8em;
                   7166:   vertical-align: top;
                   7167:   width: 150px;
                   7168:   border-top:1px solid $lg_border_color;
                   7169: }
                   7170: 
1.795     www      7171: td.LC_parm_overview_level_menu,
                   7172: td.LC_parm_overview_map_menu,
                   7173: td.LC_parm_overview_parm_selectors,
                   7174: td.LC_parm_overview_restrictions  {
1.396     albertel 7175:   border: 1px solid black;
                   7176:   border-collapse: collapse;
                   7177: }
1.795     www      7178: 
1.1285    raeburn  7179: span.LC_parm_recursive,
                   7180: td.LC_parm_recursive {
                   7181:   font-weight: bold;
                   7182:   font-size: smaller;
                   7183: }
                   7184: 
1.396     albertel 7185: table.LC_parm_overview_restrictions td {
                   7186:   border-width: 1px 4px 1px 4px;
                   7187:   border-style: solid;
                   7188:   border-color: $pgbg;
                   7189:   text-align: center;
                   7190: }
1.795     www      7191: 
1.396     albertel 7192: table.LC_parm_overview_restrictions th {
                   7193:   background: $tabbg;
                   7194:   border-width: 1px 4px 1px 4px;
                   7195:   border-style: solid;
                   7196:   border-color: $pgbg;
                   7197: }
1.795     www      7198: 
1.398     albertel 7199: table#LC_helpmenu {
1.803     bisitz   7200:   border: none;
1.398     albertel 7201:   height: 55px;
1.803     bisitz   7202:   border-spacing: 0;
1.398     albertel 7203: }
                   7204: 
                   7205: table#LC_helpmenu fieldset legend {
                   7206:   font-size: larger;
                   7207: }
1.795     www      7208: 
1.397     albertel 7209: table#LC_helpmenu_links {
                   7210:   width: 100%;
                   7211:   border: 1px solid black;
                   7212:   background: $pgbg;
1.803     bisitz   7213:   padding: 0;
1.397     albertel 7214:   border-spacing: 1px;
                   7215: }
1.795     www      7216: 
1.397     albertel 7217: table#LC_helpmenu_links tr td {
                   7218:   padding: 1px;
                   7219:   background: $tabbg;
1.399     albertel 7220:   text-align: center;
                   7221:   font-weight: bold;
1.397     albertel 7222: }
1.396     albertel 7223: 
1.795     www      7224: table#LC_helpmenu_links a:link,
                   7225: table#LC_helpmenu_links a:visited,
1.397     albertel 7226: table#LC_helpmenu_links a:active {
                   7227:   text-decoration: none;
                   7228:   color: $font;
                   7229: }
1.795     www      7230: 
1.397     albertel 7231: table#LC_helpmenu_links a:hover {
                   7232:   text-decoration: underline;
                   7233:   color: $vlink;
                   7234: }
1.396     albertel 7235: 
1.417     albertel 7236: .LC_chrt_popup_exists {
                   7237:   border: 1px solid #339933;
                   7238:   margin: -1px;
                   7239: }
1.795     www      7240: 
1.417     albertel 7241: .LC_chrt_popup_up {
                   7242:   border: 1px solid yellow;
                   7243:   margin: -1px;
                   7244: }
1.795     www      7245: 
1.417     albertel 7246: .LC_chrt_popup {
                   7247:   border: 1px solid #8888FF;
                   7248:   background: #CCCCFF;
                   7249: }
1.795     www      7250: 
1.421     albertel 7251: table.LC_pick_box {
                   7252:   border-collapse: separate;
                   7253:   background: white;
                   7254:   border: 1px solid black;
                   7255:   border-spacing: 1px;
                   7256: }
1.795     www      7257: 
1.421     albertel 7258: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   7259:   background: $sidebg;
1.421     albertel 7260:   font-weight: bold;
1.900     bisitz   7261:   text-align: left;
1.740     bisitz   7262:   vertical-align: top;
1.421     albertel 7263:   width: 184px;
                   7264:   padding: 8px;
                   7265: }
1.795     www      7266: 
1.579     raeburn  7267: table.LC_pick_box td.LC_pick_box_value {
                   7268:   text-align: left;
                   7269:   padding: 8px;
                   7270: }
1.795     www      7271: 
1.579     raeburn  7272: table.LC_pick_box td.LC_pick_box_select {
                   7273:   text-align: left;
                   7274:   padding: 8px;
                   7275: }
1.795     www      7276: 
1.424     albertel 7277: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   7278:   padding: 0;
1.421     albertel 7279:   height: 1px;
                   7280:   background: black;
                   7281: }
1.795     www      7282: 
1.421     albertel 7283: table.LC_pick_box td.LC_pick_box_submit {
                   7284:   text-align: right;
                   7285: }
1.795     www      7286: 
1.579     raeburn  7287: table.LC_pick_box td.LC_evenrow_value {
                   7288:   text-align: left;
                   7289:   padding: 8px;
                   7290:   background-color: $data_table_light;
                   7291: }
1.795     www      7292: 
1.579     raeburn  7293: table.LC_pick_box td.LC_oddrow_value {
                   7294:   text-align: left;
                   7295:   padding: 8px;
                   7296:   background-color: $data_table_light;
                   7297: }
1.795     www      7298: 
1.579     raeburn  7299: span.LC_helpform_receipt_cat {
                   7300:   font-weight: bold;
                   7301: }
1.795     www      7302: 
1.424     albertel 7303: table.LC_group_priv_box {
                   7304:   background: white;
                   7305:   border: 1px solid black;
                   7306:   border-spacing: 1px;
                   7307: }
1.795     www      7308: 
1.424     albertel 7309: table.LC_group_priv_box td.LC_pick_box_title {
                   7310:   background: $tabbg;
                   7311:   font-weight: bold;
                   7312:   text-align: right;
                   7313:   width: 184px;
                   7314: }
1.795     www      7315: 
1.424     albertel 7316: table.LC_group_priv_box td.LC_groups_fixed {
                   7317:   background: $data_table_light;
                   7318:   text-align: center;
                   7319: }
1.795     www      7320: 
1.424     albertel 7321: table.LC_group_priv_box td.LC_groups_optional {
                   7322:   background: $data_table_dark;
                   7323:   text-align: center;
                   7324: }
1.795     www      7325: 
1.424     albertel 7326: table.LC_group_priv_box td.LC_groups_functionality {
                   7327:   background: $data_table_darker;
                   7328:   text-align: center;
                   7329:   font-weight: bold;
                   7330: }
1.795     www      7331: 
1.424     albertel 7332: table.LC_group_priv td {
                   7333:   text-align: left;
1.803     bisitz   7334:   padding: 0;
1.424     albertel 7335: }
                   7336: 
                   7337: .LC_navbuttons {
                   7338:   margin: 2ex 0ex 2ex 0ex;
                   7339: }
1.795     www      7340: 
1.423     albertel 7341: .LC_topic_bar {
                   7342:   font-weight: bold;
                   7343:   background: $tabbg;
1.918     wenzelju 7344:   margin: 1em 0em 1em 2em;
1.805     bisitz   7345:   padding: 3px;
1.918     wenzelju 7346:   font-size: 1.2em;
1.423     albertel 7347: }
1.795     www      7348: 
1.423     albertel 7349: .LC_topic_bar span {
1.918     wenzelju 7350:   left: 0.5em;
                   7351:   position: absolute;
1.423     albertel 7352:   vertical-align: middle;
1.918     wenzelju 7353:   font-size: 1.2em;
1.423     albertel 7354: }
1.795     www      7355: 
1.423     albertel 7356: table.LC_course_group_status {
                   7357:   margin: 20px;
                   7358: }
1.795     www      7359: 
1.423     albertel 7360: table.LC_status_selector td {
                   7361:   vertical-align: top;
                   7362:   text-align: center;
1.424     albertel 7363:   padding: 4px;
                   7364: }
1.795     www      7365: 
1.599     albertel 7366: div.LC_feedback_link {
1.616     albertel 7367:   clear: both;
1.829     kalberla 7368:   background: $sidebg;
1.779     bisitz   7369:   width: 100%;
1.829     kalberla 7370:   padding-bottom: 10px;
                   7371:   border: 1px $tabbg solid;
1.833     kalberla 7372:   height: 22px;
                   7373:   line-height: 22px;
                   7374:   padding-top: 5px;
                   7375: }
                   7376: 
                   7377: div.LC_feedback_link img {
                   7378:   height: 22px;
1.867     kalberla 7379:   vertical-align:middle;
1.829     kalberla 7380: }
                   7381: 
1.911     bisitz   7382: div.LC_feedback_link a {
1.829     kalberla 7383:   text-decoration: none;
1.489     raeburn  7384: }
1.795     www      7385: 
1.867     kalberla 7386: div.LC_comblock {
1.911     bisitz   7387:   display:inline;
1.867     kalberla 7388:   color:$font;
                   7389:   font-size:90%;
                   7390: }
                   7391: 
                   7392: div.LC_feedback_link div.LC_comblock {
                   7393:   padding-left:5px;
                   7394: }
                   7395: 
                   7396: div.LC_feedback_link div.LC_comblock a {
                   7397:   color:$font;
                   7398: }
                   7399: 
1.489     raeburn  7400: span.LC_feedback_link {
1.858     bisitz   7401:   /* background: $feedback_link_bg; */
1.599     albertel 7402:   font-size: larger;
                   7403: }
1.795     www      7404: 
1.599     albertel 7405: span.LC_message_link {
1.858     bisitz   7406:   /* background: $feedback_link_bg; */
1.599     albertel 7407:   font-size: larger;
                   7408:   position: absolute;
                   7409:   right: 1em;
1.489     raeburn  7410: }
1.421     albertel 7411: 
1.515     albertel 7412: table.LC_prior_tries {
1.524     albertel 7413:   border: 1px solid #000000;
                   7414:   border-collapse: separate;
                   7415:   border-spacing: 1px;
1.515     albertel 7416: }
1.523     albertel 7417: 
1.515     albertel 7418: table.LC_prior_tries td {
1.524     albertel 7419:   padding: 2px;
1.515     albertel 7420: }
1.523     albertel 7421: 
                   7422: .LC_answer_correct {
1.795     www      7423:   background: lightgreen;
                   7424:   color: darkgreen;
                   7425:   padding: 6px;
1.523     albertel 7426: }
1.795     www      7427: 
1.523     albertel 7428: .LC_answer_charged_try {
1.797     www      7429:   background: #FFAAAA;
1.795     www      7430:   color: darkred;
                   7431:   padding: 6px;
1.523     albertel 7432: }
1.795     www      7433: 
1.779     bisitz   7434: .LC_answer_not_charged_try,
1.523     albertel 7435: .LC_answer_no_grade,
                   7436: .LC_answer_late {
1.795     www      7437:   background: lightyellow;
1.523     albertel 7438:   color: black;
1.795     www      7439:   padding: 6px;
1.523     albertel 7440: }
1.795     www      7441: 
1.523     albertel 7442: .LC_answer_previous {
1.795     www      7443:   background: lightblue;
                   7444:   color: darkblue;
                   7445:   padding: 6px;
1.523     albertel 7446: }
1.795     www      7447: 
1.779     bisitz   7448: .LC_answer_no_message {
1.777     tempelho 7449:   background: #FFFFFF;
                   7450:   color: black;
1.795     www      7451:   padding: 6px;
1.779     bisitz   7452: }
1.795     www      7453: 
1.1334    raeburn  7454: .LC_answer_unknown,
                   7455: .LC_answer_warning {
1.779     bisitz   7456:   background: orange;
                   7457:   color: black;
1.795     www      7458:   padding: 6px;
1.777     tempelho 7459: }
1.795     www      7460: 
1.529     albertel 7461: span.LC_prior_numerical,
                   7462: span.LC_prior_string,
                   7463: span.LC_prior_custom,
                   7464: span.LC_prior_reaction,
                   7465: span.LC_prior_math {
1.925     bisitz   7466:   font-family: $mono;
1.523     albertel 7467:   white-space: pre;
                   7468: }
                   7469: 
1.525     albertel 7470: span.LC_prior_string {
1.925     bisitz   7471:   font-family: $mono;
1.525     albertel 7472:   white-space: pre;
                   7473: }
                   7474: 
1.523     albertel 7475: table.LC_prior_option {
                   7476:   width: 100%;
                   7477:   border-collapse: collapse;
                   7478: }
1.795     www      7479: 
1.911     bisitz   7480: table.LC_prior_rank,
1.795     www      7481: table.LC_prior_match {
1.528     albertel 7482:   border-collapse: collapse;
                   7483: }
1.795     www      7484: 
1.528     albertel 7485: table.LC_prior_option tr td,
                   7486: table.LC_prior_rank tr td,
                   7487: table.LC_prior_match tr td {
1.524     albertel 7488:   border: 1px solid #000000;
1.515     albertel 7489: }
                   7490: 
1.855     bisitz   7491: .LC_nobreak {
1.544     albertel 7492:   white-space: nowrap;
1.519     raeburn  7493: }
                   7494: 
1.576     raeburn  7495: span.LC_cusr_emph {
                   7496:   font-style: italic;
                   7497: }
                   7498: 
1.633     raeburn  7499: span.LC_cusr_subheading {
                   7500:   font-weight: normal;
                   7501:   font-size: 85%;
                   7502: }
                   7503: 
1.861     bisitz   7504: div.LC_docs_entry_move {
1.859     bisitz   7505:   border: 1px solid #BBBBBB;
1.545     albertel 7506:   background: #DDDDDD;
1.861     bisitz   7507:   width: 22px;
1.859     bisitz   7508:   padding: 1px;
                   7509:   margin: 0;
1.545     albertel 7510: }
                   7511: 
1.861     bisitz   7512: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7513: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7514:   font-size: x-small;
                   7515: }
1.795     www      7516: 
1.861     bisitz   7517: .LC_docs_entry_parameter {
                   7518:   white-space: nowrap;
                   7519: }
                   7520: 
1.544     albertel 7521: .LC_docs_copy {
1.545     albertel 7522:   color: #000099;
1.544     albertel 7523: }
1.795     www      7524: 
1.544     albertel 7525: .LC_docs_cut {
1.545     albertel 7526:   color: #550044;
1.544     albertel 7527: }
1.795     www      7528: 
1.544     albertel 7529: .LC_docs_rename {
1.545     albertel 7530:   color: #009900;
1.544     albertel 7531: }
1.795     www      7532: 
1.544     albertel 7533: .LC_docs_remove {
1.545     albertel 7534:   color: #990000;
                   7535: }
                   7536: 
1.1284    raeburn  7537: .LC_docs_alias {
                   7538:   color: #440055;  
                   7539: }
                   7540: 
1.1286    raeburn  7541: .LC_domprefs_email,
1.1284    raeburn  7542: .LC_docs_alias_name,
1.547     albertel 7543: .LC_docs_reinit_warn,
                   7544: .LC_docs_ext_edit {
                   7545:   font-size: x-small;
                   7546: }
                   7547: 
1.545     albertel 7548: table.LC_docs_adddocs td,
                   7549: table.LC_docs_adddocs th {
                   7550:   border: 1px solid #BBBBBB;
                   7551:   padding: 4px;
                   7552:   background: #DDDDDD;
1.543     albertel 7553: }
                   7554: 
1.584     albertel 7555: table.LC_sty_begin {
                   7556:   background: #BBFFBB;
                   7557: }
1.795     www      7558: 
1.584     albertel 7559: table.LC_sty_end {
                   7560:   background: #FFBBBB;
                   7561: }
                   7562: 
1.589     raeburn  7563: table.LC_double_column {
1.803     bisitz   7564:   border-width: 0;
1.589     raeburn  7565:   border-collapse: collapse;
                   7566:   width: 100%;
                   7567:   padding: 2px;
                   7568: }
                   7569: 
                   7570: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7571:   top: 2px;
1.589     raeburn  7572:   left: 2px;
                   7573:   width: 47%;
                   7574:   vertical-align: top;
                   7575: }
                   7576: 
                   7577: table.LC_double_column tr td.LC_right_col {
                   7578:   top: 2px;
1.779     bisitz   7579:   right: 2px;
1.589     raeburn  7580:   width: 47%;
                   7581:   vertical-align: top;
                   7582: }
                   7583: 
1.591     raeburn  7584: div.LC_left_float {
                   7585:   float: left;
                   7586:   padding-right: 5%;
1.597     albertel 7587:   padding-bottom: 4px;
1.591     raeburn  7588: }
                   7589: 
                   7590: div.LC_clear_float_header {
1.597     albertel 7591:   padding-bottom: 2px;
1.591     raeburn  7592: }
                   7593: 
                   7594: div.LC_clear_float_footer {
1.597     albertel 7595:   padding-top: 10px;
1.591     raeburn  7596:   clear: both;
                   7597: }
                   7598: 
1.597     albertel 7599: div.LC_grade_show_user {
1.941     bisitz   7600: /*  border-left: 5px solid $sidebg; */
                   7601:   border-top: 5px solid #000000;
                   7602:   margin: 50px 0 0 0;
1.936     bisitz   7603:   padding: 15px 0 5px 10px;
1.597     albertel 7604: }
1.795     www      7605: 
1.936     bisitz   7606: div.LC_grade_show_user_odd_row {
1.941     bisitz   7607: /*  border-left: 5px solid #000000; */
                   7608: }
                   7609: 
                   7610: div.LC_grade_show_user div.LC_Box {
                   7611:   margin-right: 50px;
1.597     albertel 7612: }
                   7613: 
                   7614: div.LC_grade_submissions,
                   7615: div.LC_grade_message_center,
1.936     bisitz   7616: div.LC_grade_info_links {
1.597     albertel 7617:   margin: 5px;
                   7618:   width: 99%;
                   7619:   background: #FFFFFF;
                   7620: }
1.795     www      7621: 
1.597     albertel 7622: div.LC_grade_submissions_header,
1.936     bisitz   7623: div.LC_grade_message_center_header {
1.705     tempelho 7624:   font-weight: bold;
                   7625:   font-size: large;
1.597     albertel 7626: }
1.795     www      7627: 
1.597     albertel 7628: div.LC_grade_submissions_body,
1.936     bisitz   7629: div.LC_grade_message_center_body {
1.597     albertel 7630:   border: 1px solid black;
                   7631:   width: 99%;
                   7632:   background: #FFFFFF;
                   7633: }
1.795     www      7634: 
1.613     albertel 7635: table.LC_scantron_action {
                   7636:   width: 100%;
                   7637: }
1.795     www      7638: 
1.613     albertel 7639: table.LC_scantron_action tr th {
1.698     harmsja  7640:   font-weight:bold;
                   7641:   font-style:normal;
1.613     albertel 7642: }
1.795     www      7643: 
1.779     bisitz   7644: .LC_edit_problem_header,
1.614     albertel 7645: div.LC_edit_problem_footer {
1.705     tempelho 7646:   font-weight: normal;
                   7647:   font-size:  medium;
1.602     albertel 7648:   margin: 2px;
1.1060    bisitz   7649:   background-color: $sidebg;
1.600     albertel 7650: }
1.795     www      7651: 
1.600     albertel 7652: div.LC_edit_problem_header,
1.602     albertel 7653: div.LC_edit_problem_header div,
1.614     albertel 7654: div.LC_edit_problem_footer,
                   7655: div.LC_edit_problem_footer div,
1.602     albertel 7656: div.LC_edit_problem_editxml_header,
                   7657: div.LC_edit_problem_editxml_header div {
1.1205    golterma 7658:   z-index: 100;
1.600     albertel 7659: }
1.795     www      7660: 
1.600     albertel 7661: div.LC_edit_problem_header_title {
1.705     tempelho 7662:   font-weight: bold;
                   7663:   font-size: larger;
1.602     albertel 7664:   background: $tabbg;
                   7665:   padding: 3px;
1.1060    bisitz   7666:   margin: 0 0 5px 0;
1.602     albertel 7667: }
1.795     www      7668: 
1.602     albertel 7669: table.LC_edit_problem_header_title {
                   7670:   width: 100%;
1.600     albertel 7671:   background: $tabbg;
1.602     albertel 7672: }
                   7673: 
1.1205    golterma 7674: div.LC_edit_actionbar {
                   7675:     background-color: $sidebg;
1.1218    droeschl 7676:     margin: 0;
                   7677:     padding: 0;
                   7678:     line-height: 200%;
1.602     albertel 7679: }
1.795     www      7680: 
1.1218    droeschl 7681: div.LC_edit_actionbar div{
                   7682:     padding: 0;
                   7683:     margin: 0;
                   7684:     display: inline-block;
1.600     albertel 7685: }
1.795     www      7686: 
1.1124    bisitz   7687: .LC_edit_opt {
                   7688:   padding-left: 1em;
                   7689:   white-space: nowrap;
                   7690: }
                   7691: 
1.1152    golterma 7692: .LC_edit_problem_latexhelper{
                   7693:     text-align: right;
                   7694: }
                   7695: 
                   7696: #LC_edit_problem_colorful div{
                   7697:     margin-left: 40px;
                   7698: }
                   7699: 
1.1205    golterma 7700: #LC_edit_problem_codemirror div{
                   7701:     margin-left: 0px;
                   7702: }
                   7703: 
1.911     bisitz   7704: img.stift {
1.803     bisitz   7705:   border-width: 0;
                   7706:   vertical-align: middle;
1.677     riegler  7707: }
1.680     riegler  7708: 
1.923     bisitz   7709: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7710:   vertical-align: top;
1.777     tempelho 7711: }
1.795     www      7712: 
1.716     raeburn  7713: div.LC_createcourse {
1.911     bisitz   7714:   margin: 10px 10px 10px 10px;
1.716     raeburn  7715: }
                   7716: 
1.917     raeburn  7717: .LC_dccid {
1.1130    raeburn  7718:   float: right;
1.917     raeburn  7719:   margin: 0.2em 0 0 0;
                   7720:   padding: 0;
                   7721:   font-size: 90%;
                   7722:   display:none;
                   7723: }
                   7724: 
1.897     wenzelju 7725: ol.LC_primary_menu a:hover,
1.721     harmsja  7726: ol#LC_MenuBreadcrumbs a:hover,
                   7727: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7728: ul#LC_secondary_menu a:hover,
1.721     harmsja  7729: .LC_FormSectionClearButton input:hover
1.795     www      7730: ul.LC_TabContent   li:hover a {
1.952     onken    7731:   color:$button_hover;
1.911     bisitz   7732:   text-decoration:none;
1.693     droeschl 7733: }
                   7734: 
1.779     bisitz   7735: h1 {
1.911     bisitz   7736:   padding: 0;
                   7737:   line-height:130%;
1.693     droeschl 7738: }
1.698     harmsja  7739: 
1.911     bisitz   7740: h2,
                   7741: h3,
                   7742: h4,
                   7743: h5,
                   7744: h6 {
                   7745:   margin: 5px 0 5px 0;
                   7746:   padding: 0;
                   7747:   line-height:130%;
1.693     droeschl 7748: }
1.795     www      7749: 
                   7750: .LC_hcell {
1.911     bisitz   7751:   padding:3px 15px 3px 15px;
                   7752:   margin: 0;
                   7753:   background-color:$tabbg;
                   7754:   color:$fontmenu;
                   7755:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7756: }
1.795     www      7757: 
1.840     bisitz   7758: .LC_Box > .LC_hcell {
1.911     bisitz   7759:   margin: 0 -10px 10px -10px;
1.835     bisitz   7760: }
                   7761: 
1.721     harmsja  7762: .LC_noBorder {
1.911     bisitz   7763:   border: 0;
1.698     harmsja  7764: }
1.693     droeschl 7765: 
1.721     harmsja  7766: .LC_FormSectionClearButton input {
1.911     bisitz   7767:   background-color:transparent;
                   7768:   border: none;
                   7769:   cursor:pointer;
                   7770:   text-decoration:underline;
1.693     droeschl 7771: }
1.763     bisitz   7772: 
                   7773: .LC_help_open_topic {
1.911     bisitz   7774:   color: #FFFFFF;
                   7775:   background-color: #EEEEFF;
                   7776:   margin: 1px;
                   7777:   padding: 4px;
                   7778:   border: 1px solid #000033;
                   7779:   white-space: nowrap;
                   7780:   /* vertical-align: middle; */
1.759     neumanie 7781: }
1.693     droeschl 7782: 
1.911     bisitz   7783: dl,
                   7784: ul,
                   7785: div,
                   7786: fieldset {
                   7787:   margin: 10px 10px 10px 0;
                   7788:   /* overflow: hidden; */
1.693     droeschl 7789: }
1.795     www      7790: 
1.1211    raeburn  7791: article.geogebraweb div {
                   7792:     margin: 0;
                   7793: }
                   7794: 
1.838     bisitz   7795: fieldset > legend {
1.911     bisitz   7796:   font-weight: bold;
                   7797:   padding: 0 5px 0 5px;
1.838     bisitz   7798: }
                   7799: 
1.813     bisitz   7800: #LC_nav_bar {
1.911     bisitz   7801:   float: left;
1.995     raeburn  7802:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7803:   margin: 0 0 2px 0;
1.807     droeschl 7804: }
                   7805: 
1.916     droeschl 7806: #LC_realm {
                   7807:   margin: 0.2em 0 0 0;
                   7808:   padding: 0;
                   7809:   font-weight: bold;
                   7810:   text-align: center;
1.995     raeburn  7811:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7812: }
                   7813: 
1.911     bisitz   7814: #LC_nav_bar em {
                   7815:   font-weight: bold;
                   7816:   font-style: normal;
1.807     droeschl 7817: }
                   7818: 
1.897     wenzelju 7819: ol.LC_primary_menu {
1.934     droeschl 7820:   margin: 0;
1.1076    raeburn  7821:   padding: 0;
1.807     droeschl 7822: }
                   7823: 
1.852     droeschl 7824: ol#LC_PathBreadcrumbs {
1.911     bisitz   7825:   margin: 0;
1.693     droeschl 7826: }
                   7827: 
1.897     wenzelju 7828: ol.LC_primary_menu li {
1.1076    raeburn  7829:   color: RGB(80, 80, 80);
                   7830:   vertical-align: middle;
                   7831:   text-align: left;
                   7832:   list-style: none;
1.1205    golterma 7833:   position: relative;
1.1076    raeburn  7834:   float: left;
1.1205    golterma 7835:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7836:   line-height: 1.5em;
1.1076    raeburn  7837: }
                   7838: 
1.1205    golterma 7839: ol.LC_primary_menu li a,
                   7840: ol.LC_primary_menu li p {
1.1076    raeburn  7841:   display: block;
                   7842:   margin: 0;
                   7843:   padding: 0 5px 0 10px;
                   7844:   text-decoration: none;
                   7845: }
                   7846: 
1.1205    golterma 7847: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7848:   display: inline-block;
                   7849:   width: 95%;
                   7850:   text-align: left;
                   7851: }
                   7852: 
                   7853: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7854:   display: inline-block;	
                   7855:   width: 5%;
                   7856:   float: right;
                   7857:   text-align: right;
                   7858:   font-size: 70%;
                   7859: }
                   7860: 
                   7861: ol.LC_primary_menu ul {
1.1076    raeburn  7862:   display: none;
1.1205    golterma 7863:   width: 15em;
1.1076    raeburn  7864:   background-color: $data_table_light;
1.1205    golterma 7865:   position: absolute;
                   7866:   top: 100%;
1.1076    raeburn  7867: }
                   7868: 
1.1205    golterma 7869: ol.LC_primary_menu ul ul {
                   7870:   left: 100%;
                   7871:   top: 0;
                   7872: }
                   7873: 
                   7874: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  7875:   display: block;
                   7876:   position: absolute;
                   7877:   margin: 0;
                   7878:   padding: 0;
1.1078    raeburn  7879:   z-index: 2;
1.1076    raeburn  7880: }
                   7881: 
                   7882: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 7883: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  7884:   font-size: 90%;
1.911     bisitz   7885:   vertical-align: top;
1.1076    raeburn  7886:   float: none;
1.1079    raeburn  7887:   border-left: 1px solid black;
                   7888:   border-right: 1px solid black;
1.1205    golterma 7889: /* A dark bottom border to visualize different menu options; 
                   7890: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7891:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  7892: }
                   7893: 
1.1205    golterma 7894: ol.LC_primary_menu li li p:hover {
                   7895:   color:$button_hover;
                   7896:   text-decoration:none;
                   7897:   background-color:$data_table_dark;
1.1076    raeburn  7898: }
                   7899: 
                   7900: ol.LC_primary_menu li li a:hover {
                   7901:    color:$button_hover;
                   7902:    background-color:$data_table_dark;
1.693     droeschl 7903: }
                   7904: 
1.1205    golterma 7905: /* Font-size equal to the size of the predecessors*/
                   7906: ol.LC_primary_menu li:hover li li {
                   7907:   font-size: 100%;
                   7908: }
                   7909: 
1.897     wenzelju 7910: ol.LC_primary_menu li img {
1.911     bisitz   7911:   vertical-align: bottom;
1.934     droeschl 7912:   height: 1.1em;
1.1077    raeburn  7913:   margin: 0.2em 0 0 0;
1.693     droeschl 7914: }
                   7915: 
1.897     wenzelju 7916: ol.LC_primary_menu a {
1.911     bisitz   7917:   color: RGB(80, 80, 80);
                   7918:   text-decoration: none;
1.693     droeschl 7919: }
1.795     www      7920: 
1.949     droeschl 7921: ol.LC_primary_menu a.LC_new_message {
                   7922:   font-weight:bold;
                   7923:   color: darkred;
                   7924: }
                   7925: 
1.975     raeburn  7926: ol.LC_docs_parameters {
                   7927:   margin-left: 0;
                   7928:   padding: 0;
                   7929:   list-style: none;
                   7930: }
                   7931: 
                   7932: ol.LC_docs_parameters li {
                   7933:   margin: 0;
                   7934:   padding-right: 20px;
                   7935:   display: inline;
                   7936: }
                   7937: 
1.976     raeburn  7938: ol.LC_docs_parameters li:before {
                   7939:   content: "\\002022 \\0020";
                   7940: }
                   7941: 
                   7942: li.LC_docs_parameters_title {
                   7943:   font-weight: bold;
                   7944: }
                   7945: 
                   7946: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7947:   content: "";
                   7948: }
                   7949: 
1.897     wenzelju 7950: ul#LC_secondary_menu {
1.1107    raeburn  7951:   clear: right;
1.911     bisitz   7952:   color: $fontmenu;
                   7953:   background: $tabbg;
                   7954:   list-style: none;
                   7955:   padding: 0;
                   7956:   margin: 0;
                   7957:   width: 100%;
1.995     raeburn  7958:   text-align: left;
1.1107    raeburn  7959:   float: left;
1.808     droeschl 7960: }
                   7961: 
1.897     wenzelju 7962: ul#LC_secondary_menu li {
1.911     bisitz   7963:   font-weight: bold;
                   7964:   line-height: 1.8em;
1.1107    raeburn  7965:   border-right: 1px solid black;
                   7966:   float: left;
                   7967: }
                   7968: 
                   7969: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7970:   background-color: $data_table_light;
                   7971: }
                   7972: 
                   7973: ul#LC_secondary_menu li a {
1.911     bisitz   7974:   padding: 0 0.8em;
1.1107    raeburn  7975: }
                   7976: 
                   7977: ul#LC_secondary_menu li ul {
                   7978:   display: none;
                   7979: }
                   7980: 
                   7981: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7982:   display: block;
                   7983:   position: absolute;
                   7984:   margin: 0;
                   7985:   padding: 0;
                   7986:   list-style:none;
                   7987:   float: none;
                   7988:   background-color: $data_table_light;
                   7989:   z-index: 2;
                   7990:   margin-left: -1px;
                   7991: }
                   7992: 
                   7993: ul#LC_secondary_menu li ul li {
                   7994:   font-size: 90%;
                   7995:   vertical-align: top;
                   7996:   border-left: 1px solid black;
1.911     bisitz   7997:   border-right: 1px solid black;
1.1119    raeburn  7998:   background-color: $data_table_light;
1.1107    raeburn  7999:   list-style:none;
                   8000:   float: none;
                   8001: }
                   8002: 
                   8003: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   8004:   background-color: $data_table_dark;
1.807     droeschl 8005: }
                   8006: 
1.847     tempelho 8007: ul.LC_TabContent {
1.911     bisitz   8008:   display:block;
                   8009:   background: $sidebg;
                   8010:   border-bottom: solid 1px $lg_border_color;
                   8011:   list-style:none;
1.1020    raeburn  8012:   margin: -1px -10px 0 -10px;
1.911     bisitz   8013:   padding: 0;
1.693     droeschl 8014: }
                   8015: 
1.795     www      8016: ul.LC_TabContent li,
                   8017: ul.LC_TabContentBigger li {
1.911     bisitz   8018:   float:left;
1.741     harmsja  8019: }
1.795     www      8020: 
1.897     wenzelju 8021: ul#LC_secondary_menu li a {
1.911     bisitz   8022:   color: $fontmenu;
                   8023:   text-decoration: none;
1.693     droeschl 8024: }
1.795     www      8025: 
1.721     harmsja  8026: ul.LC_TabContent {
1.952     onken    8027:   min-height:20px;
1.721     harmsja  8028: }
1.795     www      8029: 
                   8030: ul.LC_TabContent li {
1.911     bisitz   8031:   vertical-align:middle;
1.959     onken    8032:   padding: 0 16px 0 10px;
1.911     bisitz   8033:   background-color:$tabbg;
                   8034:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  8035:   border-left: solid 1px $font;
1.721     harmsja  8036: }
1.795     www      8037: 
1.847     tempelho 8038: ul.LC_TabContent .right {
1.911     bisitz   8039:   float:right;
1.847     tempelho 8040: }
                   8041: 
1.911     bisitz   8042: ul.LC_TabContent li a,
                   8043: ul.LC_TabContent li {
                   8044:   color:rgb(47,47,47);
                   8045:   text-decoration:none;
                   8046:   font-size:95%;
                   8047:   font-weight:bold;
1.952     onken    8048:   min-height:20px;
                   8049: }
                   8050: 
1.959     onken    8051: ul.LC_TabContent li a:hover,
                   8052: ul.LC_TabContent li a:focus {
1.952     onken    8053:   color: $button_hover;
1.959     onken    8054:   background:none;
                   8055:   outline:none;
1.952     onken    8056: }
                   8057: 
                   8058: ul.LC_TabContent li:hover {
                   8059:   color: $button_hover;
                   8060:   cursor:pointer;
1.721     harmsja  8061: }
1.795     www      8062: 
1.911     bisitz   8063: ul.LC_TabContent li.active {
1.952     onken    8064:   color: $font;
1.911     bisitz   8065:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    8066:   border-bottom:solid 1px #FFFFFF;
                   8067:   cursor: default;
1.744     ehlerst  8068: }
1.795     www      8069: 
1.959     onken    8070: ul.LC_TabContent li.active a {
                   8071:   color:$font;
                   8072:   background:#FFFFFF;
                   8073:   outline: none;
                   8074: }
1.1047    raeburn  8075: 
                   8076: ul.LC_TabContent li.goback {
                   8077:   float: left;
                   8078:   border-left: none;
                   8079: }
                   8080: 
1.870     tempelho 8081: #maincoursedoc {
1.911     bisitz   8082:   clear:both;
1.870     tempelho 8083: }
                   8084: 
                   8085: ul.LC_TabContentBigger {
1.911     bisitz   8086:   display:block;
                   8087:   list-style:none;
                   8088:   padding: 0;
1.870     tempelho 8089: }
                   8090: 
1.795     www      8091: ul.LC_TabContentBigger li {
1.911     bisitz   8092:   vertical-align:bottom;
                   8093:   height: 30px;
                   8094:   font-size:110%;
                   8095:   font-weight:bold;
                   8096:   color: #737373;
1.841     tempelho 8097: }
                   8098: 
1.957     onken    8099: ul.LC_TabContentBigger li.active {
                   8100:   position: relative;
                   8101:   top: 1px;
                   8102: }
                   8103: 
1.870     tempelho 8104: ul.LC_TabContentBigger li a {
1.911     bisitz   8105:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   8106:   height: 30px;
                   8107:   line-height: 30px;
                   8108:   text-align: center;
                   8109:   display: block;
                   8110:   text-decoration: none;
1.958     onken    8111:   outline: none;  
1.741     harmsja  8112: }
1.795     www      8113: 
1.870     tempelho 8114: ul.LC_TabContentBigger li.active a {
1.911     bisitz   8115:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   8116:   color:$font;
1.744     ehlerst  8117: }
1.795     www      8118: 
1.870     tempelho 8119: ul.LC_TabContentBigger li b {
1.911     bisitz   8120:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   8121:   display: block;
                   8122:   float: left;
                   8123:   padding: 0 30px;
1.957     onken    8124:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 8125: }
                   8126: 
1.956     onken    8127: ul.LC_TabContentBigger li:hover b {
                   8128:   color:$button_hover;
                   8129: }
                   8130: 
1.870     tempelho 8131: ul.LC_TabContentBigger li.active b {
1.911     bisitz   8132:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   8133:   color:$font;
1.957     onken    8134:   border: 0;
1.741     harmsja  8135: }
1.693     droeschl 8136: 
1.870     tempelho 8137: 
1.862     bisitz   8138: ul.LC_CourseBreadcrumbs {
                   8139:   background: $sidebg;
1.1020    raeburn  8140:   height: 2em;
1.862     bisitz   8141:   padding-left: 10px;
1.1020    raeburn  8142:   margin: 0;
1.862     bisitz   8143:   list-style-position: inside;
                   8144: }
                   8145: 
1.911     bisitz   8146: ol#LC_MenuBreadcrumbs,
1.862     bisitz   8147: ol#LC_PathBreadcrumbs {
1.911     bisitz   8148:   padding-left: 10px;
                   8149:   margin: 0;
1.933     droeschl 8150:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 8151: }
                   8152: 
1.911     bisitz   8153: ol#LC_MenuBreadcrumbs li,
                   8154: ol#LC_PathBreadcrumbs li,
1.862     bisitz   8155: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   8156:   display: inline;
1.933     droeschl 8157:   white-space: normal;  
1.693     droeschl 8158: }
                   8159: 
1.823     bisitz   8160: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   8161: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   8162:   text-decoration: none;
                   8163:   font-size:90%;
1.693     droeschl 8164: }
1.795     www      8165: 
1.969     droeschl 8166: ol#LC_MenuBreadcrumbs h1 {
                   8167:   display: inline;
                   8168:   font-size: 90%;
                   8169:   line-height: 2.5em;
                   8170:   margin: 0;
                   8171:   padding: 0;
                   8172: }
                   8173: 
1.795     www      8174: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   8175:   text-decoration:none;
                   8176:   font-size:100%;
                   8177:   font-weight:bold;
1.693     droeschl 8178: }
1.795     www      8179: 
1.840     bisitz   8180: .LC_Box {
1.911     bisitz   8181:   border: solid 1px $lg_border_color;
                   8182:   padding: 0 10px 10px 10px;
1.746     neumanie 8183: }
1.795     www      8184: 
1.1020    raeburn  8185: .LC_DocsBox {
                   8186:   border: solid 1px $lg_border_color;
                   8187:   padding: 0 0 10px 10px;
                   8188: }
                   8189: 
1.795     www      8190: .LC_AboutMe_Image {
1.911     bisitz   8191:   float:left;
                   8192:   margin-right:10px;
1.747     neumanie 8193: }
1.795     www      8194: 
                   8195: .LC_Clear_AboutMe_Image {
1.911     bisitz   8196:   clear:left;
1.747     neumanie 8197: }
1.795     www      8198: 
1.721     harmsja  8199: dl.LC_ListStyleClean dt {
1.911     bisitz   8200:   padding-right: 5px;
                   8201:   display: table-header-group;
1.693     droeschl 8202: }
                   8203: 
1.721     harmsja  8204: dl.LC_ListStyleClean dd {
1.911     bisitz   8205:   display: table-row;
1.693     droeschl 8206: }
                   8207: 
1.721     harmsja  8208: .LC_ListStyleClean,
                   8209: .LC_ListStyleSimple,
                   8210: .LC_ListStyleNormal,
1.795     www      8211: .LC_ListStyleSpecial {
1.911     bisitz   8212:   /* display:block; */
                   8213:   list-style-position: inside;
                   8214:   list-style-type: none;
                   8215:   overflow: hidden;
                   8216:   padding: 0;
1.693     droeschl 8217: }
                   8218: 
1.721     harmsja  8219: .LC_ListStyleSimple li,
                   8220: .LC_ListStyleSimple dd,
                   8221: .LC_ListStyleNormal li,
                   8222: .LC_ListStyleNormal dd,
                   8223: .LC_ListStyleSpecial li,
1.795     www      8224: .LC_ListStyleSpecial dd {
1.911     bisitz   8225:   margin: 0;
                   8226:   padding: 5px 5px 5px 10px;
                   8227:   clear: both;
1.693     droeschl 8228: }
                   8229: 
1.721     harmsja  8230: .LC_ListStyleClean li,
                   8231: .LC_ListStyleClean dd {
1.911     bisitz   8232:   padding-top: 0;
                   8233:   padding-bottom: 0;
1.693     droeschl 8234: }
                   8235: 
1.721     harmsja  8236: .LC_ListStyleSimple dd,
1.795     www      8237: .LC_ListStyleSimple li {
1.911     bisitz   8238:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 8239: }
                   8240: 
1.721     harmsja  8241: .LC_ListStyleSpecial li,
                   8242: .LC_ListStyleSpecial dd {
1.911     bisitz   8243:   list-style-type: none;
                   8244:   background-color: RGB(220, 220, 220);
                   8245:   margin-bottom: 4px;
1.693     droeschl 8246: }
                   8247: 
1.721     harmsja  8248: table.LC_SimpleTable {
1.911     bisitz   8249:   margin:5px;
                   8250:   border:solid 1px $lg_border_color;
1.795     www      8251: }
1.693     droeschl 8252: 
1.721     harmsja  8253: table.LC_SimpleTable tr {
1.911     bisitz   8254:   padding: 0;
                   8255:   border:solid 1px $lg_border_color;
1.693     droeschl 8256: }
1.795     www      8257: 
                   8258: table.LC_SimpleTable thead {
1.911     bisitz   8259:   background:rgb(220,220,220);
1.693     droeschl 8260: }
                   8261: 
1.721     harmsja  8262: div.LC_columnSection {
1.911     bisitz   8263:   display: block;
                   8264:   clear: both;
                   8265:   overflow: hidden;
                   8266:   margin: 0;
1.693     droeschl 8267: }
                   8268: 
1.721     harmsja  8269: div.LC_columnSection>* {
1.911     bisitz   8270:   float: left;
                   8271:   margin: 10px 20px 10px 0;
                   8272:   overflow:hidden;
1.693     droeschl 8273: }
1.721     harmsja  8274: 
1.795     www      8275: table em {
1.911     bisitz   8276:   font-weight: bold;
                   8277:   font-style: normal;
1.748     schulted 8278: }
1.795     www      8279: 
1.779     bisitz   8280: table.LC_tableBrowseRes,
1.795     www      8281: table.LC_tableOfContent {
1.911     bisitz   8282:   border:none;
                   8283:   border-spacing: 1px;
                   8284:   padding: 3px;
                   8285:   background-color: #FFFFFF;
                   8286:   font-size: 90%;
1.753     droeschl 8287: }
1.789     droeschl 8288: 
1.911     bisitz   8289: table.LC_tableOfContent {
                   8290:   border-collapse: collapse;
1.789     droeschl 8291: }
                   8292: 
1.771     droeschl 8293: table.LC_tableBrowseRes a,
1.768     schulted 8294: table.LC_tableOfContent a {
1.911     bisitz   8295:   background-color: transparent;
                   8296:   text-decoration: none;
1.753     droeschl 8297: }
                   8298: 
1.795     www      8299: table.LC_tableOfContent img {
1.911     bisitz   8300:   border: none;
                   8301:   height: 1.3em;
                   8302:   vertical-align: text-bottom;
                   8303:   margin-right: 0.3em;
1.753     droeschl 8304: }
1.757     schulted 8305: 
1.795     www      8306: a#LC_content_toolbar_firsthomework {
1.911     bisitz   8307:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  8308: }
                   8309: 
1.795     www      8310: a#LC_content_toolbar_everything {
1.911     bisitz   8311:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  8312: }
                   8313: 
1.795     www      8314: a#LC_content_toolbar_uncompleted {
1.911     bisitz   8315:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  8316: }
                   8317: 
1.795     www      8318: #LC_content_toolbar_clearbubbles {
1.911     bisitz   8319:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  8320: }
                   8321: 
1.795     www      8322: a#LC_content_toolbar_changefolder {
1.911     bisitz   8323:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 8324: }
                   8325: 
1.795     www      8326: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   8327:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 8328: }
                   8329: 
1.1043    raeburn  8330: a#LC_content_toolbar_edittoplevel {
                   8331:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   8332: }
                   8333: 
1.795     www      8334: ul#LC_toolbar li a:hover {
1.911     bisitz   8335:   background-position: bottom center;
1.757     schulted 8336: }
                   8337: 
1.795     www      8338: ul#LC_toolbar {
1.911     bisitz   8339:   padding: 0;
                   8340:   margin: 2px;
                   8341:   list-style:none;
                   8342:   position:relative;
                   8343:   background-color:white;
1.1082    raeburn  8344:   overflow: auto;
1.757     schulted 8345: }
                   8346: 
1.795     www      8347: ul#LC_toolbar li {
1.911     bisitz   8348:   border:1px solid white;
                   8349:   padding: 0;
                   8350:   margin: 0;
                   8351:   float: left;
                   8352:   display:inline;
                   8353:   vertical-align:middle;
1.1082    raeburn  8354:   white-space: nowrap;
1.911     bisitz   8355: }
1.757     schulted 8356: 
1.783     amueller 8357: 
1.795     www      8358: a.LC_toolbarItem {
1.911     bisitz   8359:   display:block;
                   8360:   padding: 0;
                   8361:   margin: 0;
                   8362:   height: 32px;
                   8363:   width: 32px;
                   8364:   color:white;
                   8365:   border: none;
                   8366:   background-repeat:no-repeat;
                   8367:   background-color:transparent;
1.757     schulted 8368: }
                   8369: 
1.915     droeschl 8370: ul.LC_funclist {
                   8371:     margin: 0;
                   8372:     padding: 0.5em 1em 0.5em 0;
                   8373: }
                   8374: 
1.933     droeschl 8375: ul.LC_funclist > li:first-child {
                   8376:     font-weight:bold; 
                   8377:     margin-left:0.8em;
                   8378: }
                   8379: 
1.915     droeschl 8380: ul.LC_funclist + ul.LC_funclist {
                   8381:     /* 
                   8382:        left border as a seperator if we have more than
                   8383:        one list 
                   8384:     */
                   8385:     border-left: 1px solid $sidebg;
                   8386:     /* 
                   8387:        this hides the left border behind the border of the 
                   8388:        outer box if element is wrapped to the next 'line' 
                   8389:     */
                   8390:     margin-left: -1px;
                   8391: }
                   8392: 
1.843     bisitz   8393: ul.LC_funclist li {
1.915     droeschl 8394:   display: inline;
1.782     bisitz   8395:   white-space: nowrap;
1.915     droeschl 8396:   margin: 0 0 0 25px;
                   8397:   line-height: 150%;
1.782     bisitz   8398: }
                   8399: 
1.974     wenzelju 8400: .LC_hidden {
                   8401:   display: none;
                   8402: }
                   8403: 
1.1030    www      8404: .LCmodal-overlay {
                   8405: 		position:fixed;
                   8406: 		top:0;
                   8407: 		right:0;
                   8408: 		bottom:0;
                   8409: 		left:0;
                   8410: 		height:100%;
                   8411: 		width:100%;
                   8412: 		margin:0;
                   8413: 		padding:0;
                   8414: 		background:#999;
                   8415: 		opacity:.75;
                   8416: 		filter: alpha(opacity=75);
                   8417: 		-moz-opacity: 0.75;
                   8418: 		z-index:101;
                   8419: }
                   8420: 
                   8421: * html .LCmodal-overlay {   
                   8422: 		position: absolute;
                   8423: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   8424: }
                   8425: 
                   8426: .LCmodal-window {
                   8427: 		position:fixed;
                   8428: 		top:50%;
                   8429: 		left:50%;
                   8430: 		margin:0;
                   8431: 		padding:0;
                   8432: 		z-index:102;
                   8433: 	}
                   8434: 
                   8435: * html .LCmodal-window {
                   8436: 		position:absolute;
                   8437: }
                   8438: 
                   8439: .LCclose-window {
                   8440: 		position:absolute;
                   8441: 		width:32px;
                   8442: 		height:32px;
                   8443: 		right:8px;
                   8444: 		top:8px;
                   8445: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8446: 		text-indent:-99999px;
                   8447: 		overflow:hidden;
                   8448: 		cursor:pointer;
                   8449: }
                   8450: 
1.1369    raeburn  8451: .LCisDisabled {
                   8452:   cursor: not-allowed;
                   8453:   opacity: 0.5;
                   8454: }
                   8455: 
                   8456: a[aria-disabled="true"] {
                   8457:   color: currentColor;
                   8458:   display: inline-block;  /* For IE11/ MS Edge bug */
                   8459:   pointer-events: none;
                   8460:   text-decoration: none;
                   8461: }
                   8462: 
1.1335    raeburn  8463: pre.LC_wordwrap {
                   8464:   white-space: pre-wrap;
                   8465:   white-space: -moz-pre-wrap;
                   8466:   white-space: -pre-wrap;
                   8467:   white-space: -o-pre-wrap;
                   8468:   word-wrap: break-word;
                   8469: }
                   8470: 
1.1100    raeburn  8471: /*
1.1231    damieng  8472:   styles used for response display
                   8473: */
                   8474: div.LC_radiofoil, div.LC_rankfoil {
                   8475:   margin: .5em 0em .5em 0em;
                   8476: }
                   8477: table.LC_itemgroup {
                   8478:   margin-top: 1em;
                   8479: }
                   8480: 
                   8481: /*
1.1100    raeburn  8482:   styles used by TTH when "Default set of options to pass to tth/m
                   8483:   when converting TeX" in course settings has been set
                   8484: 
                   8485:   option passed: -t
                   8486: 
                   8487: */
                   8488: 
                   8489: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8490: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8491: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8492: td div.norm {line-height:normal;}
                   8493: 
                   8494: /*
                   8495:   option passed -y3
                   8496: */
                   8497: 
                   8498: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8499: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8500: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8501: 
1.1230    damieng  8502: /*
                   8503:   sections with roles, for content only
                   8504: */
                   8505: section[class^="role-"] {
                   8506:   padding-left: 10px;
                   8507:   padding-right: 5px;
                   8508:   margin-top: 8px;
                   8509:   margin-bottom: 8px;
                   8510:   border: 1px solid #2A4;
                   8511:   border-radius: 5px;
                   8512:   box-shadow: 0px 1px 1px #BBB;
                   8513: }
                   8514: section[class^="role-"]>h1 {
                   8515:   position: relative;
                   8516:   margin: 0px;
                   8517:   padding-top: 10px;
                   8518:   padding-left: 40px;
                   8519: }
                   8520: section[class^="role-"]>h1:before {
                   8521:   position: absolute;
                   8522:   left: -5px;
                   8523:   top: 5px;
                   8524: }
                   8525: section.role-activity>h1:before {
                   8526:   content:url('/adm/daxe/images/section_icons/activity.png');
                   8527: }
                   8528: section.role-advice>h1:before {
                   8529:   content:url('/adm/daxe/images/section_icons/advice.png');
                   8530: }
                   8531: section.role-bibliography>h1:before {
                   8532:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   8533: }
                   8534: section.role-citation>h1:before {
                   8535:   content:url('/adm/daxe/images/section_icons/citation.png');
                   8536: }
                   8537: section.role-conclusion>h1:before {
                   8538:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   8539: }
                   8540: section.role-definition>h1:before {
                   8541:   content:url('/adm/daxe/images/section_icons/definition.png');
                   8542: }
                   8543: section.role-demonstration>h1:before {
                   8544:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   8545: }
                   8546: section.role-example>h1:before {
                   8547:   content:url('/adm/daxe/images/section_icons/example.png');
                   8548: }
                   8549: section.role-explanation>h1:before {
                   8550:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   8551: }
                   8552: section.role-introduction>h1:before {
                   8553:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   8554: }
                   8555: section.role-method>h1:before {
                   8556:   content:url('/adm/daxe/images/section_icons/method.png');
                   8557: }
                   8558: section.role-more_information>h1:before {
                   8559:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   8560: }
                   8561: section.role-objectives>h1:before {
                   8562:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   8563: }
                   8564: section.role-prerequisites>h1:before {
                   8565:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   8566: }
                   8567: section.role-remark>h1:before {
                   8568:   content:url('/adm/daxe/images/section_icons/remark.png');
                   8569: }
                   8570: section.role-reminder>h1:before {
                   8571:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   8572: }
                   8573: section.role-summary>h1:before {
                   8574:   content:url('/adm/daxe/images/section_icons/summary.png');
                   8575: }
                   8576: section.role-syntax>h1:before {
                   8577:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   8578: }
                   8579: section.role-warning>h1:before {
                   8580:   content:url('/adm/daxe/images/section_icons/warning.png');
                   8581: }
                   8582: 
1.1269    raeburn  8583: #LC_minitab_header {
                   8584:   float:left;
                   8585:   width:100%;
                   8586:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   8587:   font-size:93%;
                   8588:   line-height:normal;
                   8589:   margin: 0.5em 0 0.5em 0;
                   8590: }
                   8591: #LC_minitab_header ul {
                   8592:   margin:0;
                   8593:   padding:10px 10px 0;
                   8594:   list-style:none;
                   8595: }
                   8596: #LC_minitab_header li {
                   8597:   float:left;
                   8598:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   8599:   margin:0;
                   8600:   padding:0 0 0 9px;
                   8601: }
                   8602: #LC_minitab_header a {
                   8603:   display:block;
                   8604:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   8605:   padding:5px 15px 4px 6px;
                   8606: }
                   8607: #LC_minitab_header #LC_current_minitab {
                   8608:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   8609: }
                   8610: #LC_minitab_header #LC_current_minitab a {
                   8611:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   8612:   padding-bottom:5px;
                   8613: }
                   8614: 
                   8615: 
1.343     albertel 8616: END
                   8617: }
                   8618: 
1.306     albertel 8619: =pod
                   8620: 
                   8621: =item * &headtag()
                   8622: 
                   8623: Returns a uniform footer for LON-CAPA web pages.
                   8624: 
1.307     albertel 8625: Inputs: $title - optional title for the head
                   8626:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8627:         $args - optional arguments
1.319     albertel 8628:             force_register - if is true call registerurl so the remote is 
                   8629:                              informed
1.415     albertel 8630:             redirect       -> array ref of
                   8631:                                    1- seconds before redirect occurs
                   8632:                                    2- url to redirect to
                   8633:                                    3- whether the side effect should occur
1.315     albertel 8634:                            (side effect of setting 
                   8635:                                $env{'internal.head.redirect'} to the url 
                   8636:                                redirected too)
1.352     albertel 8637:             domain         -> force to color decorate a page for a specific
                   8638:                                domain
                   8639:             function       -> force usage of a specific rolish color scheme
                   8640:             bgcolor        -> override the default page bgcolor
1.460     albertel 8641:             no_auto_mt_title
                   8642:                            -> prevent &mt()ing the title arg
1.464     albertel 8643: 
1.306     albertel 8644: =cut
                   8645: 
                   8646: sub headtag {
1.313     albertel 8647:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8648:     
1.363     albertel 8649:     my $function = $args->{'function'} || &get_users_function();
                   8650:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8651:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  8652:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8653:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8654: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8655: 		   #time(),
1.418     albertel 8656: 		   $env{'environment.color.timestamp'},
1.363     albertel 8657: 		   $function,$domain,$bgcolor);
                   8658: 
1.369     www      8659:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8660: 
1.308     albertel 8661:     my $result =
                   8662: 	'<head>'.
1.1160    raeburn  8663: 	&font_settings($args);
1.319     albertel 8664: 
1.1188    raeburn  8665:     my $inhibitprint;
                   8666:     if ($args->{'print_suppress'}) {
                   8667:         $inhibitprint = &print_suppression();
                   8668:     }
1.1064    raeburn  8669: 
1.461     albertel 8670:     if (!$args->{'frameset'}) {
                   8671: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8672:     }
1.962     droeschl 8673:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   8674:         $result .= Apache::lonxml::display_title();
1.319     albertel 8675:     }
1.436     albertel 8676:     if (!$args->{'no_nav_bar'} 
                   8677: 	&& !$args->{'only_body'}
                   8678: 	&& !$args->{'frameset'}) {
1.1154    raeburn  8679: 	$result .= &help_menu_js($httphost);
1.1032    www      8680:         $result.=&modal_window();
1.1038    www      8681:         $result.=&togglebox_script();
1.1034    www      8682:         $result.=&wishlist_window();
1.1041    www      8683:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8684:     } else {
                   8685:         if ($args->{'add_modal'}) {
                   8686:            $result.=&modal_window();
                   8687:         }
                   8688:         if ($args->{'add_wishlist'}) {
                   8689:            $result.=&wishlist_window();
                   8690:         }
1.1038    www      8691:         if ($args->{'add_togglebox'}) {
                   8692:            $result.=&togglebox_script();
                   8693:         }
1.1041    www      8694:         if ($args->{'add_progressbar'}) {
                   8695:            $result.=&LCprogressbarUpdate_script();
                   8696:         }
1.436     albertel 8697:     }
1.314     albertel 8698:     if (ref($args->{'redirect'})) {
1.414     albertel 8699: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 8700: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 8701: 	if (!$inhibit_continue) {
                   8702: 	    $env{'internal.head.redirect'} = $url;
                   8703: 	}
1.313     albertel 8704: 	$result.=<<ADDMETA
                   8705: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 8706: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 8707: ADDMETA
1.1210    raeburn  8708:     } else {
                   8709:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   8710:             my $requrl = $env{'request.uri'};
                   8711:             if ($requrl eq '') {
                   8712:                 $requrl = $ENV{'REQUEST_URI'};
                   8713:                 $requrl =~ s/\?.+$//;
                   8714:             }
                   8715:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   8716:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   8717:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   8718:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   8719:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   8720:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1340    raeburn  8721:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1352    raeburn  8722:                     my ($offload,$offloadoth);
1.1210    raeburn  8723:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   8724:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1340    raeburn  8725:                             $offload = 1;
1.1353    raeburn  8726:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8727:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8728:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8729:                                     $offloadoth = 1;
                   8730:                                     $dom_in_use = $env{'user.domain'};
                   8731:                                 }
                   8732:                             }
1.1340    raeburn  8733:                         }
                   8734:                     }
                   8735:                     unless ($offload) {
                   8736:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   8737:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   8738:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8739:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8740:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8741:                                         $offload = 1;
1.1352    raeburn  8742:                                         $offloadoth = 1;
1.1340    raeburn  8743:                                         $dom_in_use = $env{'user.domain'};
                   8744:                                     }
1.1210    raeburn  8745:                                 }
1.1340    raeburn  8746:                             }
                   8747:                         }
                   8748:                     }
                   8749:                     if ($offload) {
1.1358    raeburn  8750:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1352    raeburn  8751:                         if (($newserver eq '') && ($offloadoth)) {
                   8752:                             my @domains = &Apache::lonnet::current_machine_domains();
                   8753:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
                   8754:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   8755:                             }
                   8756:                         }
1.1340    raeburn  8757:                         if (($newserver) && ($newserver ne $lonhost)) {
                   8758:                             my $numsec = 5;
                   8759:                             my $timeout = $numsec * 1000;
                   8760:                             my ($newurl,$locknum,%locks,$msg);
                   8761:                             if ($env{'request.role.adv'}) {
                   8762:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   8763:                             }
                   8764:                             my $disable_submit = 0;
                   8765:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   8766:                                 $disable_submit = 1;
                   8767:                             }
                   8768:                             if ($locknum) {
                   8769:                                 my @lockinfo = sort(values(%locks));
1.1354    raeburn  8770:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1340    raeburn  8771:                                        join(", ",sort(values(%locks)))."\n";
                   8772:                                 if (&show_course()) {
                   8773:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
                   8774:                                 } else {
                   8775:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
1.1210    raeburn  8776:                                 }
1.1340    raeburn  8777:                             } else {
                   8778:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8779:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   8780:                                 }
                   8781:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8782:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8783:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8784:                                     $newurl .= '&role='.$env{'request.role'};
                   8785:                                 }
                   8786:                                 if ($env{'request.symb'}) {
                   8787:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   8788:                                     if ($shownsymb =~ m{^/enc/}) {
                   8789:                                         my $reqdmajor = 2;
                   8790:                                         my $reqdminor = 11;
                   8791:                                         my $reqdsubminor = 3;
                   8792:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   8793:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   8794:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   8795:                                         if (($major eq '' && $minor eq '') ||
                   8796:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   8797:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   8798:                                              ($reqdsubminor > $subminor))))) {
                   8799:                                             undef($shownsymb);
                   8800:                                         }
1.1210    raeburn  8801:                                     }
1.1340    raeburn  8802:                                     if ($shownsymb) {
                   8803:                                         &js_escape(\$shownsymb);
                   8804:                                         $newurl .= '&symb='.$shownsymb;
1.1210    raeburn  8805:                                     }
1.1340    raeburn  8806:                                 } else {
                   8807:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   8808:                                     &js_escape(\$shownurl);
                   8809:                                     $newurl .= '&origurl='.$shownurl;
1.1210    raeburn  8810:                                 }
1.1340    raeburn  8811:                             }
                   8812:                             &js_escape(\$msg);
                   8813:                             $result.=<<OFFLOAD
1.1210    raeburn  8814: <meta http-equiv="pragma" content="no-cache" />
                   8815: <script type="text/javascript">
1.1215    raeburn  8816: // <![CDATA[
1.1210    raeburn  8817: function LC_Offload_Now() {
                   8818:     var dest = "$newurl";
                   8819:     if (dest != '') {
                   8820:         window.location.href="$newurl";
                   8821:     }
                   8822: }
1.1214    raeburn  8823: \$(document).ready(function () {
                   8824:     window.alert('$msg');
                   8825:     if ($disable_submit) {
1.1210    raeburn  8826:         \$(".LC_hwk_submit").prop("disabled", true);
                   8827:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  8828:     }
                   8829:     setTimeout('LC_Offload_Now()', $timeout);
                   8830: });
1.1215    raeburn  8831: // ]]>
1.1210    raeburn  8832: </script>
                   8833: OFFLOAD
                   8834:                         }
                   8835:                     }
                   8836:                 }
                   8837:             }
                   8838:         }
1.313     albertel 8839:     }
1.306     albertel 8840:     if (!defined($title)) {
                   8841: 	$title = 'The LearningOnline Network with CAPA';
                   8842:     }
1.460     albertel 8843:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   8844:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  8845: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   8846:     if (!$args->{'frameset'}) {
                   8847:         $result .= ' /';
                   8848:     }
                   8849:     $result .= '>' 
1.1064    raeburn  8850:         .$inhibitprint
1.414     albertel 8851: 	.$head_extra;
1.1242    raeburn  8852:     my $clientmobile;
                   8853:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   8854:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   8855:     } else {
                   8856:         $clientmobile = $env{'browser.mobile'};
                   8857:     }
                   8858:     if ($clientmobile) {
1.1137    raeburn  8859:         $result .= '
                   8860: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   8861: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   8862:     }
1.1278    raeburn  8863:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 8864:     return $result.'</head>';
1.306     albertel 8865: }
                   8866: 
                   8867: =pod
                   8868: 
1.340     albertel 8869: =item * &font_settings()
                   8870: 
                   8871: Returns neccessary <meta> to set the proper encoding
                   8872: 
1.1160    raeburn  8873: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 8874: 
                   8875: =cut
                   8876: 
                   8877: sub font_settings {
1.1160    raeburn  8878:     my ($args) = @_;
1.340     albertel 8879:     my $headerstring='';
1.1160    raeburn  8880:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   8881:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  8882:         $headerstring.=
                   8883:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   8884:         if (!$args->{'frameset'}) {
                   8885: 	    $headerstring.= ' /';
                   8886:         }
                   8887: 	$headerstring .= '>'."\n";
1.340     albertel 8888:     }
                   8889:     return $headerstring;
                   8890: }
                   8891: 
1.341     albertel 8892: =pod
                   8893: 
1.1064    raeburn  8894: =item * &print_suppression()
                   8895: 
                   8896: In course context returns css which causes the body to be blank when media="print",
                   8897: if printout generation is unavailable for the current resource.
                   8898: 
                   8899: This could be because:
                   8900: 
                   8901: (a) printstartdate is in the future
                   8902: 
                   8903: (b) printenddate is in the past
                   8904: 
                   8905: (c) there is an active exam block with "printout"
                   8906: functionality blocked
                   8907: 
                   8908: Users with pav, pfo or evb privileges are exempt.
                   8909: 
                   8910: Inputs: none
                   8911: 
                   8912: =cut
                   8913: 
                   8914: 
                   8915: sub print_suppression {
                   8916:     my $noprint;
                   8917:     if ($env{'request.course.id'}) {
                   8918:         my $scope = $env{'request.course.id'};
                   8919:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8920:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8921:             return;
                   8922:         }
                   8923:         if ($env{'request.course.sec'} ne '') {
                   8924:             $scope .= "/$env{'request.course.sec'}";
                   8925:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8926:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8927:                 return;
1.1064    raeburn  8928:             }
                   8929:         }
                   8930:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8931:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372  ! raeburn  8932:         my $clientip = &Apache::lonnet::get_requestor_ip();
        !          8933:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
1.1064    raeburn  8934:         if ($blocked) {
                   8935:             my $checkrole = "cm./$cdom/$cnum";
                   8936:             if ($env{'request.course.sec'} ne '') {
                   8937:                 $checkrole .= "/$env{'request.course.sec'}";
                   8938:             }
                   8939:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8940:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8941:                 $noprint = 1;
                   8942:             }
                   8943:         }
                   8944:         unless ($noprint) {
                   8945:             my $symb = &Apache::lonnet::symbread();
                   8946:             if ($symb ne '') {
                   8947:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8948:                 if (ref($navmap)) {
                   8949:                     my $res = $navmap->getBySymb($symb);
                   8950:                     if (ref($res)) {
                   8951:                         if (!$res->resprintable()) {
                   8952:                             $noprint = 1;
                   8953:                         }
                   8954:                     }
                   8955:                 }
                   8956:             }
                   8957:         }
                   8958:         if ($noprint) {
                   8959:             return <<"ENDSTYLE";
                   8960: <style type="text/css" media="print">
                   8961:     body { display:none }
                   8962: </style>
                   8963: ENDSTYLE
                   8964:         }
                   8965:     }
                   8966:     return;
                   8967: }
                   8968: 
                   8969: =pod
                   8970: 
1.341     albertel 8971: =item * &xml_begin()
                   8972: 
                   8973: Returns the needed doctype and <html>
                   8974: 
                   8975: Inputs: none
                   8976: 
                   8977: =cut
                   8978: 
                   8979: sub xml_begin {
1.1168    raeburn  8980:     my ($is_frameset) = @_;
1.341     albertel 8981:     my $output='';
                   8982: 
                   8983:     if ($env{'browser.mathml'}) {
                   8984: 	$output='<?xml version="1.0"?>'
                   8985:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8986: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8987:             
                   8988: #	    .'<!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">] >'
                   8989: 	    .'<!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">'
                   8990:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8991: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  8992:     } elsif ($is_frameset) {
                   8993:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8994:                 '<html>'."\n";
1.341     albertel 8995:     } else {
1.1168    raeburn  8996: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8997:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8998:     }
                   8999:     return $output;
                   9000: }
1.340     albertel 9001: 
                   9002: =pod
                   9003: 
1.306     albertel 9004: =item * &start_page()
                   9005: 
                   9006: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   9007: 
1.648     raeburn  9008: Inputs:
                   9009: 
                   9010: =over 4
                   9011: 
                   9012: $title - optional title for the page
                   9013: 
                   9014: $head_extra - optional extra HTML to incude inside the <head>
                   9015: 
                   9016: $args - additional optional args supported are:
                   9017: 
                   9018: =over 8
                   9019: 
                   9020:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 9021:                                     arg on
1.814     bisitz   9022:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  9023:              add_entries    -> additional attributes to add to the  <body>
                   9024:              domain         -> force to color decorate a page for a 
1.317     albertel 9025:                                     specific domain
1.648     raeburn  9026:              function       -> force usage of a specific rolish color
1.317     albertel 9027:                                     scheme
1.648     raeburn  9028:              redirect       -> see &headtag()
                   9029:              bgcolor        -> override the default page bg color
                   9030:              js_ready       -> return a string ready for being used in 
1.317     albertel 9031:                                     a javascript writeln
1.648     raeburn  9032:              html_encode    -> return a string ready for being used in 
1.320     albertel 9033:                                     a html attribute
1.648     raeburn  9034:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 9035:                                     $forcereg arg
1.648     raeburn  9036:              frameset       -> if true will start with a <frameset>
1.330     albertel 9037:                                     rather than <body>
1.648     raeburn  9038:              skip_phases    -> hash ref of 
1.338     albertel 9039:                                     head -> skip the <html><head> generation
                   9040:                                     body -> skip all <body> generation
1.648     raeburn  9041:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 9042:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  9043:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1272    raeburn  9044:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   9045:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  9046:              group          -> includes the current group, if page is for a 
1.1274    raeburn  9047:                                specific group
                   9048:              use_absolute   -> for request for external resource or syllabus, this
                   9049:                                will contain https://<hostname> if server uses
                   9050:                                https (as per hosts.tab), but request is for http
                   9051:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.1369    raeburn  9052:              links_disabled -> Links in primary and secondary menus are disabled
                   9053:                                (Can enable them once page has loaded - see lonroles.pm
                   9054:                                for an example).
1.361     albertel 9055: 
1.648     raeburn  9056: =back
1.460     albertel 9057: 
1.648     raeburn  9058: =back
1.562     albertel 9059: 
1.306     albertel 9060: =cut
                   9061: 
                   9062: sub start_page {
1.309     albertel 9063:     my ($title,$head_extra,$args) = @_;
1.318     albertel 9064:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 9065: 
1.315     albertel 9066:     $env{'internal.start_page'}++;
1.1359    raeburn  9067:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
1.964     droeschl 9068: 
1.338     albertel 9069:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  9070:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 9071:     }
1.1316    raeburn  9072: 
                   9073:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
1.1318    raeburn  9074:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   9075:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   9076:                 $args->{'no_primary_menu'} = 1;
                   9077:             }
                   9078:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   9079:                 $args->{'no_inline_menu'} = 1;
                   9080:             }
                   9081:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   9082:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   9083:             }
                   9084:         } else {
                   9085:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9086:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   9087:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   9088:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   9089:                     $args->{'no_primary_menu'} = 1;
                   9090:                 }
                   9091:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   9092:                     $args->{'no_inline_menu'} = 1;
                   9093:                 }
                   9094:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   9095:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   9096:                 }
                   9097:             }
                   9098:         }
1.1316    raeburn  9099:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   9100:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   9101:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
1.1359    raeburn  9102:     } elsif ($env{'request.course.id'}) {
                   9103:         my $expiretime=600;
                   9104:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
                   9105:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
                   9106:         }
                   9107:         my ($deeplinkmenu,$menuref);
                   9108:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
                   9109:         if ($menucoll) {
                   9110:             if (ref($menuref) eq 'HASH') {
                   9111:                 %menu = %{$menuref};
                   9112:             }
                   9113:             if ($menu{'top'} eq 'n') {
                   9114:                 $args->{'no_primary_menu'} = 1;
                   9115:             }
                   9116:             if ($menu{'inline'} eq 'n') {
                   9117:                 unless (&Apache::lonnet::allowed('opa')) {
                   9118:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9119:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9120:                     my $crstype = &course_type();
                   9121:                     my $now = time;
                   9122:                     my $ccrole;
                   9123:                     if ($crstype eq 'Community') {
                   9124:                         $ccrole = 'co';
                   9125:                     } else {
                   9126:                         $ccrole = 'cc';
                   9127:                     }
                   9128:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
                   9129:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
                   9130:                         if ((($start) && ($start<0)) ||
                   9131:                             (($end) && ($end<$now))  ||
                   9132:                             (($start) && ($now<$start))) {
                   9133:                             $args->{'no_inline_menu'} = 1;
                   9134:                         }
                   9135:                     } else {
                   9136:                         $args->{'no_inline_menu'} = 1;
                   9137:                     }
                   9138:                 }
                   9139:             }
                   9140:         }
1.1316    raeburn  9141:     }
1.1359    raeburn  9142: 
1.338     albertel 9143:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   9144: 	if ($args->{'frameset'}) {
                   9145: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   9146: 						$args->{'add_entries'});
                   9147: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   9148:         } else {
                   9149:             $result .=
                   9150:                 &bodytag($title, 
                   9151:                          $args->{'function'},       $args->{'add_entries'},
                   9152:                          $args->{'only_body'},      $args->{'domain'},
                   9153:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  9154:                          $args->{'bgcolor'},        $args,
1.1359    raeburn  9155:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,\%menu);
1.831     bisitz   9156:         }
1.330     albertel 9157:     }
1.338     albertel 9158: 
1.315     albertel 9159:     if ($args->{'js_ready'}) {
1.713     kaisler  9160: 		$result = &js_ready($result);
1.315     albertel 9161:     }
1.320     albertel 9162:     if ($args->{'html_encode'}) {
1.713     kaisler  9163: 		$result = &html_encode($result);
                   9164:     }
                   9165: 
1.813     bisitz   9166:     # Preparation for new and consistent functionlist at top of screen
                   9167:     # if ($args->{'functionlist'}) {
                   9168:     #            $result .= &build_functionlist();
                   9169:     #}
                   9170: 
1.964     droeschl 9171:     # Don't add anything more if only_body wanted or in const space
                   9172:     return $result if    $args->{'only_body'} 
                   9173:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   9174: 
                   9175:     #Breadcrumbs
1.758     kaisler  9176:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   9177: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   9178: 		#if any br links exists, add them to the breadcrumbs
                   9179: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   9180: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   9181: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   9182: 			}
                   9183: 		}
1.1096    raeburn  9184:                 # if @advtools array contains items add then to the breadcrumbs
                   9185:                 if (@advtools > 0) {
                   9186:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   9187:                 }
1.1272    raeburn  9188:                 my $menulink;
                   9189:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   9190:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
1.1312    raeburn  9191:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
1.1272    raeburn  9192:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   9193:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   9194:                      (!$env{'request.role.adv'}))) {
                   9195:                     $menulink = 0;
                   9196:                 } else {
                   9197:                     undef($menulink);
                   9198:                 }
1.758     kaisler  9199: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   9200: 		if(exists($args->{'bread_crumbs_component'})){
1.1272    raeburn  9201: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.1237    raeburn  9202:                 } else {
1.1272    raeburn  9203: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  9204: 		}
1.320     albertel 9205:     }
1.315     albertel 9206:     return $result;
1.306     albertel 9207: }
                   9208: 
                   9209: sub end_page {
1.315     albertel 9210:     my ($args) = @_;
                   9211:     $env{'internal.end_page'}++;
1.330     albertel 9212:     my $result;
1.335     albertel 9213:     if ($args->{'discussion'}) {
                   9214: 	my ($target,$parser);
                   9215: 	if (ref($args->{'discussion'})) {
                   9216: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   9217: 				$args->{'discussion'}{'parser'});
                   9218: 	}
                   9219: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   9220:     }
1.330     albertel 9221:     if ($args->{'frameset'}) {
                   9222: 	$result .= '</frameset>';
                   9223:     } else {
1.635     raeburn  9224: 	$result .= &endbodytag($args);
1.330     albertel 9225:     }
1.1080    raeburn  9226:     unless ($args->{'notbody'}) {
                   9227:         $result .= "\n</html>";
                   9228:     }
1.330     albertel 9229: 
1.315     albertel 9230:     if ($args->{'js_ready'}) {
1.317     albertel 9231: 	$result = &js_ready($result);
1.315     albertel 9232:     }
1.335     albertel 9233: 
1.320     albertel 9234:     if ($args->{'html_encode'}) {
                   9235: 	$result = &html_encode($result);
                   9236:     }
1.335     albertel 9237: 
1.315     albertel 9238:     return $result;
                   9239: }
                   9240: 
1.1359    raeburn  9241: sub menucoll_in_effect {
                   9242:     my ($menucoll,$deeplinkmenu,%menu);
                   9243:     if ($env{'request.course.id'}) {
                   9244:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
1.1362    raeburn  9245:         if ($env{'request.deeplink.login'}) {
1.1370    raeburn  9246:             my ($deeplink_symb,$deeplink,$check_login_symb);
1.1362    raeburn  9247:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9248:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9249:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
                   9250:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
                   9251:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9252:                     if (ref($navmap)) {
                   9253:                         $deeplink = $navmap->get_mapparam(undef,
                   9254:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
                   9255:                                                           '0.deeplink');
1.1370    raeburn  9256:                     } else {
                   9257:                         $check_login_symb = 1;
1.1362    raeburn  9258:                     }
                   9259:                 } else {
1.1370    raeburn  9260:                     my $symb = &Apache::lonnet::symbread();
                   9261:                     if ($symb) {
                   9262:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                   9263:                     } else {
                   9264:                         $check_login_symb = 1;
                   9265:                     }
1.1362    raeburn  9266:                 }
                   9267:             } else {
1.1370    raeburn  9268:                 $check_login_symb = 1;
                   9269:             }
                   9270:             if ($check_login_symb) {
1.1362    raeburn  9271:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
                   9272:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9273:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                   9274:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9275:                     if (ref($navmap)) {
                   9276:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                   9277:                     }
                   9278:                 } else {
                   9279:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
                   9280:                 }
                   9281:             }
1.1359    raeburn  9282:             if ($deeplink ne '') {
1.1363    raeburn  9283:                 my ($state,$others,$listed,$scope,$protect,$display) = split(/,/,$deeplink);
1.1359    raeburn  9284:                 if ($display =~ /^\d+$/) {
                   9285:                     $deeplinkmenu = 1;
                   9286:                     $menucoll = $display;
                   9287:                 }
                   9288:             }
                   9289:         }
                   9290:         if ($menucoll) {
                   9291:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
                   9292:         }
                   9293:     }
                   9294:     return ($menucoll,$deeplinkmenu,\%menu);
                   9295: }
                   9296: 
1.1362    raeburn  9297: sub deeplink_login_symb {
                   9298:     my ($cnum,$cdom) = @_;
                   9299:     my $login_symb;
                   9300:     if ($env{'request.deeplink.login'}) {
1.1364    raeburn  9301:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
                   9302:     }
                   9303:     return $login_symb;
                   9304: }
                   9305: 
                   9306: sub symb_from_tinyurl {
                   9307:     my ($url,$cnum,$cdom) = @_;
                   9308:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   9309:         my $key = $1;
                   9310:         my ($tinyurl,$login);
                   9311:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   9312:         if (defined($cached)) {
                   9313:             $tinyurl = $result;
                   9314:         } else {
                   9315:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   9316:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   9317:             if ($currtiny{$key} ne '') {
                   9318:                 $tinyurl = $currtiny{$key};
                   9319:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
1.1362    raeburn  9320:             }
1.1364    raeburn  9321:         }
                   9322:         if ($tinyurl ne '') {
                   9323:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
                   9324:             if (wantarray) {
                   9325:                 return ($cnumreq,$symb);
                   9326:             } elsif ($cnumreq eq $cnum) {
                   9327:                 return $symb;
1.1362    raeburn  9328:             }
                   9329:         }
                   9330:     }
1.1364    raeburn  9331:     if (wantarray) {
                   9332:         return ();
                   9333:     } else {
                   9334:         return;
                   9335:     }
1.1362    raeburn  9336: }
                   9337: 
1.1034    www      9338: sub wishlist_window {
                   9339:     return(<<'ENDWISHLIST');
1.1046    raeburn  9340: <script type="text/javascript">
1.1034    www      9341: // <![CDATA[
                   9342: // <!-- BEGIN LON-CAPA Internal
                   9343: function set_wishlistlink(title, path) {
                   9344:     if (!title) {
                   9345:         title = document.title;
                   9346:         title = title.replace(/^LON-CAPA /,'');
                   9347:     }
1.1175    raeburn  9348:     title = encodeURIComponent(title);
1.1203    raeburn  9349:     title = title.replace("'","\\\'");
1.1034    www      9350:     if (!path) {
                   9351:         path = location.pathname;
                   9352:     }
1.1175    raeburn  9353:     path = encodeURIComponent(path);
1.1203    raeburn  9354:     path = path.replace("'","\\\'");
1.1034    www      9355:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   9356:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   9357: }
                   9358: // END LON-CAPA Internal -->
                   9359: // ]]>
                   9360: </script>
                   9361: ENDWISHLIST
                   9362: }
                   9363: 
1.1030    www      9364: sub modal_window {
                   9365:     return(<<'ENDMODAL');
1.1046    raeburn  9366: <script type="text/javascript">
1.1030    www      9367: // <![CDATA[
                   9368: // <!-- BEGIN LON-CAPA Internal
                   9369: var modalWindow = {
                   9370: 	parent:"body",
                   9371: 	windowId:null,
                   9372: 	content:null,
                   9373: 	width:null,
                   9374: 	height:null,
                   9375: 	close:function()
                   9376: 	{
                   9377: 	        $(".LCmodal-window").remove();
                   9378: 	        $(".LCmodal-overlay").remove();
                   9379: 	},
                   9380: 	open:function()
                   9381: 	{
                   9382: 		var modal = "";
                   9383: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   9384: 		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;\">";
                   9385: 		modal += this.content;
                   9386: 		modal += "</div>";	
                   9387: 
                   9388: 		$(this.parent).append(modal);
                   9389: 
                   9390: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   9391: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   9392: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   9393: 	}
                   9394: };
1.1140    raeburn  9395: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      9396: 	{
1.1266    raeburn  9397:                 source = source.replace(/'/g,"&#39;");
1.1030    www      9398: 		modalWindow.windowId = "myModal";
                   9399: 		modalWindow.width = width;
                   9400: 		modalWindow.height = height;
1.1196    raeburn  9401: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      9402: 		modalWindow.open();
1.1208    raeburn  9403: 	};
1.1030    www      9404: // END LON-CAPA Internal -->
                   9405: // ]]>
                   9406: </script>
                   9407: ENDMODAL
                   9408: }
                   9409: 
                   9410: sub modal_link {
1.1140    raeburn  9411:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      9412:     unless ($width) { $width=480; }
                   9413:     unless ($height) { $height=400; }
1.1031    www      9414:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  9415:     unless ($transparency) { $transparency='true'; }
                   9416: 
1.1074    raeburn  9417:     my $target_attr;
                   9418:     if (defined($target)) {
                   9419:         $target_attr = 'target="'.$target.'"';
                   9420:     }
                   9421:     return <<"ENDLINK";
1.1336    raeburn  9422: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  9423: ENDLINK
1.1030    www      9424: }
                   9425: 
1.1032    www      9426: sub modal_adhoc_script {
1.1365    raeburn  9427:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   9428:     my $mathjax;
                   9429:     if ($possmathjax) {
                   9430:         $mathjax = <<'ENDJAX';
                   9431:                if (typeof MathJax == 'object') {
                   9432:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   9433:                }
                   9434: ENDJAX
                   9435:     }
1.1032    www      9436:     return (<<ENDADHOC);
1.1046    raeburn  9437: <script type="text/javascript">
1.1032    www      9438: // <![CDATA[
                   9439:         var $funcname = function()
                   9440:         {
                   9441:                 modalWindow.windowId = "myModal";
                   9442:                 modalWindow.width = $width;
                   9443:                 modalWindow.height = $height;
                   9444:                 modalWindow.content = '$content';
                   9445:                 modalWindow.open();
1.1365    raeburn  9446:                 $mathjax
1.1032    www      9447:         };  
                   9448: // ]]>
                   9449: </script>
                   9450: ENDADHOC
                   9451: }
                   9452: 
1.1041    www      9453: sub modal_adhoc_inner {
1.1365    raeburn  9454:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      9455:     my $innerwidth=$width-20;
                   9456:     $content=&js_ready(
1.1140    raeburn  9457:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   9458:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   9459:                  $content.
1.1041    www      9460:                  &end_scrollbox().
1.1140    raeburn  9461:                  &end_page()
1.1041    www      9462:              );
1.1365    raeburn  9463:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      9464: }
                   9465: 
                   9466: sub modal_adhoc_window {
1.1365    raeburn  9467:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   9468:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      9469:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   9470: }
                   9471: 
                   9472: sub modal_adhoc_launch {
                   9473:     my ($funcname,$width,$height,$content)=@_;
                   9474:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   9475: <script type="text/javascript">
                   9476: // <![CDATA[
                   9477: $funcname();
                   9478: // ]]>
                   9479: </script>
                   9480: ENDLAUNCH
                   9481: }
                   9482: 
                   9483: sub modal_adhoc_close {
                   9484:     return (<<ENDCLOSE);
                   9485: <script type="text/javascript">
                   9486: // <![CDATA[
                   9487: modalWindow.close();
                   9488: // ]]>
                   9489: </script>
                   9490: ENDCLOSE
                   9491: }
                   9492: 
1.1038    www      9493: sub togglebox_script {
                   9494:    return(<<ENDTOGGLE);
                   9495: <script type="text/javascript"> 
                   9496: // <![CDATA[
                   9497: function LCtoggleDisplay(id,hidetext,showtext) {
                   9498:    link = document.getElementById(id + "link").childNodes[0];
                   9499:    with (document.getElementById(id).style) {
                   9500:       if (display == "none" ) {
                   9501:           display = "inline";
                   9502:           link.nodeValue = hidetext;
                   9503:         } else {
                   9504:           display = "none";
                   9505:           link.nodeValue = showtext;
                   9506:        }
                   9507:    }
                   9508: }
                   9509: // ]]>
                   9510: </script>
                   9511: ENDTOGGLE
                   9512: }
                   9513: 
1.1039    www      9514: sub start_togglebox {
                   9515:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   9516:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   9517:     unless ($showtext) { $showtext=&mt('show'); }
                   9518:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   9519:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   9520:     return &start_data_table().
                   9521:            &start_data_table_header_row().
                   9522:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   9523:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   9524:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   9525:            &end_data_table_header_row().
                   9526:            '<tr id="'.$id.'" style="display:none""><td>';
                   9527: }
                   9528: 
                   9529: sub end_togglebox {
                   9530:     return '</td></tr>'.&end_data_table();
                   9531: }
                   9532: 
1.1041    www      9533: sub LCprogressbar_script {
1.1302    raeburn  9534:    my ($id,$number_to_do)=@_;
                   9535:    if ($number_to_do) {
                   9536:        return(<<ENDPROGRESS);
1.1041    www      9537: <script type="text/javascript">
                   9538: // <![CDATA[
1.1045    www      9539: \$('#progressbar$id').progressbar({
1.1041    www      9540:   value: 0,
                   9541:   change: function(event, ui) {
                   9542:     var newVal = \$(this).progressbar('option', 'value');
                   9543:     \$('.pblabel', this).text(LCprogressTxt);
                   9544:   }
                   9545: });
                   9546: // ]]>
                   9547: </script>
                   9548: ENDPROGRESS
1.1302    raeburn  9549:    } else {
                   9550:        return(<<ENDPROGRESS);
                   9551: <script type="text/javascript">
                   9552: // <![CDATA[
                   9553: \$('#progressbar$id').progressbar({
                   9554:   value: false,
                   9555:   create: function(event, ui) {
                   9556:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   9557:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   9558:   }
                   9559: });
                   9560: // ]]>
                   9561: </script>
                   9562: ENDPROGRESS
                   9563:    }
1.1041    www      9564: }
                   9565: 
                   9566: sub LCprogressbarUpdate_script {
                   9567:    return(<<ENDPROGRESSUPDATE);
                   9568: <style type="text/css">
                   9569: .ui-progressbar { position:relative; }
1.1302    raeburn  9570: .progress-label {position: absolute; width: 100%; text-align: center; top: 1px; font-weight: bold; text-shadow: 1px 1px 0 #fff;margin: 0; line-height: 200%; }
1.1041    www      9571: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   9572: </style>
                   9573: <script type="text/javascript">
                   9574: // <![CDATA[
1.1045    www      9575: var LCprogressTxt='---';
                   9576: 
1.1302    raeburn  9577: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      9578:    LCprogressTxt=progresstext;
1.1302    raeburn  9579:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   9580:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   9581:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
1.1301    raeburn  9582:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   9583:    } else {
                   9584:        \$('#progressbar'+id).progressbar('value',percent);
                   9585:    }
1.1041    www      9586: }
                   9587: // ]]>
                   9588: </script>
                   9589: ENDPROGRESSUPDATE
                   9590: }
                   9591: 
1.1042    www      9592: my $LClastpercent;
1.1045    www      9593: my $LCidcnt;
                   9594: my $LCcurrentid;
1.1042    www      9595: 
1.1041    www      9596: sub LCprogressbar {
1.1302    raeburn  9597:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      9598:     $LClastpercent=0;
1.1045    www      9599:     $LCidcnt++;
                   9600:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1302    raeburn  9601:     my ($starting,$content);
                   9602:     if ($number_to_do) {
                   9603:         $starting=&mt('Starting');
                   9604:         $content=(<<ENDPROGBAR);
                   9605: $preamble
1.1045    www      9606:   <div id="progressbar$LCcurrentid">
1.1041    www      9607:     <span class="pblabel">$starting</span>
                   9608:   </div>
                   9609: ENDPROGBAR
1.1302    raeburn  9610:     } else {
                   9611:         $starting=&mt('Loading...');
                   9612:         $LClastpercent='false';
                   9613:         $content=(<<ENDPROGBAR);
                   9614: $preamble
                   9615:   <div id="progressbar$LCcurrentid">
                   9616:       <div class="progress-label">$starting</div>
                   9617:   </div>
                   9618: ENDPROGBAR
                   9619:     }
                   9620:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      9621: }
                   9622: 
                   9623: sub LCprogressbarUpdate {
1.1302    raeburn  9624:     my ($r,$val,$text,$number_to_do)=@_;
                   9625:     if ($number_to_do) {
                   9626:         unless ($val) { 
                   9627:             if ($LClastpercent) {
                   9628:                 $val=$LClastpercent;
                   9629:             } else {
                   9630:                 $val=0;
                   9631:             }
                   9632:         }
                   9633:         if ($val<0) { $val=0; }
                   9634:         if ($val>100) { $val=0; }
                   9635:         $LClastpercent=$val;
                   9636:         unless ($text) { $text=$val.'%'; }
                   9637:     } else {
                   9638:         $val = 'false';
1.1042    www      9639:     }
1.1041    www      9640:     $text=&js_ready($text);
1.1044    www      9641:     &r_print($r,<<ENDUPDATE);
1.1041    www      9642: <script type="text/javascript">
                   9643: // <![CDATA[
1.1302    raeburn  9644: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      9645: // ]]>
                   9646: </script>
                   9647: ENDUPDATE
1.1035    www      9648: }
                   9649: 
1.1042    www      9650: sub LCprogressbarClose {
                   9651:     my ($r)=@_;
                   9652:     $LClastpercent=0;
1.1044    www      9653:     &r_print($r,<<ENDCLOSE);
1.1042    www      9654: <script type="text/javascript">
                   9655: // <![CDATA[
1.1045    www      9656: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      9657: // ]]>
                   9658: </script>
                   9659: ENDCLOSE
1.1044    www      9660: }
                   9661: 
                   9662: sub r_print {
                   9663:     my ($r,$to_print)=@_;
                   9664:     if ($r) {
                   9665:       $r->print($to_print);
                   9666:       $r->rflush();
                   9667:     } else {
                   9668:       print($to_print);
                   9669:     }
1.1042    www      9670: }
                   9671: 
1.320     albertel 9672: sub html_encode {
                   9673:     my ($result) = @_;
                   9674: 
1.322     albertel 9675:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 9676:     
                   9677:     return $result;
                   9678: }
1.1044    www      9679: 
1.317     albertel 9680: sub js_ready {
                   9681:     my ($result) = @_;
                   9682: 
1.323     albertel 9683:     $result =~ s/[\n\r]/ /xmsg;
                   9684:     $result =~ s/\\/\\\\/xmsg;
                   9685:     $result =~ s/'/\\'/xmsg;
1.372     albertel 9686:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 9687:     
                   9688:     return $result;
                   9689: }
                   9690: 
1.315     albertel 9691: sub validate_page {
                   9692:     if (  exists($env{'internal.start_page'})
1.316     albertel 9693: 	  &&     $env{'internal.start_page'} > 1) {
                   9694: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 9695: 				 $env{'internal.start_page'}.' '.
1.316     albertel 9696: 				 $ENV{'request.filename'});
1.315     albertel 9697:     }
                   9698:     if (  exists($env{'internal.end_page'})
1.316     albertel 9699: 	  &&     $env{'internal.end_page'} > 1) {
                   9700: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 9701: 				 $env{'internal.end_page'}.' '.
1.316     albertel 9702: 				 $env{'request.filename'});
1.315     albertel 9703:     }
                   9704:     if (     exists($env{'internal.start_page'})
                   9705: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 9706: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   9707: 				 $env{'request.filename'});
1.315     albertel 9708:     }
                   9709:     if (   ! exists($env{'internal.start_page'})
                   9710: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 9711: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   9712: 				 $env{'request.filename'});
1.315     albertel 9713:     }
1.306     albertel 9714: }
1.315     albertel 9715: 
1.996     www      9716: 
                   9717: sub start_scrollbox {
1.1140    raeburn  9718:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  9719:     unless ($outerwidth) { $outerwidth='520px'; }
                   9720:     unless ($width) { $width='500px'; }
                   9721:     unless ($height) { $height='200px'; }
1.1075    raeburn  9722:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  9723:     if ($id ne '') {
1.1140    raeburn  9724:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  9725:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  9726:     }
1.1075    raeburn  9727:     if ($bgcolor ne '') {
                   9728:         $tdcol = "background-color: $bgcolor;";
                   9729:     }
1.1137    raeburn  9730:     my $nicescroll_js;
                   9731:     if ($env{'browser.mobile'}) {
1.1140    raeburn  9732:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   9733:     }
                   9734:     return <<"END";
                   9735: $nicescroll_js
                   9736: 
                   9737: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   9738: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   9739: END
                   9740: }
                   9741: 
                   9742: sub end_scrollbox {
                   9743:     return '</div></td></tr></table>';
                   9744: }
                   9745: 
                   9746: sub nicescroll_javascript {
                   9747:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   9748:     my %options;
                   9749:     if (ref($cursor) eq 'HASH') {
                   9750:         %options = %{$cursor};
                   9751:     }
                   9752:     unless ($options{'railalign'} =~ /^left|right$/) {
                   9753:         $options{'railalign'} = 'left';
                   9754:     }
                   9755:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   9756:         my $function  = &get_users_function();
                   9757:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  9758:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  9759:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  9760:         }
1.1140    raeburn  9761:     }
                   9762:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   9763:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  9764:             $options{'cursoropacity'}='1.0';
                   9765:         }
1.1140    raeburn  9766:     } else {
                   9767:         $options{'cursoropacity'}='1.0';
                   9768:     }
                   9769:     if ($options{'cursorfixedheight'} eq 'none') {
                   9770:         delete($options{'cursorfixedheight'});
                   9771:     } else {
                   9772:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   9773:     }
                   9774:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   9775:         delete($options{'railoffset'});
                   9776:     }
                   9777:     my @niceoptions;
                   9778:     while (my($key,$value) = each(%options)) {
                   9779:         if ($value =~ /^\{.+\}$/) {
                   9780:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  9781:         } else {
1.1140    raeburn  9782:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  9783:         }
1.1140    raeburn  9784:     }
                   9785:     my $nicescroll_js = '
1.1137    raeburn  9786: $(document).ready(
1.1140    raeburn  9787:       function() {
                   9788:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   9789:       }
1.1137    raeburn  9790: );
                   9791: ';
1.1140    raeburn  9792:     if ($framecheck) {
                   9793:         $nicescroll_js .= '
                   9794: function expand_div(caller) {
                   9795:     if (top === self) {
                   9796:         document.getElementById("'.$id.'").style.width = "auto";
                   9797:         document.getElementById("'.$id.'").style.height = "auto";
                   9798:     } else {
                   9799:         try {
                   9800:             if (parent.frames) {
                   9801:                 if (parent.frames.length > 1) {
                   9802:                     var framesrc = parent.frames[1].location.href;
                   9803:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   9804:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   9805:                         document.getElementById("'.$id.'").style.width = "auto";
                   9806:                         document.getElementById("'.$id.'").style.height = "auto";
                   9807:                     }
                   9808:                 }
                   9809:             }
                   9810:         } catch (e) {
                   9811:             return;
                   9812:         }
1.1137    raeburn  9813:     }
1.1140    raeburn  9814:     return;
1.996     www      9815: }
1.1140    raeburn  9816: ';
                   9817:     }
                   9818:     if ($needjsready) {
                   9819:         $nicescroll_js = '
                   9820: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   9821:     } else {
                   9822:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   9823:     }
                   9824:     return $nicescroll_js;
1.996     www      9825: }
                   9826: 
1.318     albertel 9827: sub simple_error_page {
1.1150    bisitz   9828:     my ($r,$title,$msg,$args) = @_;
1.1304    raeburn  9829:     my %displayargs;
1.1151    raeburn  9830:     if (ref($args) eq 'HASH') {
                   9831:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1304    raeburn  9832:         if ($args->{'only_body'}) {
                   9833:             $displayargs{'only_body'} = 1;
                   9834:         }
                   9835:         if ($args->{'no_nav_bar'}) {
                   9836:             $displayargs{'no_nav_bar'} = 1;
                   9837:         }
1.1151    raeburn  9838:     } else {
                   9839:         $msg = &mt($msg);
                   9840:     }
1.1150    bisitz   9841: 
1.318     albertel 9842:     my $page =
1.1304    raeburn  9843: 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1150    bisitz   9844: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 9845: 	&Apache::loncommon::end_page();
                   9846:     if (ref($r)) {
                   9847: 	$r->print($page);
1.327     albertel 9848: 	return;
1.318     albertel 9849:     }
                   9850:     return $page;
                   9851: }
1.347     albertel 9852: 
                   9853: {
1.610     albertel 9854:     my @row_count;
1.961     onken    9855: 
                   9856:     sub start_data_table_count {
                   9857:         unshift(@row_count, 0);
                   9858:         return;
                   9859:     }
                   9860: 
                   9861:     sub end_data_table_count {
                   9862:         shift(@row_count);
                   9863:         return;
                   9864:     }
                   9865: 
1.347     albertel 9866:     sub start_data_table {
1.1018    raeburn  9867: 	my ($add_class,$id) = @_;
1.422     albertel 9868: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  9869:         my $table_id;
                   9870:         if (defined($id)) {
                   9871:             $table_id = ' id="'.$id.'"';
                   9872:         }
1.961     onken    9873: 	&start_data_table_count();
1.1018    raeburn  9874: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 9875:     }
                   9876: 
                   9877:     sub end_data_table {
1.961     onken    9878: 	&end_data_table_count();
1.389     albertel 9879: 	return '</table>'."\n";;
1.347     albertel 9880:     }
                   9881: 
                   9882:     sub start_data_table_row {
1.974     wenzelju 9883: 	my ($add_class, $id) = @_;
1.610     albertel 9884: 	$row_count[0]++;
                   9885: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   9886: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 9887:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9888:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 9889:     }
1.471     banghart 9890:     
                   9891:     sub continue_data_table_row {
1.974     wenzelju 9892: 	my ($add_class, $id) = @_;
1.610     albertel 9893: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 9894: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   9895:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9896:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 9897:     }
1.347     albertel 9898: 
                   9899:     sub end_data_table_row {
1.389     albertel 9900: 	return '</tr>'."\n";;
1.347     albertel 9901:     }
1.367     www      9902: 
1.421     albertel 9903:     sub start_data_table_empty_row {
1.707     bisitz   9904: #	$row_count[0]++;
1.421     albertel 9905: 	return  '<tr class="LC_empty_row" >'."\n";;
                   9906:     }
                   9907: 
                   9908:     sub end_data_table_empty_row {
                   9909: 	return '</tr>'."\n";;
                   9910:     }
                   9911: 
1.367     www      9912:     sub start_data_table_header_row {
1.389     albertel 9913: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      9914:     }
                   9915: 
                   9916:     sub end_data_table_header_row {
1.389     albertel 9917: 	return '</tr>'."\n";;
1.367     www      9918:     }
1.890     droeschl 9919: 
                   9920:     sub data_table_caption {
                   9921:         my $caption = shift;
                   9922:         return "<caption class=\"LC_caption\">$caption</caption>";
                   9923:     }
1.347     albertel 9924: }
                   9925: 
1.548     albertel 9926: =pod
                   9927: 
                   9928: =item * &inhibit_menu_check($arg)
                   9929: 
                   9930: Checks for a inhibitmenu state and generates output to preserve it
                   9931: 
                   9932: Inputs:         $arg - can be any of
                   9933:                      - undef - in which case the return value is a string 
                   9934:                                to add  into arguments list of a uri
                   9935:                      - 'input' - in which case the return value is a HTML
                   9936:                                  <form> <input> field of type hidden to
                   9937:                                  preserve the value
                   9938:                      - a url - in which case the return value is the url with
                   9939:                                the neccesary cgi args added to preserve the
                   9940:                                inhibitmenu state
                   9941:                      - a ref to a url - no return value, but the string is
                   9942:                                         updated to include the neccessary cgi
                   9943:                                         args to preserve the inhibitmenu state
                   9944: 
                   9945: =cut
                   9946: 
                   9947: sub inhibit_menu_check {
                   9948:     my ($arg) = @_;
                   9949:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   9950:     if ($arg eq 'input') {
                   9951: 	if ($env{'form.inhibitmenu'}) {
                   9952: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   9953: 	} else {
                   9954: 	    return
                   9955: 	}
                   9956:     }
                   9957:     if ($env{'form.inhibitmenu'}) {
                   9958: 	if (ref($arg)) {
                   9959: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9960: 	} elsif ($arg eq '') {
                   9961: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   9962: 	} else {
                   9963: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9964: 	}
                   9965:     }
                   9966:     if (!ref($arg)) {
                   9967: 	return $arg;
                   9968:     }
                   9969: }
                   9970: 
1.251     albertel 9971: ###############################################
1.182     matthew  9972: 
                   9973: =pod
                   9974: 
1.549     albertel 9975: =back
                   9976: 
                   9977: =head1 User Information Routines
                   9978: 
                   9979: =over 4
                   9980: 
1.405     albertel 9981: =item * &get_users_function()
1.182     matthew  9982: 
                   9983: Used by &bodytag to determine the current users primary role.
                   9984: Returns either 'student','coordinator','admin', or 'author'.
                   9985: 
                   9986: =cut
                   9987: 
                   9988: ###############################################
                   9989: sub get_users_function {
1.815     tempelho 9990:     my $function = 'norole';
1.818     tempelho 9991:     if ($env{'request.role'}=~/^(st)/) {
                   9992:         $function='student';
                   9993:     }
1.907     raeburn  9994:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  9995:         $function='coordinator';
                   9996:     }
1.258     albertel 9997:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  9998:         $function='admin';
                   9999:     }
1.826     bisitz   10000:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  10001:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  10002:         $function='author';
                   10003:     }
                   10004:     return $function;
1.54      www      10005: }
1.99      www      10006: 
                   10007: ###############################################
                   10008: 
1.233     raeburn  10009: =pod
                   10010: 
1.821     raeburn  10011: =item * &show_course()
                   10012: 
                   10013: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   10014: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   10015: 
                   10016: Inputs:
                   10017: None
                   10018: 
                   10019: Outputs:
                   10020: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   10021: 
                   10022: =cut
                   10023: 
                   10024: ###############################################
                   10025: sub show_course {
                   10026:     my $course = !$env{'user.adv'};
                   10027:     if (!$env{'user.adv'}) {
                   10028:         foreach my $env (keys(%env)) {
                   10029:             next if ($env !~ m/^user\.priv\./);
                   10030:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   10031:                 $course = 0;
                   10032:                 last;
                   10033:             }
                   10034:         }
                   10035:     }
                   10036:     return $course;
                   10037: }
                   10038: 
                   10039: ###############################################
                   10040: 
                   10041: =pod
                   10042: 
1.542     raeburn  10043: =item * &check_user_status()
1.274     raeburn  10044: 
                   10045: Determines current status of supplied role for a
                   10046: specific user. Roles can be active, previous or future.
                   10047: 
                   10048: Inputs: 
                   10049: user's domain, user's username, course's domain,
1.375     raeburn  10050: course's number, optional section ID.
1.274     raeburn  10051: 
                   10052: Outputs:
                   10053: role status: active, previous or future. 
                   10054: 
                   10055: =cut
                   10056: 
                   10057: sub check_user_status {
1.412     raeburn  10058:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  10059:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  10060:     my @uroles = keys(%userinfo);
1.274     raeburn  10061:     my $srchstr;
                   10062:     my $active_chk = 'none';
1.412     raeburn  10063:     my $now = time;
1.274     raeburn  10064:     if (@uroles > 0) {
1.908     raeburn  10065:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  10066:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   10067:         } else {
1.412     raeburn  10068:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   10069:         }
                   10070:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  10071:             my $role_end = 0;
                   10072:             my $role_start = 0;
                   10073:             $active_chk = 'active';
1.412     raeburn  10074:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   10075:                 $role_end = $1;
                   10076:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   10077:                     $role_start = $1;
1.274     raeburn  10078:                 }
                   10079:             }
                   10080:             if ($role_start > 0) {
1.412     raeburn  10081:                 if ($now < $role_start) {
1.274     raeburn  10082:                     $active_chk = 'future';
                   10083:                 }
                   10084:             }
                   10085:             if ($role_end > 0) {
1.412     raeburn  10086:                 if ($now > $role_end) {
1.274     raeburn  10087:                     $active_chk = 'previous';
                   10088:                 }
                   10089:             }
                   10090:         }
                   10091:     }
                   10092:     return $active_chk;
                   10093: }
                   10094: 
                   10095: ###############################################
                   10096: 
                   10097: =pod
                   10098: 
1.405     albertel 10099: =item * &get_sections()
1.233     raeburn  10100: 
                   10101: Determines all the sections for a course including
                   10102: sections with students and sections containing other roles.
1.419     raeburn  10103: Incoming parameters: 
                   10104: 
                   10105: 1. domain
                   10106: 2. course number 
                   10107: 3. reference to array containing roles for which sections should 
                   10108: be gathered (optional).
                   10109: 4. reference to array containing status types for which sections 
                   10110: should be gathered (optional).
                   10111: 
                   10112: If the third argument is undefined, sections are gathered for any role. 
                   10113: If the fourth argument is undefined, sections are gathered for any status.
                   10114: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  10115:  
1.374     raeburn  10116: Returns section hash (keys are section IDs, values are
                   10117: number of users in each section), subject to the
1.419     raeburn  10118: optional roles filter, optional status filter 
1.233     raeburn  10119: 
                   10120: =cut
                   10121: 
                   10122: ###############################################
                   10123: sub get_sections {
1.419     raeburn  10124:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 10125:     if (!defined($cdom) || !defined($cnum)) {
                   10126:         my $cid =  $env{'request.course.id'};
                   10127: 
                   10128: 	return if (!defined($cid));
                   10129: 
                   10130:         $cdom = $env{'course.'.$cid.'.domain'};
                   10131:         $cnum = $env{'course.'.$cid.'.num'};
                   10132:     }
                   10133: 
                   10134:     my %sectioncount;
1.419     raeburn  10135:     my $now = time;
1.240     albertel 10136: 
1.1118    raeburn  10137:     my $check_students = 1;
                   10138:     my $only_students = 0;
                   10139:     if (ref($possible_roles) eq 'ARRAY') {
                   10140:         if (grep(/^st$/,@{$possible_roles})) {
                   10141:             if (@{$possible_roles} == 1) {
                   10142:                 $only_students = 1;
                   10143:             }
                   10144:         } else {
                   10145:             $check_students = 0;
                   10146:         }
                   10147:     }
                   10148: 
                   10149:     if ($check_students) { 
1.276     albertel 10150: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 10151: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   10152: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  10153:         my $start_index = &Apache::loncoursedata::CL_START();
                   10154:         my $end_index = &Apache::loncoursedata::CL_END();
                   10155:         my $status;
1.366     albertel 10156: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  10157: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   10158: 				                     $data->[$status_index],
                   10159:                                                      $data->[$start_index],
                   10160:                                                      $data->[$end_index]);
                   10161:             if ($stu_status eq 'Active') {
                   10162:                 $status = 'active';
                   10163:             } elsif ($end < $now) {
                   10164:                 $status = 'previous';
                   10165:             } elsif ($start > $now) {
                   10166:                 $status = 'future';
                   10167:             } 
                   10168: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   10169:                 if ((!defined($possible_status)) || (($status ne '') && 
                   10170:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   10171: 		    $sectioncount{$section}++;
                   10172:                 }
1.240     albertel 10173: 	    }
                   10174: 	}
                   10175:     }
1.1118    raeburn  10176:     if ($only_students) {
                   10177:         return %sectioncount;
                   10178:     }
1.240     albertel 10179:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10180:     foreach my $user (sort(keys(%courseroles))) {
                   10181: 	if ($user !~ /^(\w{2})/) { next; }
                   10182: 	my ($role) = ($user =~ /^(\w{2})/);
                   10183: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  10184: 	my ($section,$status);
1.240     albertel 10185: 	if ($role eq 'cr' &&
                   10186: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   10187: 	    $section=$1;
                   10188: 	}
                   10189: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   10190: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  10191:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   10192:         if ($end == -1 && $start == -1) {
                   10193:             next; #deleted role
                   10194:         }
                   10195:         if (!defined($possible_status)) { 
                   10196:             $sectioncount{$section}++;
                   10197:         } else {
                   10198:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   10199:                 $status = 'active';
                   10200:             } elsif ($end < $now) {
                   10201:                 $status = 'future';
                   10202:             } elsif ($start > $now) {
                   10203:                 $status = 'previous';
                   10204:             }
                   10205:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   10206:                 $sectioncount{$section}++;
                   10207:             }
                   10208:         }
1.233     raeburn  10209:     }
1.366     albertel 10210:     return %sectioncount;
1.233     raeburn  10211: }
                   10212: 
1.274     raeburn  10213: ###############################################
1.294     raeburn  10214: 
                   10215: =pod
1.405     albertel 10216: 
                   10217: =item * &get_course_users()
                   10218: 
1.275     raeburn  10219: Retrieves usernames:domains for users in the specified course
                   10220: with specific role(s), and access status. 
                   10221: 
                   10222: Incoming parameters:
1.277     albertel 10223: 1. course domain
                   10224: 2. course number
                   10225: 3. access status: users must have - either active, 
1.275     raeburn  10226: previous, future, or all.
1.277     albertel 10227: 4. reference to array of permissible roles
1.288     raeburn  10228: 5. reference to array of section restrictions (optional)
                   10229: 6. reference to results object (hash of hashes).
                   10230: 7. reference to optional userdata hash
1.609     raeburn  10231: 8. reference to optional statushash
1.630     raeburn  10232: 9. flag if privileged users (except those set to unhide in
                   10233:    course settings) should be excluded    
1.609     raeburn  10234: Keys of top level results hash are roles.
1.275     raeburn  10235: Keys of inner hashes are username:domain, with 
                   10236: values set to access type.
1.288     raeburn  10237: Optional userdata hash returns an array with arguments in the 
                   10238: same order as loncoursedata::get_classlist() for student data.
                   10239: 
1.609     raeburn  10240: Optional statushash returns
                   10241: 
1.288     raeburn  10242: Entries for end, start, section and status are blank because
                   10243: of the possibility of multiple values for non-student roles.
                   10244: 
1.275     raeburn  10245: =cut
1.405     albertel 10246: 
1.275     raeburn  10247: ###############################################
1.405     albertel 10248: 
1.275     raeburn  10249: sub get_course_users {
1.630     raeburn  10250:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  10251:     my %idx = ();
1.419     raeburn  10252:     my %seclists;
1.288     raeburn  10253: 
                   10254:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   10255:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   10256:     $idx{end} = &Apache::loncoursedata::CL_END();
                   10257:     $idx{start} = &Apache::loncoursedata::CL_START();
                   10258:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   10259:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   10260:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   10261:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   10262: 
1.290     albertel 10263:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 10264:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  10265:         my $now = time;
1.277     albertel 10266:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  10267:             my $match = 0;
1.412     raeburn  10268:             my $secmatch = 0;
1.419     raeburn  10269:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  10270:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  10271:             if ($section eq '') {
                   10272:                 $section = 'none';
                   10273:             }
1.291     albertel 10274:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10275:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10276:                     $secmatch = 1;
                   10277:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 10278:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10279:                         $secmatch = 1;
                   10280:                     }
                   10281:                 } else {  
1.419     raeburn  10282: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  10283: 		        $secmatch = 1;
                   10284:                     }
1.290     albertel 10285: 		}
1.412     raeburn  10286:                 if (!$secmatch) {
                   10287:                     next;
                   10288:                 }
1.419     raeburn  10289:             }
1.275     raeburn  10290:             if (defined($$types{'active'})) {
1.288     raeburn  10291:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  10292:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  10293:                     $match = 1;
1.275     raeburn  10294:                 }
                   10295:             }
                   10296:             if (defined($$types{'previous'})) {
1.609     raeburn  10297:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  10298:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  10299:                     $match = 1;
1.275     raeburn  10300:                 }
                   10301:             }
                   10302:             if (defined($$types{'future'})) {
1.609     raeburn  10303:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  10304:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  10305:                     $match = 1;
1.275     raeburn  10306:                 }
                   10307:             }
1.609     raeburn  10308:             if ($match) {
                   10309:                 push(@{$seclists{$student}},$section);
                   10310:                 if (ref($userdata) eq 'HASH') {
                   10311:                     $$userdata{$student} = $$classlist{$student};
                   10312:                 }
                   10313:                 if (ref($statushash) eq 'HASH') {
                   10314:                     $statushash->{$student}{'st'}{$section} = $status;
                   10315:                 }
1.288     raeburn  10316:             }
1.275     raeburn  10317:         }
                   10318:     }
1.412     raeburn  10319:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  10320:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10321:         my $now = time;
1.609     raeburn  10322:         my %displaystatus = ( previous => 'Expired',
                   10323:                               active   => 'Active',
                   10324:                               future   => 'Future',
                   10325:                             );
1.1121    raeburn  10326:         my (%nothide,@possdoms);
1.630     raeburn  10327:         if ($hidepriv) {
                   10328:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   10329:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   10330:                 if ($user !~ /:/) {
                   10331:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   10332:                 } else {
                   10333:                     $nothide{$user} = 1;
                   10334:                 }
                   10335:             }
1.1121    raeburn  10336:             my @possdoms = ($cdom);
                   10337:             if ($coursehash{'checkforpriv'}) {
                   10338:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   10339:             }
1.630     raeburn  10340:         }
1.439     raeburn  10341:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  10342:             my $match = 0;
1.412     raeburn  10343:             my $secmatch = 0;
1.439     raeburn  10344:             my $status;
1.412     raeburn  10345:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  10346:             $user =~ s/:$//;
1.439     raeburn  10347:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   10348:             if ($end == -1 || $start == -1) {
                   10349:                 next;
                   10350:             }
                   10351:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   10352:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  10353:                 my ($uname,$udom) = split(/:/,$user);
                   10354:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10355:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10356:                         $secmatch = 1;
                   10357:                     } elsif ($usec eq '') {
1.420     albertel 10358:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10359:                             $secmatch = 1;
                   10360:                         }
                   10361:                     } else {
                   10362:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   10363:                             $secmatch = 1;
                   10364:                         }
                   10365:                     }
                   10366:                     if (!$secmatch) {
                   10367:                         next;
                   10368:                     }
1.288     raeburn  10369:                 }
1.419     raeburn  10370:                 if ($usec eq '') {
                   10371:                     $usec = 'none';
                   10372:                 }
1.275     raeburn  10373:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  10374:                     if ($hidepriv) {
1.1121    raeburn  10375:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  10376:                             (!$nothide{$uname.':'.$udom})) {
                   10377:                             next;
                   10378:                         }
                   10379:                     }
1.503     raeburn  10380:                     if ($end > 0 && $end < $now) {
1.439     raeburn  10381:                         $status = 'previous';
                   10382:                     } elsif ($start > $now) {
                   10383:                         $status = 'future';
                   10384:                     } else {
                   10385:                         $status = 'active';
                   10386:                     }
1.277     albertel 10387:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  10388:                         if ($status eq $type) {
1.420     albertel 10389:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  10390:                                 push(@{$$users{$role}{$user}},$type);
                   10391:                             }
1.288     raeburn  10392:                             $match = 1;
                   10393:                         }
                   10394:                     }
1.419     raeburn  10395:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   10396:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   10397: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   10398:                         }
1.420     albertel 10399:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  10400:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   10401:                         }
1.609     raeburn  10402:                         if (ref($statushash) eq 'HASH') {
                   10403:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   10404:                         }
1.275     raeburn  10405:                     }
                   10406:                 }
                   10407:             }
                   10408:         }
1.290     albertel 10409:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  10410:             if ((defined($cdom)) && (defined($cnum))) {
                   10411:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   10412:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   10413:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  10414:                     next if ($owner eq '');
                   10415:                     my ($ownername,$ownerdom);
                   10416:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   10417:                         $ownername = $1;
                   10418:                         $ownerdom = $2;
                   10419:                     } else {
                   10420:                         $ownername = $owner;
                   10421:                         $ownerdom = $cdom;
                   10422:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  10423:                     }
                   10424:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 10425:                     if (defined($userdata) && 
1.609     raeburn  10426: 			!exists($$userdata{$owner})) {
                   10427: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   10428:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   10429:                             push(@{$seclists{$owner}},'none');
                   10430:                         }
                   10431:                         if (ref($statushash) eq 'HASH') {
                   10432:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  10433:                         }
1.290     albertel 10434: 		    }
1.279     raeburn  10435:                 }
                   10436:             }
                   10437:         }
1.419     raeburn  10438:         foreach my $user (keys(%seclists)) {
                   10439:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   10440:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   10441:         }
1.275     raeburn  10442:     }
                   10443:     return;
                   10444: }
                   10445: 
1.288     raeburn  10446: sub get_user_info {
                   10447:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 10448:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   10449: 	&plainname($uname,$udom,'lastname');
1.291     albertel 10450:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  10451:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  10452:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   10453:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  10454:     return;
                   10455: }
1.275     raeburn  10456: 
1.472     raeburn  10457: ###############################################
                   10458: 
                   10459: =pod
                   10460: 
                   10461: =item * &get_user_quota()
                   10462: 
1.1134    raeburn  10463: Retrieves quota assigned for storage of user files.
                   10464: Default is to report quota for portfolio files.
1.472     raeburn  10465: 
                   10466: Incoming parameters:
                   10467: 1. user's username
                   10468: 2. user's domain
1.1134    raeburn  10469: 3. quota name - portfolio, author, or course
1.1136    raeburn  10470:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  10471: 4. crstype - official, unofficial, textbook, placement or community, 
                   10472:    if quota name is course
1.472     raeburn  10473: 
                   10474: Returns:
1.1163    raeburn  10475: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  10476: 2. (Optional) Type of setting: custom or default
                   10477:    (individually assigned or default for user's 
                   10478:    institutional status).
                   10479: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   10480:    or student - types as defined in localenroll::inst_usertypes 
                   10481:    for user's domain, which determines default quota for user.
                   10482: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  10483: 
                   10484: If a value has been stored in the user's environment, 
1.536     raeburn  10485: it will return that, otherwise it returns the maximal default
1.1134    raeburn  10486: defined for the user's institutional status(es) in the domain.
1.472     raeburn  10487: 
                   10488: =cut
                   10489: 
                   10490: ###############################################
                   10491: 
                   10492: 
                   10493: sub get_user_quota {
1.1136    raeburn  10494:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  10495:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  10496:     if (!defined($udom)) {
                   10497:         $udom = $env{'user.domain'};
                   10498:     }
                   10499:     if (!defined($uname)) {
                   10500:         $uname = $env{'user.name'};
                   10501:     }
                   10502:     if (($udom eq '' || $uname eq '') ||
                   10503:         ($udom eq 'public') && ($uname eq 'public')) {
                   10504:         $quota = 0;
1.536     raeburn  10505:         $quotatype = 'default';
                   10506:         $defquota = 0; 
1.472     raeburn  10507:     } else {
1.536     raeburn  10508:         my $inststatus;
1.1134    raeburn  10509:         if ($quotaname eq 'course') {
                   10510:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   10511:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   10512:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   10513:             } else {
                   10514:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   10515:                 $quota = $cenv{'internal.uploadquota'};
                   10516:             }
1.536     raeburn  10517:         } else {
1.1134    raeburn  10518:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   10519:                 if ($quotaname eq 'author') {
                   10520:                     $quota = $env{'environment.authorquota'};
                   10521:                 } else {
                   10522:                     $quota = $env{'environment.portfolioquota'};
                   10523:                 }
                   10524:                 $inststatus = $env{'environment.inststatus'};
                   10525:             } else {
                   10526:                 my %userenv = 
                   10527:                     &Apache::lonnet::get('environment',['portfolioquota',
                   10528:                                          'authorquota','inststatus'],$udom,$uname);
                   10529:                 my ($tmp) = keys(%userenv);
                   10530:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10531:                     if ($quotaname eq 'author') {
                   10532:                         $quota = $userenv{'authorquota'};
                   10533:                     } else {
                   10534:                         $quota = $userenv{'portfolioquota'};
                   10535:                     }
                   10536:                     $inststatus = $userenv{'inststatus'};
                   10537:                 } else {
                   10538:                     undef(%userenv);
                   10539:                 }
                   10540:             }
                   10541:         }
                   10542:         if ($quota eq '' || wantarray) {
                   10543:             if ($quotaname eq 'course') {
                   10544:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  10545:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  10546:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   10547:                     ($crstype eq 'placement')) { 
1.1136    raeburn  10548:                     $defquota = $domdefs{$crstype.'quota'};
                   10549:                 }
                   10550:                 if ($defquota eq '') {
                   10551:                     $defquota = 500;
                   10552:                 }
1.1134    raeburn  10553:             } else {
                   10554:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   10555:             }
                   10556:             if ($quota eq '') {
                   10557:                 $quota = $defquota;
                   10558:                 $quotatype = 'default';
                   10559:             } else {
                   10560:                 $quotatype = 'custom';
                   10561:             }
1.472     raeburn  10562:         }
                   10563:     }
1.536     raeburn  10564:     if (wantarray) {
                   10565:         return ($quota,$quotatype,$settingstatus,$defquota);
                   10566:     } else {
                   10567:         return $quota;
                   10568:     }
1.472     raeburn  10569: }
                   10570: 
                   10571: ###############################################
                   10572: 
                   10573: =pod
                   10574: 
                   10575: =item * &default_quota()
                   10576: 
1.536     raeburn  10577: Retrieves default quota assigned for storage of user portfolio files,
                   10578: given an (optional) user's institutional status.
1.472     raeburn  10579: 
                   10580: Incoming parameters:
1.1142    raeburn  10581: 
1.472     raeburn  10582: 1. domain
1.536     raeburn  10583: 2. (Optional) institutional status(es).  This is a : separated list of 
                   10584:    status types (e.g., faculty, staff, student etc.)
                   10585:    which apply to the user for whom the default is being retrieved.
                   10586:    If the institutional status string in undefined, the domain
1.1134    raeburn  10587:    default quota will be returned.
                   10588: 3.  quota name - portfolio, author, or course
                   10589:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  10590: 
                   10591: Returns:
1.1142    raeburn  10592: 
1.1163    raeburn  10593: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  10594: 2. (Optional) institutional type which determined the value of the
                   10595:    default quota.
1.472     raeburn  10596: 
                   10597: If a value has been stored in the domain's configuration db,
                   10598: it will return that, otherwise it returns 20 (for backwards 
                   10599: compatibility with domains which have not set up a configuration
1.1163    raeburn  10600: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  10601: 
1.536     raeburn  10602: If the user's status includes multiple types (e.g., staff and student),
                   10603: the largest default quota which applies to the user determines the
                   10604: default quota returned.
                   10605: 
1.472     raeburn  10606: =cut
                   10607: 
                   10608: ###############################################
                   10609: 
                   10610: 
                   10611: sub default_quota {
1.1134    raeburn  10612:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  10613:     my ($defquota,$settingstatus);
                   10614:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  10615:                                             ['quotas'],$udom);
1.1134    raeburn  10616:     my $key = 'defaultquota';
                   10617:     if ($quotaname eq 'author') {
                   10618:         $key = 'authorquota';
                   10619:     }
1.622     raeburn  10620:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  10621:         if ($inststatus ne '') {
1.765     raeburn  10622:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  10623:             foreach my $item (@statuses) {
1.1134    raeburn  10624:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10625:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  10626:                         if ($defquota eq '') {
1.1134    raeburn  10627:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10628:                             $settingstatus = $item;
1.1134    raeburn  10629:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   10630:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10631:                             $settingstatus = $item;
                   10632:                         }
                   10633:                     }
1.1134    raeburn  10634:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  10635:                     if ($quotahash{'quotas'}{$item} ne '') {
                   10636:                         if ($defquota eq '') {
                   10637:                             $defquota = $quotahash{'quotas'}{$item};
                   10638:                             $settingstatus = $item;
                   10639:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   10640:                             $defquota = $quotahash{'quotas'}{$item};
                   10641:                             $settingstatus = $item;
                   10642:                         }
1.536     raeburn  10643:                     }
                   10644:                 }
                   10645:             }
                   10646:         }
                   10647:         if ($defquota eq '') {
1.1134    raeburn  10648:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10649:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   10650:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  10651:                 $defquota = $quotahash{'quotas'}{'default'};
                   10652:             }
1.536     raeburn  10653:             $settingstatus = 'default';
1.1139    raeburn  10654:             if ($defquota eq '') {
                   10655:                 if ($quotaname eq 'author') {
                   10656:                     $defquota = 500;
                   10657:                 }
                   10658:             }
1.536     raeburn  10659:         }
                   10660:     } else {
                   10661:         $settingstatus = 'default';
1.1134    raeburn  10662:         if ($quotaname eq 'author') {
                   10663:             $defquota = 500;
                   10664:         } else {
                   10665:             $defquota = 20;
                   10666:         }
1.536     raeburn  10667:     }
                   10668:     if (wantarray) {
                   10669:         return ($defquota,$settingstatus);
1.472     raeburn  10670:     } else {
1.536     raeburn  10671:         return $defquota;
1.472     raeburn  10672:     }
                   10673: }
                   10674: 
1.1135    raeburn  10675: ###############################################
                   10676: 
                   10677: =pod
                   10678: 
1.1136    raeburn  10679: =item * &excess_filesize_warning()
1.1135    raeburn  10680: 
                   10681: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  10682: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  10683: space to be exceeded.
1.1136    raeburn  10684: 
                   10685: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  10686: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  10687: 
1.1165    raeburn  10688: Inputs: 7 
1.1136    raeburn  10689: 1. username or coursenum
1.1135    raeburn  10690: 2. domain
1.1136    raeburn  10691: 3. context ('author' or 'course')
1.1135    raeburn  10692: 4. filename of file for which action is being requested
                   10693: 5. filesize (kB) of file
                   10694: 6. action being taken: copy or upload.
1.1237    raeburn  10695: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  10696: 
                   10697: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  10698:          otherwise return null.
                   10699: 
                   10700: =back
1.1135    raeburn  10701: 
                   10702: =cut
                   10703: 
1.1136    raeburn  10704: sub excess_filesize_warning {
1.1165    raeburn  10705:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  10706:     my $current_disk_usage = 0;
1.1165    raeburn  10707:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  10708:     if ($context eq 'author') {
                   10709:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   10710:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   10711:     } else {
                   10712:         foreach my $subdir ('docs','supplemental') {
                   10713:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   10714:         }
                   10715:     }
1.1135    raeburn  10716:     $disk_quota = int($disk_quota * 1000);
                   10717:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   10718:         return '<p class="LC_warning">'.
1.1135    raeburn  10719:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   10720:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   10721:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  10722:                             $disk_quota,$current_disk_usage).
                   10723:                '</p>';
                   10724:     }
                   10725:     return;
                   10726: }
                   10727: 
                   10728: ###############################################
                   10729: 
                   10730: 
1.1136    raeburn  10731: 
                   10732: 
1.384     raeburn  10733: sub get_secgrprole_info {
                   10734:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   10735:     my %sections_count = &get_sections($cdom,$cnum);
                   10736:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   10737:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   10738:     my @groups = sort(keys(%curr_groups));
                   10739:     my $allroles = [];
                   10740:     my $rolehash;
                   10741:     my $accesshash = {
                   10742:                      active => 'Currently has access',
                   10743:                      future => 'Will have future access',
                   10744:                      previous => 'Previously had access',
                   10745:                   };
                   10746:     if ($needroles) {
                   10747:         $rolehash = {'all' => 'all'};
1.385     albertel 10748:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10749: 	if (&Apache::lonnet::error(%user_roles)) {
                   10750: 	    undef(%user_roles);
                   10751: 	}
                   10752:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  10753:             my ($role)=split(/\:/,$item,2);
                   10754:             if ($role eq 'cr') { next; }
                   10755:             if ($role =~ /^cr/) {
                   10756:                 $$rolehash{$role} = (split('/',$role))[3];
                   10757:             } else {
                   10758:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   10759:             }
                   10760:         }
                   10761:         foreach my $key (sort(keys(%{$rolehash}))) {
                   10762:             push(@{$allroles},$key);
                   10763:         }
                   10764:         push (@{$allroles},'st');
                   10765:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   10766:     }
                   10767:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   10768: }
                   10769: 
1.555     raeburn  10770: sub user_picker {
1.1279    raeburn  10771:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  10772:     my $currdom = $dom;
1.1253    raeburn  10773:     my @alldoms = &Apache::lonnet::all_domains();
                   10774:     if (@alldoms == 1) {
                   10775:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   10776:                                                ['directorysrch'],$alldoms[0]);
                   10777:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   10778:         my $showdom = $domdesc;
                   10779:         if ($showdom eq '') {
                   10780:             $showdom = $dom;
                   10781:         }
                   10782:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   10783:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   10784:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   10785:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   10786:             }
                   10787:         }
                   10788:     }
1.555     raeburn  10789:     my %curr_selected = (
                   10790:                         srchin => 'dom',
1.580     raeburn  10791:                         srchby => 'lastname',
1.555     raeburn  10792:                       );
                   10793:     my $srchterm;
1.625     raeburn  10794:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  10795:         if ($srch->{'srchby'} ne '') {
                   10796:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   10797:         }
                   10798:         if ($srch->{'srchin'} ne '') {
                   10799:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   10800:         }
                   10801:         if ($srch->{'srchtype'} ne '') {
                   10802:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   10803:         }
                   10804:         if ($srch->{'srchdomain'} ne '') {
                   10805:             $currdom = $srch->{'srchdomain'};
                   10806:         }
                   10807:         $srchterm = $srch->{'srchterm'};
                   10808:     }
1.1222    damieng  10809:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  10810:                     'usr'       => 'Search criteria',
1.563     raeburn  10811:                     'doma'      => 'Domain/institution to search',
1.558     albertel 10812:                     'uname'     => 'username',
                   10813:                     'lastname'  => 'last name',
1.555     raeburn  10814:                     'lastfirst' => 'last name, first name',
1.558     albertel 10815:                     'crs'       => 'in this course',
1.576     raeburn  10816:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 10817:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  10818:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 10819:                     'exact'     => 'is',
                   10820:                     'contains'  => 'contains',
1.569     raeburn  10821:                     'begins'    => 'begins with',
1.1222    damieng  10822:                                        );
                   10823:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  10824:                     'youm'      => "You must include some text to search for.",
                   10825:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   10826:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   10827:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   10828:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   10829:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   10830:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   10831:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  10832:                                        );
1.1222    damieng  10833:     &html_escape(\%html_lt);
                   10834:     &js_escape(\%js_lt);
1.1255    raeburn  10835:     my $domform;
1.1277    raeburn  10836:     my $allow_blank = 1;
1.1255    raeburn  10837:     if ($fixeddom) {
1.1277    raeburn  10838:         $allow_blank = 0;
                   10839:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  10840:     } else {
1.1287    raeburn  10841:         my $defdom = $env{'request.role.domain'};
1.1288    raeburn  10842:         my ($trusted,$untrusted);
1.1287    raeburn  10843:         if (($context eq 'requestcrs') || ($context eq 'course')) {
1.1288    raeburn  10844:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
1.1287    raeburn  10845:         } elsif ($context eq 'author') {
1.1288    raeburn  10846:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
1.1287    raeburn  10847:         } elsif ($context eq 'domain') {
1.1288    raeburn  10848:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
1.1287    raeburn  10849:         }
1.1288    raeburn  10850:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
1.1255    raeburn  10851:     }
1.563     raeburn  10852:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  10853: 
                   10854:     my @srchins = ('crs','dom','alc','instd');
                   10855: 
                   10856:     foreach my $option (@srchins) {
                   10857:         # FIXME 'alc' option unavailable until 
                   10858:         #       loncreateuser::print_user_query_page()
                   10859:         #       has been completed.
                   10860:         next if ($option eq 'alc');
1.880     raeburn  10861:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  10862:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  10863:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  10864:         if ($curr_selected{'srchin'} eq $option) {
                   10865:             $srchinsel .= ' 
1.1222    damieng  10866:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  10867:         } else {
                   10868:             $srchinsel .= '
1.1222    damieng  10869:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  10870:         }
1.555     raeburn  10871:     }
1.563     raeburn  10872:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  10873: 
                   10874:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  10875:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  10876:         if ($curr_selected{'srchby'} eq $option) {
                   10877:             $srchbysel .= '
1.1222    damieng  10878:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10879:         } else {
                   10880:             $srchbysel .= '
1.1222    damieng  10881:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10882:          }
                   10883:     }
                   10884:     $srchbysel .= "\n  </select>\n";
                   10885: 
                   10886:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  10887:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  10888:         if ($curr_selected{'srchtype'} eq $option) {
                   10889:             $srchtypesel .= '
1.1222    damieng  10890:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10891:         } else {
                   10892:             $srchtypesel .= '
1.1222    damieng  10893:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10894:         }
                   10895:     }
                   10896:     $srchtypesel .= "\n  </select>\n";
                   10897: 
1.558     albertel 10898:     my ($newuserscript,$new_user_create);
1.994     raeburn  10899:     my $context_dom = $env{'request.role.domain'};
                   10900:     if ($context eq 'requestcrs') {
                   10901:         if ($env{'form.coursedom'} ne '') { 
                   10902:             $context_dom = $env{'form.coursedom'};
                   10903:         }
                   10904:     }
1.556     raeburn  10905:     if ($forcenewuser) {
1.576     raeburn  10906:         if (ref($srch) eq 'HASH') {
1.994     raeburn  10907:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  10908:                 if ($cancreate) {
                   10909:                     $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>';
                   10910:                 } else {
1.799     bisitz   10911:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  10912:                     my %usertypetext = (
                   10913:                         official   => 'institutional',
                   10914:                         unofficial => 'non-institutional',
                   10915:                     );
1.799     bisitz   10916:                     $new_user_create = '<p class="LC_warning">'
                   10917:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   10918:                                       .' '
                   10919:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   10920:                                           ,'<a href="'.$helplink.'">','</a>')
                   10921:                                       .'</p><br />';
1.627     raeburn  10922:                 }
1.576     raeburn  10923:             }
                   10924:         }
                   10925: 
1.556     raeburn  10926:         $newuserscript = <<"ENDSCRIPT";
                   10927: 
1.570     raeburn  10928: function setSearch(createnew,callingForm) {
1.556     raeburn  10929:     if (createnew == 1) {
1.570     raeburn  10930:         for (var i=0; i<callingForm.srchby.length; i++) {
                   10931:             if (callingForm.srchby.options[i].value == 'uname') {
                   10932:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  10933:             }
                   10934:         }
1.570     raeburn  10935:         for (var i=0; i<callingForm.srchin.length; i++) {
                   10936:             if ( callingForm.srchin.options[i].value == 'dom') {
                   10937: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  10938:             }
                   10939:         }
1.570     raeburn  10940:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   10941:             if (callingForm.srchtype.options[i].value == 'exact') {
                   10942:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  10943:             }
                   10944:         }
1.570     raeburn  10945:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  10946:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  10947:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  10948:             }
                   10949:         }
                   10950:     }
                   10951: }
                   10952: ENDSCRIPT
1.558     albertel 10953: 
1.556     raeburn  10954:     }
                   10955: 
1.555     raeburn  10956:     my $output = <<"END_BLOCK";
1.556     raeburn  10957: <script type="text/javascript">
1.824     bisitz   10958: // <![CDATA[
1.570     raeburn  10959: function validateEntry(callingForm) {
1.558     albertel 10960: 
1.556     raeburn  10961:     var checkok = 1;
1.558     albertel 10962:     var srchin;
1.570     raeburn  10963:     for (var i=0; i<callingForm.srchin.length; i++) {
                   10964: 	if ( callingForm.srchin[i].checked ) {
                   10965: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 10966: 	}
                   10967:     }
                   10968: 
1.570     raeburn  10969:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   10970:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   10971:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   10972:     var srchterm =  callingForm.srchterm.value;
                   10973:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  10974:     var msg = "";
                   10975: 
                   10976:     if (srchterm == "") {
                   10977:         checkok = 0;
1.1222    damieng  10978:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  10979:     }
                   10980: 
1.569     raeburn  10981:     if (srchtype== 'begins') {
                   10982:         if (srchterm.length < 2) {
                   10983:             checkok = 0;
1.1222    damieng  10984:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  10985:         }
                   10986:     }
                   10987: 
1.556     raeburn  10988:     if (srchtype== 'contains') {
                   10989:         if (srchterm.length < 3) {
                   10990:             checkok = 0;
1.1222    damieng  10991:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  10992:         }
                   10993:     }
                   10994:     if (srchin == 'instd') {
                   10995:         if (srchdomain == '') {
                   10996:             checkok = 0;
1.1222    damieng  10997:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  10998:         }
                   10999:     }
                   11000:     if (srchin == 'dom') {
                   11001:         if (srchdomain == '') {
                   11002:             checkok = 0;
1.1222    damieng  11003:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  11004:         }
                   11005:     }
                   11006:     if (srchby == 'lastfirst') {
                   11007:         if (srchterm.indexOf(",") == -1) {
                   11008:             checkok = 0;
1.1222    damieng  11009:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  11010:         }
                   11011:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   11012:             checkok = 0;
1.1222    damieng  11013:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  11014:         }
                   11015:     }
                   11016:     if (checkok == 0) {
1.1222    damieng  11017:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  11018:         return;
                   11019:     }
                   11020:     if (checkok == 1) {
1.570     raeburn  11021:         callingForm.submit();
1.556     raeburn  11022:     }
                   11023: }
                   11024: 
                   11025: $newuserscript
                   11026: 
1.824     bisitz   11027: // ]]>
1.556     raeburn  11028: </script>
1.558     albertel 11029: 
                   11030: $new_user_create
                   11031: 
1.555     raeburn  11032: END_BLOCK
1.558     albertel 11033: 
1.876     raeburn  11034:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  11035:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  11036:                $domform.
                   11037:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  11038:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  11039:                $srchbysel.
                   11040:                $srchtypesel. 
                   11041:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   11042:                $srchinsel.
                   11043:                &Apache::lonhtmlcommon::row_closure(1). 
                   11044:                &Apache::lonhtmlcommon::end_pick_box().
                   11045:                '<br />';
1.1253    raeburn  11046:     return ($output,1);
1.555     raeburn  11047: }
                   11048: 
1.612     raeburn  11049: sub user_rule_check {
1.615     raeburn  11050:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  11051:     my ($response,%inst_response);
1.612     raeburn  11052:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  11053:         if (keys(%{$usershash}) > 1) {
                   11054:             my (%by_username,%by_id,%userdoms);
                   11055:             my $checkid; 
                   11056:             if (ref($checks) eq 'HASH') {
                   11057:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   11058:                     $checkid = 1;
                   11059:                 }
                   11060:             }
                   11061:             foreach my $user (keys(%{$usershash})) {
                   11062:                 my ($uname,$udom) = split(/:/,$user);
                   11063:                 if ($checkid) {
                   11064:                     if (ref($usershash->{$user}) eq 'HASH') {
                   11065:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  11066:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  11067:                             $userdoms{$udom} = 1;
1.1227    raeburn  11068:                             if (ref($inst_results) eq 'HASH') {
                   11069:                                 $inst_results->{$uname.':'.$udom} = {};
                   11070:                             }
1.1226    raeburn  11071:                         }
                   11072:                     }
                   11073:                 } else {
                   11074:                     $by_username{$udom}{$uname} = 1;
                   11075:                     $userdoms{$udom} = 1;
1.1227    raeburn  11076:                     if (ref($inst_results) eq 'HASH') {
                   11077:                         $inst_results->{$uname.':'.$udom} = {};
                   11078:                     }
1.1226    raeburn  11079:                 }
                   11080:             }
                   11081:             foreach my $udom (keys(%userdoms)) {
                   11082:                 if (!$got_rules->{$udom}) {
                   11083:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11084:                                                              ['usercreation'],$udom);
                   11085:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11086:                         foreach my $item ('username','id') {
                   11087:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  11088:                                 $$curr_rules{$udom}{$item} =
                   11089:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  11090:                             }
                   11091:                         }
                   11092:                     }
                   11093:                     $got_rules->{$udom} = 1;
                   11094:                 }
1.612     raeburn  11095:             }
1.1226    raeburn  11096:             if ($checkid) {
                   11097:                 foreach my $udom (keys(%by_id)) {
                   11098:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   11099:                     if ($outcome eq 'ok') {
1.1227    raeburn  11100:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   11101:                             my $uname = $by_id{$udom}{$id};
                   11102:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11103:                         }
1.1226    raeburn  11104:                         if (ref($results) eq 'HASH') {
                   11105:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  11106:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   11107:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   11108:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11109:                                 }
1.1226    raeburn  11110:                             }
                   11111:                         }
                   11112:                     }
1.612     raeburn  11113:                 }
1.615     raeburn  11114:             } else {
1.1226    raeburn  11115:                 foreach my $udom (keys(%by_username)) {
                   11116:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   11117:                     if ($outcome eq 'ok') {
1.1227    raeburn  11118:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   11119:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11120:                         }
1.1226    raeburn  11121:                         if (ref($results) eq 'HASH') {
                   11122:                             foreach my $uname (keys(%{$results})) {
                   11123:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11124:                             }
                   11125:                         }
                   11126:                     }
                   11127:                 }
1.612     raeburn  11128:             }
1.1226    raeburn  11129:         } elsif (keys(%{$usershash}) == 1) {
                   11130:             my $user = (keys(%{$usershash}))[0];
                   11131:             my ($uname,$udom) = split(/:/,$user);
                   11132:             if (($udom ne '') && ($uname ne '')) {
                   11133:                 if (ref($usershash->{$user}) eq 'HASH') {
                   11134:                     if (ref($checks) eq 'HASH') {
                   11135:                         if (defined($checks->{'username'})) {
                   11136:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   11137:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   11138:                         } elsif (defined($checks->{'id'})) {
                   11139:                             if ($usershash->{$user}->{'id'} ne '') {
                   11140:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11141:                                     &Apache::lonnet::get_instuser($udom,undef,
                   11142:                                                                   $usershash->{$user}->{'id'});
                   11143:                             } else {
                   11144:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11145:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   11146:                             }
1.585     raeburn  11147:                         }
1.1226    raeburn  11148:                     } else {
                   11149:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   11150:                             &Apache::lonnet::get_instuser($udom,$uname);
                   11151:                        return;
                   11152:                     }
                   11153:                     if (!$got_rules->{$udom}) {
                   11154:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11155:                                                                  ['usercreation'],$udom);
                   11156:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11157:                             foreach my $item ('username','id') {
                   11158:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   11159:                                    $$curr_rules{$udom}{$item} = 
                   11160:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   11161:                                 }
                   11162:                             }
                   11163:                         }
                   11164:                         $got_rules->{$udom} = 1;
1.585     raeburn  11165:                     }
                   11166:                 }
1.1226    raeburn  11167:             } else {
                   11168:                 return;
                   11169:             }
                   11170:         } else {
                   11171:             return;
                   11172:         }
                   11173:         foreach my $user (keys(%{$usershash})) {
                   11174:             my ($uname,$udom) = split(/:/,$user);
                   11175:             next if (($udom eq '') || ($uname eq ''));
                   11176:             my $id;
1.1227    raeburn  11177:             if (ref($inst_results) eq 'HASH') {
                   11178:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   11179:                     $id = $inst_results->{$user}->{'id'};
                   11180:                 }
                   11181:             }
                   11182:             if ($id eq '') { 
                   11183:                 if (ref($usershash->{$user})) {
                   11184:                     $id = $usershash->{$user}->{'id'};
                   11185:                 }
1.585     raeburn  11186:             }
1.612     raeburn  11187:             foreach my $item (keys(%{$checks})) {
                   11188:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   11189:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   11190:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  11191:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   11192:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  11193:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   11194:                                 if ($rule_check{$rule}) {
                   11195:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  11196:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  11197:                                         if (ref($inst_results) eq 'HASH') {
                   11198:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   11199:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   11200:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  11201:                                                 } elsif ($item eq 'id') {
                   11202:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   11203:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   11204:                                                     }
1.615     raeburn  11205:                                                 }
1.612     raeburn  11206:                                             }
                   11207:                                         }
1.615     raeburn  11208:                                     }
                   11209:                                     last;
1.585     raeburn  11210:                                 }
                   11211:                             }
                   11212:                         }
                   11213:                     }
                   11214:                 }
                   11215:             }
                   11216:         }
                   11217:     }
1.612     raeburn  11218:     return;
                   11219: }
                   11220: 
                   11221: sub user_rule_formats {
                   11222:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   11223:     my %text = ( 
                   11224:                  'username' => 'Usernames',
                   11225:                  'id'       => 'IDs',
                   11226:                );
                   11227:     my $output;
                   11228:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   11229:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   11230:         if (@{$ruleorder} > 0) {
1.1102    raeburn  11231:             $output = '<br />'.
                   11232:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   11233:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   11234:                       ' <ul>';
1.612     raeburn  11235:             foreach my $rule (@{$ruleorder}) {
                   11236:                 if (ref($curr_rules) eq 'ARRAY') {
                   11237:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   11238:                         if (ref($rules->{$rule}) eq 'HASH') {
                   11239:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   11240:                                         $rules->{$rule}{'desc'}.'</li>';
                   11241:                         }
                   11242:                     }
                   11243:                 }
                   11244:             }
                   11245:             $output .= '</ul>';
                   11246:         }
                   11247:     }
                   11248:     return $output;
                   11249: }
                   11250: 
                   11251: sub instrule_disallow_msg {
1.615     raeburn  11252:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  11253:     my $response;
                   11254:     my %text = (
                   11255:                   item   => 'username',
                   11256:                   items  => 'usernames',
                   11257:                   match  => 'matches',
                   11258:                   do     => 'does',
                   11259:                   action => 'a username',
                   11260:                   one    => 'one',
                   11261:                );
                   11262:     if ($count > 1) {
                   11263:         $text{'item'} = 'usernames';
                   11264:         $text{'match'} ='match';
                   11265:         $text{'do'} = 'do';
                   11266:         $text{'action'} = 'usernames',
                   11267:         $text{'one'} = 'ones';
                   11268:     }
                   11269:     if ($checkitem eq 'id') {
                   11270:         $text{'items'} = 'IDs';
                   11271:         $text{'item'} = 'ID';
                   11272:         $text{'action'} = 'an ID';
1.615     raeburn  11273:         if ($count > 1) {
                   11274:             $text{'item'} = 'IDs';
                   11275:             $text{'action'} = 'IDs';
                   11276:         }
1.612     raeburn  11277:     }
1.674     bisitz   11278:     $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  11279:     if ($mode eq 'upload') {
                   11280:         if ($checkitem eq 'username') {
                   11281:             $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'}.");
                   11282:         } elsif ($checkitem eq 'id') {
1.674     bisitz   11283:             $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  11284:         }
1.669     raeburn  11285:     } elsif ($mode eq 'selfcreate') {
                   11286:         if ($checkitem eq 'id') {
                   11287:             $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.");
                   11288:         }
1.615     raeburn  11289:     } else {
                   11290:         if ($checkitem eq 'username') {
                   11291:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   11292:         } elsif ($checkitem eq 'id') {
                   11293:             $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.");
                   11294:         }
1.612     raeburn  11295:     }
                   11296:     return $response;
1.585     raeburn  11297: }
                   11298: 
1.624     raeburn  11299: sub personal_data_fieldtitles {
                   11300:     my %fieldtitles = &Apache::lonlocal::texthash (
                   11301:                         id => 'Student/Employee ID',
                   11302:                         permanentemail => 'E-mail address',
                   11303:                         lastname => 'Last Name',
                   11304:                         firstname => 'First Name',
                   11305:                         middlename => 'Middle Name',
                   11306:                         generation => 'Generation',
                   11307:                         gen => 'Generation',
1.765     raeburn  11308:                         inststatus => 'Affiliation',
1.624     raeburn  11309:                    );
                   11310:     return %fieldtitles;
                   11311: }
                   11312: 
1.642     raeburn  11313: sub sorted_inst_types {
                   11314:     my ($dom) = @_;
1.1185    raeburn  11315:     my ($usertypes,$order);
                   11316:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   11317:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   11318:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   11319:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   11320:     } else {
                   11321:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   11322:     }
1.642     raeburn  11323:     my $othertitle = &mt('All users');
                   11324:     if ($env{'request.course.id'}) {
1.668     raeburn  11325:         $othertitle  = &mt('Any users');
1.642     raeburn  11326:     }
                   11327:     my @types;
                   11328:     if (ref($order) eq 'ARRAY') {
                   11329:         @types = @{$order};
                   11330:     }
                   11331:     if (@types == 0) {
                   11332:         if (ref($usertypes) eq 'HASH') {
                   11333:             @types = sort(keys(%{$usertypes}));
                   11334:         }
                   11335:     }
                   11336:     if (keys(%{$usertypes}) > 0) {
                   11337:         $othertitle = &mt('Other users');
                   11338:     }
                   11339:     return ($othertitle,$usertypes,\@types);
                   11340: }
                   11341: 
1.645     raeburn  11342: sub get_institutional_codes {
1.1361    raeburn  11343:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  11344: # Get complete list of course sections to update
                   11345:     my @currsections = ();
                   11346:     my @currxlists = ();
1.1361    raeburn  11347:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  11348:     my $coursecode = $$settings{'internal.coursecode'};
1.1361    raeburn  11349:     my $crskey = $crs.':'.$coursecode;
                   11350:     @{$unclutteredsec{$crskey}} = ();
                   11351:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  11352: 
                   11353:     if ($$settings{'internal.sectionnums'} ne '') {
                   11354:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   11355:     }
                   11356: 
                   11357:     if ($$settings{'internal.crosslistings'} ne '') {
                   11358:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   11359:     }
                   11360: 
                   11361:     if (@currxlists > 0) {
1.1361    raeburn  11362:         foreach my $xl (@currxlists) {
                   11363:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  11364:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  11365:                     push(@{$allcourses},$1);
1.645     raeburn  11366:                     $$LC_code{$1} = $2;
                   11367:                 }
                   11368:             }
                   11369:         }
                   11370:     }
1.1361    raeburn  11371: 
1.645     raeburn  11372:     if (@currsections > 0) {
1.1361    raeburn  11373:         foreach my $sec (@currsections) {
                   11374:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   11375:                 my $instsec = $1;
1.645     raeburn  11376:                 my $lc_sec = $2;
1.1361    raeburn  11377:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   11378:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   11379:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   11380:                 }
                   11381:             }
                   11382:         }
                   11383:     }
                   11384: 
                   11385:     if (@{$unclutteredsec{$crskey}} > 0) {
                   11386:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   11387:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   11388:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   11389:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   11390:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1263    raeburn  11391:                     push(@{$allcourses},$sec);
1.1361    raeburn  11392:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  11393:                 }
                   11394:             }
                   11395:         }
                   11396:     }
                   11397:     return;
                   11398: }
                   11399: 
1.971     raeburn  11400: sub get_standard_codeitems {
                   11401:     return ('Year','Semester','Department','Number','Section');
                   11402: }
                   11403: 
1.112     bowersj2 11404: =pod
                   11405: 
1.780     raeburn  11406: =head1 Slot Helpers
                   11407: 
                   11408: =over 4
                   11409: 
                   11410: =item * sorted_slots()
                   11411: 
1.1040    raeburn  11412: Sorts an array of slot names in order of an optional sort key,
                   11413: default sort is by slot start time (earliest first). 
1.780     raeburn  11414: 
                   11415: Inputs:
                   11416: 
                   11417: =over 4
                   11418: 
                   11419: slotsarr  - Reference to array of unsorted slot names.
                   11420: 
                   11421: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   11422: 
1.1040    raeburn  11423: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   11424: 
1.549     albertel 11425: =back
                   11426: 
1.780     raeburn  11427: Returns:
                   11428: 
                   11429: =over 4
                   11430: 
1.1040    raeburn  11431: sorted   - An array of slot names sorted by a specified sort key 
                   11432:            (default sort key is start time of the slot).
1.780     raeburn  11433: 
                   11434: =back
                   11435: 
                   11436: =cut
                   11437: 
                   11438: 
                   11439: sub sorted_slots {
1.1040    raeburn  11440:     my ($slotsarr,$slots,$sortkey) = @_;
                   11441:     if ($sortkey eq '') {
                   11442:         $sortkey = 'starttime';
                   11443:     }
1.780     raeburn  11444:     my @sorted;
                   11445:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   11446:         @sorted =
                   11447:             sort {
                   11448:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  11449:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  11450:                      }
                   11451:                      if (ref($slots->{$a})) { return -1;}
                   11452:                      if (ref($slots->{$b})) { return 1;}
                   11453:                      return 0;
                   11454:                  } @{$slotsarr};
                   11455:     }
                   11456:     return @sorted;
                   11457: }
                   11458: 
1.1040    raeburn  11459: =pod
                   11460: 
                   11461: =item * get_future_slots()
                   11462: 
                   11463: Inputs:
                   11464: 
                   11465: =over 4
                   11466: 
                   11467: cnum - course number
                   11468: 
                   11469: cdom - course domain
                   11470: 
                   11471: now - current UNIX time
                   11472: 
                   11473: symb - optional symb
                   11474: 
                   11475: =back
                   11476: 
                   11477: Returns:
                   11478: 
                   11479: =over 4
                   11480: 
                   11481: sorted_reservable - ref to array of student_schedulable slots currently 
                   11482:                     reservable, ordered by end date of reservation period.
                   11483: 
                   11484: reservable_now - ref to hash of student_schedulable slots currently
                   11485:                  reservable.
                   11486: 
                   11487:     Keys in inner hash are:
                   11488:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11489:     (b) endreserve: end date of reservation period.
                   11490:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11491:         selected.
1.1040    raeburn  11492: 
                   11493: sorted_future - ref to array of student_schedulable slots reservable in
                   11494:                 the future, ordered by start date of reservation period.
                   11495: 
                   11496: future_reservable - ref to hash of student_schedulable slots reservable
                   11497:                     in the future.
                   11498: 
                   11499:     Keys in inner hash are:
                   11500:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11501:     (b) startreserve: start date of reservation period.
                   11502:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11503:         selected.
1.1040    raeburn  11504: 
                   11505: =back
                   11506: 
                   11507: =cut
                   11508: 
                   11509: sub get_future_slots {
                   11510:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  11511:     my $map;
                   11512:     if ($symb) {
                   11513:         ($map) = &Apache::lonnet::decode_symb($symb);
                   11514:     }
1.1040    raeburn  11515:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   11516:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   11517:     foreach my $slot (keys(%slots)) {
                   11518:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   11519:         if ($symb) {
1.1229    raeburn  11520:             if ($slots{$slot}->{'symb'} ne '') {
                   11521:                 my $canuse;
                   11522:                 my %oksymbs;
                   11523:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   11524:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   11525:                 if ($oksymbs{$symb}) {
                   11526:                     $canuse = 1;
                   11527:                 } else {
                   11528:                     foreach my $item (@slotsymbs) {
                   11529:                         if ($item =~ /\.(page|sequence)$/) {
                   11530:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   11531:                             if (($map ne '') && ($map eq $sloturl)) {
                   11532:                                 $canuse = 1;
                   11533:                                 last;
                   11534:                             }
                   11535:                         }
                   11536:                     }
                   11537:                 }
                   11538:                 next unless ($canuse);
                   11539:             }
1.1040    raeburn  11540:         }
                   11541:         if (($slots{$slot}->{'starttime'} > $now) &&
                   11542:             ($slots{$slot}->{'endtime'} > $now)) {
                   11543:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   11544:                 my $userallowed = 0;
                   11545:                 if ($slots{$slot}->{'allowedsections'}) {
                   11546:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   11547:                     if (!defined($env{'request.role.sec'})
                   11548:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   11549:                         $userallowed=1;
                   11550:                     } else {
                   11551:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   11552:                             $userallowed=1;
                   11553:                         }
                   11554:                     }
                   11555:                     unless ($userallowed) {
                   11556:                         if (defined($env{'request.course.groups'})) {
                   11557:                             my @groups = split(/:/,$env{'request.course.groups'});
                   11558:                             foreach my $group (@groups) {
                   11559:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   11560:                                     $userallowed=1;
                   11561:                                     last;
                   11562:                                 }
                   11563:                             }
                   11564:                         }
                   11565:                     }
                   11566:                 }
                   11567:                 if ($slots{$slot}->{'allowedusers'}) {
                   11568:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   11569:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   11570:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   11571:                         $userallowed = 1;
                   11572:                     }
                   11573:                 }
                   11574:                 next unless($userallowed);
                   11575:             }
                   11576:             my $startreserve = $slots{$slot}->{'startreserve'};
                   11577:             my $endreserve = $slots{$slot}->{'endreserve'};
                   11578:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  11579:             my $uniqueperiod;
                   11580:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   11581:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   11582:             }
1.1040    raeburn  11583:             if (($startreserve < $now) &&
                   11584:                 (!$endreserve || $endreserve > $now)) {
                   11585:                 my $lastres = $endreserve;
                   11586:                 if (!$lastres) {
                   11587:                     $lastres = $slots{$slot}->{'starttime'};
                   11588:                 }
                   11589:                 $reservable_now{$slot} = {
                   11590:                                            symb       => $symb,
1.1250    raeburn  11591:                                            endreserve => $lastres,
                   11592:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  11593:                                          };
                   11594:             } elsif (($startreserve > $now) &&
                   11595:                      (!$endreserve || $endreserve > $startreserve)) {
                   11596:                 $future_reservable{$slot} = {
                   11597:                                               symb         => $symb,
1.1250    raeburn  11598:                                               startreserve => $startreserve,
                   11599:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  11600:                                             };
                   11601:             }
                   11602:         }
                   11603:     }
                   11604:     my @unsorted_reservable = keys(%reservable_now);
                   11605:     if (@unsorted_reservable > 0) {
                   11606:         @sorted_reservable = 
                   11607:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   11608:     }
                   11609:     my @unsorted_future = keys(%future_reservable);
                   11610:     if (@unsorted_future > 0) {
                   11611:         @sorted_future =
                   11612:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   11613:     }
                   11614:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   11615: }
1.780     raeburn  11616: 
                   11617: =pod
                   11618: 
1.1057    foxr     11619: =back
                   11620: 
1.549     albertel 11621: =head1 HTTP Helpers
                   11622: 
                   11623: =over 4
                   11624: 
1.648     raeburn  11625: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 11626: 
1.258     albertel 11627: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 11628: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 11629: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 11630: 
                   11631: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   11632: $possible_names is an ref to an array of form element names.  As an example:
                   11633: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 11634: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 11635: 
                   11636: =cut
1.1       albertel 11637: 
1.6       albertel 11638: sub get_unprocessed_cgi {
1.25      albertel 11639:   my ($query,$possible_names)= @_;
1.26      matthew  11640:   # $Apache::lonxml::debug=1;
1.356     albertel 11641:   foreach my $pair (split(/&/,$query)) {
                   11642:     my ($name, $value) = split(/=/,$pair);
1.369     www      11643:     $name = &unescape($name);
1.25      albertel 11644:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   11645:       $value =~ tr/+/ /;
                   11646:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 11647:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 11648:     }
1.16      harris41 11649:   }
1.6       albertel 11650: }
                   11651: 
1.112     bowersj2 11652: =pod
                   11653: 
1.648     raeburn  11654: =item * &cacheheader() 
1.112     bowersj2 11655: 
                   11656: returns cache-controlling header code
                   11657: 
                   11658: =cut
                   11659: 
1.7       albertel 11660: sub cacheheader {
1.258     albertel 11661:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 11662:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   11663:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 11664:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   11665:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 11666:     return $output;
1.7       albertel 11667: }
                   11668: 
1.112     bowersj2 11669: =pod
                   11670: 
1.648     raeburn  11671: =item * &no_cache($r) 
1.112     bowersj2 11672: 
                   11673: specifies header code to not have cache
                   11674: 
                   11675: =cut
                   11676: 
1.9       albertel 11677: sub no_cache {
1.216     albertel 11678:     my ($r) = @_;
                   11679:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 11680: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 11681:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   11682:     $r->no_cache(1);
                   11683:     $r->header_out("Expires" => $date);
                   11684:     $r->header_out("Pragma" => "no-cache");
1.123     www      11685: }
                   11686: 
                   11687: sub content_type {
1.181     albertel 11688:     my ($r,$type,$charset) = @_;
1.299     foxr     11689:     if ($r) {
                   11690: 	#  Note that printout.pl calls this with undef for $r.
                   11691: 	&no_cache($r);
                   11692:     }
1.258     albertel 11693:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 11694:     unless ($charset) {
                   11695: 	$charset=&Apache::lonlocal::current_encoding;
                   11696:     }
                   11697:     if ($charset) { $type.='; charset='.$charset; }
                   11698:     if ($r) {
                   11699: 	$r->content_type($type);
                   11700:     } else {
                   11701: 	print("Content-type: $type\n\n");
                   11702:     }
1.9       albertel 11703: }
1.25      albertel 11704: 
1.112     bowersj2 11705: =pod
                   11706: 
1.648     raeburn  11707: =item * &add_to_env($name,$value) 
1.112     bowersj2 11708: 
1.258     albertel 11709: adds $name to the %env hash with value
1.112     bowersj2 11710: $value, if $name already exists, the entry is converted to an array
                   11711: reference and $value is added to the array.
                   11712: 
                   11713: =cut
                   11714: 
1.25      albertel 11715: sub add_to_env {
                   11716:   my ($name,$value)=@_;
1.258     albertel 11717:   if (defined($env{$name})) {
                   11718:     if (ref($env{$name})) {
1.25      albertel 11719:       #already have multiple values
1.258     albertel 11720:       push(@{ $env{$name} },$value);
1.25      albertel 11721:     } else {
                   11722:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 11723:       my $first=$env{$name};
                   11724:       undef($env{$name});
                   11725:       push(@{ $env{$name} },$first,$value);
1.25      albertel 11726:     }
                   11727:   } else {
1.258     albertel 11728:     $env{$name}=$value;
1.25      albertel 11729:   }
1.31      albertel 11730: }
1.149     albertel 11731: 
                   11732: =pod
                   11733: 
1.648     raeburn  11734: =item * &get_env_multiple($name) 
1.149     albertel 11735: 
1.258     albertel 11736: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 11737: values may be defined and end up as an array ref.
                   11738: 
                   11739: returns an array of values
                   11740: 
                   11741: =cut
                   11742: 
                   11743: sub get_env_multiple {
                   11744:     my ($name) = @_;
                   11745:     my @values;
1.258     albertel 11746:     if (defined($env{$name})) {
1.149     albertel 11747:         # exists is it an array
1.258     albertel 11748:         if (ref($env{$name})) {
                   11749:             @values=@{ $env{$name} };
1.149     albertel 11750:         } else {
1.258     albertel 11751:             $values[0]=$env{$name};
1.149     albertel 11752:         }
                   11753:     }
                   11754:     return(@values);
                   11755: }
                   11756: 
1.1249    damieng  11757: # Looks at given dependencies, and returns something depending on the context.
                   11758: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   11759: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   11760: # For all other contexts, returns ($output, $counter, $numpathchg).
                   11761: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   11762: # $counter: integer with the number of existing dependencies when no HTML output is returned, and the number of missing dependencies when an HTML output is returned.
                   11763: # $numpathchg: integer with the number of cleaned up dependency paths.
                   11764: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   11765: # \%mapping: hash reference clean path -> original path for all dependencies.
                   11766: # @param {string} actionurl - The path to the handler, indicative of the context.
                   11767: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   11768: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   11769: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   11770: # @param {hash reference} args - More parameters ! Possible keys: error_on_invalid_names (boolean), ignore_remote_references (boolean), current_path (string), docs_url (string), docs_title (string), context (string)
                   11771: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  11772: sub ask_for_embedded_content {
1.1249    damieng  11773:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  11774:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  11775:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  11776:         %currsubfile,%unused,$rem);
1.1071    raeburn  11777:     my $counter = 0;
                   11778:     my $numnew = 0;
1.987     raeburn  11779:     my $numremref = 0;
                   11780:     my $numinvalid = 0;
                   11781:     my $numpathchg = 0;
                   11782:     my $numexisting = 0;
1.1071    raeburn  11783:     my $numunused = 0;
                   11784:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  11785:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  11786:     my $heading = &mt('Upload embedded files');
                   11787:     my $buttontext = &mt('Upload');
                   11788: 
1.1249    damieng  11789:     # fills these variables based on the context:
                   11790:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   11791:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  11792:     if ($env{'request.course.id'}) {
1.1123    raeburn  11793:         if ($actionurl eq '/adm/dependencies') {
                   11794:             $navmap = Apache::lonnavmaps::navmap->new();
                   11795:         }
                   11796:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11797:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  11798:     }
1.1123    raeburn  11799:     if (($actionurl eq '/adm/portfolio') || 
                   11800:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  11801:         my $current_path='/';
                   11802:         if ($env{'form.currentpath'}) {
                   11803:             $current_path = $env{'form.currentpath'};
                   11804:         }
                   11805:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  11806:             $udom = $cdom;
                   11807:             $uname = $cnum;
1.984     raeburn  11808:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   11809:         } else {
                   11810:             $udom = $env{'user.domain'};
                   11811:             $uname = $env{'user.name'};
                   11812:             $url = '/userfiles/portfolio';
                   11813:         }
1.987     raeburn  11814:         $toplevel = $url.'/';
1.984     raeburn  11815:         $url .= $current_path;
                   11816:         $getpropath = 1;
1.987     raeburn  11817:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   11818:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      11819:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  11820:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  11821:         $toplevel = $url;
1.984     raeburn  11822:         if ($rest ne '') {
1.987     raeburn  11823:             $url .= $rest;
                   11824:         }
                   11825:     } elsif ($actionurl eq '/adm/coursedocs') {
                   11826:         if (ref($args) eq 'HASH') {
1.1071    raeburn  11827:             $url = $args->{'docs_url'};
                   11828:             $toplevel = $url;
1.1084    raeburn  11829:             if ($args->{'context'} eq 'paste') {
                   11830:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   11831:                 ($path) = 
                   11832:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11833:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11834:                 $fileloc =~ s{^/}{};
                   11835:             }
1.1071    raeburn  11836:         }
1.1084    raeburn  11837:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  11838:         if ($env{'request.course.id'} ne '') {
                   11839:             if (ref($args) eq 'HASH') {
                   11840:                 $url = $args->{'docs_url'};
                   11841:                 $title = $args->{'docs_title'};
1.1126    raeburn  11842:                 $toplevel = $url; 
                   11843:                 unless ($toplevel =~ m{^/}) {
                   11844:                     $toplevel = "/$url";
                   11845:                 }
1.1085    raeburn  11846:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  11847:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   11848:                     $path = $1;
                   11849:                 } else {
                   11850:                     ($path) =
                   11851:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11852:                 }
1.1195    raeburn  11853:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   11854:                     $fileloc = $toplevel;
                   11855:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   11856:                     my ($udom,$uname,$fname) =
                   11857:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   11858:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   11859:                 } else {
                   11860:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11861:                 }
1.1071    raeburn  11862:                 $fileloc =~ s{^/}{};
                   11863:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   11864:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   11865:             }
1.987     raeburn  11866:         }
1.1123    raeburn  11867:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11868:         $udom = $cdom;
                   11869:         $uname = $cnum;
                   11870:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   11871:         $toplevel = $url;
                   11872:         $path = $url;
                   11873:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   11874:         $fileloc =~ s{^/}{};
1.987     raeburn  11875:     }
1.1249    damieng  11876:     
                   11877:     # parses the dependency paths to get some info
                   11878:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   11879:     # $newfiles: hash URL -> 1 for new files or external URLs
                   11880:     # (will be completed later)
                   11881:     # $mapping:
                   11882:     #   for external URLs: external URL -> external URL
                   11883:     #   for relative paths: clean path -> original path
                   11884:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   11885:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  11886:     foreach my $file (keys(%{$allfiles})) {
                   11887:         my $embed_file;
                   11888:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   11889:             $embed_file = $1;
                   11890:         } else {
                   11891:             $embed_file = $file;
                   11892:         }
1.1158    raeburn  11893:         my ($absolutepath,$cleaned_file);
                   11894:         if ($embed_file =~ m{^\w+://}) {
                   11895:             $cleaned_file = $embed_file;
1.1147    raeburn  11896:             $newfiles{$cleaned_file} = 1;
                   11897:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11898:         } else {
1.1158    raeburn  11899:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  11900:             if ($embed_file =~ m{^/}) {
                   11901:                 $absolutepath = $embed_file;
                   11902:             }
1.1147    raeburn  11903:             if ($cleaned_file =~ m{/}) {
                   11904:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  11905:                 $path = &check_for_traversal($path,$url,$toplevel);
                   11906:                 my $item = $fname;
                   11907:                 if ($path ne '') {
                   11908:                     $item = $path.'/'.$fname;
                   11909:                     $subdependencies{$path}{$fname} = 1;
                   11910:                 } else {
                   11911:                     $dependencies{$item} = 1;
                   11912:                 }
                   11913:                 if ($absolutepath) {
                   11914:                     $mapping{$item} = $absolutepath;
                   11915:                 } else {
                   11916:                     $mapping{$item} = $embed_file;
                   11917:                 }
                   11918:             } else {
                   11919:                 $dependencies{$embed_file} = 1;
                   11920:                 if ($absolutepath) {
1.1147    raeburn  11921:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  11922:                 } else {
1.1147    raeburn  11923:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11924:                 }
                   11925:             }
1.984     raeburn  11926:         }
                   11927:     }
1.1249    damieng  11928:     
                   11929:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   11930:     # and lists
                   11931:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   11932:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   11933:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   11934:     #                                    the path had to be cleaned up
                   11935:     # $existing: hash clean path -> 1 if the file exists
                   11936:     # $numexisting: number of keys in $existing
                   11937:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   11938:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   11939:     #                                      dependency subdirectories that are
                   11940:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  11941:     my $dirptr = 16384;
1.984     raeburn  11942:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  11943:         $currsubfile{$path} = {};
1.1123    raeburn  11944:         if (($actionurl eq '/adm/portfolio') || 
                   11945:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11946:             my ($sublistref,$listerror) =
                   11947:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   11948:             if (ref($sublistref) eq 'ARRAY') {
                   11949:                 foreach my $line (@{$sublistref}) {
                   11950:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  11951:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  11952:                 }
1.984     raeburn  11953:             }
1.987     raeburn  11954:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11955:             if (opendir(my $dir,$url.'/'.$path)) {
                   11956:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  11957:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   11958:             }
1.1084    raeburn  11959:         } elsif (($actionurl eq '/adm/dependencies') ||
                   11960:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11961:                   ($args->{'context'} eq 'paste')) ||
                   11962:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11963:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  11964:                 my $dir;
                   11965:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11966:                     $dir = $fileloc;
                   11967:                 } else {
                   11968:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11969:                 }
1.1071    raeburn  11970:                 if ($dir ne '') {
                   11971:                     my ($sublistref,$listerror) =
                   11972:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   11973:                     if (ref($sublistref) eq 'ARRAY') {
                   11974:                         foreach my $line (@{$sublistref}) {
                   11975:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   11976:                                 undef,$mtime)=split(/\&/,$line,12);
                   11977:                             unless (($testdir&$dirptr) ||
                   11978:                                     ($file_name =~ /^\.\.?$/)) {
                   11979:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   11980:                             }
                   11981:                         }
                   11982:                     }
                   11983:                 }
1.984     raeburn  11984:             }
                   11985:         }
                   11986:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  11987:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  11988:                 my $item = $path.'/'.$file;
                   11989:                 unless ($mapping{$item} eq $item) {
                   11990:                     $pathchanges{$item} = 1;
                   11991:                 }
                   11992:                 $existing{$item} = 1;
                   11993:                 $numexisting ++;
                   11994:             } else {
                   11995:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  11996:             }
                   11997:         }
1.1071    raeburn  11998:         if ($actionurl eq '/adm/dependencies') {
                   11999:             foreach my $path (keys(%currsubfile)) {
                   12000:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   12001:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   12002:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  12003:                              next if (($rem ne '') &&
                   12004:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   12005:                                        (ref($navmap) &&
                   12006:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   12007:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12008:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  12009:                              $unused{$path.'/'.$file} = 1; 
                   12010:                          }
                   12011:                     }
                   12012:                 }
                   12013:             }
                   12014:         }
1.984     raeburn  12015:     }
1.1249    damieng  12016:     
                   12017:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   12018:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  12019:     my %currfile;
1.1123    raeburn  12020:     if (($actionurl eq '/adm/portfolio') ||
                   12021:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12022:         my ($dirlistref,$listerror) =
                   12023:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   12024:         if (ref($dirlistref) eq 'ARRAY') {
                   12025:             foreach my $line (@{$dirlistref}) {
                   12026:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   12027:                 $currfile{$file_name} = 1;
                   12028:             }
1.984     raeburn  12029:         }
1.987     raeburn  12030:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12031:         if (opendir(my $dir,$url)) {
1.987     raeburn  12032:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  12033:             map {$currfile{$_} = 1;} @dir_list;
                   12034:         }
1.1084    raeburn  12035:     } elsif (($actionurl eq '/adm/dependencies') ||
                   12036:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  12037:               ($args->{'context'} eq 'paste')) ||
                   12038:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12039:         if ($env{'request.course.id'} ne '') {
                   12040:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12041:             if ($dir ne '') {
                   12042:                 my ($dirlistref,$listerror) =
                   12043:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   12044:                 if (ref($dirlistref) eq 'ARRAY') {
                   12045:                     foreach my $line (@{$dirlistref}) {
                   12046:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   12047:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   12048:                         unless (($testdir&$dirptr) ||
                   12049:                                 ($file_name =~ /^\.\.?$/)) {
                   12050:                             $currfile{$file_name} = [$size,$mtime];
                   12051:                         }
                   12052:                     }
                   12053:                 }
                   12054:             }
                   12055:         }
1.984     raeburn  12056:     }
1.1249    damieng  12057:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   12058:     # are not in subdirectories, using $currfile
1.984     raeburn  12059:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  12060:         if (exists($currfile{$file})) {
1.987     raeburn  12061:             unless ($mapping{$file} eq $file) {
                   12062:                 $pathchanges{$file} = 1;
                   12063:             }
                   12064:             $existing{$file} = 1;
                   12065:             $numexisting ++;
                   12066:         } else {
1.984     raeburn  12067:             $newfiles{$file} = 1;
                   12068:         }
                   12069:     }
1.1071    raeburn  12070:     foreach my $file (keys(%currfile)) {
                   12071:         unless (($file eq $filename) ||
                   12072:                 ($file eq $filename.'.bak') ||
                   12073:                 ($dependencies{$file})) {
1.1085    raeburn  12074:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  12075:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   12076:                     next if (($rem ne '') &&
                   12077:                              (($env{"httpref.$rem".$file} ne '') ||
                   12078:                               (ref($navmap) &&
                   12079:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   12080:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12081:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   12082:                 }
1.1085    raeburn  12083:             }
1.1071    raeburn  12084:             $unused{$file} = 1;
                   12085:         }
                   12086:     }
1.1249    damieng  12087:     
                   12088:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  12089:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   12090:         ($args->{'context'} eq 'paste')) {
                   12091:         $counter = scalar(keys(%existing));
                   12092:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  12093:         return ($output,$counter,$numpathchg,\%existing);
                   12094:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   12095:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   12096:         $counter = scalar(keys(%existing));
                   12097:         $numpathchg = scalar(keys(%pathchanges));
                   12098:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  12099:     }
1.1249    damieng  12100:     
                   12101:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   12102:     
                   12103:     # $upload_output: missing dependencies (with upload form)
                   12104:     # $modify_output: uploaded dependencies (in use)
                   12105:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  12106:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  12107:         if ($actionurl eq '/adm/dependencies') {
                   12108:             next if ($embed_file =~ m{^\w+://});
                   12109:         }
1.660     raeburn  12110:         $upload_output .= &start_data_table_row().
1.1123    raeburn  12111:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  12112:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  12113:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  12114:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   12115:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  12116:         }
1.1123    raeburn  12117:         $upload_output .= '</td>';
1.1071    raeburn  12118:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  12119:             $upload_output.='<td align="right">'.
                   12120:                             '<span class="LC_info LC_fontsize_medium">'.
                   12121:                             &mt("URL points to web address").'</span>';
1.987     raeburn  12122:             $numremref++;
1.660     raeburn  12123:         } elsif ($args->{'error_on_invalid_names'}
                   12124:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  12125:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   12126:                             &mt('Invalid characters').'</span>';
1.987     raeburn  12127:             $numinvalid++;
1.660     raeburn  12128:         } else {
1.1123    raeburn  12129:             $upload_output .= '<td>'.
                   12130:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  12131:                                                      $embed_file,\%mapping,
1.1071    raeburn  12132:                                                      $allfiles,$codebase,'upload');
                   12133:             $counter ++;
                   12134:             $numnew ++;
1.987     raeburn  12135:         }
                   12136:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   12137:     }
                   12138:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  12139:         if ($actionurl eq '/adm/dependencies') {
                   12140:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   12141:             $modify_output .= &start_data_table_row().
                   12142:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   12143:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   12144:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   12145:                               '<td>'.$size.'</td>'.
                   12146:                               '<td>'.$mtime.'</td>'.
                   12147:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   12148:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   12149:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   12150:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   12151:                               &embedded_file_element('upload_embedded',$counter,
                   12152:                                                      $embed_file,\%mapping,
                   12153:                                                      $allfiles,$codebase,'modify').
                   12154:                               '</div></td>'.
                   12155:                               &end_data_table_row()."\n";
                   12156:             $counter ++;
                   12157:         } else {
                   12158:             $upload_output .= &start_data_table_row().
1.1123    raeburn  12159:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   12160:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   12161:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  12162:                               &Apache::loncommon::end_data_table_row()."\n";
                   12163:         }
                   12164:     }
                   12165:     my $delidx = $counter;
                   12166:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   12167:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   12168:         $delete_output .= &start_data_table_row().
                   12169:                           '<td><img src="'.&icon($oldfile).'" />'.
                   12170:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   12171:                           '<td>'.$size.'</td>'.
                   12172:                           '<td>'.$mtime.'</td>'.
                   12173:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   12174:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   12175:                           &embedded_file_element('upload_embedded',$delidx,
                   12176:                                                  $oldfile,\%mapping,$allfiles,
                   12177:                                                  $codebase,'delete').'</td>'.
                   12178:                           &end_data_table_row()."\n"; 
                   12179:         $numunused ++;
                   12180:         $delidx ++;
1.987     raeburn  12181:     }
                   12182:     if ($upload_output) {
                   12183:         $upload_output = &start_data_table().
                   12184:                          $upload_output.
                   12185:                          &end_data_table()."\n";
                   12186:     }
1.1071    raeburn  12187:     if ($modify_output) {
                   12188:         $modify_output = &start_data_table().
                   12189:                          &start_data_table_header_row().
                   12190:                          '<th>'.&mt('File').'</th>'.
                   12191:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12192:                          '<th>'.&mt('Modified').'</th>'.
                   12193:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   12194:                          &end_data_table_header_row().
                   12195:                          $modify_output.
                   12196:                          &end_data_table()."\n";
                   12197:     }
                   12198:     if ($delete_output) {
                   12199:         $delete_output = &start_data_table().
                   12200:                          &start_data_table_header_row().
                   12201:                          '<th>'.&mt('File').'</th>'.
                   12202:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12203:                          '<th>'.&mt('Modified').'</th>'.
                   12204:                          '<th>'.&mt('Delete?').'</th>'.
                   12205:                          &end_data_table_header_row().
                   12206:                          $delete_output.
                   12207:                          &end_data_table()."\n";
                   12208:     }
1.987     raeburn  12209:     my $applies = 0;
                   12210:     if ($numremref) {
                   12211:         $applies ++;
                   12212:     }
                   12213:     if ($numinvalid) {
                   12214:         $applies ++;
                   12215:     }
                   12216:     if ($numexisting) {
                   12217:         $applies ++;
                   12218:     }
1.1071    raeburn  12219:     if ($counter || $numunused) {
1.987     raeburn  12220:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   12221:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  12222:                   $state.'<h3>'.$heading.'</h3>'; 
                   12223:         if ($actionurl eq '/adm/dependencies') {
                   12224:             if ($numnew) {
                   12225:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   12226:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   12227:                            $upload_output.'<br />'."\n";
                   12228:             }
                   12229:             if ($numexisting) {
                   12230:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   12231:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   12232:                            $modify_output.'<br />'."\n";
                   12233:                            $buttontext = &mt('Save changes');
                   12234:             }
                   12235:             if ($numunused) {
                   12236:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   12237:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   12238:                            $delete_output.'<br />'."\n";
                   12239:                            $buttontext = &mt('Save changes');
                   12240:             }
                   12241:         } else {
                   12242:             $output .= $upload_output.'<br />'."\n";
                   12243:         }
                   12244:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   12245:                    $counter.'" />'."\n";
                   12246:         if ($actionurl eq '/adm/dependencies') { 
                   12247:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   12248:                        $numnew.'" />'."\n";
                   12249:         } elsif ($actionurl eq '') {
1.987     raeburn  12250:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   12251:         }
                   12252:     } elsif ($applies) {
                   12253:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   12254:         if ($applies > 1) {
                   12255:             $output .=  
1.1123    raeburn  12256:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  12257:             if ($numremref) {
                   12258:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   12259:             }
                   12260:             if ($numinvalid) {
                   12261:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   12262:             }
                   12263:             if ($numexisting) {
                   12264:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   12265:             }
                   12266:             $output .= '</ul><br />';
                   12267:         } elsif ($numremref) {
                   12268:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   12269:         } elsif ($numinvalid) {
                   12270:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   12271:         } elsif ($numexisting) {
                   12272:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   12273:         }
                   12274:         $output .= $upload_output.'<br />';
                   12275:     }
                   12276:     my ($pathchange_output,$chgcount);
1.1071    raeburn  12277:     $chgcount = $counter;
1.987     raeburn  12278:     if (keys(%pathchanges) > 0) {
                   12279:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  12280:             if ($counter) {
1.987     raeburn  12281:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   12282:                                                   $embed_file,\%mapping,
1.1071    raeburn  12283:                                                   $allfiles,$codebase,'change');
1.987     raeburn  12284:             } else {
                   12285:                 $pathchange_output .= 
                   12286:                     &start_data_table_row().
                   12287:                     '<td><input type ="checkbox" name="namechange" value="'.
                   12288:                     $chgcount.'" checked="checked" /></td>'.
                   12289:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   12290:                     '<td>'.$embed_file.
                   12291:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  12292:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  12293:                     '</td>'.&end_data_table_row();
1.660     raeburn  12294:             }
1.987     raeburn  12295:             $numpathchg ++;
                   12296:             $chgcount ++;
1.660     raeburn  12297:         }
                   12298:     }
1.1127    raeburn  12299:     if (($counter) || ($numunused)) {
1.987     raeburn  12300:         if ($numpathchg) {
                   12301:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   12302:                        $numpathchg.'" />'."\n";
                   12303:         }
                   12304:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   12305:             ($actionurl eq '/adm/imsimport')) {
                   12306:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   12307:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   12308:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  12309:         } elsif ($actionurl eq '/adm/dependencies') {
                   12310:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  12311:         }
1.1123    raeburn  12312:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  12313:     } elsif ($numpathchg) {
                   12314:         my %pathchange = ();
                   12315:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   12316:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12317:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  12318:         }
1.987     raeburn  12319:     }
1.1071    raeburn  12320:     return ($output,$counter,$numpathchg);
1.987     raeburn  12321: }
                   12322: 
1.1147    raeburn  12323: =pod
                   12324: 
                   12325: =item * clean_path($name)
                   12326: 
                   12327: Performs clean-up of directories, subdirectories and filename in an
                   12328: embedded object, referenced in an HTML file which is being uploaded
                   12329: to a course or portfolio, where 
                   12330: "Upload embedded images/multimedia files if HTML file" checkbox was
                   12331: checked.
                   12332: 
                   12333: Clean-up is similar to replacements in lonnet::clean_filename()
                   12334: except each / between sub-directory and next level is preserved.
                   12335: 
                   12336: =cut
                   12337: 
                   12338: sub clean_path {
                   12339:     my ($embed_file) = @_;
                   12340:     $embed_file =~s{^/+}{};
                   12341:     my @contents;
                   12342:     if ($embed_file =~ m{/}) {
                   12343:         @contents = split(/\//,$embed_file);
                   12344:     } else {
                   12345:         @contents = ($embed_file);
                   12346:     }
                   12347:     my $lastidx = scalar(@contents)-1;
                   12348:     for (my $i=0; $i<=$lastidx; $i++) { 
                   12349:         $contents[$i]=~s{\\}{/}g;
                   12350:         $contents[$i]=~s/\s+/\_/g;
                   12351:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   12352:         if ($i == $lastidx) {
                   12353:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   12354:         }
                   12355:     }
                   12356:     if ($lastidx > 0) {
                   12357:         return join('/',@contents);
                   12358:     } else {
                   12359:         return $contents[0];
                   12360:     }
                   12361: }
                   12362: 
1.987     raeburn  12363: sub embedded_file_element {
1.1071    raeburn  12364:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  12365:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   12366:                    (ref($codebase) eq 'HASH'));
                   12367:     my $output;
1.1071    raeburn  12368:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  12369:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   12370:     }
                   12371:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   12372:                &escape($embed_file).'" />';
                   12373:     unless (($context eq 'upload_embedded') && 
                   12374:             ($mapping->{$embed_file} eq $embed_file)) {
                   12375:         $output .='
                   12376:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   12377:     }
                   12378:     my $attrib;
                   12379:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   12380:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   12381:     }
                   12382:     $output .=
                   12383:         "\n\t\t".
                   12384:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   12385:         $attrib.'" />';
                   12386:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   12387:         $output .=
                   12388:             "\n\t\t".
                   12389:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   12390:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  12391:     }
1.987     raeburn  12392:     return $output;
1.660     raeburn  12393: }
                   12394: 
1.1071    raeburn  12395: sub get_dependency_details {
                   12396:     my ($currfile,$currsubfile,$embed_file) = @_;
                   12397:     my ($size,$mtime,$showsize,$showmtime);
                   12398:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   12399:         if ($embed_file =~ m{/}) {
                   12400:             my ($path,$fname) = split(/\//,$embed_file);
                   12401:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   12402:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   12403:             }
                   12404:         } else {
                   12405:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   12406:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   12407:             }
                   12408:         }
                   12409:         $showsize = $size/1024.0;
                   12410:         $showsize = sprintf("%.1f",$showsize);
                   12411:         if ($mtime > 0) {
                   12412:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   12413:         }
                   12414:     }
                   12415:     return ($showsize,$showmtime);
                   12416: }
                   12417: 
                   12418: sub ask_embedded_js {
                   12419:     return <<"END";
                   12420: <script type="text/javascript"">
                   12421: // <![CDATA[
                   12422: function toggleBrowse(counter) {
                   12423:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   12424:     var fileid = document.getElementById('embedded_item_'+counter);
                   12425:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   12426:     if (chkboxid.checked == true) {
                   12427:         uploaddivid.style.display='block';
                   12428:     } else {
                   12429:         uploaddivid.style.display='none';
                   12430:         fileid.value = '';
                   12431:     }
                   12432: }
                   12433: // ]]>
                   12434: </script>
                   12435: 
                   12436: END
                   12437: }
                   12438: 
1.661     raeburn  12439: sub upload_embedded {
                   12440:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  12441:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   12442:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  12443:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   12444:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   12445:         my $orig_uploaded_filename =
                   12446:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  12447:         foreach my $type ('orig','ref','attrib','codebase') {
                   12448:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   12449:                 $env{'form.embedded_'.$type.'_'.$i} =
                   12450:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   12451:             }
                   12452:         }
1.661     raeburn  12453:         my ($path,$fname) =
                   12454:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   12455:         # no path, whole string is fname
                   12456:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   12457:         $fname = &Apache::lonnet::clean_filename($fname);
                   12458:         # See if there is anything left
                   12459:         next if ($fname eq '');
                   12460: 
                   12461:         # Check if file already exists as a file or directory.
                   12462:         my ($state,$msg);
                   12463:         if ($context eq 'portfolio') {
                   12464:             my $port_path = $dirpath;
                   12465:             if ($group ne '') {
                   12466:                 $port_path = "groups/$group/$port_path";
                   12467:             }
1.987     raeburn  12468:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   12469:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  12470:                                               $dir_root,$port_path,$disk_quota,
                   12471:                                               $current_disk_usage,$uname,$udom);
                   12472:             if ($state eq 'will_exceed_quota'
1.984     raeburn  12473:                 || $state eq 'file_locked') {
1.661     raeburn  12474:                 $output .= $msg;
                   12475:                 next;
                   12476:             }
                   12477:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   12478:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   12479:             if ($state eq 'exists') {
                   12480:                 $output .= $msg;
                   12481:                 next;
                   12482:             }
                   12483:         }
                   12484:         # Check if extension is valid
                   12485:         if (($fname =~ /\.(\w+)$/) &&
                   12486:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   12487:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   12488:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  12489:             next;
                   12490:         } elsif (($fname =~ /\.(\w+)$/) &&
                   12491:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  12492:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  12493:             next;
                   12494:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   12495:             $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  12496:             next;
                   12497:         }
                   12498:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  12499:         my $subdir = $path;
                   12500:         $subdir =~ s{/+$}{};
1.661     raeburn  12501:         if ($context eq 'portfolio') {
1.984     raeburn  12502:             my $result;
                   12503:             if ($state eq 'existingfile') {
                   12504:                 $result=
                   12505:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  12506:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  12507:             } else {
1.984     raeburn  12508:                 $result=
                   12509:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  12510:                                                     $dirpath.
1.1123    raeburn  12511:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  12512:                 if ($result !~ m|^/uploaded/|) {
                   12513:                     $output .= '<span class="LC_error">'
                   12514:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12515:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12516:                                .'</span><br />';
                   12517:                     next;
                   12518:                 } else {
1.987     raeburn  12519:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12520:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  12521:                 }
1.661     raeburn  12522:             }
1.1123    raeburn  12523:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  12524:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   12525:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  12526:             my $result =
1.1126    raeburn  12527:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  12528:             if ($result !~ m|^/uploaded/|) {
                   12529:                 $output .= '<span class="LC_error">'
                   12530:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12531:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12532:                            .'</span><br />';
                   12533:                     next;
                   12534:             } else {
                   12535:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12536:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  12537:                 if ($context eq 'syllabus') {
                   12538:                     &Apache::lonnet::make_public_indefinitely($result);
                   12539:                 }
1.987     raeburn  12540:             }
1.661     raeburn  12541:         } else {
                   12542: # Save the file
                   12543:             my $target = $env{'form.embedded_item_'.$i};
                   12544:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   12545:             my $dest = $fullpath.$fname;
                   12546:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  12547:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  12548:             my $count;
                   12549:             my $filepath = $dir_root;
1.1027    raeburn  12550:             foreach my $subdir (@parts) {
                   12551:                 $filepath .= "/$subdir";
                   12552:                 if (!-e $filepath) {
1.661     raeburn  12553:                     mkdir($filepath,0770);
                   12554:                 }
                   12555:             }
                   12556:             my $fh;
                   12557:             if (!open($fh,'>'.$dest)) {
                   12558:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   12559:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  12560:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   12561:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12562:                            '</span><br />';
                   12563:             } else {
                   12564:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   12565:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   12566:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  12567:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   12568:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12569:                               '</span><br />';
                   12570:                 } else {
1.987     raeburn  12571:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12572:                                $url.'</span>').'<br />';
                   12573:                     unless ($context eq 'testbank') {
                   12574:                         $footer .= &mt('View embedded file: [_1]',
                   12575:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   12576:                     }
                   12577:                 }
                   12578:                 close($fh);
                   12579:             }
                   12580:         }
                   12581:         if ($env{'form.embedded_ref_'.$i}) {
                   12582:             $pathchange{$i} = 1;
                   12583:         }
                   12584:     }
                   12585:     if ($output) {
                   12586:         $output = '<p>'.$output.'</p>';
                   12587:     }
                   12588:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   12589:     $returnflag = 'ok';
1.1071    raeburn  12590:     my $numpathchgs = scalar(keys(%pathchange));
                   12591:     if ($numpathchgs > 0) {
1.987     raeburn  12592:         if ($context eq 'portfolio') {
                   12593:             $output .= '<p>'.&mt('or').'</p>';
                   12594:         } elsif ($context eq 'testbank') {
1.1071    raeburn  12595:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   12596:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  12597:             $returnflag = 'modify_orightml';
                   12598:         }
                   12599:     }
1.1071    raeburn  12600:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  12601: }
                   12602: 
                   12603: sub modify_html_form {
                   12604:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   12605:     my $end = 0;
                   12606:     my $modifyform;
                   12607:     if ($context eq 'upload_embedded') {
                   12608:         return unless (ref($pathchange) eq 'HASH');
                   12609:         if ($env{'form.number_embedded_items'}) {
                   12610:             $end += $env{'form.number_embedded_items'};
                   12611:         }
                   12612:         if ($env{'form.number_pathchange_items'}) {
                   12613:             $end += $env{'form.number_pathchange_items'};
                   12614:         }
                   12615:         if ($end) {
                   12616:             for (my $i=0; $i<$end; $i++) {
                   12617:                 if ($i < $env{'form.number_embedded_items'}) {
                   12618:                     next unless($pathchange->{$i});
                   12619:                 }
                   12620:                 $modifyform .=
                   12621:                     &start_data_table_row().
                   12622:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   12623:                     'checked="checked" /></td>'.
                   12624:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   12625:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   12626:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   12627:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   12628:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   12629:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   12630:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   12631:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   12632:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   12633:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   12634:                     &end_data_table_row();
1.1071    raeburn  12635:             }
1.987     raeburn  12636:         }
                   12637:     } else {
                   12638:         $modifyform = $pathchgtable;
                   12639:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   12640:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   12641:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12642:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   12643:         }
                   12644:     }
                   12645:     if ($modifyform) {
1.1071    raeburn  12646:         if ($actionurl eq '/adm/dependencies') {
                   12647:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   12648:         }
1.987     raeburn  12649:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   12650:                '<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".
                   12651:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   12652:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   12653:                '</ol></p>'."\n".'<p>'.
                   12654:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   12655:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   12656:                &start_data_table()."\n".
                   12657:                &start_data_table_header_row().
                   12658:                '<th>'.&mt('Change?').'</th>'.
                   12659:                '<th>'.&mt('Current reference').'</th>'.
                   12660:                '<th>'.&mt('Required reference').'</th>'.
                   12661:                &end_data_table_header_row()."\n".
                   12662:                $modifyform.
                   12663:                &end_data_table().'<br />'."\n".$hiddenstate.
                   12664:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   12665:                '</form>'."\n";
                   12666:     }
                   12667:     return;
                   12668: }
                   12669: 
                   12670: sub modify_html_refs {
1.1123    raeburn  12671:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  12672:     my $container;
                   12673:     if ($context eq 'portfolio') {
                   12674:         $container = $env{'form.container'};
                   12675:     } elsif ($context eq 'coursedoc') {
                   12676:         $container = $env{'form.primaryurl'};
1.1071    raeburn  12677:     } elsif ($context eq 'manage_dependencies') {
                   12678:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   12679:         $container = "/$container";
1.1123    raeburn  12680:     } elsif ($context eq 'syllabus') {
                   12681:         $container = $url;
1.987     raeburn  12682:     } else {
1.1027    raeburn  12683:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  12684:     }
                   12685:     my (%allfiles,%codebase,$output,$content);
                   12686:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  12687:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  12688:         if (wantarray) {
                   12689:             return ('',0,0); 
                   12690:         } else {
                   12691:             return;
                   12692:         }
                   12693:     }
                   12694:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12695:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  12696:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   12697:             if (wantarray) {
                   12698:                 return ('',0,0);
                   12699:             } else {
                   12700:                 return;
                   12701:             }
                   12702:         } 
1.987     raeburn  12703:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  12704:         if ($content eq '-1') {
                   12705:             if (wantarray) {
                   12706:                 return ('',0,0);
                   12707:             } else {
                   12708:                 return;
                   12709:             }
                   12710:         }
1.987     raeburn  12711:     } else {
1.1071    raeburn  12712:         unless ($container =~ /^\Q$dir_root\E/) {
                   12713:             if (wantarray) {
                   12714:                 return ('',0,0);
                   12715:             } else {
                   12716:                 return;
                   12717:             }
                   12718:         } 
1.1317    raeburn  12719:         if (open(my $fh,'<',$container)) {
1.987     raeburn  12720:             $content = join('', <$fh>);
                   12721:             close($fh);
                   12722:         } else {
1.1071    raeburn  12723:             if (wantarray) {
                   12724:                 return ('',0,0);
                   12725:             } else {
                   12726:                 return;
                   12727:             }
1.987     raeburn  12728:         }
                   12729:     }
                   12730:     my ($count,$codebasecount) = (0,0);
                   12731:     my $mm = new File::MMagic;
                   12732:     my $mime_type = $mm->checktype_contents($content);
                   12733:     if ($mime_type eq 'text/html') {
                   12734:         my $parse_result = 
                   12735:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   12736:                                                     \%codebase,\$content);
                   12737:         if ($parse_result eq 'ok') {
                   12738:             foreach my $i (@changes) {
                   12739:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   12740:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   12741:                 if ($allfiles{$ref}) {
                   12742:                     my $newname =  $orig;
                   12743:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  12744:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  12745:                     if ($attrib_regexp =~ /:/) {
                   12746:                         $attrib_regexp =~ s/\:/|/g;
                   12747:                     }
                   12748:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12749:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12750:                         $count += $numchg;
1.1123    raeburn  12751:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  12752:                         delete($allfiles{$ref});
1.987     raeburn  12753:                     }
                   12754:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  12755:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  12756:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   12757:                         $codebasecount ++;
                   12758:                     }
                   12759:                 }
                   12760:             }
1.1123    raeburn  12761:             my $skiprewrites;
1.987     raeburn  12762:             if ($count || $codebasecount) {
                   12763:                 my $saveresult;
1.1071    raeburn  12764:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12765:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  12766:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12767:                     if ($url eq $container) {
                   12768:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   12769:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12770:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  12771:                                             $fname.'</span>').'</p>';
1.987     raeburn  12772:                     } else {
                   12773:                          $output = '<p class="LC_error">'.
                   12774:                                    &mt('Error: update failed for: [_1].',
                   12775:                                    '<span class="LC_filename">'.
                   12776:                                    $container.'</span>').'</p>';
                   12777:                     }
1.1123    raeburn  12778:                     if ($context eq 'syllabus') {
                   12779:                         unless ($saveresult eq 'ok') {
                   12780:                             $skiprewrites = 1;
                   12781:                         }
                   12782:                     }
1.987     raeburn  12783:                 } else {
1.1317    raeburn  12784:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  12785:                         print $fh $content;
                   12786:                         close($fh);
                   12787:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12788:                                   $count,'<span class="LC_filename">'.
                   12789:                                   $container.'</span>').'</p>';
1.661     raeburn  12790:                     } else {
1.987     raeburn  12791:                          $output = '<p class="LC_error">'.
                   12792:                                    &mt('Error: could not update [_1].',
                   12793:                                    '<span class="LC_filename">'.
                   12794:                                    $container.'</span>').'</p>';
1.661     raeburn  12795:                     }
                   12796:                 }
                   12797:             }
1.1123    raeburn  12798:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   12799:                 my ($actionurl,$state);
                   12800:                 $actionurl = "/public/$udom/$uname/syllabus";
                   12801:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   12802:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   12803:                                               \%codebase,
                   12804:                                               {'context' => 'rewrites',
                   12805:                                                'ignore_remote_references' => 1,});
                   12806:                 if (ref($mapping) eq 'HASH') {
                   12807:                     my $rewrites = 0;
                   12808:                     foreach my $key (keys(%{$mapping})) {
                   12809:                         next if ($key =~ m{^https?://});
                   12810:                         my $ref = $mapping->{$key};
                   12811:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   12812:                         my $attrib;
                   12813:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   12814:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   12815:                         }
                   12816:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12817:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12818:                             $rewrites += $numchg;
                   12819:                         }
                   12820:                     }
                   12821:                     if ($rewrites) {
                   12822:                         my $saveresult; 
                   12823:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12824:                         if ($url eq $container) {
                   12825:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   12826:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   12827:                                             $count,'<span class="LC_filename">'.
                   12828:                                             $fname.'</span>').'</p>';
                   12829:                         } else {
                   12830:                             $output .= '<p class="LC_error">'.
                   12831:                                        &mt('Error: could not update links in [_1].',
                   12832:                                        '<span class="LC_filename">'.
                   12833:                                        $container.'</span>').'</p>';
                   12834: 
                   12835:                         }
                   12836:                     }
                   12837:                 }
                   12838:             }
1.987     raeburn  12839:         } else {
                   12840:             &logthis('Failed to parse '.$container.
                   12841:                      ' to modify references: '.$parse_result);
1.661     raeburn  12842:         }
                   12843:     }
1.1071    raeburn  12844:     if (wantarray) {
                   12845:         return ($output,$count,$codebasecount);
                   12846:     } else {
                   12847:         return $output;
                   12848:     }
1.661     raeburn  12849: }
                   12850: 
                   12851: sub check_for_existing {
                   12852:     my ($path,$fname,$element) = @_;
                   12853:     my ($state,$msg);
                   12854:     if (-d $path.'/'.$fname) {
                   12855:         $state = 'exists';
                   12856:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12857:     } elsif (-e $path.'/'.$fname) {
                   12858:         $state = 'exists';
                   12859:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12860:     }
                   12861:     if ($state eq 'exists') {
                   12862:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   12863:     }
                   12864:     return ($state,$msg);
                   12865: }
                   12866: 
                   12867: sub check_for_upload {
                   12868:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   12869:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  12870:     my $filesize = length($env{'form.'.$element});
                   12871:     if (!$filesize) {
                   12872:         my $msg = '<span class="LC_error">'.
                   12873:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   12874:                       '<span class="LC_filename">'.$fname.'</span>',
                   12875:                       $filesize).'<br />'.
1.1007    raeburn  12876:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  12877:                   '</span>';
                   12878:         return ('zero_bytes',$msg);
                   12879:     }
                   12880:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  12881:     my $getpropath = 1;
1.1021    raeburn  12882:     my ($dirlistref,$listerror) =
                   12883:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  12884:     my $found_file = 0;
                   12885:     my $locked_file = 0;
1.991     raeburn  12886:     my @lockers;
                   12887:     my $navmap;
                   12888:     if ($env{'request.course.id'}) {
                   12889:         $navmap = Apache::lonnavmaps::navmap->new();
                   12890:     }
1.1021    raeburn  12891:     if (ref($dirlistref) eq 'ARRAY') {
                   12892:         foreach my $line (@{$dirlistref}) {
                   12893:             my ($file_name,$rest)=split(/\&/,$line,2);
                   12894:             if ($file_name eq $fname){
                   12895:                 $file_name = $path.$file_name;
                   12896:                 if ($group ne '') {
                   12897:                     $file_name = $group.$file_name;
                   12898:                 }
                   12899:                 $found_file = 1;
                   12900:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   12901:                     foreach my $lock (@lockers) {
                   12902:                         if (ref($lock) eq 'ARRAY') {
                   12903:                             my ($symb,$crsid) = @{$lock};
                   12904:                             if ($crsid eq $env{'request.course.id'}) {
                   12905:                                 if (ref($navmap)) {
                   12906:                                     my $res = $navmap->getBySymb($symb);
                   12907:                                     foreach my $part (@{$res->parts()}) { 
                   12908:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   12909:                                         unless (($slot_status == $res->RESERVED) ||
                   12910:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   12911:                                             $locked_file = 1;
                   12912:                                         }
1.991     raeburn  12913:                                     }
1.1021    raeburn  12914:                                 } else {
                   12915:                                     $locked_file = 1;
1.991     raeburn  12916:                                 }
                   12917:                             } else {
                   12918:                                 $locked_file = 1;
                   12919:                             }
                   12920:                         }
1.1021    raeburn  12921:                    }
                   12922:                 } else {
                   12923:                     my @info = split(/\&/,$rest);
                   12924:                     my $currsize = $info[6]/1000;
                   12925:                     if ($currsize < $filesize) {
                   12926:                         my $extra = $filesize - $currsize;
                   12927:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   12928:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  12929:                                       &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   12930:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   12931:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   12932:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  12933:                             return ('will_exceed_quota',$msg);
                   12934:                         }
1.984     raeburn  12935:                     }
                   12936:                 }
1.661     raeburn  12937:             }
                   12938:         }
                   12939:     }
                   12940:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   12941:         my $msg = '<p class="LC_warning">'.
                   12942:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  12943:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  12944:         return ('will_exceed_quota',$msg);
                   12945:     } elsif ($found_file) {
                   12946:         if ($locked_file) {
1.1179    bisitz   12947:             my $msg = '<p class="LC_warning">';
1.661     raeburn  12948:             $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   12949:             $msg .= '</p>';
1.661     raeburn  12950:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   12951:             return ('file_locked',$msg);
                   12952:         } else {
1.1179    bisitz   12953:             my $msg = '<p class="LC_error">';
1.984     raeburn  12954:             $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   12955:             $msg .= '</p>';
1.984     raeburn  12956:             return ('existingfile',$msg);
1.661     raeburn  12957:         }
                   12958:     }
                   12959: }
                   12960: 
1.987     raeburn  12961: sub check_for_traversal {
                   12962:     my ($path,$url,$toplevel) = @_;
                   12963:     my @parts=split(/\//,$path);
                   12964:     my $cleanpath;
                   12965:     my $fullpath = $url;
                   12966:     for (my $i=0;$i<@parts;$i++) {
                   12967:         next if ($parts[$i] eq '.');
                   12968:         if ($parts[$i] eq '..') {
                   12969:             $fullpath =~ s{([^/]+/)$}{};
                   12970:         } else {
                   12971:             $fullpath .= $parts[$i].'/';
                   12972:         }
                   12973:     }
                   12974:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   12975:         $cleanpath = $1;
                   12976:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   12977:         my $curr_toprel = $1;
                   12978:         my @parts = split(/\//,$curr_toprel);
                   12979:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   12980:         my @urlparts = split(/\//,$url_toprel);
                   12981:         my $doubledots;
                   12982:         my $startdiff = -1;
                   12983:         for (my $i=0; $i<@urlparts; $i++) {
                   12984:             if ($startdiff == -1) {
                   12985:                 unless ($urlparts[$i] eq $parts[$i]) {
                   12986:                     $startdiff = $i;
                   12987:                     $doubledots .= '../';
                   12988:                 }
                   12989:             } else {
                   12990:                 $doubledots .= '../';
                   12991:             }
                   12992:         }
                   12993:         if ($startdiff > -1) {
                   12994:             $cleanpath = $doubledots;
                   12995:             for (my $i=$startdiff; $i<@parts; $i++) {
                   12996:                 $cleanpath .= $parts[$i].'/';
                   12997:             }
                   12998:         }
                   12999:     }
                   13000:     $cleanpath =~ s{(/)$}{};
                   13001:     return $cleanpath;
                   13002: }
1.31      albertel 13003: 
1.1053    raeburn  13004: sub is_archive_file {
                   13005:     my ($mimetype) = @_;
                   13006:     if (($mimetype eq 'application/octet-stream') ||
                   13007:         ($mimetype eq 'application/x-stuffit') ||
                   13008:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   13009:         return 1;
                   13010:     }
                   13011:     return;
                   13012: }
                   13013: 
                   13014: sub decompress_form {
1.1065    raeburn  13015:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  13016:     my %lt = &Apache::lonlocal::texthash (
                   13017:         this => 'This file is an archive file.',
1.1067    raeburn  13018:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  13019:         itsc => 'Its contents are as follows:',
1.1053    raeburn  13020:         youm => 'You may wish to extract its contents.',
                   13021:         extr => 'Extract contents',
1.1067    raeburn  13022:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   13023:         proa => 'Process automatically?',
1.1053    raeburn  13024:         yes  => 'Yes',
                   13025:         no   => 'No',
1.1067    raeburn  13026:         fold => 'Title for folder containing movie',
                   13027:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  13028:     );
1.1065    raeburn  13029:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  13030:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  13031:     my $info = &list_archive_contents($fileloc,\@paths);
                   13032:     if (@paths) {
                   13033:         foreach my $path (@paths) {
                   13034:             $path =~ s{^/}{};
1.1067    raeburn  13035:             if ($path =~ m{^([^/]+)/$}) {
                   13036:                 $topdir = $1;
                   13037:             }
1.1065    raeburn  13038:             if ($path =~ m{^([^/]+)/}) {
                   13039:                 $toplevel{$1} = $path;
                   13040:             } else {
                   13041:                 $toplevel{$path} = $path;
                   13042:             }
                   13043:         }
                   13044:     }
1.1067    raeburn  13045:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  13046:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  13047:                         "$topdir/media/",
                   13048:                         "$topdir/media/$topdir.mp4",
                   13049:                         "$topdir/media/FirstFrame.png",
                   13050:                         "$topdir/media/player.swf",
                   13051:                         "$topdir/media/swfobject.js",
                   13052:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  13053:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  13054:                          "$topdir/$topdir.mp4",
                   13055:                          "$topdir/$topdir\_config.xml",
                   13056:                          "$topdir/$topdir\_controller.swf",
                   13057:                          "$topdir/$topdir\_embed.css",
                   13058:                          "$topdir/$topdir\_First_Frame.png",
                   13059:                          "$topdir/$topdir\_player.html",
                   13060:                          "$topdir/$topdir\_Thumbnails.png",
                   13061:                          "$topdir/playerProductInstall.swf",
                   13062:                          "$topdir/scripts/",
                   13063:                          "$topdir/scripts/config_xml.js",
                   13064:                          "$topdir/scripts/handlebars.js",
                   13065:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   13066:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   13067:                          "$topdir/scripts/modernizr.js",
                   13068:                          "$topdir/scripts/player-min.js",
                   13069:                          "$topdir/scripts/swfobject.js",
                   13070:                          "$topdir/skins/",
                   13071:                          "$topdir/skins/configuration_express.xml",
                   13072:                          "$topdir/skins/express_show/",
                   13073:                          "$topdir/skins/express_show/player-min.css",
                   13074:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  13075:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   13076:                          "$topdir/$topdir.mp4",
                   13077:                          "$topdir/$topdir\_config.xml",
                   13078:                          "$topdir/$topdir\_controller.swf",
                   13079:                          "$topdir/$topdir\_embed.css",
                   13080:                          "$topdir/$topdir\_First_Frame.png",
                   13081:                          "$topdir/$topdir\_player.html",
                   13082:                          "$topdir/$topdir\_Thumbnails.png",
                   13083:                          "$topdir/playerProductInstall.swf",
                   13084:                          "$topdir/scripts/",
                   13085:                          "$topdir/scripts/config_xml.js",
                   13086:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   13087:                          "$topdir/skins/",
                   13088:                          "$topdir/skins/configuration_express.xml",
                   13089:                          "$topdir/skins/express_show/",
                   13090:                          "$topdir/skins/express_show/spritesheet.min.css",
                   13091:                          "$topdir/skins/express_show/spritesheet.png",
                   13092:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  13093:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  13094:         if (@diffs == 0) {
1.1164    raeburn  13095:             $is_camtasia = 6;
                   13096:         } else {
1.1197    raeburn  13097:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  13098:             if (@diffs == 0) {
                   13099:                 $is_camtasia = 8;
1.1197    raeburn  13100:             } else {
                   13101:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   13102:                 if (@diffs == 0) {
                   13103:                     $is_camtasia = 8;
                   13104:                 }
1.1164    raeburn  13105:             }
1.1067    raeburn  13106:         }
                   13107:     }
                   13108:     my $output;
                   13109:     if ($is_camtasia) {
                   13110:         $output = <<"ENDCAM";
                   13111: <script type="text/javascript" language="Javascript">
                   13112: // <![CDATA[
                   13113: 
                   13114: function camtasiaToggle() {
                   13115:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   13116:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  13117:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  13118:                 document.getElementById('camtasia_titles').style.display='block';
                   13119:             } else {
                   13120:                 document.getElementById('camtasia_titles').style.display='none';
                   13121:             }
                   13122:         }
                   13123:     }
                   13124:     return;
                   13125: }
                   13126: 
                   13127: // ]]>
                   13128: </script>
                   13129: <p>$lt{'camt'}</p>
                   13130: ENDCAM
1.1065    raeburn  13131:     } else {
1.1067    raeburn  13132:         $output = '<p>'.$lt{'this'};
                   13133:         if ($info eq '') {
                   13134:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   13135:         } else {
                   13136:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   13137:                        '<div><pre>'.$info.'</pre></div>';
                   13138:         }
1.1065    raeburn  13139:     }
1.1067    raeburn  13140:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  13141:     my $duplicates;
                   13142:     my $num = 0;
                   13143:     if (ref($dirlist) eq 'ARRAY') {
                   13144:         foreach my $item (@{$dirlist}) {
                   13145:             if (ref($item) eq 'ARRAY') {
                   13146:                 if (exists($toplevel{$item->[0]})) {
                   13147:                     $duplicates .= 
                   13148:                         &start_data_table_row().
                   13149:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13150:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   13151:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13152:                         'value="1" />'.&mt('Yes').'</label>'.
                   13153:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   13154:                         '<td>'.$item->[0].'</td>';
                   13155:                     if ($item->[2]) {
                   13156:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   13157:                     } else {
                   13158:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   13159:                     }
                   13160:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   13161:                                    '<td>'.
                   13162:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   13163:                                    '</td>'.
                   13164:                                    &end_data_table_row();
                   13165:                     $num ++;
                   13166:                 }
                   13167:             }
                   13168:         }
                   13169:     }
                   13170:     my $itemcount;
                   13171:     if (@paths > 0) {
                   13172:         $itemcount = scalar(@paths);
                   13173:     } else {
                   13174:         $itemcount = 1;
                   13175:     }
1.1067    raeburn  13176:     if ($is_camtasia) {
                   13177:         $output .= $lt{'auto'}.'<br />'.
                   13178:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  13179:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  13180:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   13181:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   13182:                    $lt{'no'}.'</label></span><br />'.
                   13183:                    '<div id="camtasia_titles" style="display:block">'.
                   13184:                    &Apache::lonhtmlcommon::start_pick_box().
                   13185:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   13186:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   13187:                    &Apache::lonhtmlcommon::row_closure().
                   13188:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   13189:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   13190:                    &Apache::lonhtmlcommon::row_closure(1).
                   13191:                    &Apache::lonhtmlcommon::end_pick_box().
                   13192:                    '</div>';
                   13193:     }
1.1065    raeburn  13194:     $output .= 
                   13195:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  13196:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   13197:         "\n";
1.1065    raeburn  13198:     if ($duplicates ne '') {
                   13199:         $output .= '<p><span class="LC_warning">'.
                   13200:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   13201:                    &start_data_table().
                   13202:                    &start_data_table_header_row().
                   13203:                    '<th>'.&mt('Overwrite?').'</th>'.
                   13204:                    '<th>'.&mt('Name').'</th>'.
                   13205:                    '<th>'.&mt('Type').'</th>'.
                   13206:                    '<th>'.&mt('Size').'</th>'.
                   13207:                    '<th>'.&mt('Last modified').'</th>'.
                   13208:                    &end_data_table_header_row().
                   13209:                    $duplicates.
                   13210:                    &end_data_table().
                   13211:                    '</p>';
                   13212:     }
1.1067    raeburn  13213:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  13214:     if (ref($hiddenelements) eq 'HASH') {
                   13215:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   13216:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   13217:         }
                   13218:     }
                   13219:     $output .= <<"END";
1.1067    raeburn  13220: <br />
1.1053    raeburn  13221: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   13222: </form>
                   13223: $noextract
                   13224: END
                   13225:     return $output;
                   13226: }
                   13227: 
1.1065    raeburn  13228: sub decompression_utility {
                   13229:     my ($program) = @_;
                   13230:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   13231:     my $location;
                   13232:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   13233:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   13234:                          '/usr/sbin/') {
                   13235:             if (-x $dir.$program) {
                   13236:                 $location = $dir.$program;
                   13237:                 last;
                   13238:             }
                   13239:         }
                   13240:     }
                   13241:     return $location;
                   13242: }
                   13243: 
                   13244: sub list_archive_contents {
                   13245:     my ($file,$pathsref) = @_;
                   13246:     my (@cmd,$output);
                   13247:     my $needsregexp;
                   13248:     if ($file =~ /\.zip$/) {
                   13249:         @cmd = (&decompression_utility('unzip'),"-l");
                   13250:         $needsregexp = 1;
                   13251:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   13252:              ($file =~ /\.tgz$/)) {
                   13253:         @cmd = (&decompression_utility('tar'),"-ztf");
                   13254:     } elsif ($file =~ /\.tar\.bz2$/) {
                   13255:         @cmd = (&decompression_utility('tar'),"-jtf");
                   13256:     } elsif ($file =~ m|\.tar$|) {
                   13257:         @cmd = (&decompression_utility('tar'),"-tf");
                   13258:     }
                   13259:     if (@cmd) {
                   13260:         undef($!);
                   13261:         undef($@);
                   13262:         if (open(my $fh,"-|", @cmd, $file)) {
                   13263:             while (my $line = <$fh>) {
                   13264:                 $output .= $line;
                   13265:                 chomp($line);
                   13266:                 my $item;
                   13267:                 if ($needsregexp) {
                   13268:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   13269:                 } else {
                   13270:                     $item = $line;
                   13271:                 }
                   13272:                 if ($item ne '') {
                   13273:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   13274:                         push(@{$pathsref},$item);
                   13275:                     } 
                   13276:                 }
                   13277:             }
                   13278:             close($fh);
                   13279:         }
                   13280:     }
                   13281:     return $output;
                   13282: }
                   13283: 
1.1053    raeburn  13284: sub decompress_uploaded_file {
                   13285:     my ($file,$dir) = @_;
                   13286:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   13287:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   13288:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   13289:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   13290:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   13291:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   13292:     my $decompressed = $env{'cgi.decompressed'};
                   13293:     &Apache::lonnet::delenv('cgi.file');
                   13294:     &Apache::lonnet::delenv('cgi.dir');
                   13295:     &Apache::lonnet::delenv('cgi.decompressed');
                   13296:     return ($decompressed,$result);
                   13297: }
                   13298: 
1.1055    raeburn  13299: sub process_decompression {
                   13300:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1292    raeburn  13301:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   13302:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13303:                &mt('Unexpected file path.').'</p>'."\n";
                   13304:     }
                   13305:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   13306:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13307:                &mt('Unexpected course context.').'</p>'."\n";
                   13308:     }
1.1293    raeburn  13309:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
1.1292    raeburn  13310:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13311:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   13312:     }
1.1055    raeburn  13313:     my ($dir,$error,$warning,$output);
1.1180    raeburn  13314:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   13315:         $error = &mt('Filename not a supported archive file type.').
                   13316:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  13317:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   13318:     } else {
                   13319:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13320:         if ($docuhome eq 'no_host') {
                   13321:             $error = &mt('Could not determine home server for course.');
                   13322:         } else {
                   13323:             my @ids=&Apache::lonnet::current_machine_ids();
                   13324:             my $currdir = "$dir_root/$destination";
                   13325:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13326:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   13327:                        "$dir_root/$destination";
                   13328:             } else {
                   13329:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   13330:                        "$dir_root/$docudom/$docuname/$destination";
                   13331:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   13332:                     $error = &mt('Archive file not found.');
                   13333:                 }
                   13334:             }
1.1065    raeburn  13335:             my (@to_overwrite,@to_skip);
                   13336:             if ($env{'form.archive_overwrite_total'} > 0) {
                   13337:                 my $total = $env{'form.archive_overwrite_total'};
                   13338:                 for (my $i=0; $i<$total; $i++) {
                   13339:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   13340:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   13341:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   13342:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   13343:                     }
                   13344:                 }
                   13345:             }
                   13346:             my $numskip = scalar(@to_skip);
1.1292    raeburn  13347:             my $numoverwrite = scalar(@to_overwrite);
                   13348:             if (($numskip) && (!$numoverwrite)) { 
1.1065    raeburn  13349:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   13350:             } elsif ($dir eq '') {
1.1055    raeburn  13351:                 $error = &mt('Directory containing archive file unavailable.');
                   13352:             } elsif (!$error) {
1.1065    raeburn  13353:                 my ($decompressed,$display);
1.1292    raeburn  13354:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  13355:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   13356:                     mkdir("$dir/$tempdir",0755);
1.1292    raeburn  13357:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   13358:                         ($decompressed,$display) = 
                   13359:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   13360:                         foreach my $item (@to_skip) {
                   13361:                             if (($item ne '') && ($item !~ /\.\./)) {
                   13362:                                 if (-f "$dir/$tempdir/$item") { 
                   13363:                                     unlink("$dir/$tempdir/$item");
                   13364:                                 } elsif (-d "$dir/$tempdir/$item") {
1.1300    raeburn  13365:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
1.1292    raeburn  13366:                                 }
                   13367:                             }
                   13368:                         }
                   13369:                         foreach my $item (@to_overwrite) {
                   13370:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   13371:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   13372:                                     if (-f "$dir/$item") {
                   13373:                                         unlink("$dir/$item");
                   13374:                                     } elsif (-d "$dir/$item") {
1.1300    raeburn  13375:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
1.1292    raeburn  13376:                                     }
                   13377:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   13378:                                 }
1.1065    raeburn  13379:                             }
                   13380:                         }
1.1292    raeburn  13381:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
1.1300    raeburn  13382:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
1.1292    raeburn  13383:                         }
1.1065    raeburn  13384:                     }
                   13385:                 } else {
                   13386:                     ($decompressed,$display) = 
                   13387:                         &decompress_uploaded_file($file,$dir);
                   13388:                 }
1.1055    raeburn  13389:                 if ($decompressed eq 'ok') {
1.1065    raeburn  13390:                     $output = '<p class="LC_info">'.
                   13391:                               &mt('Files extracted successfully from archive.').
                   13392:                               '</p>'."\n";
1.1055    raeburn  13393:                     my ($warning,$result,@contents);
                   13394:                     my ($newdirlistref,$newlisterror) =
                   13395:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   13396:                                                  $docuname,1);
                   13397:                     my (%is_dir,%changes,@newitems);
                   13398:                     my $dirptr = 16384;
1.1065    raeburn  13399:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  13400:                         foreach my $dir_line (@{$newdirlistref}) {
                   13401:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1292    raeburn  13402:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
1.1055    raeburn  13403:                                 push(@newitems,$item);
                   13404:                                 if ($dirptr&$testdir) {
                   13405:                                     $is_dir{$item} = 1;
                   13406:                                 }
                   13407:                                 $changes{$item} = 1;
                   13408:                             }
                   13409:                         }
                   13410:                     }
                   13411:                     if (keys(%changes) > 0) {
                   13412:                         foreach my $item (sort(@newitems)) {
                   13413:                             if ($changes{$item}) {
                   13414:                                 push(@contents,$item);
                   13415:                             }
                   13416:                         }
                   13417:                     }
                   13418:                     if (@contents > 0) {
1.1067    raeburn  13419:                         my $wantform;
                   13420:                         unless ($env{'form.autoextract_camtasia'}) {
                   13421:                             $wantform = 1;
                   13422:                         }
1.1056    raeburn  13423:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  13424:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   13425:                                                                 $currdir,\%is_dir,
                   13426:                                                                 \%children,\%parent,
1.1056    raeburn  13427:                                                                 \@contents,\%dirorder,
                   13428:                                                                 \%titles,$wantform);
1.1055    raeburn  13429:                         if ($datatable ne '') {
                   13430:                             $output .= &archive_options_form('decompressed',$datatable,
                   13431:                                                              $count,$hiddenelem);
1.1065    raeburn  13432:                             my $startcount = 6;
1.1055    raeburn  13433:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  13434:                                                            \%titles,\%children);
1.1055    raeburn  13435:                         }
1.1067    raeburn  13436:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  13437:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  13438:                             my %displayed;
                   13439:                             my $total = 1;
                   13440:                             $env{'form.archive_directory'} = [];
                   13441:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   13442:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   13443:                                 $path =~ s{/$}{};
                   13444:                                 my $item;
                   13445:                                 if ($path ne '') {
                   13446:                                     $item = "$path/$titles{$i}";
                   13447:                                 } else {
                   13448:                                     $item = $titles{$i};
                   13449:                                 }
                   13450:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   13451:                                 if ($item eq $contents[0]) {
                   13452:                                     push(@{$env{'form.archive_directory'}},$i);
                   13453:                                     $env{'form.archive_'.$i} = 'display';
                   13454:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   13455:                                     $displayed{'folder'} = $i;
1.1164    raeburn  13456:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   13457:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  13458:                                     $env{'form.archive_'.$i} = 'display';
                   13459:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   13460:                                     $displayed{'web'} = $i;
                   13461:                                 } else {
1.1164    raeburn  13462:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   13463:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   13464:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  13465:                                         push(@{$env{'form.archive_directory'}},$i);
                   13466:                                     }
                   13467:                                     $env{'form.archive_'.$i} = 'dependency';
                   13468:                                 }
                   13469:                                 $total ++;
                   13470:                             }
                   13471:                             for (my $i=1; $i<$total; $i++) {
                   13472:                                 next if ($i == $displayed{'web'});
                   13473:                                 next if ($i == $displayed{'folder'});
                   13474:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   13475:                             }
                   13476:                             $env{'form.phase'} = 'decompress_cleanup';
                   13477:                             $env{'form.archivedelete'} = 1;
                   13478:                             $env{'form.archive_count'} = $total-1;
                   13479:                             $output .=
                   13480:                                 &process_extracted_files('coursedocs',$docudom,
                   13481:                                                          $docuname,$destination,
                   13482:                                                          $dir_root,$hiddenelem);
                   13483:                         }
1.1055    raeburn  13484:                     } else {
                   13485:                         $warning = &mt('No new items extracted from archive file.');
                   13486:                     }
                   13487:                 } else {
                   13488:                     $output = $display;
                   13489:                     $error = &mt('An error occurred during extraction from the archive file.');
                   13490:                 }
                   13491:             }
                   13492:         }
                   13493:     }
                   13494:     if ($error) {
                   13495:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13496:                    $error.'</p>'."\n";
                   13497:     }
                   13498:     if ($warning) {
                   13499:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13500:     }
                   13501:     return $output;
                   13502: }
                   13503: 
                   13504: sub get_extracted {
1.1056    raeburn  13505:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   13506:         $titles,$wantform) = @_;
1.1055    raeburn  13507:     my $count = 0;
                   13508:     my $depth = 0;
                   13509:     my $datatable;
1.1056    raeburn  13510:     my @hierarchy;
1.1055    raeburn  13511:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  13512:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   13513:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  13514:     foreach my $item (@{$contents}) {
                   13515:         $count ++;
1.1056    raeburn  13516:         @{$dirorder->{$count}} = @hierarchy;
                   13517:         $titles->{$count} = $item;
1.1055    raeburn  13518:         &archive_hierarchy($depth,$count,$parent,$children);
                   13519:         if ($wantform) {
                   13520:             $datatable .= &archive_row($is_dir->{$item},$item,
                   13521:                                        $currdir,$depth,$count);
                   13522:         }
                   13523:         if ($is_dir->{$item}) {
                   13524:             $depth ++;
1.1056    raeburn  13525:             push(@hierarchy,$count);
                   13526:             $parent->{$depth} = $count;
1.1055    raeburn  13527:             $datatable .=
                   13528:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  13529:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   13530:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  13531:             $depth --;
1.1056    raeburn  13532:             pop(@hierarchy);
1.1055    raeburn  13533:         }
                   13534:     }
                   13535:     return ($count,$datatable);
                   13536: }
                   13537: 
                   13538: sub recurse_extracted_archive {
1.1056    raeburn  13539:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   13540:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  13541:     my $result='';
1.1056    raeburn  13542:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   13543:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   13544:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  13545:         return $result;
                   13546:     }
                   13547:     my $dirptr = 16384;
                   13548:     my ($newdirlistref,$newlisterror) =
                   13549:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   13550:     if (ref($newdirlistref) eq 'ARRAY') {
                   13551:         foreach my $dir_line (@{$newdirlistref}) {
                   13552:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   13553:             unless ($item =~ /^\.+$/) {
                   13554:                 $$count ++;
1.1056    raeburn  13555:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   13556:                 $titles->{$$count} = $item;
1.1055    raeburn  13557:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  13558: 
1.1055    raeburn  13559:                 my $is_dir;
                   13560:                 if ($dirptr&$testdir) {
                   13561:                     $is_dir = 1;
                   13562:                 }
                   13563:                 if ($wantform) {
                   13564:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   13565:                 }
                   13566:                 if ($is_dir) {
                   13567:                     $$depth ++;
1.1056    raeburn  13568:                     push(@{$hierarchy},$$count);
                   13569:                     $parent->{$$depth} = $$count;
1.1055    raeburn  13570:                     $result .=
                   13571:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   13572:                                                    $docuname,$depth,$count,
1.1056    raeburn  13573:                                                    $hierarchy,$dirorder,$children,
                   13574:                                                    $parent,$titles,$wantform);
1.1055    raeburn  13575:                     $$depth --;
1.1056    raeburn  13576:                     pop(@{$hierarchy});
1.1055    raeburn  13577:                 }
                   13578:             }
                   13579:         }
                   13580:     }
                   13581:     return $result;
                   13582: }
                   13583: 
                   13584: sub archive_hierarchy {
                   13585:     my ($depth,$count,$parent,$children) =@_;
                   13586:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   13587:         if (exists($parent->{$depth})) {
                   13588:              $children->{$parent->{$depth}} .= $count.':';
                   13589:         }
                   13590:     }
                   13591:     return;
                   13592: }
                   13593: 
                   13594: sub archive_row {
                   13595:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   13596:     my ($name) = ($item =~ m{([^/]+)$});
                   13597:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  13598:                                        'display'    => 'Add as file',
1.1055    raeburn  13599:                                        'dependency' => 'Include as dependency',
                   13600:                                        'discard'    => 'Discard',
                   13601:                                       );
                   13602:     if ($is_dir) {
1.1059    raeburn  13603:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  13604:     }
1.1056    raeburn  13605:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   13606:     my $offset = 0;
1.1055    raeburn  13607:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  13608:         $offset ++;
1.1065    raeburn  13609:         if ($action ne 'display') {
                   13610:             $offset ++;
                   13611:         }  
1.1055    raeburn  13612:         $output .= '<td><span class="LC_nobreak">'.
                   13613:                    '<label><input type="radio" name="archive_'.$count.
                   13614:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   13615:         my $text = $choices{$action};
                   13616:         if ($is_dir) {
                   13617:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   13618:             if ($action eq 'display') {
1.1059    raeburn  13619:                 $text = &mt('Add as folder');
1.1055    raeburn  13620:             }
1.1056    raeburn  13621:         } else {
                   13622:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   13623: 
                   13624:         }
                   13625:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   13626:         if ($action eq 'dependency') {
                   13627:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   13628:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   13629:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   13630:                        '<option value=""></option>'."\n".
                   13631:                        '</select>'."\n".
                   13632:                        '</div>';
1.1059    raeburn  13633:         } elsif ($action eq 'display') {
                   13634:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   13635:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   13636:                        '</div>';
1.1055    raeburn  13637:         }
1.1056    raeburn  13638:         $output .= '</td>';
1.1055    raeburn  13639:     }
                   13640:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   13641:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   13642:     for (my $i=0; $i<$depth; $i++) {
                   13643:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   13644:     }
                   13645:     if ($is_dir) {
                   13646:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   13647:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   13648:     } else {
                   13649:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   13650:     }
                   13651:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   13652:                &end_data_table_row();
                   13653:     return $output;
                   13654: }
                   13655: 
                   13656: sub archive_options_form {
1.1065    raeburn  13657:     my ($form,$display,$count,$hiddenelem) = @_;
                   13658:     my %lt = &Apache::lonlocal::texthash(
                   13659:                perm => 'Permanently remove archive file?',
                   13660:                hows => 'How should each extracted item be incorporated in the course?',
                   13661:                cont => 'Content actions for all',
                   13662:                addf => 'Add as folder/file',
                   13663:                incd => 'Include as dependency for a displayed file',
                   13664:                disc => 'Discard',
                   13665:                no   => 'No',
                   13666:                yes  => 'Yes',
                   13667:                save => 'Save',
                   13668:     );
                   13669:     my $output = <<"END";
                   13670: <form name="$form" method="post" action="">
                   13671: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   13672: <label>
                   13673:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   13674: </label>
                   13675: &nbsp;
                   13676: <label>
                   13677:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   13678: </span>
                   13679: </p>
                   13680: <input type="hidden" name="phase" value="decompress_cleanup" />
                   13681: <br />$lt{'hows'}
                   13682: <div class="LC_columnSection">
                   13683:   <fieldset>
                   13684:     <legend>$lt{'cont'}</legend>
                   13685:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   13686:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   13687:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   13688:   </fieldset>
                   13689: </div>
                   13690: END
                   13691:     return $output.
1.1055    raeburn  13692:            &start_data_table()."\n".
1.1065    raeburn  13693:            $display."\n".
1.1055    raeburn  13694:            &end_data_table()."\n".
                   13695:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   13696:            $hiddenelem.
1.1065    raeburn  13697:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  13698:            '</form>';
                   13699: }
                   13700: 
                   13701: sub archive_javascript {
1.1056    raeburn  13702:     my ($startcount,$numitems,$titles,$children) = @_;
                   13703:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  13704:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  13705:     my $scripttag = <<START;
                   13706: <script type="text/javascript">
                   13707: // <![CDATA[
                   13708: 
                   13709: function checkAll(form,prefix) {
                   13710:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   13711:     for (var i=0; i < form.elements.length; i++) {
                   13712:         var id = form.elements[i].id;
                   13713:         if ((id != '') && (id != undefined)) {
                   13714:             if (idstr.test(id)) {
                   13715:                 if (form.elements[i].type == 'radio') {
                   13716:                     form.elements[i].checked = true;
1.1056    raeburn  13717:                     var nostart = i-$startcount;
1.1059    raeburn  13718:                     var offset = nostart%7;
                   13719:                     var count = (nostart-offset)/7;    
1.1056    raeburn  13720:                     dependencyCheck(form,count,offset);
1.1055    raeburn  13721:                 }
                   13722:             }
                   13723:         }
                   13724:     }
                   13725: }
                   13726: 
                   13727: function propagateCheck(form,count) {
                   13728:     if (count > 0) {
1.1059    raeburn  13729:         var startelement = $startcount + ((count-1) * 7);
                   13730:         for (var j=1; j<6; j++) {
                   13731:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  13732:                 var item = startelement + j; 
                   13733:                 if (form.elements[item].type == 'radio') {
                   13734:                     if (form.elements[item].checked) {
                   13735:                         containerCheck(form,count,j);
                   13736:                         break;
                   13737:                     }
1.1055    raeburn  13738:                 }
                   13739:             }
                   13740:         }
                   13741:     }
                   13742: }
                   13743: 
                   13744: numitems = $numitems
1.1056    raeburn  13745: var titles = new Array(numitems);
                   13746: var parents = new Array(numitems);
1.1055    raeburn  13747: for (var i=0; i<numitems; i++) {
1.1056    raeburn  13748:     parents[i] = new Array;
1.1055    raeburn  13749: }
1.1059    raeburn  13750: var maintitle = '$maintitle';
1.1055    raeburn  13751: 
                   13752: START
                   13753: 
1.1056    raeburn  13754:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   13755:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  13756:         for (my $i=0; $i<@contents; $i ++) {
                   13757:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   13758:         }
                   13759:     }
                   13760: 
1.1056    raeburn  13761:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   13762:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   13763:     }
                   13764: 
1.1055    raeburn  13765:     $scripttag .= <<END;
                   13766: 
                   13767: function containerCheck(form,count,offset) {
                   13768:     if (count > 0) {
1.1056    raeburn  13769:         dependencyCheck(form,count,offset);
1.1059    raeburn  13770:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  13771:         form.elements[item].checked = true;
                   13772:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13773:             if (parents[count].length > 0) {
                   13774:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  13775:                     containerCheck(form,parents[count][j],offset);
                   13776:                 }
                   13777:             }
                   13778:         }
                   13779:     }
                   13780: }
                   13781: 
                   13782: function dependencyCheck(form,count,offset) {
                   13783:     if (count > 0) {
1.1059    raeburn  13784:         var chosen = (offset+$startcount)+7*(count-1);
                   13785:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  13786:         var currtype = form.elements[depitem].type;
                   13787:         if (form.elements[chosen].value == 'dependency') {
                   13788:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   13789:             form.elements[depitem].options.length = 0;
                   13790:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  13791:             for (var i=1; i<=numitems; i++) {
                   13792:                 if (i == count) {
                   13793:                     continue;
                   13794:                 }
1.1059    raeburn  13795:                 var startelement = $startcount + (i-1) * 7;
                   13796:                 for (var j=1; j<6; j++) {
                   13797:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  13798:                         var item = startelement + j;
                   13799:                         if (form.elements[item].type == 'radio') {
                   13800:                             if (form.elements[item].checked) {
                   13801:                                 if (form.elements[item].value == 'display') {
                   13802:                                     var n = form.elements[depitem].options.length;
                   13803:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   13804:                                 }
                   13805:                             }
                   13806:                         }
                   13807:                     }
                   13808:                 }
                   13809:             }
                   13810:         } else {
                   13811:             document.getElementById('arc_depon_'+count).style.display='none';
                   13812:             form.elements[depitem].options.length = 0;
                   13813:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   13814:         }
1.1059    raeburn  13815:         titleCheck(form,count,offset);
1.1056    raeburn  13816:     }
                   13817: }
                   13818: 
                   13819: function propagateSelect(form,count,offset) {
                   13820:     if (count > 0) {
1.1065    raeburn  13821:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  13822:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   13823:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13824:             if (parents[count].length > 0) {
                   13825:                 for (var j=0; j<parents[count].length; j++) {
                   13826:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  13827:                 }
                   13828:             }
                   13829:         }
                   13830:     }
                   13831: }
1.1056    raeburn  13832: 
                   13833: function containerSelect(form,count,offset,picked) {
                   13834:     if (count > 0) {
1.1065    raeburn  13835:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  13836:         if (form.elements[item].type == 'radio') {
                   13837:             if (form.elements[item].value == 'dependency') {
                   13838:                 if (form.elements[item+1].type == 'select-one') {
                   13839:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   13840:                         if (form.elements[item+1].options[i].value == picked) {
                   13841:                             form.elements[item+1].selectedIndex = i;
                   13842:                             break;
                   13843:                         }
                   13844:                     }
                   13845:                 }
                   13846:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13847:                     if (parents[count].length > 0) {
                   13848:                         for (var j=0; j<parents[count].length; j++) {
                   13849:                             containerSelect(form,parents[count][j],offset,picked);
                   13850:                         }
                   13851:                     }
                   13852:                 }
                   13853:             }
                   13854:         }
                   13855:     }
                   13856: }
                   13857: 
1.1059    raeburn  13858: function titleCheck(form,count,offset) {
                   13859:     if (count > 0) {
                   13860:         var chosen = (offset+$startcount)+7*(count-1);
                   13861:         var depitem = $startcount + ((count-1) * 7) + 2;
                   13862:         var currtype = form.elements[depitem].type;
                   13863:         if (form.elements[chosen].value == 'display') {
                   13864:             document.getElementById('arc_title_'+count).style.display='block';
                   13865:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   13866:                 document.getElementById('archive_title_'+count).value=maintitle;
                   13867:             }
                   13868:         } else {
                   13869:             document.getElementById('arc_title_'+count).style.display='none';
                   13870:             if (currtype == 'text') { 
                   13871:                 document.getElementById('archive_title_'+count).value='';
                   13872:             }
                   13873:         }
                   13874:     }
                   13875:     return;
                   13876: }
                   13877: 
1.1055    raeburn  13878: // ]]>
                   13879: </script>
                   13880: END
                   13881:     return $scripttag;
                   13882: }
                   13883: 
                   13884: sub process_extracted_files {
1.1067    raeburn  13885:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  13886:     my $numitems = $env{'form.archive_count'};
1.1294    raeburn  13887:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  13888:     my @ids=&Apache::lonnet::current_machine_ids();
                   13889:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  13890:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  13891:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13892:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13893:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   13894:         $pathtocheck = "$dir_root/$destination";
                   13895:         $dir = $dir_root;
                   13896:         $ishome = 1;
                   13897:     } else {
                   13898:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   13899:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1294    raeburn  13900:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  13901:     }
                   13902:     my $currdir = "$dir_root/$destination";
                   13903:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   13904:     if ($env{'form.folderpath'}) {
                   13905:         my @items = split('&',$env{'form.folderpath'});
                   13906:         $folders{'0'} = $items[-2];
1.1099    raeburn  13907:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   13908:             $containers{'0'}='page';
                   13909:         } else {  
                   13910:             $containers{'0'}='sequence';
                   13911:         }
1.1055    raeburn  13912:     }
                   13913:     my @archdirs = &get_env_multiple('form.archive_directory');
                   13914:     if ($numitems) {
                   13915:         for (my $i=1; $i<=$numitems; $i++) {
                   13916:             my $path = $env{'form.archive_content_'.$i};
                   13917:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   13918:                 my $item = $1;
                   13919:                 $toplevelitems{$item} = $i;
                   13920:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   13921:                     $is_dir{$item} = 1;
                   13922:                 }
                   13923:             }
                   13924:         }
                   13925:     }
1.1067    raeburn  13926:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  13927:     if (keys(%toplevelitems) > 0) {
                   13928:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  13929:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   13930:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  13931:     }
1.1066    raeburn  13932:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  13933:     if ($numitems) {
                   13934:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  13935:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  13936:             my $path = $env{'form.archive_content_'.$i};
                   13937:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13938:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   13939:                     if ($prefix ne '' && $path ne '') {
                   13940:                         if (-e $prefix.$path) {
1.1066    raeburn  13941:                             if ((@archdirs > 0) && 
                   13942:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   13943:                                 $todeletedir{$prefix.$path} = 1;
                   13944:                             } else {
                   13945:                                 $todelete{$prefix.$path} = 1;
                   13946:                             }
1.1055    raeburn  13947:                         }
                   13948:                     }
                   13949:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  13950:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  13951:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  13952:                     $docstitle = $env{'form.archive_title_'.$i};
                   13953:                     if ($docstitle eq '') {
                   13954:                         $docstitle = $title;
                   13955:                     }
1.1055    raeburn  13956:                     $outer = 0;
1.1056    raeburn  13957:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13958:                         if (@{$dirorder{$i}} > 0) {
                   13959:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  13960:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   13961:                                     $outer = $item;
                   13962:                                     last;
                   13963:                                 }
                   13964:                             }
                   13965:                         }
                   13966:                     }
                   13967:                     my ($errtext,$fatal) = 
                   13968:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   13969:                                                '/'.$folders{$outer}.'.'.
                   13970:                                                $containers{$outer});
                   13971:                     next if ($fatal);
                   13972:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   13973:                         if ($context eq 'coursedocs') {
1.1056    raeburn  13974:                             $mapinner{$i} = time;
1.1055    raeburn  13975:                             $folders{$i} = 'default_'.$mapinner{$i};
                   13976:                             $containers{$i} = 'sequence';
                   13977:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13978:                                       $folders{$i}.'.'.$containers{$i};
                   13979:                             my $newidx = &LONCAPA::map::getresidx();
                   13980:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  13981:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  13982:                             push(@LONCAPA::map::order,$newidx);
                   13983:                             my ($outtext,$errtext) =
                   13984:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13985:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  13986:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  13987:                             $newseqid{$i} = $newidx;
1.1067    raeburn  13988:                             unless ($errtext) {
1.1294    raeburn  13989:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   13990:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
                   13991:                                             '</li>'."\n";
1.1067    raeburn  13992:                             }
1.1055    raeburn  13993:                         }
                   13994:                     } else {
                   13995:                         if ($context eq 'coursedocs') {
                   13996:                             my $newidx=&LONCAPA::map::getresidx();
                   13997:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13998:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   13999:                                       $title;
1.1294    raeburn  14000:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
                   14001:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   14002:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   14003:                                 }
                   14004:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14005:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   14006:                                 }
                   14007:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14008:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   14009:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   14010:                                         unless ($ishome) {
                   14011:                                             my $fetch = "$newdest{$i}/$title";
                   14012:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   14013:                                             $prompttofetch{$fetch} = 1;
                   14014:                                         }
1.1292    raeburn  14015:                                     }
1.1067    raeburn  14016:                                 }
1.1294    raeburn  14017:                                 $LONCAPA::map::resources[$newidx]=
                   14018:                                     $docstitle.':'.$url.':false:normal:res';
                   14019:                                 push(@LONCAPA::map::order, $newidx);
                   14020:                                 my ($outtext,$errtext)=
                   14021:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14022:                                                             $docuname.'/'.$folders{$outer}.
                   14023:                                                             '.'.$containers{$outer},1,1);
                   14024:                                 unless ($errtext) {
                   14025:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   14026:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   14027:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   14028:                                                    '</li>'."\n";
                   14029:                                     }
1.1067    raeburn  14030:                                 }
1.1294    raeburn  14031:                             } else {
                   14032:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14033:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1296    raeburn  14034:                             }
1.1055    raeburn  14035:                         }
                   14036:                     }
1.1086    raeburn  14037:                 }
                   14038:             } else {
1.1294    raeburn  14039:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14040:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
1.1086    raeburn  14041:             }
                   14042:         }
                   14043:         for (my $i=1; $i<=$numitems; $i++) {
                   14044:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   14045:             my $path = $env{'form.archive_content_'.$i};
                   14046:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14047:                 my ($title) = ($path =~ m{/([^/]+)$});
                   14048:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   14049:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   14050:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14051:                         my ($itemidx,$fullpath,$relpath);
                   14052:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   14053:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  14054:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  14055:                                 if ($dirorder{$i}->[$j] eq $container) {
                   14056:                                     $itemidx = $j;
1.1056    raeburn  14057:                                 }
                   14058:                             }
1.1086    raeburn  14059:                         }
                   14060:                         if ($itemidx eq '') {
                   14061:                             $itemidx =  0;
                   14062:                         } 
                   14063:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   14064:                             if ($mapinner{$referrer{$i}}) {
                   14065:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   14066:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14067:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14068:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14069:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14070:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14071:                                             if (!-e $fullpath) {
                   14072:                                                 mkdir($fullpath,0755);
1.1056    raeburn  14073:                                             }
                   14074:                                         }
1.1086    raeburn  14075:                                     } else {
                   14076:                                         last;
1.1056    raeburn  14077:                                     }
1.1086    raeburn  14078:                                 }
                   14079:                             }
                   14080:                         } elsif ($newdest{$referrer{$i}}) {
                   14081:                             $fullpath = $newdest{$referrer{$i}};
                   14082:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14083:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   14084:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   14085:                                     last;
                   14086:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14087:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14088:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14089:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14090:                                         if (!-e $fullpath) {
                   14091:                                             mkdir($fullpath,0755);
1.1056    raeburn  14092:                                         }
                   14093:                                     }
1.1086    raeburn  14094:                                 } else {
                   14095:                                     last;
1.1056    raeburn  14096:                                 }
1.1055    raeburn  14097:                             }
                   14098:                         }
1.1086    raeburn  14099:                         if ($fullpath ne '') {
                   14100:                             if (-e "$prefix$path") {
1.1292    raeburn  14101:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   14102:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   14103:                                 }
1.1086    raeburn  14104:                             }
                   14105:                             if (-e "$fullpath/$title") {
                   14106:                                 my $showpath;
                   14107:                                 if ($relpath ne '') {
                   14108:                                     $showpath = "$relpath/$title";
                   14109:                                 } else {
                   14110:                                     $showpath = "/$title";
                   14111:                                 } 
1.1294    raeburn  14112:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   14113:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   14114:                                            '</li>'."\n";
1.1292    raeburn  14115:                                 unless ($ishome) {
                   14116:                                     my $fetch = "$fullpath/$title";
                   14117:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
                   14118:                                     $prompttofetch{$fetch} = 1;
                   14119:                                 }
1.1086    raeburn  14120:                             }
                   14121:                         }
1.1055    raeburn  14122:                     }
1.1086    raeburn  14123:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   14124:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1294    raeburn  14125:                                     &HTML::Entities::encode($path,'<>&"'),
                   14126:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   14127:                                 '<br />';
1.1055    raeburn  14128:                 }
                   14129:             } else {
1.1294    raeburn  14130:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
1.1296    raeburn  14131:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  14132:             }
                   14133:         }
                   14134:         if (keys(%todelete)) {
                   14135:             foreach my $key (keys(%todelete)) {
                   14136:                 unlink($key);
1.1066    raeburn  14137:             }
                   14138:         }
                   14139:         if (keys(%todeletedir)) {
                   14140:             foreach my $key (keys(%todeletedir)) {
                   14141:                 rmdir($key);
                   14142:             }
                   14143:         }
                   14144:         foreach my $dir (sort(keys(%is_dir))) {
                   14145:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   14146:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  14147:             }
                   14148:         }
1.1067    raeburn  14149:         if ($result ne '') {
                   14150:             $output .= '<ul>'."\n".
                   14151:                        $result."\n".
                   14152:                        '</ul>';
                   14153:         }
                   14154:         unless ($ishome) {
                   14155:             my $replicationfail;
                   14156:             foreach my $item (keys(%prompttofetch)) {
                   14157:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   14158:                 unless ($fetchresult eq 'ok') {
                   14159:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   14160:                 }
                   14161:             }
                   14162:             if ($replicationfail) {
                   14163:                 $output .= '<p class="LC_error">'.
                   14164:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   14165:                            $replicationfail.
                   14166:                            '</ul></p>';
                   14167:             }
                   14168:         }
1.1055    raeburn  14169:     } else {
                   14170:         $warning = &mt('No items found in archive.');
                   14171:     }
                   14172:     if ($error) {
                   14173:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14174:                    $error.'</p>'."\n";
                   14175:     }
                   14176:     if ($warning) {
                   14177:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   14178:     }
                   14179:     return $output;
                   14180: }
                   14181: 
1.1066    raeburn  14182: sub cleanup_empty_dirs {
                   14183:     my ($path) = @_;
                   14184:     if (($path ne '') && (-d $path)) {
                   14185:         if (opendir(my $dirh,$path)) {
                   14186:             my @dircontents = grep(!/^\./,readdir($dirh));
                   14187:             my $numitems = 0;
                   14188:             foreach my $item (@dircontents) {
                   14189:                 if (-d "$path/$item") {
1.1111    raeburn  14190:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  14191:                     if (-e "$path/$item") {
                   14192:                         $numitems ++;
                   14193:                     }
                   14194:                 } else {
                   14195:                     $numitems ++;
                   14196:                 }
                   14197:             }
                   14198:             if ($numitems == 0) {
                   14199:                 rmdir($path);
                   14200:             }
                   14201:             closedir($dirh);
                   14202:         }
                   14203:     }
                   14204:     return;
                   14205: }
                   14206: 
1.41      ng       14207: =pod
1.45      matthew  14208: 
1.1162    raeburn  14209: =item * &get_folder_hierarchy()
1.1068    raeburn  14210: 
                   14211: Provides hierarchy of names of folders/sub-folders containing the current
                   14212: item,
                   14213: 
                   14214: Inputs: 3
                   14215:      - $navmap - navmaps object
                   14216: 
                   14217:      - $map - url for map (either the trigger itself, or map containing
                   14218:                            the resource, which is the trigger).
                   14219: 
                   14220:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   14221: 
                   14222: Outputs: 1 @pathitems - array of folder/subfolder names.
                   14223: 
                   14224: =cut
                   14225: 
                   14226: sub get_folder_hierarchy {
                   14227:     my ($navmap,$map,$showitem) = @_;
                   14228:     my @pathitems;
                   14229:     if (ref($navmap)) {
                   14230:         my $mapres = $navmap->getResourceByUrl($map);
                   14231:         if (ref($mapres)) {
                   14232:             my $pcslist = $mapres->map_hierarchy();
                   14233:             if ($pcslist ne '') {
                   14234:                 my @pcs = split(/,/,$pcslist);
                   14235:                 foreach my $pc (@pcs) {
                   14236:                     if ($pc == 1) {
1.1129    raeburn  14237:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  14238:                     } else {
                   14239:                         my $res = $navmap->getByMapPc($pc);
                   14240:                         if (ref($res)) {
                   14241:                             my $title = $res->compTitle();
                   14242:                             $title =~ s/\W+/_/g;
                   14243:                             if ($title ne '') {
                   14244:                                 push(@pathitems,$title);
                   14245:                             }
                   14246:                         }
                   14247:                     }
                   14248:                 }
                   14249:             }
1.1071    raeburn  14250:             if ($showitem) {
                   14251:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  14252:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  14253:                 } else {
                   14254:                     my $maptitle = $mapres->compTitle();
                   14255:                     $maptitle =~ s/\W+/_/g;
                   14256:                     if ($maptitle ne '') {
                   14257:                         push(@pathitems,$maptitle);
                   14258:                     }
1.1068    raeburn  14259:                 }
                   14260:             }
                   14261:         }
                   14262:     }
                   14263:     return @pathitems;
                   14264: }
                   14265: 
                   14266: =pod
                   14267: 
1.1015    raeburn  14268: =item * &get_turnedin_filepath()
                   14269: 
                   14270: Determines path in a user's portfolio file for storage of files uploaded
                   14271: to a specific essayresponse or dropbox item.
                   14272: 
                   14273: Inputs: 3 required + 1 optional.
                   14274: $symb is symb for resource, $uname and $udom are for current user (required).
                   14275: $caller is optional (can be "submission", if routine is called when storing
                   14276: an upoaded file when "Submit Answer" button was pressed).
                   14277: 
                   14278: Returns array containing $path and $multiresp. 
                   14279: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   14280: than one file upload item.  Callers of routine should append partid as a 
                   14281: subdirectory to $path in cases where $multiresp is 1.
                   14282: 
                   14283: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   14284: 
                   14285: =cut
                   14286: 
                   14287: sub get_turnedin_filepath {
                   14288:     my ($symb,$uname,$udom,$caller) = @_;
                   14289:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   14290:     my $turnindir;
                   14291:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   14292:     $turnindir = $userhash{'turnindir'};
                   14293:     my ($path,$multiresp);
                   14294:     if ($turnindir eq '') {
                   14295:         if ($caller eq 'submission') {
                   14296:             $turnindir = &mt('turned in');
                   14297:             $turnindir =~ s/\W+/_/g;
                   14298:             my %newhash = (
                   14299:                             'turnindir' => $turnindir,
                   14300:                           );
                   14301:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   14302:         }
                   14303:     }
                   14304:     if ($turnindir ne '') {
                   14305:         $path = '/'.$turnindir.'/';
                   14306:         my ($multipart,$turnin,@pathitems);
                   14307:         my $navmap = Apache::lonnavmaps::navmap->new();
                   14308:         if (defined($navmap)) {
                   14309:             my $mapres = $navmap->getResourceByUrl($map);
                   14310:             if (ref($mapres)) {
                   14311:                 my $pcslist = $mapres->map_hierarchy();
                   14312:                 if ($pcslist ne '') {
                   14313:                     foreach my $pc (split(/,/,$pcslist)) {
                   14314:                         my $res = $navmap->getByMapPc($pc);
                   14315:                         if (ref($res)) {
                   14316:                             my $title = $res->compTitle();
                   14317:                             $title =~ s/\W+/_/g;
                   14318:                             if ($title ne '') {
1.1149    raeburn  14319:                                 if (($pc > 1) && (length($title) > 12)) {
                   14320:                                     $title = substr($title,0,12);
                   14321:                                 }
1.1015    raeburn  14322:                                 push(@pathitems,$title);
                   14323:                             }
                   14324:                         }
                   14325:                     }
                   14326:                 }
                   14327:                 my $maptitle = $mapres->compTitle();
                   14328:                 $maptitle =~ s/\W+/_/g;
                   14329:                 if ($maptitle ne '') {
1.1149    raeburn  14330:                     if (length($maptitle) > 12) {
                   14331:                         $maptitle = substr($maptitle,0,12);
                   14332:                     }
1.1015    raeburn  14333:                     push(@pathitems,$maptitle);
                   14334:                 }
                   14335:                 unless ($env{'request.state'} eq 'construct') {
                   14336:                     my $res = $navmap->getBySymb($symb);
                   14337:                     if (ref($res)) {
                   14338:                         my $partlist = $res->parts();
                   14339:                         my $totaluploads = 0;
                   14340:                         if (ref($partlist) eq 'ARRAY') {
                   14341:                             foreach my $part (@{$partlist}) {
                   14342:                                 my @types = $res->responseType($part);
                   14343:                                 my @ids = $res->responseIds($part);
                   14344:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   14345:                                     if ($types[$i] eq 'essay') {
                   14346:                                         my $partid = $part.'_'.$ids[$i];
                   14347:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   14348:                                             $totaluploads ++;
                   14349:                                         }
                   14350:                                     }
                   14351:                                 }
                   14352:                             }
                   14353:                             if ($totaluploads > 1) {
                   14354:                                 $multiresp = 1;
                   14355:                             }
                   14356:                         }
                   14357:                     }
                   14358:                 }
                   14359:             } else {
                   14360:                 return;
                   14361:             }
                   14362:         } else {
                   14363:             return;
                   14364:         }
                   14365:         my $restitle=&Apache::lonnet::gettitle($symb);
                   14366:         $restitle =~ s/\W+/_/g;
                   14367:         if ($restitle eq '') {
                   14368:             $restitle = ($resurl =~ m{/[^/]+$});
                   14369:             if ($restitle eq '') {
                   14370:                 $restitle = time;
                   14371:             }
                   14372:         }
1.1149    raeburn  14373:         if (length($restitle) > 12) {
                   14374:             $restitle = substr($restitle,0,12);
                   14375:         }
1.1015    raeburn  14376:         push(@pathitems,$restitle);
                   14377:         $path .= join('/',@pathitems);
                   14378:     }
                   14379:     return ($path,$multiresp);
                   14380: }
                   14381: 
                   14382: =pod
                   14383: 
1.464     albertel 14384: =back
1.41      ng       14385: 
1.112     bowersj2 14386: =head1 CSV Upload/Handling functions
1.38      albertel 14387: 
1.41      ng       14388: =over 4
                   14389: 
1.648     raeburn  14390: =item * &upfile_store($r)
1.41      ng       14391: 
                   14392: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 14393: needs $env{'form.upfile'}
1.41      ng       14394: returns $datatoken to be put into hidden field
                   14395: 
                   14396: =cut
1.31      albertel 14397: 
                   14398: sub upfile_store {
                   14399:     my $r=shift;
1.258     albertel 14400:     $env{'form.upfile'}=~s/\r/\n/gs;
                   14401:     $env{'form.upfile'}=~s/\f/\n/gs;
                   14402:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   14403:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 14404: 
1.1299    raeburn  14405:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   14406:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   14407:                                      time.'_'.$$);
                   14408:     return if ($datatoken eq '');
                   14409: 
1.31      albertel 14410:     {
1.158     raeburn  14411:         my $datafile = $r->dir_config('lonDaemons').
                   14412:                            '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  14413:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 14414:             print $fh $env{'form.upfile'};
1.158     raeburn  14415:             close($fh);
                   14416:         }
1.31      albertel 14417:     }
                   14418:     return $datatoken;
                   14419: }
                   14420: 
1.56      matthew  14421: =pod
                   14422: 
1.1290    raeburn  14423: =item * &load_tmp_file($r,$datatoken)
1.41      ng       14424: 
                   14425: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1290    raeburn  14426: $datatoken is the name to assign to the temporary file.
1.258     albertel 14427: sets $env{'form.upfile'} to the contents of the file
1.41      ng       14428: 
                   14429: =cut
1.31      albertel 14430: 
                   14431: sub load_tmp_file {
1.1290    raeburn  14432:     my ($r,$datatoken) = @_;
                   14433:     return if ($datatoken eq '');
1.31      albertel 14434:     my @studentdata=();
                   14435:     {
1.158     raeburn  14436:         my $studentfile = $r->dir_config('lonDaemons').
1.1290    raeburn  14437:                               '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  14438:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  14439:             @studentdata=<$fh>;
                   14440:             close($fh);
                   14441:         }
1.31      albertel 14442:     }
1.258     albertel 14443:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 14444: }
                   14445: 
1.1290    raeburn  14446: sub valid_datatoken {
                   14447:     my ($datatoken) = @_;
1.1325    raeburn  14448:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1290    raeburn  14449:         return $datatoken;
                   14450:     }
                   14451:     return;
                   14452: }
                   14453: 
1.56      matthew  14454: =pod
                   14455: 
1.648     raeburn  14456: =item * &upfile_record_sep()
1.41      ng       14457: 
                   14458: Separate uploaded file into records
                   14459: returns array of records,
1.258     albertel 14460: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       14461: 
                   14462: =cut
1.31      albertel 14463: 
                   14464: sub upfile_record_sep {
1.258     albertel 14465:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 14466:     } else {
1.248     albertel 14467: 	my @records;
1.258     albertel 14468: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 14469: 	    if ($line=~/^\s*$/) { next; }
                   14470: 	    push(@records,$line);
                   14471: 	}
                   14472: 	return @records;
1.31      albertel 14473:     }
                   14474: }
                   14475: 
1.56      matthew  14476: =pod
                   14477: 
1.648     raeburn  14478: =item * &record_sep($record)
1.41      ng       14479: 
1.258     albertel 14480: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       14481: 
                   14482: =cut
                   14483: 
1.263     www      14484: sub takeleft {
                   14485:     my $index=shift;
                   14486:     return substr('0000'.$index,-4,4);
                   14487: }
                   14488: 
1.31      albertel 14489: sub record_sep {
                   14490:     my $record=shift;
                   14491:     my %components=();
1.258     albertel 14492:     if ($env{'form.upfiletype'} eq 'xml') {
                   14493:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 14494:         my $i=0;
1.356     albertel 14495:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 14496:             $field=~s/^(\"|\')//;
                   14497:             $field=~s/(\"|\')$//;
1.263     www      14498:             $components{&takeleft($i)}=$field;
1.31      albertel 14499:             $i++;
                   14500:         }
1.258     albertel 14501:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 14502:         my $i=0;
1.356     albertel 14503:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 14504:             $field=~s/^(\"|\')//;
                   14505:             $field=~s/(\"|\')$//;
1.263     www      14506:             $components{&takeleft($i)}=$field;
1.31      albertel 14507:             $i++;
                   14508:         }
                   14509:     } else {
1.561     www      14510:         my $separator=',';
1.480     banghart 14511:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      14512:             $separator=';';
1.480     banghart 14513:         }
1.31      albertel 14514:         my $i=0;
1.561     www      14515: # the character we are looking for to indicate the end of a quote or a record 
                   14516:         my $looking_for=$separator;
                   14517: # do not add the characters to the fields
                   14518:         my $ignore=0;
                   14519: # we just encountered a separator (or the beginning of the record)
                   14520:         my $just_found_separator=1;
                   14521: # store the field we are working on here
                   14522:         my $field='';
                   14523: # work our way through all characters in record
                   14524:         foreach my $character ($record=~/(.)/g) {
                   14525:             if ($character eq $looking_for) {
                   14526:                if ($character ne $separator) {
                   14527: # Found the end of a quote, again looking for separator
                   14528:                   $looking_for=$separator;
                   14529:                   $ignore=1;
                   14530:                } else {
                   14531: # Found a separator, store away what we got
                   14532:                   $components{&takeleft($i)}=$field;
                   14533: 	          $i++;
                   14534:                   $just_found_separator=1;
                   14535:                   $ignore=0;
                   14536:                   $field='';
                   14537:                }
                   14538:                next;
                   14539:             }
                   14540: # single or double quotation marks after a separator indicate beginning of a quote
                   14541: # we are now looking for the end of the quote and need to ignore separators
                   14542:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   14543:                $looking_for=$character;
                   14544:                next;
                   14545:             }
                   14546: # ignore would be true after we reached the end of a quote
                   14547:             if ($ignore) { next; }
                   14548:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   14549:             $field.=$character;
                   14550:             $just_found_separator=0; 
1.31      albertel 14551:         }
1.561     www      14552: # catch the very last entry, since we never encountered the separator
                   14553:         $components{&takeleft($i)}=$field;
1.31      albertel 14554:     }
                   14555:     return %components;
                   14556: }
                   14557: 
1.144     matthew  14558: ######################################################
                   14559: ######################################################
                   14560: 
1.56      matthew  14561: =pod
                   14562: 
1.648     raeburn  14563: =item * &upfile_select_html()
1.41      ng       14564: 
1.144     matthew  14565: Return HTML code to select a file from the users machine and specify 
                   14566: the file type.
1.41      ng       14567: 
                   14568: =cut
                   14569: 
1.144     matthew  14570: ######################################################
                   14571: ######################################################
1.31      albertel 14572: sub upfile_select_html {
1.144     matthew  14573:     my %Types = (
                   14574:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 14575:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  14576:                  space => &mt('Space separated'),
                   14577:                  tab   => &mt('Tabulator separated'),
                   14578: #                 xml   => &mt('HTML/XML'),
                   14579:                  );
                   14580:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  14581:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  14582:     foreach my $type (sort(keys(%Types))) {
                   14583:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   14584:     }
                   14585:     $Str .= "</select>\n";
                   14586:     return $Str;
1.31      albertel 14587: }
                   14588: 
1.301     albertel 14589: sub get_samples {
                   14590:     my ($records,$toget) = @_;
                   14591:     my @samples=({});
                   14592:     my $got=0;
                   14593:     foreach my $rec (@$records) {
                   14594: 	my %temp = &record_sep($rec);
                   14595: 	if (! grep(/\S/, values(%temp))) { next; }
                   14596: 	if (%temp) {
                   14597: 	    $samples[$got]=\%temp;
                   14598: 	    $got++;
                   14599: 	    if ($got == $toget) { last; }
                   14600: 	}
                   14601:     }
                   14602:     return \@samples;
                   14603: }
                   14604: 
1.144     matthew  14605: ######################################################
                   14606: ######################################################
                   14607: 
1.56      matthew  14608: =pod
                   14609: 
1.648     raeburn  14610: =item * &csv_print_samples($r,$records)
1.41      ng       14611: 
                   14612: Prints a table of sample values from each column uploaded $r is an
                   14613: Apache Request ref, $records is an arrayref from
                   14614: &Apache::loncommon::upfile_record_sep
                   14615: 
                   14616: =cut
                   14617: 
1.144     matthew  14618: ######################################################
                   14619: ######################################################
1.31      albertel 14620: sub csv_print_samples {
                   14621:     my ($r,$records) = @_;
1.662     bisitz   14622:     my $samples = &get_samples($records,5);
1.301     albertel 14623: 
1.594     raeburn  14624:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   14625:               &start_data_table_header_row());
1.356     albertel 14626:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   14627:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  14628:     $r->print(&end_data_table_header_row());
1.301     albertel 14629:     foreach my $hash (@$samples) {
1.594     raeburn  14630: 	$r->print(&start_data_table_row());
1.356     albertel 14631: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 14632: 	    $r->print('<td>');
1.356     albertel 14633: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 14634: 	    $r->print('</td>');
                   14635: 	}
1.594     raeburn  14636: 	$r->print(&end_data_table_row());
1.31      albertel 14637:     }
1.594     raeburn  14638:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 14639: }
                   14640: 
1.144     matthew  14641: ######################################################
                   14642: ######################################################
                   14643: 
1.56      matthew  14644: =pod
                   14645: 
1.648     raeburn  14646: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       14647: 
                   14648: Prints a table to create associations between values and table columns.
1.144     matthew  14649: 
1.41      ng       14650: $r is an Apache Request ref,
                   14651: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  14652: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       14653: 
                   14654: =cut
                   14655: 
1.144     matthew  14656: ######################################################
                   14657: ######################################################
1.31      albertel 14658: sub csv_print_select_table {
                   14659:     my ($r,$records,$d) = @_;
1.301     albertel 14660:     my $i=0;
                   14661:     my $samples = &get_samples($records,1);
1.144     matthew  14662:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  14663: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  14664:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  14665:               '<th>'.&mt('Column').'</th>'.
                   14666:               &end_data_table_header_row()."\n");
1.356     albertel 14667:     foreach my $array_ref (@$d) {
                   14668: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  14669: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 14670: 
1.875     bisitz   14671: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  14672: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 14673: 	$r->print('<option value="none"></option>');
1.356     albertel 14674: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   14675: 	    $r->print('<option value="'.$sample.'"'.
                   14676:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   14677:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 14678: 	}
1.594     raeburn  14679: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 14680: 	$i++;
                   14681:     }
1.594     raeburn  14682:     $r->print(&end_data_table());
1.31      albertel 14683:     $i--;
                   14684:     return $i;
                   14685: }
1.56      matthew  14686: 
1.144     matthew  14687: ######################################################
                   14688: ######################################################
                   14689: 
1.56      matthew  14690: =pod
1.31      albertel 14691: 
1.648     raeburn  14692: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       14693: 
                   14694: Prints a table of sample values from the upload and can make associate samples to internal names.
                   14695: 
                   14696: $r is an Apache Request ref,
                   14697: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   14698: $d is an array of 2 element arrays (internal name, displayed name)
                   14699: 
                   14700: =cut
                   14701: 
1.144     matthew  14702: ######################################################
                   14703: ######################################################
1.31      albertel 14704: sub csv_samples_select_table {
                   14705:     my ($r,$records,$d) = @_;
                   14706:     my $i=0;
1.144     matthew  14707:     #
1.662     bisitz   14708:     my $max_samples = 5;
                   14709:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  14710:     $r->print(&start_data_table().
                   14711:               &start_data_table_header_row().'<th>'.
                   14712:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   14713:               &end_data_table_header_row());
1.301     albertel 14714: 
                   14715:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  14716: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  14717: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 14718: 	foreach my $option (@$d) {
                   14719: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  14720: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 14721:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  14722:                       $display.'</option>');
1.31      albertel 14723: 	}
                   14724: 	$r->print('</select></td><td>');
1.662     bisitz   14725: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 14726: 	    if (defined($samples->[$line]{$key})) { 
                   14727: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   14728: 	    }
                   14729: 	}
1.594     raeburn  14730: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 14731: 	$i++;
                   14732:     }
1.594     raeburn  14733:     $r->print(&end_data_table());
1.31      albertel 14734:     $i--;
                   14735:     return($i);
1.115     matthew  14736: }
                   14737: 
1.144     matthew  14738: ######################################################
                   14739: ######################################################
                   14740: 
1.115     matthew  14741: =pod
                   14742: 
1.648     raeburn  14743: =item * &clean_excel_name($name)
1.115     matthew  14744: 
                   14745: Returns a replacement for $name which does not contain any illegal characters.
                   14746: 
                   14747: =cut
                   14748: 
1.144     matthew  14749: ######################################################
                   14750: ######################################################
1.115     matthew  14751: sub clean_excel_name {
                   14752:     my ($name) = @_;
                   14753:     $name =~ s/[:\*\?\/\\]//g;
                   14754:     if (length($name) > 31) {
                   14755:         $name = substr($name,0,31);
                   14756:     }
                   14757:     return $name;
1.25      albertel 14758: }
1.84      albertel 14759: 
1.85      albertel 14760: =pod
                   14761: 
1.648     raeburn  14762: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 14763: 
                   14764: Returns either 1 or undef
                   14765: 
                   14766: 1 if the part is to be hidden, undef if it is to be shown
                   14767: 
                   14768: Arguments are:
                   14769: 
                   14770: $id the id of the part to be checked
                   14771: $symb, optional the symb of the resource to check
                   14772: $udom, optional the domain of the user to check for
                   14773: $uname, optional the username of the user to check for
                   14774: 
                   14775: =cut
1.84      albertel 14776: 
                   14777: sub check_if_partid_hidden {
                   14778:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 14779:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 14780: 					 $symb,$udom,$uname);
1.141     albertel 14781:     my $truth=1;
                   14782:     #if the string starts with !, then the list is the list to show not hide
                   14783:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 14784:     my @hiddenlist=split(/,/,$hiddenparts);
                   14785:     foreach my $checkid (@hiddenlist) {
1.141     albertel 14786: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 14787:     }
1.141     albertel 14788:     return !$truth;
1.84      albertel 14789: }
1.127     matthew  14790: 
1.138     matthew  14791: 
                   14792: ############################################################
                   14793: ############################################################
                   14794: 
                   14795: =pod
                   14796: 
1.157     matthew  14797: =back 
                   14798: 
1.138     matthew  14799: =head1 cgi-bin script and graphing routines
                   14800: 
1.157     matthew  14801: =over 4
                   14802: 
1.648     raeburn  14803: =item * &get_cgi_id()
1.138     matthew  14804: 
                   14805: Inputs: none
                   14806: 
                   14807: Returns an id which can be used to pass environment variables
                   14808: to various cgi-bin scripts.  These environment variables will
                   14809: be removed from the users environment after a given time by
                   14810: the routine &Apache::lonnet::transfer_profile_to_env.
                   14811: 
                   14812: =cut
                   14813: 
                   14814: ############################################################
                   14815: ############################################################
1.152     albertel 14816: my $uniq=0;
1.136     matthew  14817: sub get_cgi_id {
1.154     albertel 14818:     $uniq=($uniq+1)%100000;
1.280     albertel 14819:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  14820: }
                   14821: 
1.127     matthew  14822: ############################################################
                   14823: ############################################################
                   14824: 
                   14825: =pod
                   14826: 
1.648     raeburn  14827: =item * &DrawBarGraph()
1.127     matthew  14828: 
1.138     matthew  14829: Facilitates the plotting of data in a (stacked) bar graph.
                   14830: Puts plot definition data into the users environment in order for 
                   14831: graph.png to plot it.  Returns an <img> tag for the plot.
                   14832: The bars on the plot are labeled '1','2',...,'n'.
                   14833: 
                   14834: Inputs:
                   14835: 
                   14836: =over 4
                   14837: 
                   14838: =item $Title: string, the title of the plot
                   14839: 
                   14840: =item $xlabel: string, text describing the X-axis of the plot
                   14841: 
                   14842: =item $ylabel: string, text describing the Y-axis of the plot
                   14843: 
                   14844: =item $Max: scalar, the maximum Y value to use in the plot
                   14845: If $Max is < any data point, the graph will not be rendered.
                   14846: 
1.140     matthew  14847: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  14848: they are plotted.  If undefined, default values will be used.
                   14849: 
1.178     matthew  14850: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   14851: 
1.138     matthew  14852: =item @Values: An array of array references.  Each array reference holds data
                   14853: to be plotted in a stacked bar chart.
                   14854: 
1.239     matthew  14855: =item If the final element of @Values is a hash reference the key/value
                   14856: pairs will be added to the graph definition.
                   14857: 
1.138     matthew  14858: =back
                   14859: 
                   14860: Returns:
                   14861: 
                   14862: An <img> tag which references graph.png and the appropriate identifying
                   14863: information for the plot.
                   14864: 
1.127     matthew  14865: =cut
                   14866: 
                   14867: ############################################################
                   14868: ############################################################
1.134     matthew  14869: sub DrawBarGraph {
1.178     matthew  14870:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  14871:     #
                   14872:     if (! defined($colors)) {
                   14873:         $colors = ['#33ff00', 
                   14874:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   14875:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   14876:                   ]; 
                   14877:     }
1.228     matthew  14878:     my $extra_settings = {};
                   14879:     if (ref($Values[-1]) eq 'HASH') {
                   14880:         $extra_settings = pop(@Values);
                   14881:     }
1.127     matthew  14882:     #
1.136     matthew  14883:     my $identifier = &get_cgi_id();
                   14884:     my $id = 'cgi.'.$identifier;        
1.129     matthew  14885:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  14886:         return '';
                   14887:     }
1.225     matthew  14888:     #
                   14889:     my @Labels;
                   14890:     if (defined($labels)) {
                   14891:         @Labels = @$labels;
                   14892:     } else {
                   14893:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  14894:             push(@Labels,$i+1);
1.225     matthew  14895:         }
                   14896:     }
                   14897:     #
1.129     matthew  14898:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  14899:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  14900:     my %ValuesHash;
                   14901:     my $NumSets=1;
                   14902:     foreach my $array (@Values) {
                   14903:         next if (! ref($array));
1.136     matthew  14904:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  14905:             join(',',@$array);
1.129     matthew  14906:     }
1.127     matthew  14907:     #
1.136     matthew  14908:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  14909:     if ($NumBars < 3) {
                   14910:         $width = 120+$NumBars*32;
1.220     matthew  14911:         $xskip = 1;
1.225     matthew  14912:         $bar_width = 30;
                   14913:     } elsif ($NumBars < 5) {
                   14914:         $width = 120+$NumBars*20;
                   14915:         $xskip = 1;
                   14916:         $bar_width = 20;
1.220     matthew  14917:     } elsif ($NumBars < 10) {
1.136     matthew  14918:         $width = 120+$NumBars*15;
                   14919:         $xskip = 1;
                   14920:         $bar_width = 15;
                   14921:     } elsif ($NumBars <= 25) {
                   14922:         $width = 120+$NumBars*11;
                   14923:         $xskip = 5;
                   14924:         $bar_width = 8;
                   14925:     } elsif ($NumBars <= 50) {
                   14926:         $width = 120+$NumBars*8;
                   14927:         $xskip = 5;
                   14928:         $bar_width = 4;
                   14929:     } else {
                   14930:         $width = 120+$NumBars*8;
                   14931:         $xskip = 5;
                   14932:         $bar_width = 4;
                   14933:     }
                   14934:     #
1.137     matthew  14935:     $Max = 1 if ($Max < 1);
                   14936:     if ( int($Max) < $Max ) {
                   14937:         $Max++;
                   14938:         $Max = int($Max);
                   14939:     }
1.127     matthew  14940:     $Title  = '' if (! defined($Title));
                   14941:     $xlabel = '' if (! defined($xlabel));
                   14942:     $ylabel = '' if (! defined($ylabel));
1.369     www      14943:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   14944:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   14945:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  14946:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  14947:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   14948:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   14949:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   14950:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14951:     $ValuesHash{$id.'.height'}   = $height;
                   14952:     $ValuesHash{$id.'.width'}    = $width;
                   14953:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   14954:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   14955:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  14956:     #
1.228     matthew  14957:     # Deal with other parameters
                   14958:     while (my ($key,$value) = each(%$extra_settings)) {
                   14959:         $ValuesHash{$id.'.'.$key} = $value;
                   14960:     }
                   14961:     #
1.646     raeburn  14962:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  14963:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14964: }
                   14965: 
                   14966: ############################################################
                   14967: ############################################################
                   14968: 
                   14969: =pod
                   14970: 
1.648     raeburn  14971: =item * &DrawXYGraph()
1.137     matthew  14972: 
1.138     matthew  14973: Facilitates the plotting of data in an XY graph.
                   14974: Puts plot definition data into the users environment in order for 
                   14975: graph.png to plot it.  Returns an <img> tag for the plot.
                   14976: 
                   14977: Inputs:
                   14978: 
                   14979: =over 4
                   14980: 
                   14981: =item $Title: string, the title of the plot
                   14982: 
                   14983: =item $xlabel: string, text describing the X-axis of the plot
                   14984: 
                   14985: =item $ylabel: string, text describing the Y-axis of the plot
                   14986: 
                   14987: =item $Max: scalar, the maximum Y value to use in the plot
                   14988: If $Max is < any data point, the graph will not be rendered.
                   14989: 
                   14990: =item $colors: Array ref containing the hex color codes for the data to be 
                   14991: plotted in.  If undefined, default values will be used.
                   14992: 
                   14993: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14994: 
                   14995: =item $Ydata: Array ref containing Array refs.  
1.185     www      14996: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  14997: 
                   14998: =item %Values: hash indicating or overriding any default values which are 
                   14999: passed to graph.png.  
                   15000: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15001: 
                   15002: =back
                   15003: 
                   15004: Returns:
                   15005: 
                   15006: An <img> tag which references graph.png and the appropriate identifying
                   15007: information for the plot.
                   15008: 
1.137     matthew  15009: =cut
                   15010: 
                   15011: ############################################################
                   15012: ############################################################
                   15013: sub DrawXYGraph {
                   15014:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   15015:     #
                   15016:     # Create the identifier for the graph
                   15017:     my $identifier = &get_cgi_id();
                   15018:     my $id = 'cgi.'.$identifier;
                   15019:     #
                   15020:     $Title  = '' if (! defined($Title));
                   15021:     $xlabel = '' if (! defined($xlabel));
                   15022:     $ylabel = '' if (! defined($ylabel));
                   15023:     my %ValuesHash = 
                   15024:         (
1.369     www      15025:          $id.'.title'  => &escape($Title),
                   15026:          $id.'.xlabel' => &escape($xlabel),
                   15027:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  15028:          $id.'.y_max_value'=> $Max,
                   15029:          $id.'.labels'     => join(',',@$Xlabels),
                   15030:          $id.'.PlotType'   => 'XY',
                   15031:          );
                   15032:     #
                   15033:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15034:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15035:     }
                   15036:     #
                   15037:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   15038:         return '';
                   15039:     }
                   15040:     my $NumSets=1;
1.138     matthew  15041:     foreach my $array (@{$Ydata}){
1.137     matthew  15042:         next if (! ref($array));
                   15043:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   15044:     }
1.138     matthew  15045:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  15046:     #
                   15047:     # Deal with other parameters
                   15048:     while (my ($key,$value) = each(%Values)) {
                   15049:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  15050:     }
                   15051:     #
1.646     raeburn  15052:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  15053:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15054: }
                   15055: 
                   15056: ############################################################
                   15057: ############################################################
                   15058: 
                   15059: =pod
                   15060: 
1.648     raeburn  15061: =item * &DrawXYYGraph()
1.138     matthew  15062: 
                   15063: Facilitates the plotting of data in an XY graph with two Y axes.
                   15064: Puts plot definition data into the users environment in order for 
                   15065: graph.png to plot it.  Returns an <img> tag for the plot.
                   15066: 
                   15067: Inputs:
                   15068: 
                   15069: =over 4
                   15070: 
                   15071: =item $Title: string, the title of the plot
                   15072: 
                   15073: =item $xlabel: string, text describing the X-axis of the plot
                   15074: 
                   15075: =item $ylabel: string, text describing the Y-axis of the plot
                   15076: 
                   15077: =item $colors: Array ref containing the hex color codes for the data to be 
                   15078: plotted in.  If undefined, default values will be used.
                   15079: 
                   15080: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15081: 
                   15082: =item $Ydata1: The first data set
                   15083: 
                   15084: =item $Min1: The minimum value of the left Y-axis
                   15085: 
                   15086: =item $Max1: The maximum value of the left Y-axis
                   15087: 
                   15088: =item $Ydata2: The second data set
                   15089: 
                   15090: =item $Min2: The minimum value of the right Y-axis
                   15091: 
                   15092: =item $Max2: The maximum value of the left Y-axis
                   15093: 
                   15094: =item %Values: hash indicating or overriding any default values which are 
                   15095: passed to graph.png.  
                   15096: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15097: 
                   15098: =back
                   15099: 
                   15100: Returns:
                   15101: 
                   15102: An <img> tag which references graph.png and the appropriate identifying
                   15103: information for the plot.
1.136     matthew  15104: 
                   15105: =cut
                   15106: 
                   15107: ############################################################
                   15108: ############################################################
1.137     matthew  15109: sub DrawXYYGraph {
                   15110:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   15111:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  15112:     #
                   15113:     # Create the identifier for the graph
                   15114:     my $identifier = &get_cgi_id();
                   15115:     my $id = 'cgi.'.$identifier;
                   15116:     #
                   15117:     $Title  = '' if (! defined($Title));
                   15118:     $xlabel = '' if (! defined($xlabel));
                   15119:     $ylabel = '' if (! defined($ylabel));
                   15120:     my %ValuesHash = 
                   15121:         (
1.369     www      15122:          $id.'.title'  => &escape($Title),
                   15123:          $id.'.xlabel' => &escape($xlabel),
                   15124:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  15125:          $id.'.labels' => join(',',@$Xlabels),
                   15126:          $id.'.PlotType' => 'XY',
                   15127:          $id.'.NumSets' => 2,
1.137     matthew  15128:          $id.'.two_axes' => 1,
                   15129:          $id.'.y1_max_value' => $Max1,
                   15130:          $id.'.y1_min_value' => $Min1,
                   15131:          $id.'.y2_max_value' => $Max2,
                   15132:          $id.'.y2_min_value' => $Min2,
1.136     matthew  15133:          );
                   15134:     #
1.137     matthew  15135:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15136:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15137:     }
                   15138:     #
                   15139:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   15140:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  15141:         return '';
                   15142:     }
                   15143:     my $NumSets=1;
1.137     matthew  15144:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  15145:         next if (! ref($array));
                   15146:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  15147:     }
                   15148:     #
                   15149:     # Deal with other parameters
                   15150:     while (my ($key,$value) = each(%Values)) {
                   15151:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  15152:     }
                   15153:     #
1.646     raeburn  15154:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 15155:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  15156: }
                   15157: 
                   15158: ############################################################
                   15159: ############################################################
                   15160: 
                   15161: =pod
                   15162: 
1.157     matthew  15163: =back 
                   15164: 
1.139     matthew  15165: =head1 Statistics helper routines?  
                   15166: 
                   15167: Bad place for them but what the hell.
                   15168: 
1.157     matthew  15169: =over 4
                   15170: 
1.648     raeburn  15171: =item * &chartlink()
1.139     matthew  15172: 
                   15173: Returns a link to the chart for a specific student.  
                   15174: 
                   15175: Inputs:
                   15176: 
                   15177: =over 4
                   15178: 
                   15179: =item $linktext: The text of the link
                   15180: 
                   15181: =item $sname: The students username
                   15182: 
                   15183: =item $sdomain: The students domain
                   15184: 
                   15185: =back
                   15186: 
1.157     matthew  15187: =back
                   15188: 
1.139     matthew  15189: =cut
                   15190: 
                   15191: ############################################################
                   15192: ############################################################
                   15193: sub chartlink {
                   15194:     my ($linktext, $sname, $sdomain) = @_;
                   15195:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      15196:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 15197:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  15198:        '">'.$linktext.'</a>';
1.153     matthew  15199: }
                   15200: 
                   15201: #######################################################
                   15202: #######################################################
                   15203: 
                   15204: =pod
                   15205: 
                   15206: =head1 Course Environment Routines
1.157     matthew  15207: 
                   15208: =over 4
1.153     matthew  15209: 
1.648     raeburn  15210: =item * &restore_course_settings()
1.153     matthew  15211: 
1.648     raeburn  15212: =item * &store_course_settings()
1.153     matthew  15213: 
                   15214: Restores/Store indicated form parameters from the course environment.
                   15215: Will not overwrite existing values of the form parameters.
                   15216: 
                   15217: Inputs: 
                   15218: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   15219: 
                   15220: a hash ref describing the data to be stored.  For example:
                   15221:    
                   15222: %Save_Parameters = ('Status' => 'scalar',
                   15223:     'chartoutputmode' => 'scalar',
                   15224:     'chartoutputdata' => 'scalar',
                   15225:     'Section' => 'array',
1.373     raeburn  15226:     'Group' => 'array',
1.153     matthew  15227:     'StudentData' => 'array',
                   15228:     'Maps' => 'array');
                   15229: 
                   15230: Returns: both routines return nothing
                   15231: 
1.631     raeburn  15232: =back
                   15233: 
1.153     matthew  15234: =cut
                   15235: 
                   15236: #######################################################
                   15237: #######################################################
                   15238: sub store_course_settings {
1.496     albertel 15239:     return &store_settings($env{'request.course.id'},@_);
                   15240: }
                   15241: 
                   15242: sub store_settings {
1.153     matthew  15243:     # save to the environment
                   15244:     # appenv the same items, just to be safe
1.300     albertel 15245:     my $udom  = $env{'user.domain'};
                   15246:     my $uname = $env{'user.name'};
1.496     albertel 15247:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15248:     my %SaveHash;
                   15249:     my %AppHash;
                   15250:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 15251:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 15252:         my $envname = 'environment.'.$basename;
1.258     albertel 15253:         if (exists($env{'form.'.$setting})) {
1.153     matthew  15254:             # Save this value away
                   15255:             if ($type eq 'scalar' &&
1.258     albertel 15256:                 (! exists($env{$envname}) || 
                   15257:                  $env{$envname} ne $env{'form.'.$setting})) {
                   15258:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   15259:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  15260:             } elsif ($type eq 'array') {
                   15261:                 my $stored_form;
1.258     albertel 15262:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  15263:                     $stored_form = join(',',
                   15264:                                         map {
1.369     www      15265:                                             &escape($_);
1.258     albertel 15266:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  15267:                 } else {
                   15268:                     $stored_form = 
1.369     www      15269:                         &escape($env{'form.'.$setting});
1.153     matthew  15270:                 }
                   15271:                 # Determine if the array contents are the same.
1.258     albertel 15272:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  15273:                     $SaveHash{$basename} = $stored_form;
                   15274:                     $AppHash{$envname}   = $stored_form;
                   15275:                 }
                   15276:             }
                   15277:         }
                   15278:     }
                   15279:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 15280:                                           $udom,$uname);
1.153     matthew  15281:     if ($put_result !~ /^(ok|delayed)/) {
                   15282:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   15283:                                  'got error:'.$put_result);
                   15284:     }
                   15285:     # Make sure these settings stick around in this session, too
1.646     raeburn  15286:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  15287:     return;
                   15288: }
                   15289: 
                   15290: sub restore_course_settings {
1.499     albertel 15291:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 15292: }
                   15293: 
                   15294: sub restore_settings {
                   15295:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15296:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 15297:         next if (exists($env{'form.'.$setting}));
1.496     albertel 15298:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  15299:             '.'.$setting;
1.258     albertel 15300:         if (exists($env{$envname})) {
1.153     matthew  15301:             if ($type eq 'scalar') {
1.258     albertel 15302:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  15303:             } elsif ($type eq 'array') {
1.258     albertel 15304:                 $env{'form.'.$setting} = [ 
1.153     matthew  15305:                                            map { 
1.369     www      15306:                                                &unescape($_); 
1.258     albertel 15307:                                            } split(',',$env{$envname})
1.153     matthew  15308:                                            ];
                   15309:             }
                   15310:         }
                   15311:     }
1.127     matthew  15312: }
                   15313: 
1.618     raeburn  15314: #######################################################
                   15315: #######################################################
                   15316: 
                   15317: =pod
                   15318: 
                   15319: =head1 Domain E-mail Routines  
                   15320: 
                   15321: =over 4
                   15322: 
1.648     raeburn  15323: =item * &build_recipient_list()
1.618     raeburn  15324: 
1.1144    raeburn  15325: Build recipient lists for following types of e-mail:
1.766     raeburn  15326: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  15327: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   15328: module change checking, student/employee ID conflict checks, as
                   15329: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   15330: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  15331: 
                   15332: Inputs:
1.619     raeburn  15333: defmail (scalar - email address of default recipient), 
1.1144    raeburn  15334: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   15335: requestsmail, updatesmail, or idconflictsmail).
                   15336: 
1.619     raeburn  15337: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  15338: 
1.619     raeburn  15339: origmail (scalar - email address of recipient from loncapa.conf, 
1.1297    raeburn  15340: i.e., predates configuration by DC via domainprefs.pm
                   15341: 
                   15342: $requname username of requester (if mailing type is helpdeskmail)
                   15343: 
                   15344: $requdom domain of requester (if mailing type is helpdeskmail)
                   15345: 
                   15346: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   15347: 
1.618     raeburn  15348: 
1.655     raeburn  15349: Returns: comma separated list of addresses to which to send e-mail.
                   15350: 
                   15351: =back
1.618     raeburn  15352: 
                   15353: =cut
                   15354: 
                   15355: ############################################################
                   15356: ############################################################
                   15357: sub build_recipient_list {
1.1297    raeburn  15358:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  15359:     my @recipients;
1.1270    raeburn  15360:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  15361:     my %domconfig =
1.1270    raeburn  15362:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  15363:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  15364:         if (exists($domconfig{'contacts'}{$mailing})) {
                   15365:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   15366:                 my @contacts = ('adminemail','supportemail');
                   15367:                 foreach my $item (@contacts) {
                   15368:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   15369:                         my $addr = $domconfig{'contacts'}{$item}; 
                   15370:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15371:                             push(@recipients,$addr);
                   15372:                         }
1.619     raeburn  15373:                     }
1.1270    raeburn  15374:                 }
                   15375:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   15376:                 if ($mailing eq 'helpdeskmail') {
                   15377:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   15378:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   15379:                         my @ok_bccs;
                   15380:                         foreach my $bcc (@bccs) {
                   15381:                             $bcc =~ s/^\s+//g;
                   15382:                             $bcc =~ s/\s+$//g;
                   15383:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15384:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15385:                                     push(@ok_bccs,$bcc);
                   15386:                                 }
                   15387:                             }
                   15388:                         }
                   15389:                         if (@ok_bccs > 0) {
                   15390:                             $allbcc = join(', ',@ok_bccs);
                   15391:                         }
                   15392:                     }
                   15393:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  15394:                 }
                   15395:             }
1.766     raeburn  15396:         } elsif ($origmail ne '') {
1.1270    raeburn  15397:             $lastresort = $origmail;
1.618     raeburn  15398:         }
1.1297    raeburn  15399:         if ($mailing eq 'helpdeskmail') {
                   15400:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   15401:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   15402:                 my ($inststatus,$inststatus_checked);
                   15403:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   15404:                     ($env{'user.domain'} ne 'public')) {
                   15405:                     $inststatus_checked = 1;
                   15406:                     $inststatus = $env{'environment.inststatus'};
                   15407:                 }
                   15408:                 unless ($inststatus_checked) {
                   15409:                     if (($requname ne '') && ($requdom ne '')) {
                   15410:                         if (($requname =~ /^$match_username$/) &&
                   15411:                             ($requdom =~ /^$match_domain$/) &&
                   15412:                             (&Apache::lonnet::domain($requdom))) {
                   15413:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   15414:                                                                       $requdom);
                   15415:                             unless ($requhome eq 'no_host') {
                   15416:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   15417:                                 $inststatus = $userenv{'inststatus'};
                   15418:                                 $inststatus_checked = 1;
                   15419:                             }
                   15420:                         }
                   15421:                     }
                   15422:                 }
                   15423:                 unless ($inststatus_checked) {
                   15424:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   15425:                         my %srch = (srchby     => 'email',
                   15426:                                     srchdomain => $defdom,
                   15427:                                     srchterm   => $reqemail,
                   15428:                                     srchtype   => 'exact');
                   15429:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   15430:                         foreach my $uname (keys(%srch_results)) {
                   15431:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15432:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15433:                                 $inststatus_checked = 1;
                   15434:                                 last;
                   15435:                             }
                   15436:                         }
                   15437:                         unless ($inststatus_checked) {
                   15438:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   15439:                             if ($dirsrchres eq 'ok') {
                   15440:                                 foreach my $uname (keys(%srch_results)) {
                   15441:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15442:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15443:                                         $inststatus_checked = 1;
                   15444:                                         last;
                   15445:                                     }
                   15446:                                 }
                   15447:                             }
                   15448:                         }
                   15449:                     }
                   15450:                 }
                   15451:                 if ($inststatus ne '') {
                   15452:                     foreach my $status (split(/\:/,$inststatus)) {
                   15453:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   15454:                             my @contacts = ('adminemail','supportemail');
                   15455:                             foreach my $item (@contacts) {
                   15456:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   15457:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   15458:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15459:                                         push(@recipients,$addr);
                   15460:                                     }
                   15461:                                 }
                   15462:                             }
                   15463:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   15464:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   15465:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   15466:                                 my @ok_bccs;
                   15467:                                 foreach my $bcc (@bccs) {
                   15468:                                     $bcc =~ s/^\s+//g;
                   15469:                                     $bcc =~ s/\s+$//g;
                   15470:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15471:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15472:                                             push(@ok_bccs,$bcc);
                   15473:                                         }
                   15474:                                     }
                   15475:                                 }
                   15476:                                 if (@ok_bccs > 0) {
                   15477:                                     $allbcc = join(', ',@ok_bccs);
                   15478:                                 }
                   15479:                             }
                   15480:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   15481:                             last;
                   15482:                         }
                   15483:                     }
                   15484:                 }
                   15485:             }
                   15486:         }
1.619     raeburn  15487:     } elsif ($origmail ne '') {
1.1270    raeburn  15488:         $lastresort = $origmail;
                   15489:     }
1.1297    raeburn  15490:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1270    raeburn  15491:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   15492:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   15493:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   15494:             my %what = (
                   15495:                           perlvar => 1,
                   15496:                        );
                   15497:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   15498:             if ($primary) {
                   15499:                 my $gotaddr;
                   15500:                 my ($result,$returnhash) =
                   15501:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   15502:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   15503:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   15504:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   15505:                         $gotaddr = 1;
                   15506:                     }
                   15507:                 }
                   15508:                 unless ($gotaddr) {
                   15509:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   15510:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   15511:                     unless ($uintdom eq $intdom) {
                   15512:                         my %domconfig =
                   15513:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   15514:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   15515:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   15516:                                 my @contacts = ('adminemail','supportemail');
                   15517:                                 foreach my $item (@contacts) {
                   15518:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   15519:                                         my $addr = $domconfig{'contacts'}{$item};
                   15520:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15521:                                             push(@recipients,$addr);
                   15522:                                         }
                   15523:                                     }
                   15524:                                 }
                   15525:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   15526:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   15527:                                 }
                   15528:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   15529:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   15530:                                     my @ok_bccs;
                   15531:                                     foreach my $bcc (@bccs) {
                   15532:                                         $bcc =~ s/^\s+//g;
                   15533:                                         $bcc =~ s/\s+$//g;
                   15534:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15535:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15536:                                                 push(@ok_bccs,$bcc);
                   15537:                                             }
                   15538:                                         }
                   15539:                                     }
                   15540:                                     if (@ok_bccs > 0) {
                   15541:                                         $allbcc = join(', ',@ok_bccs);
                   15542:                                     }
                   15543:                                 }
                   15544:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   15545:                             }
                   15546:                         }
                   15547:                     }
                   15548:                 }
                   15549:             }
                   15550:         }
1.618     raeburn  15551:     }
1.688     raeburn  15552:     if (defined($defmail)) {
                   15553:         if ($defmail ne '') {
                   15554:             push(@recipients,$defmail);
                   15555:         }
1.618     raeburn  15556:     }
                   15557:     if ($otheremails) {
1.619     raeburn  15558:         my @others;
                   15559:         if ($otheremails =~ /,/) {
                   15560:             @others = split(/,/,$otheremails);
1.618     raeburn  15561:         } else {
1.619     raeburn  15562:             push(@others,$otheremails);
                   15563:         }
                   15564:         foreach my $addr (@others) {
                   15565:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15566:                 push(@recipients,$addr);
                   15567:             }
1.618     raeburn  15568:         }
                   15569:     }
1.1298    raeburn  15570:     if ($mailing eq 'helpdeskmail') {
1.1270    raeburn  15571:         if ((!@recipients) && ($lastresort ne '')) {
                   15572:             push(@recipients,$lastresort);
                   15573:         }
                   15574:     } elsif ($lastresort ne '') {
                   15575:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   15576:             push(@recipients,$lastresort);
                   15577:         }
                   15578:     }
1.1271    raeburn  15579:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  15580:     if (wantarray) {
                   15581:         return ($recipientlist,$allbcc,$addtext);
                   15582:     } else {
                   15583:         return $recipientlist;
                   15584:     }
1.618     raeburn  15585: }
                   15586: 
1.127     matthew  15587: ############################################################
                   15588: ############################################################
1.154     albertel 15589: 
1.655     raeburn  15590: =pod
                   15591: 
1.1224    musolffc 15592: =over 4
                   15593: 
1.1223    musolffc 15594: =item * &mime_email()
                   15595: 
                   15596: Sends an email with a possible attachment
                   15597: 
                   15598: Inputs:
                   15599: 
                   15600: =over 4
                   15601: 
                   15602: from -              Sender's email address
                   15603: 
1.1343    raeburn  15604: replyto -           Reply-To email address
                   15605: 
1.1223    musolffc 15606: to -                Email address of recipient
                   15607: 
                   15608: subject -           Subject of email
                   15609: 
                   15610: body -              Body of email
                   15611: 
                   15612: cc_string -         Carbon copy email address
                   15613: 
                   15614: bcc -               Blind carbon copy email address
                   15615: 
                   15616: attachment_path -   Path of file to be attached
                   15617: 
                   15618: file_name -         Name of file to be attached
                   15619: 
                   15620: attachment_text -   The body of an attachment of type "TEXT"
                   15621: 
                   15622: =back
                   15623: 
                   15624: =back
                   15625: 
                   15626: =cut
                   15627: 
                   15628: ############################################################
                   15629: ############################################################
                   15630: 
                   15631: sub mime_email {
1.1343    raeburn  15632:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
                   15633:         $file_name,$attachment_text) = @_;
                   15634:  
1.1223    musolffc 15635:     my $msg = MIME::Lite->new(
                   15636:              From    => $from,
                   15637:              To      => $to,
                   15638:              Subject => $subject,
                   15639:              Type    =>'TEXT',
                   15640:              Data    => $body,
                   15641:              );
1.1343    raeburn  15642:     if ($replyto ne '') {
                   15643:         $msg->add("Reply-To" => $replyto);
                   15644:     }
1.1223    musolffc 15645:     if ($cc_string ne '') {
                   15646:         $msg->add("Cc" => $cc_string);
                   15647:     }
                   15648:     if ($bcc ne '') {
                   15649:         $msg->add("Bcc" => $bcc);
                   15650:     }
                   15651:     $msg->attr("content-type"         => "text/plain");
                   15652:     $msg->attr("content-type.charset" => "UTF-8");
                   15653:     # Attach file if given
                   15654:     if ($attachment_path) {
                   15655:         unless ($file_name) {
                   15656:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   15657:         }
                   15658:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   15659:         $msg->attach(Type     => $type,
                   15660:                      Path     => $attachment_path,
                   15661:                      Filename => $file_name
                   15662:                      );
                   15663:     # Otherwise attach text if given
                   15664:     } elsif ($attachment_text) {
                   15665:         $msg->attach(Type => 'TEXT',
                   15666:                      Data => $attachment_text);
                   15667:     }
                   15668:     # Send it
                   15669:     $msg->send('sendmail');
                   15670: }
                   15671: 
                   15672: ############################################################
                   15673: ############################################################
                   15674: 
                   15675: =pod
                   15676: 
1.655     raeburn  15677: =head1 Course Catalog Routines
                   15678: 
                   15679: =over 4
                   15680: 
                   15681: =item * &gather_categories()
                   15682: 
                   15683: Converts category definitions - keys of categories hash stored in  
                   15684: coursecategories in configuration.db on the primary library server in a 
                   15685: domain - to an array.  Also generates javascript and idx hash used to 
                   15686: generate Domain Coordinator interface for editing Course Categories.
                   15687: 
                   15688: Inputs:
1.663     raeburn  15689: 
1.655     raeburn  15690: categories (reference to hash of category definitions).
1.663     raeburn  15691: 
1.655     raeburn  15692: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15693:       categories and subcategories).
1.663     raeburn  15694: 
1.655     raeburn  15695: idx (reference to hash of counters used in Domain Coordinator interface for 
                   15696:       editing Course Categories).
1.663     raeburn  15697: 
1.655     raeburn  15698: jsarray (reference to array of categories used to create Javascript arrays for
                   15699:          Domain Coordinator interface for editing Course Categories).
                   15700: 
                   15701: Returns: nothing
                   15702: 
                   15703: Side effects: populates cats, idx and jsarray. 
                   15704: 
                   15705: =cut
                   15706: 
                   15707: sub gather_categories {
                   15708:     my ($categories,$cats,$idx,$jsarray) = @_;
                   15709:     my %counters;
                   15710:     my $num = 0;
                   15711:     foreach my $item (keys(%{$categories})) {
                   15712:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   15713:         if ($container eq '' && $depth == 0) {
                   15714:             $cats->[$depth][$categories->{$item}] = $cat;
                   15715:         } else {
                   15716:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   15717:         }
                   15718:         my ($escitem,$tail) = split(/:/,$item,2);
                   15719:         if ($counters{$tail} eq '') {
                   15720:             $counters{$tail} = $num;
                   15721:             $num ++;
                   15722:         }
                   15723:         if (ref($idx) eq 'HASH') {
                   15724:             $idx->{$item} = $counters{$tail};
                   15725:         }
                   15726:         if (ref($jsarray) eq 'ARRAY') {
                   15727:             push(@{$jsarray->[$counters{$tail}]},$item);
                   15728:         }
                   15729:     }
                   15730:     return;
                   15731: }
                   15732: 
                   15733: =pod
                   15734: 
                   15735: =item * &extract_categories()
                   15736: 
                   15737: Used to generate breadcrumb trails for course categories.
                   15738: 
                   15739: Inputs:
1.663     raeburn  15740: 
1.655     raeburn  15741: categories (reference to hash of category definitions).
1.663     raeburn  15742: 
1.655     raeburn  15743: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15744:       categories and subcategories).
1.663     raeburn  15745: 
1.655     raeburn  15746: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  15747: 
1.655     raeburn  15748: allitems (reference to hash - key is category key 
                   15749:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15750: 
1.655     raeburn  15751: idx (reference to hash of counters used in Domain Coordinator interface for
                   15752:       editing Course Categories).
1.663     raeburn  15753: 
1.655     raeburn  15754: jsarray (reference to array of categories used to create Javascript arrays for
                   15755:          Domain Coordinator interface for editing Course Categories).
                   15756: 
1.665     raeburn  15757: subcats (reference to hash of arrays containing all subcategories within each 
                   15758:          category, -recursive)
                   15759: 
1.1321    raeburn  15760: maxd (reference to hash used to hold max depth for all top-level categories).
                   15761: 
1.655     raeburn  15762: Returns: nothing
                   15763: 
                   15764: Side effects: populates trails and allitems hash references.
                   15765: 
                   15766: =cut
                   15767: 
                   15768: sub extract_categories {
1.1321    raeburn  15769:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  15770:     if (ref($categories) eq 'HASH') {
                   15771:         &gather_categories($categories,$cats,$idx,$jsarray);
                   15772:         if (ref($cats->[0]) eq 'ARRAY') {
                   15773:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   15774:                 my $name = $cats->[0][$i];
                   15775:                 my $item = &escape($name).'::0';
                   15776:                 my $trailstr;
                   15777:                 if ($name eq 'instcode') {
                   15778:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  15779:                 } elsif ($name eq 'communities') {
                   15780:                     $trailstr = &mt('Communities');
1.1239    raeburn  15781:                 } elsif ($name eq 'placement') {
                   15782:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  15783:                 } else {
                   15784:                     $trailstr = $name;
                   15785:                 }
                   15786:                 if ($allitems->{$item} eq '') {
                   15787:                     push(@{$trails},$trailstr);
                   15788:                     $allitems->{$item} = scalar(@{$trails})-1;
                   15789:                 }
                   15790:                 my @parents = ($name);
                   15791:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   15792:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   15793:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  15794:                         if (ref($subcats) eq 'HASH') {
                   15795:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   15796:                         }
1.1321    raeburn  15797:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  15798:                     }
                   15799:                 } else {
                   15800:                     if (ref($subcats) eq 'HASH') {
                   15801:                         $subcats->{$item} = [];
1.655     raeburn  15802:                     }
1.1321    raeburn  15803:                     if (ref($maxd) eq 'HASH') {
                   15804:                         $maxd->{$name} = 1;
                   15805:                     }
1.655     raeburn  15806:                 }
                   15807:             }
                   15808:         }
                   15809:     }
                   15810:     return;
                   15811: }
                   15812: 
                   15813: =pod
                   15814: 
1.1162    raeburn  15815: =item * &recurse_categories()
1.655     raeburn  15816: 
                   15817: Recursively used to generate breadcrumb trails for course categories.
                   15818: 
                   15819: Inputs:
1.663     raeburn  15820: 
1.655     raeburn  15821: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15822:       categories and subcategories).
1.663     raeburn  15823: 
1.655     raeburn  15824: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  15825: 
                   15826: category (current course category, for which breadcrumb trail is being generated).
                   15827: 
                   15828: trails (reference to array of breadcrumb trails for each category).
                   15829: 
1.655     raeburn  15830: allitems (reference to hash - key is category key
                   15831:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15832: 
1.655     raeburn  15833: parents (array containing containers directories for current category, 
                   15834:          back to top level). 
                   15835: 
                   15836: Returns: nothing
                   15837: 
                   15838: Side effects: populates trails and allitems hash references
                   15839: 
                   15840: =cut
                   15841: 
                   15842: sub recurse_categories {
1.1321    raeburn  15843:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  15844:     my $shallower = $depth - 1;
                   15845:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   15846:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   15847:             my $name = $cats->[$depth]{$category}[$k];
                   15848:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  15849:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  15850:             if ($allitems->{$item} eq '') {
                   15851:                 push(@{$trails},$trailstr);
                   15852:                 $allitems->{$item} = scalar(@{$trails})-1;
                   15853:             }
                   15854:             my $deeper = $depth+1;
                   15855:             push(@{$parents},$category);
1.665     raeburn  15856:             if (ref($subcats) eq 'HASH') {
                   15857:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   15858:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   15859:                     my $higher;
                   15860:                     if ($j > 0) {
                   15861:                         $higher = &escape($parents->[$j]).':'.
                   15862:                                   &escape($parents->[$j-1]).':'.$j;
                   15863:                     } else {
                   15864:                         $higher = &escape($parents->[$j]).'::'.$j;
                   15865:                     }
                   15866:                     push(@{$subcats->{$higher}},$subcat);
                   15867:                 }
                   15868:             }
                   15869:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1321    raeburn  15870:                                 $subcats,$maxd);
1.655     raeburn  15871:             pop(@{$parents});
                   15872:         }
                   15873:     } else {
                   15874:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  15875:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  15876:         if ($allitems->{$item} eq '') {
                   15877:             push(@{$trails},$trailstr);
                   15878:             $allitems->{$item} = scalar(@{$trails})-1;
                   15879:         }
1.1321    raeburn  15880:         if (ref($maxd) eq 'HASH') {
                   15881:             if ($depth > $maxd->{$parents->[0]}) {
                   15882:                 $maxd->{$parents->[0]} = $depth;
                   15883:             }
                   15884:         }
1.655     raeburn  15885:     }
                   15886:     return;
                   15887: }
                   15888: 
1.663     raeburn  15889: =pod
                   15890: 
1.1162    raeburn  15891: =item * &assign_categories_table()
1.663     raeburn  15892: 
                   15893: Create a datatable for display of hierarchical categories in a domain,
                   15894: with checkboxes to allow a course to be categorized. 
                   15895: 
                   15896: Inputs:
                   15897: 
                   15898: cathash - reference to hash of categories defined for the domain (from
                   15899:           configuration.db)
                   15900: 
                   15901: currcat - scalar with an & separated list of categories assigned to a course. 
                   15902: 
1.919     raeburn  15903: type    - scalar contains course type (Course or Community).
                   15904: 
1.1260    raeburn  15905: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15906:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15907: 
1.663     raeburn  15908: Returns: $output (markup to be displayed) 
                   15909: 
                   15910: =cut
                   15911: 
                   15912: sub assign_categories_table {
1.1259    raeburn  15913:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  15914:     my $output;
                   15915:     if (ref($cathash) eq 'HASH') {
1.1321    raeburn  15916:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   15917:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  15918:         $maxdepth = scalar(@cats);
                   15919:         if (@cats > 0) {
                   15920:             my $itemcount = 0;
                   15921:             if (ref($cats[0]) eq 'ARRAY') {
                   15922:                 my @currcategories;
                   15923:                 if ($currcat ne '') {
                   15924:                     @currcategories = split('&',$currcat);
                   15925:                 }
1.919     raeburn  15926:                 my $table;
1.663     raeburn  15927:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   15928:                     my $parent = $cats[0][$i];
1.919     raeburn  15929:                     next if ($parent eq 'instcode');
                   15930:                     if ($type eq 'Community') {
                   15931:                         next unless ($parent eq 'communities');
1.1239    raeburn  15932:                     } elsif ($type eq 'Placement') {
                   15933:                         next unless ($parent eq 'placement');
1.919     raeburn  15934:                     } else {
1.1239    raeburn  15935:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  15936:                     }
1.663     raeburn  15937:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   15938:                     my $item = &escape($parent).'::0';
                   15939:                     my $checked = '';
                   15940:                     if (@currcategories > 0) {
                   15941:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   15942:                             $checked = ' checked="checked"';
1.663     raeburn  15943:                         }
                   15944:                     }
1.919     raeburn  15945:                     my $parent_title = $parent;
                   15946:                     if ($parent eq 'communities') {
                   15947:                         $parent_title = &mt('Communities');
1.1239    raeburn  15948:                     } elsif ($parent eq 'placement') {
                   15949:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  15950:                     }
                   15951:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   15952:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  15953:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  15954:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  15955:                     my $depth = 1;
                   15956:                     push(@path,$parent);
1.1259    raeburn  15957:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  15958:                     pop(@path);
1.919     raeburn  15959:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  15960:                     $itemcount ++;
                   15961:                 }
1.919     raeburn  15962:                 if ($itemcount) {
                   15963:                     $output = &Apache::loncommon::start_data_table().
                   15964:                               $table.
                   15965:                               &Apache::loncommon::end_data_table();
                   15966:                 }
1.663     raeburn  15967:             }
                   15968:         }
                   15969:     }
                   15970:     return $output;
                   15971: }
                   15972: 
                   15973: =pod
                   15974: 
1.1162    raeburn  15975: =item * &assign_category_rows()
1.663     raeburn  15976: 
                   15977: Create a datatable row for display of nested categories in a domain,
                   15978: with checkboxes to allow a course to be categorized,called recursively.
                   15979: 
                   15980: Inputs:
                   15981: 
                   15982: itemcount - track row number for alternating colors
                   15983: 
                   15984: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   15985:       categories and subcategories.
                   15986: 
                   15987: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   15988: 
                   15989: parent - parent of current category item
                   15990: 
                   15991: path - Array containing all categories back up through the hierarchy from the
                   15992:        current category to the top level.
                   15993: 
                   15994: currcategories - reference to array of current categories assigned to the course
                   15995: 
1.1260    raeburn  15996: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15997:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15998: 
1.663     raeburn  15999: Returns: $output (markup to be displayed).
                   16000: 
                   16001: =cut
                   16002: 
                   16003: sub assign_category_rows {
1.1259    raeburn  16004:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  16005:     my ($text,$name,$item,$chgstr);
                   16006:     if (ref($cats) eq 'ARRAY') {
                   16007:         my $maxdepth = scalar(@{$cats});
                   16008:         if (ref($cats->[$depth]) eq 'HASH') {
                   16009:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   16010:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   16011:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  16012:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  16013:                 for (my $j=0; $j<$numchildren; $j++) {
                   16014:                     $name = $cats->[$depth]{$parent}[$j];
                   16015:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   16016:                     my $deeper = $depth+1;
                   16017:                     my $checked = '';
                   16018:                     if (ref($currcategories) eq 'ARRAY') {
                   16019:                         if (@{$currcategories} > 0) {
                   16020:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   16021:                                 $checked = ' checked="checked"';
1.663     raeburn  16022:                             }
                   16023:                         }
                   16024:                     }
1.664     raeburn  16025:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   16026:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16027:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  16028:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   16029:                              '</td><td>';
1.663     raeburn  16030:                     if (ref($path) eq 'ARRAY') {
                   16031:                         push(@{$path},$name);
1.1259    raeburn  16032:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  16033:                         pop(@{$path});
                   16034:                     }
                   16035:                     $text .= '</td></tr>';
                   16036:                 }
                   16037:                 $text .= '</table></td>';
                   16038:             }
                   16039:         }
                   16040:     }
                   16041:     return $text;
                   16042: }
                   16043: 
1.1181    raeburn  16044: =pod
                   16045: 
                   16046: =back
                   16047: 
                   16048: =cut
                   16049: 
1.655     raeburn  16050: ############################################################
                   16051: ############################################################
                   16052: 
                   16053: 
1.443     albertel 16054: sub commit_customrole {
1.664     raeburn  16055:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  16056:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 16057:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   16058:                          ($end?', ending '.localtime($end):'').': <b>'.
                   16059:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  16060:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 16061:                  '</b><br />';
                   16062:     return $output;
                   16063: }
                   16064: 
                   16065: sub commit_standardrole {
1.1116    raeburn  16066:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  16067:     my ($output,$logmsg,$linefeed);
                   16068:     if ($context eq 'auto') {
                   16069:         $linefeed = "\n";
                   16070:     } else {
                   16071:         $linefeed = "<br />\n";
                   16072:     }  
1.443     albertel 16073:     if ($three eq 'st') {
1.541     raeburn  16074:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  16075:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  16076:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  16077:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   16078:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 16079:         } else {
1.541     raeburn  16080:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 16081:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16082:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   16083:             if ($context eq 'auto') {
                   16084:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   16085:             } else {
                   16086:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   16087:                &mt('Add to classlist').': <b>ok</b>';
                   16088:             }
                   16089:             $output .= $linefeed;
1.443     albertel 16090:         }
                   16091:     } else {
                   16092:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   16093:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16094:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  16095:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  16096:         if ($context eq 'auto') {
                   16097:             $output .= $result.$linefeed;
                   16098:         } else {
                   16099:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   16100:         }
1.443     albertel 16101:     }
                   16102:     return $output;
                   16103: }
                   16104: 
                   16105: sub commit_studentrole {
1.1116    raeburn  16106:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   16107:         $credits) = @_;
1.626     raeburn  16108:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  16109:     if ($context eq 'auto') {
                   16110:         $linefeed = "\n";
                   16111:     } else {
                   16112:         $linefeed = '<br />'."\n";
                   16113:     }
1.443     albertel 16114:     if (defined($one) && defined($two)) {
                   16115:         my $cid=$one.'_'.$two;
                   16116:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   16117:         my $secchange = 0;
                   16118:         my $expire_role_result;
                   16119:         my $modify_section_result;
1.628     raeburn  16120:         if ($oldsec ne '-1') { 
                   16121:             if ($oldsec ne $sec) {
1.443     albertel 16122:                 $secchange = 1;
1.628     raeburn  16123:                 my $now = time;
1.443     albertel 16124:                 my $uurl='/'.$cid;
                   16125:                 $uurl=~s/\_/\//g;
                   16126:                 if ($oldsec) {
                   16127:                     $uurl.='/'.$oldsec;
                   16128:                 }
1.626     raeburn  16129:                 $oldsecurl = $uurl;
1.628     raeburn  16130:                 $expire_role_result = 
1.652     raeburn  16131:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  16132:                 if ($env{'request.course.sec'} ne '') { 
                   16133:                     if ($expire_role_result eq 'refused') {
                   16134:                         my @roles = ('st');
                   16135:                         my @statuses = ('previous');
                   16136:                         my @roledoms = ($one);
                   16137:                         my $withsec = 1;
                   16138:                         my %roleshash = 
                   16139:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   16140:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   16141:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   16142:                             my ($oldstart,$oldend) = 
                   16143:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   16144:                             if ($oldend > 0 && $oldend <= $now) {
                   16145:                                 $expire_role_result = 'ok';
                   16146:                             }
                   16147:                         }
                   16148:                     }
                   16149:                 }
1.443     albertel 16150:                 $result = $expire_role_result;
                   16151:             }
                   16152:         }
                   16153:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  16154:             $modify_section_result = 
                   16155:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   16156:                                                            undef,undef,undef,$sec,
                   16157:                                                            $end,$start,'','',$cid,
                   16158:                                                            '',$context,$credits);
1.443     albertel 16159:             if ($modify_section_result =~ /^ok/) {
                   16160:                 if ($secchange == 1) {
1.628     raeburn  16161:                     if ($sec eq '') {
                   16162:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   16163:                     } else {
                   16164:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   16165:                     }
1.443     albertel 16166:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  16167:                     if ($sec eq '') {
                   16168:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   16169:                     } else {
                   16170:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16171:                     }
1.443     albertel 16172:                 } else {
1.628     raeburn  16173:                     if ($sec eq '') {
                   16174:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   16175:                     } else {
                   16176:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16177:                     }
1.443     albertel 16178:                 }
                   16179:             } else {
1.1115    raeburn  16180:                 if ($secchange) { 
1.628     raeburn  16181:                     $$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;
                   16182:                 } else {
                   16183:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   16184:                 }
1.443     albertel 16185:             }
                   16186:             $result = $modify_section_result;
                   16187:         } elsif ($secchange == 1) {
1.628     raeburn  16188:             if ($oldsec eq '') {
1.1103    raeburn  16189:                 $$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  16190:             } else {
                   16191:                 $$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;
                   16192:             }
1.626     raeburn  16193:             if ($expire_role_result eq 'refused') {
                   16194:                 my $newsecurl = '/'.$cid;
                   16195:                 $newsecurl =~ s/\_/\//g;
                   16196:                 if ($sec ne '') {
                   16197:                     $newsecurl.='/'.$sec;
                   16198:                 }
                   16199:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   16200:                     if ($sec eq '') {
                   16201:                         $$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;
                   16202:                     } else {
                   16203:                         $$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;
                   16204:                     }
                   16205:                 }
                   16206:             }
1.443     albertel 16207:         }
                   16208:     } else {
1.626     raeburn  16209:         $$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 16210:         $result = "error: incomplete course id\n";
                   16211:     }
                   16212:     return $result;
                   16213: }
                   16214: 
1.1108    raeburn  16215: sub show_role_extent {
                   16216:     my ($scope,$context,$role) = @_;
                   16217:     $scope =~ s{^/}{};
                   16218:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   16219:     push(@courseroles,'co');
                   16220:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   16221:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   16222:         $scope =~ s{/}{_};
                   16223:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   16224:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   16225:         my ($audom,$auname) = split(/\//,$scope);
                   16226:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   16227:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   16228:     } else {
                   16229:         $scope =~ s{/$}{};
                   16230:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   16231:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   16232:     }
                   16233: }
                   16234: 
1.443     albertel 16235: ############################################################
                   16236: ############################################################
                   16237: 
1.566     albertel 16238: sub check_clone {
1.578     raeburn  16239:     my ($args,$linefeed) = @_;
1.566     albertel 16240:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   16241:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   16242:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1344    raeburn  16243:     my $clonetitle;
                   16244:     my @clonemsg;
1.566     albertel 16245:     my $can_clone = 0;
1.944     raeburn  16246:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  16247:     if ($lctype ne 'community') {
                   16248:         $lctype = 'course';
                   16249:     }
1.566     albertel 16250:     if ($clonehome eq 'no_host') {
1.944     raeburn  16251:         if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  16252:             push(@clonemsg,({
                   16253:                               mt => 'No new community created.',
                   16254:                               args => [],
                   16255:                             },
                   16256:                             {
                   16257:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   16258:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   16259:                             }));
1.908     raeburn  16260:         } else {
1.1344    raeburn  16261:             push(@clonemsg,({
                   16262:                               mt => 'No new course created.',
                   16263:                               args => [],
                   16264:                             },
                   16265:                             {
                   16266:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   16267:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16268:                             }));
                   16269:         }
1.566     albertel 16270:     } else {
                   16271: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1344    raeburn  16272:         $clonetitle = $clonedesc{'description'};
1.944     raeburn  16273:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  16274:             if ($clonedesc{'type'} ne 'Community') {
1.1344    raeburn  16275:                 push(@clonemsg,({
                   16276:                                   mt => 'No new community created.',
                   16277:                                   args => [],
                   16278:                                 },
                   16279:                                 {
                   16280:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   16281:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16282:                                 }));
                   16283:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  16284:             }
                   16285:         }
1.1262    raeburn  16286: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  16287:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 16288: 	    $can_clone = 1;
                   16289: 	} else {
1.1221    raeburn  16290: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 16291: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  16292:             if ($clonehash{'cloners'} eq '') {
                   16293:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   16294:                 if ($domdefs{'canclone'}) {
                   16295:                     unless ($domdefs{'canclone'} eq 'none') {
                   16296:                         if ($domdefs{'canclone'} eq 'domain') {
                   16297:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   16298:                                 $can_clone = 1;
                   16299:                             }
                   16300:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   16301:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   16302:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   16303:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   16304:                                 $can_clone = 1;
                   16305:                             }
                   16306:                         }
                   16307:                     }
                   16308:                 }
1.578     raeburn  16309:             } else {
1.1221    raeburn  16310: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   16311:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  16312:                     $can_clone = 1;
1.1221    raeburn  16313:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  16314:                     $can_clone = 1;
1.1225    raeburn  16315:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   16316:                     $can_clone = 1;
1.1221    raeburn  16317:                 }
                   16318:                 unless ($can_clone) {
1.1225    raeburn  16319:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   16320:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  16321:                         my (%gotdomdefaults,%gotcodedefaults);
                   16322:                         foreach my $cloner (@cloners) {
                   16323:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   16324:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   16325:                                 my (%codedefaults,@code_order);
                   16326:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   16327:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   16328:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   16329:                                     }
                   16330:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   16331:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   16332:                                     }
                   16333:                                 } else {
                   16334:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   16335:                                                                             \%codedefaults,
                   16336:                                                                             \@code_order);
                   16337:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   16338:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   16339:                                 }
                   16340:                                 if (@code_order > 0) {
                   16341:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   16342:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   16343:                                                                                 $args->{'crscode'})) {
                   16344:                                         $can_clone = 1;
                   16345:                                         last;
                   16346:                                     }
                   16347:                                 }
                   16348:                             }
                   16349:                         }
                   16350:                     }
1.1225    raeburn  16351:                 }
                   16352:             }
                   16353:             unless ($can_clone) {
                   16354:                 my $ccrole = 'cc';
                   16355:                 if ($args->{'crstype'} eq 'Community') {
                   16356:                     $ccrole = 'co';
                   16357:                 }
                   16358: 	        my %roleshash =
                   16359: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   16360: 					          $args->{'ccdomain'},
                   16361:                                                   'userroles',['active'],[$ccrole],
                   16362: 					          [$args->{'clonedomain'}]);
                   16363: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   16364:                     $can_clone = 1;
                   16365:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   16366:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   16367:                     $can_clone = 1;
1.1221    raeburn  16368:                 }
                   16369:             }
                   16370:             unless ($can_clone) {
                   16371:                 if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  16372:                     push(@clonemsg,({
                   16373:                                       mt => 'No new community created.',
                   16374:                                       args => [],
                   16375:                                     },
                   16376:                                     {
                   16377:                                       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]).',
                   16378:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16379:                                     }));
1.942     raeburn  16380:                 } else {
1.1344    raeburn  16381:                     push(@clonemsg,({
                   16382:                                       mt => 'No new course created.',
                   16383:                                       args => [],
                   16384:                                     },
                   16385:                                     {
                   16386:                                       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]).',
                   16387:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16388:                                     }));
1.1221    raeburn  16389:                 }
1.566     albertel 16390: 	    }
1.578     raeburn  16391:         }
1.566     albertel 16392:     }
1.1344    raeburn  16393:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16394: }
                   16395: 
1.444     albertel 16396: sub construct_course {
1.1262    raeburn  16397:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1344    raeburn  16398:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   16399:     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  16400:     my $linefeed =  '<br />'."\n";
                   16401:     if ($context eq 'auto') {
                   16402:         $linefeed = "\n";
                   16403:     }
1.566     albertel 16404: 
                   16405: #
                   16406: # Are we cloning?
                   16407: #
1.1344    raeburn  16408:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16409:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1344    raeburn  16410: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 16411:         if (!$can_clone) {
1.1344    raeburn  16412: 	    return (0,$outcome,$clonemsgref);
1.566     albertel 16413: 	}
                   16414:     }
                   16415: 
1.444     albertel 16416: #
                   16417: # Open course
                   16418: #
1.1239    raeburn  16419:     my $showncrstype;
                   16420:     if ($args->{'crstype'} eq 'Placement') {
                   16421:         $showncrstype = 'placement test'; 
                   16422:     } else {  
                   16423:         $showncrstype = lc($args->{'crstype'});
                   16424:     }
1.444     albertel 16425:     my %cenv=();
                   16426:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   16427:                                              $args->{'cdescr'},
                   16428:                                              $args->{'curl'},
                   16429:                                              $args->{'course_home'},
                   16430:                                              $args->{'nonstandard'},
                   16431:                                              $args->{'crscode'},
                   16432:                                              $args->{'ccuname'}.':'.
                   16433:                                              $args->{'ccdomain'},
1.882     raeburn  16434:                                              $args->{'crstype'},
1.1344    raeburn  16435:                                              $cnum,$context,$category,
                   16436:                                              $callercontext);
1.444     albertel 16437: 
                   16438:     # Note: The testing routines depend on this being output; see 
                   16439:     # Utils::Course. This needs to at least be output as a comment
                   16440:     # if anyone ever decides to not show this, and Utils::Course::new
                   16441:     # will need to be suitably modified.
1.1344    raeburn  16442:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16443:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   16444:     } else {
                   16445:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   16446:     }
1.943     raeburn  16447:     if ($$courseid =~ /^error:/) {
1.1344    raeburn  16448:         return (0,$outcome,$clonemsgref);
1.943     raeburn  16449:     }
                   16450: 
1.444     albertel 16451: #
                   16452: # Check if created correctly
                   16453: #
1.479     albertel 16454:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 16455:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  16456:     if ($crsuhome eq 'no_host') {
1.1344    raeburn  16457:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16458:             $outcome .= &mt_user($user_lh,
                   16459:                             'Course creation failed, unrecognized course home server.');
                   16460:         } else {
                   16461:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   16462:         }
                   16463:         $outcome .= $linefeed;
                   16464:         return (0,$outcome,$clonemsgref);
1.943     raeburn  16465:     }
1.541     raeburn  16466:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 16467: 
1.444     albertel 16468: #
1.566     albertel 16469: # Do the cloning
                   16470: #   
1.1344    raeburn  16471:     my @clonemsg;
1.566     albertel 16472:     if ($can_clone && $cloneid) {
1.1344    raeburn  16473:         push(@clonemsg,
                   16474:                       {
                   16475:                           mt => 'Created [_1] by cloning from [_2]',
                   16476:                           args => [$showncrstype,$clonetitle],
                   16477:                       });
1.566     albertel 16478: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 16479: # Copy all files
1.1344    raeburn  16480:         my @info =
                   16481: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   16482: 	                                             $args->{'dateshift'},$args->{'crscode'},
                   16483:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   16484:                                                      $args->{'tinyurls'});
                   16485:         if (@info) {
                   16486:             push(@clonemsg,@info);
                   16487:         }
1.444     albertel 16488: # Restore URL
1.566     albertel 16489: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 16490: # Restore title
1.566     albertel 16491: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  16492: # Restore creation date, creator and creation context.
                   16493:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   16494:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   16495:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 16496: # Mark as cloned
1.566     albertel 16497: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      16498: # Need to clone grading mode
                   16499:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   16500:         $cenv{'grading'}=$newenv{'grading'};
                   16501: # Do not clone these environment entries
                   16502:         &Apache::lonnet::del('environment',
                   16503:                   ['default_enrollment_start_date',
                   16504:                    'default_enrollment_end_date',
                   16505:                    'question.email',
                   16506:                    'policy.email',
                   16507:                    'comment.email',
                   16508:                    'pch.users.denied',
1.725     raeburn  16509:                    'plc.users.denied',
                   16510:                    'hidefromcat',
1.1121    raeburn  16511:                    'checkforpriv',
1.1355    raeburn  16512:                    'categories'],
1.638     www      16513:                    $$crsudom,$$crsunum);
1.1170    raeburn  16514:         if ($args->{'textbook'}) {
                   16515:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   16516:         }
1.444     albertel 16517:     }
1.566     albertel 16518: 
1.444     albertel 16519: #
                   16520: # Set environment (will override cloned, if existing)
                   16521: #
                   16522:     my @sections = ();
                   16523:     my @xlists = ();
                   16524:     if ($args->{'crstype'}) {
                   16525:         $cenv{'type'}=$args->{'crstype'};
                   16526:     }
1.1371    raeburn  16527:     if ($args->{'lti'}) {
                   16528:         $cenv{'internal.lti'}=$args->{'lti'};
                   16529:     }
1.444     albertel 16530:     if ($args->{'crsid'}) {
                   16531:         $cenv{'courseid'}=$args->{'crsid'};
                   16532:     }
                   16533:     if ($args->{'crscode'}) {
                   16534:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   16535:     }
                   16536:     if ($args->{'crsquota'} ne '') {
                   16537:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   16538:     } else {
                   16539:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   16540:     }
                   16541:     if ($args->{'ccuname'}) {
                   16542:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   16543:                                         ':'.$args->{'ccdomain'};
                   16544:     } else {
                   16545:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   16546:     }
1.1116    raeburn  16547:     if ($args->{'defaultcredits'}) {
                   16548:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   16549:     }
1.444     albertel 16550:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   16551:     if ($args->{'crssections'}) {
                   16552:         $cenv{'internal.sectionnums'} = '';
                   16553:         if ($args->{'crssections'} =~ m/,/) {
                   16554:             @sections = split/,/,$args->{'crssections'};
                   16555:         } else {
                   16556:             $sections[0] = $args->{'crssections'};
                   16557:         }
                   16558:         if (@sections > 0) {
                   16559:             foreach my $item (@sections) {
                   16560:                 my ($sec,$gp) = split/:/,$item;
                   16561:                 my $class = $args->{'crscode'}.$sec;
                   16562:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   16563:                 $cenv{'internal.sectionnums'} .= $item.',';
                   16564:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  16565:                     push(@badclasses,$class);
1.444     albertel 16566:                 }
                   16567:             }
                   16568:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   16569:         }
                   16570:     }
                   16571: # do not hide course coordinator from staff listing, 
                   16572: # even if privileged
                   16573:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  16574: # add course coordinator's domain to domains to check for privileged users
                   16575: # if different to course domain
                   16576:     if ($$crsudom ne $args->{'ccdomain'}) {
                   16577:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   16578:     }
1.444     albertel 16579: # add crosslistings
                   16580:     if ($args->{'crsxlist'}) {
                   16581:         $cenv{'internal.crosslistings'}='';
                   16582:         if ($args->{'crsxlist'} =~ m/,/) {
                   16583:             @xlists = split/,/,$args->{'crsxlist'};
                   16584:         } else {
                   16585:             $xlists[0] = $args->{'crsxlist'};
                   16586:         }
                   16587:         if (@xlists > 0) {
                   16588:             foreach my $item (@xlists) {
                   16589:                 my ($xl,$gp) = split/:/,$item;
                   16590:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   16591:                 $cenv{'internal.crosslistings'} .= $item.',';
                   16592:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  16593:                     push(@badclasses,$xl);
1.444     albertel 16594:                 }
                   16595:             }
                   16596:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   16597:         }
                   16598:     }
                   16599:     if ($args->{'autoadds'}) {
                   16600:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   16601:     }
                   16602:     if ($args->{'autodrops'}) {
                   16603:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   16604:     }
                   16605: # check for notification of enrollment changes
                   16606:     my @notified = ();
                   16607:     if ($args->{'notify_owner'}) {
                   16608:         if ($args->{'ccuname'} ne '') {
                   16609:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   16610:         }
                   16611:     }
                   16612:     if ($args->{'notify_dc'}) {
                   16613:         if ($uname ne '') { 
1.630     raeburn  16614:             push(@notified,$uname.':'.$udom);
1.444     albertel 16615:         }
                   16616:     }
                   16617:     if (@notified > 0) {
                   16618:         my $notifylist;
                   16619:         if (@notified > 1) {
                   16620:             $notifylist = join(',',@notified);
                   16621:         } else {
                   16622:             $notifylist = $notified[0];
                   16623:         }
                   16624:         $cenv{'internal.notifylist'} = $notifylist;
                   16625:     }
                   16626:     if (@badclasses > 0) {
                   16627:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  16628:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   16629:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   16630:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 16631:         );
1.1264    raeburn  16632:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   16633:                            &mt('That is because the user identified as the course owner ([_1]) does not have rights to access enrollment in these classes, as determined by the policies of your institution on access to official classlists',$cenv{'internal.courseowner'}).$linefeed.$lt{'itis'};
1.541     raeburn  16634:         if ($context eq 'auto') {
                   16635:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  16636:         } else {
1.566     albertel 16637:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  16638:         }
                   16639:         foreach my $item (@badclasses) {
1.541     raeburn  16640:             if ($context eq 'auto') {
1.1261    raeburn  16641:                 $outcome .= " - $item\n";
1.541     raeburn  16642:             } else {
1.1261    raeburn  16643:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  16644:             }
1.1261    raeburn  16645:         }
                   16646:         if ($context eq 'auto') {
                   16647:             $outcome .= $linefeed;
                   16648:         } else {
                   16649:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  16650:         } 
1.444     albertel 16651:     }
                   16652:     if ($args->{'no_end_date'}) {
                   16653:         $args->{'endaccess'} = 0;
                   16654:     }
                   16655:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   16656:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   16657:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   16658:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   16659:     if ($args->{'showphotos'}) {
                   16660:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   16661:     }
                   16662:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   16663:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   16664:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   16665:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  16666:             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'); 
                   16667:             if ($context eq 'auto') {
                   16668:                 $outcome .= $krb_msg;
                   16669:             } else {
1.566     albertel 16670:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  16671:             }
                   16672:             $outcome .= $linefeed;
1.444     albertel 16673:         }
                   16674:     }
                   16675:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   16676:        if ($args->{'setpolicy'}) {
                   16677:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16678:        }
                   16679:        if ($args->{'setcontent'}) {
                   16680:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16681:        }
1.1251    raeburn  16682:        if ($args->{'setcomment'}) {
                   16683:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16684:        }
1.444     albertel 16685:     }
                   16686:     if ($args->{'reshome'}) {
                   16687: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   16688: 	$cenv{'reshome'}=~s/\/+$/\//;
                   16689:     }
                   16690: #
                   16691: # course has keyed access
                   16692: #
                   16693:     if ($args->{'setkeys'}) {
                   16694:        $cenv{'keyaccess'}='yes';
                   16695:     }
                   16696: # if specified, key authority is not course, but user
                   16697: # only active if keyaccess is yes
                   16698:     if ($args->{'keyauth'}) {
1.487     albertel 16699: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   16700: 	$user = &LONCAPA::clean_username($user);
                   16701: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     16702: 	if ($user ne '' && $domain ne '') {
1.487     albertel 16703: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 16704: 	}
                   16705:     }
                   16706: 
1.1166    raeburn  16707: #
1.1167    raeburn  16708: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  16709: #
                   16710:     if ($args->{'uniquecode'}) {
                   16711:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   16712:         if ($code) {
                   16713:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  16714:             my %crsinfo =
                   16715:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   16716:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   16717:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   16718:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   16719:             } 
1.1166    raeburn  16720:             if (ref($coderef)) {
                   16721:                 $$coderef = $code;
                   16722:             }
                   16723:         }
                   16724:     }
                   16725: 
1.444     albertel 16726:     if ($args->{'disresdis'}) {
                   16727:         $cenv{'pch.roles.denied'}='st';
                   16728:     }
                   16729:     if ($args->{'disablechat'}) {
                   16730:         $cenv{'plc.roles.denied'}='st';
                   16731:     }
                   16732: 
                   16733:     # Record we've not yet viewed the Course Initialization Helper for this 
                   16734:     # course
                   16735:     $cenv{'course.helper.not.run'} = 1;
                   16736:     #
                   16737:     # Use new Randomseed
                   16738:     #
                   16739:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   16740:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   16741:     #
                   16742:     # The encryption code and receipt prefix for this course
                   16743:     #
                   16744:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   16745:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   16746:     #
                   16747:     # By default, use standard grading
                   16748:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   16749: 
1.541     raeburn  16750:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   16751:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16752: #
                   16753: # Open all assignments
                   16754: #
                   16755:     if ($args->{'openall'}) {
1.1341    raeburn  16756:        my $opendate = time;
                   16757:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   16758:            $opendate = $args->{'openallfrom'};
                   16759:        }
1.444     albertel 16760:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1341    raeburn  16761:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 16762:                            $storeunder.'.type' => 'date_start');
1.1341    raeburn  16763:        $outcome .= &mt('All assignments open starting [_1]',
                   16764:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   16765:                    &Apache::lonnet::cput
                   16766:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16767:    }
                   16768: #
                   16769: # Set first page
                   16770: #
                   16771:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   16772: 	    || ($cloneid)) {
1.445     albertel 16773: 	use LONCAPA::map;
1.444     albertel 16774: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 16775: 
                   16776: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   16777:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   16778: 
1.444     albertel 16779:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   16780:         my $title; my $url;
                   16781:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   16782: 	    $title=&mt('Syllabus');
1.444     albertel 16783:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   16784:         } else {
1.963     raeburn  16785:             $title=&mt('Table of Contents');
1.444     albertel 16786:             $url='/adm/navmaps';
                   16787:         }
1.445     albertel 16788: 
                   16789:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   16790: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   16791: 
                   16792: 	if ($errtext) { $fatal=2; }
1.541     raeburn  16793:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 16794:     }
1.566     albertel 16795: 
1.1237    raeburn  16796: # 
                   16797: # Set params for Placement Tests
                   16798: #
1.1239    raeburn  16799:     if ($args->{'crstype'} eq 'Placement') {
                   16800:        my %storecontent; 
                   16801:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   16802:        my %defaults = (
                   16803:                         buttonshide   => { value => 'yes',
                   16804:                                            type => 'string_yesno',},
                   16805:                         type          => { value => 'randomizetry',
                   16806:                                            type  => 'string_questiontype',},
                   16807:                         maxtries      => { value => 1,
                   16808:                                            type => 'int_pos',},
                   16809:                         problemstatus => { value => 'no',
                   16810:                                            type  => 'string_problemstatus',},
                   16811:                       );
                   16812:        foreach my $key (keys(%defaults)) {
                   16813:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   16814:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   16815:        }
1.1237    raeburn  16816:        &Apache::lonnet::cput
                   16817:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   16818:     }
                   16819: 
1.1344    raeburn  16820:     return (1,$outcome,\@clonemsg);
1.444     albertel 16821: }
                   16822: 
1.1166    raeburn  16823: sub make_unique_code {
                   16824:     my ($cdom,$cnum) = @_;
                   16825:     # get lock on uniquecodes db
                   16826:     my $lockhash = {
                   16827:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   16828:                                                   ':'.$env{'user.domain'},
                   16829:                    };
                   16830:     my $tries = 0;
                   16831:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16832:     my ($code,$error);
                   16833:   
                   16834:     while (($gotlock ne 'ok') && ($tries<3)) {
                   16835:         $tries ++;
                   16836:         sleep 1;
                   16837:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16838:     }
                   16839:     if ($gotlock eq 'ok') {
                   16840:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   16841:         my $gotcode;
                   16842:         my $attempts = 0;
                   16843:         while ((!$gotcode) && ($attempts < 100)) {
                   16844:             $code = &generate_code();
                   16845:             if (!exists($currcodes{$code})) {
                   16846:                 $gotcode = 1;
                   16847:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   16848:                     $error = 'nostore';
                   16849:                 }
                   16850:             }
                   16851:             $attempts ++;
                   16852:         }
                   16853:         my @del_lock = ($cnum."\0".'uniquecodes');
                   16854:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   16855:     } else {
                   16856:         $error = 'nolock';
                   16857:     }
                   16858:     return ($code,$error);
                   16859: }
                   16860: 
                   16861: sub generate_code {
                   16862:     my $code;
                   16863:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   16864:     for (my $i=0; $i<6; $i++) {
                   16865:         my $lettnum = int (rand 2);
                   16866:         my $item = '';
                   16867:         if ($lettnum) {
                   16868:             $item = $letts[int( rand(18) )];
                   16869:         } else {
                   16870:             $item = 1+int( rand(8) );
                   16871:         }
                   16872:         $code .= $item;
                   16873:     }
                   16874:     return $code;
                   16875: }
                   16876: 
1.444     albertel 16877: ############################################################
                   16878: ############################################################
                   16879: 
1.1237    raeburn  16880: # Community, Course and Placement Test
1.378     raeburn  16881: sub course_type {
                   16882:     my ($cid) = @_;
                   16883:     if (!defined($cid)) {
                   16884:         $cid = $env{'request.course.id'};
                   16885:     }
1.404     albertel 16886:     if (defined($env{'course.'.$cid.'.type'})) {
                   16887:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  16888:     } else {
                   16889:         return 'Course';
1.377     raeburn  16890:     }
                   16891: }
1.156     albertel 16892: 
1.406     raeburn  16893: sub group_term {
                   16894:     my $crstype = &course_type();
                   16895:     my %names = (
                   16896:                   'Course' => 'group',
1.865     raeburn  16897:                   'Community' => 'group',
1.1237    raeburn  16898:                   'Placement' => 'group',
1.406     raeburn  16899:                 );
                   16900:     return $names{$crstype};
                   16901: }
                   16902: 
1.902     raeburn  16903: sub course_types {
1.1310    raeburn  16904:     my @types = ('official','unofficial','community','textbook','placement','lti');
1.902     raeburn  16905:     my %typename = (
                   16906:                          official   => 'Official course',
                   16907:                          unofficial => 'Unofficial course',
                   16908:                          community  => 'Community',
1.1165    raeburn  16909:                          textbook   => 'Textbook course',
1.1237    raeburn  16910:                          placement  => 'Placement test',
1.1310    raeburn  16911:                          lti        => 'LTI provider',
1.902     raeburn  16912:                    );
                   16913:     return (\@types,\%typename);
                   16914: }
                   16915: 
1.156     albertel 16916: sub icon {
                   16917:     my ($file)=@_;
1.505     albertel 16918:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 16919:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 16920:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 16921:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   16922: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   16923: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16924: 	            $curfext.".gif") {
                   16925: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16926: 		$curfext.".gif";
                   16927: 	}
                   16928:     }
1.249     albertel 16929:     return &lonhttpdurl($iconname);
1.154     albertel 16930: } 
1.84      albertel 16931: 
1.575     albertel 16932: sub lonhttpdurl {
1.692     www      16933: #
                   16934: # Had been used for "small fry" static images on separate port 8080.
                   16935: # Modify here if lightweight http functionality desired again.
                   16936: # Currently eliminated due to increasing firewall issues.
                   16937: #
1.575     albertel 16938:     my ($url)=@_;
1.692     www      16939:     return $url;
1.215     albertel 16940: }
                   16941: 
1.213     albertel 16942: sub connection_aborted {
                   16943:     my ($r)=@_;
                   16944:     $r->print(" ");$r->rflush();
                   16945:     my $c = $r->connection;
                   16946:     return $c->aborted();
                   16947: }
                   16948: 
1.221     foxr     16949: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     16950: #    strings as 'strings'.
                   16951: sub escape_single {
1.221     foxr     16952:     my ($input) = @_;
1.223     albertel 16953:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     16954:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   16955:     return $input;
                   16956: }
1.223     albertel 16957: 
1.222     foxr     16958: #  Same as escape_single, but escape's "'s  This 
                   16959: #  can be used for  "strings"
                   16960: sub escape_double {
                   16961:     my ($input) = @_;
                   16962:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   16963:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   16964:     return $input;
                   16965: }
1.223     albertel 16966:  
1.222     foxr     16967: #   Escapes the last element of a full URL.
                   16968: sub escape_url {
                   16969:     my ($url)   = @_;
1.238     raeburn  16970:     my @urlslices = split(/\//, $url,-1);
1.369     www      16971:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  16972:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     16973: }
1.462     albertel 16974: 
1.820     raeburn  16975: sub compare_arrays {
                   16976:     my ($arrayref1,$arrayref2) = @_;
                   16977:     my (@difference,%count);
                   16978:     @difference = ();
                   16979:     %count = ();
                   16980:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   16981:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   16982:         foreach my $element (keys(%count)) {
                   16983:             if ($count{$element} == 1) {
                   16984:                 push(@difference,$element);
                   16985:             }
                   16986:         }
                   16987:     }
                   16988:     return @difference;
                   16989: }
                   16990: 
1.1322    raeburn  16991: sub lon_status_items {
                   16992:     my %defaults = (
                   16993:                      E         => 100,
                   16994:                      W         => 4,
                   16995:                      N         => 1,
1.1324    raeburn  16996:                      U         => 5,
1.1322    raeburn  16997:                      threshold => 200,
                   16998:                      sysmail   => 2500,
                   16999:                    );
                   17000:     my %names = (
                   17001:                    E => 'Errors',
                   17002:                    W => 'Warnings',
                   17003:                    N => 'Notices',
1.1324    raeburn  17004:                    U => 'Unsent',
1.1322    raeburn  17005:                 );
                   17006:     return (\%defaults,\%names);
                   17007: }
                   17008: 
1.817     bisitz   17009: # -------------------------------------------------------- Initialize user login
1.462     albertel 17010: sub init_user_environment {
1.463     albertel 17011:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 17012:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   17013: 
                   17014:     my $public=($username eq 'public' && $domain eq 'public');
                   17015: 
1.1062    raeburn  17016:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 17017:     my $now=time;
                   17018: 
                   17019:     if ($public) {
                   17020: 	my $max_public=100;
                   17021: 	my $oldest;
                   17022: 	my $oldest_time=0;
                   17023: 	for(my $next=1;$next<=$max_public;$next++) {
                   17024: 	    if (-e $lonids."/publicuser_$next.id") {
                   17025: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   17026: 		if ($mtime<$oldest_time || !$oldest_time) {
                   17027: 		    $oldest_time=$mtime;
                   17028: 		    $oldest=$next;
                   17029: 		}
                   17030: 	    } else {
                   17031: 		$cookie="publicuser_$next";
                   17032: 		last;
                   17033: 	    }
                   17034: 	}
                   17035: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   17036:     } else {
1.1275    raeburn  17037: 	# See if old ID present, if so, remove if this isn't a robot,
                   17038: 	# killing any existing non-robot sessions
1.463     albertel 17039: 	if (!$args->{'robot'}) {
                   17040: 	    opendir(DIR,$lonids);
                   17041: 	    while ($filename=readdir(DIR)) {
                   17042: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1320    raeburn  17043:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   17044:                             &GDBM_READER(),0640)) {
1.1295    raeburn  17045:                         my $linkedfile;
1.1320    raeburn  17046:                         if (exists($oldenv{'user.linkedenv'})) {
                   17047:                             $linkedfile = $oldenv{'user.linkedenv'};
1.1295    raeburn  17048:                         }
1.1320    raeburn  17049:                         untie(%oldenv);
                   17050:                         if (unlink("$lonids/$filename")) {
                   17051:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   17052:                                 if (-l "$lonids/$linkedfile.id") {
                   17053:                                     unlink("$lonids/$linkedfile.id");
                   17054:                                 }
1.1295    raeburn  17055:                             }
                   17056:                         }
                   17057:                     } else {
                   17058:                         unlink($lonids.'/'.$filename);
                   17059:                     }
1.463     albertel 17060: 		}
1.462     albertel 17061: 	    }
1.463     albertel 17062: 	    closedir(DIR);
1.1204    raeburn  17063: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   17064:             my $namespace = 'nohist_courseeditor';
                   17065:             my $lockingkey = 'paste'."\0".'locked_num';
                   17066:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   17067:                                                 $domain,$username);
                   17068:             if (exists($lockhash{$lockingkey})) {
                   17069:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   17070:                 unless ($delresult eq 'ok') {
                   17071:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   17072:                 }
                   17073:             }
1.462     albertel 17074: 	}
                   17075: # Give them a new cookie
1.463     albertel 17076: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      17077: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 17078: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 17079:     
                   17080: # Initialize roles
                   17081: 
1.1062    raeburn  17082: 	($userroles,$firstaccenv,$timerintenv) = 
                   17083:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 17084:     }
                   17085: # ------------------------------------ Check browser type and MathML capability
                   17086: 
1.1194    raeburn  17087:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   17088:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 17089: 
                   17090: # ------------------------------------------------------------- Get environment
                   17091: 
                   17092:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   17093:     my ($tmp) = keys(%userenv);
1.1275    raeburn  17094:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 17095: 	undef(%userenv);
                   17096:     }
                   17097:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   17098: 	$form->{'interface'}=$userenv{'interface'};
                   17099:     }
                   17100:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   17101: 
                   17102: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   17103:     foreach my $option ('interface','localpath','localres') {
                   17104:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 17105:     }
                   17106: # --------------------------------------------------------- Write first profile
                   17107: 
                   17108:     {
1.1350    raeburn  17109:         my $ip = &Apache::lonnet::get_requestor_ip($r);
1.462     albertel 17110: 	my %initial_env = 
                   17111: 	    ("user.name"          => $username,
                   17112: 	     "user.domain"        => $domain,
                   17113: 	     "user.home"          => $authhost,
                   17114: 	     "browser.type"       => $clientbrowser,
                   17115: 	     "browser.version"    => $clientversion,
                   17116: 	     "browser.mathml"     => $clientmathml,
                   17117: 	     "browser.unicode"    => $clientunicode,
                   17118: 	     "browser.os"         => $clientos,
1.1137    raeburn  17119:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  17120:              "browser.info"       => $clientinfo,
1.1194    raeburn  17121:              "browser.osversion"  => $clientosversion,
1.462     albertel 17122: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   17123: 	     "request.course.fn"  => '',
                   17124: 	     "request.course.uri" => '',
                   17125: 	     "request.course.sec" => '',
                   17126: 	     "request.role"       => 'cm',
                   17127: 	     "request.role.adv"   => $env{'user.adv'},
1.1350    raeburn  17128: 	     "request.host"       => $ip,);
1.462     albertel 17129: 
                   17130:         if ($form->{'localpath'}) {
                   17131: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   17132: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   17133:         }
                   17134: 	
                   17135: 	if ($form->{'interface'}) {
                   17136: 	    $form->{'interface'}=~s/\W//gs;
                   17137: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   17138: 	    $env{'browser.interface'}=$form->{'interface'};
                   17139: 	}
                   17140: 
1.1157    raeburn  17141:         if ($form->{'iptoken'}) {
                   17142:             my $lonhost = $r->dir_config('lonHostID');
                   17143:             $initial_env{"user.noloadbalance"} = $lonhost;
                   17144:             $env{'user.noloadbalance'} = $lonhost;
                   17145:         }
                   17146: 
1.1268    raeburn  17147:         if ($form->{'noloadbalance'}) {
                   17148:             my @hosts = &Apache::lonnet::current_machine_ids();
                   17149:             my $hosthere = $form->{'noloadbalance'};
                   17150:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   17151:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   17152:                 $env{'user.noloadbalance'} = $hosthere;
                   17153:             }
                   17154:         }
                   17155: 
1.1016    raeburn  17156:         unless ($domain eq 'public') {
1.1273    raeburn  17157:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   17158:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   17159: 
                   17160:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
                   17161:                 $userenv{'availabletools.'.$tool} = 
                   17162:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   17163:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   17164:             }
1.980     raeburn  17165: 
1.1311    raeburn  17166:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
1.1273    raeburn  17167:                 $userenv{'canrequest.'.$crstype} =
                   17168:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   17169:                                                       'reload','requestcourses',
                   17170:                                                       \%userenv,\%domdef,\%is_adv);
                   17171:             }
1.724     raeburn  17172: 
1.1273    raeburn  17173:             $userenv{'canrequest.author'} =
                   17174:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   17175:                                                   'reload','requestauthor',
1.980     raeburn  17176:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  17177:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   17178:                                                  $domain,$username);
                   17179:             my $reqstatus = $reqauthor{'author_status'};
                   17180:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   17181:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   17182:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   17183:                                                       $reqauthor{'author'}{'timestamp'};
                   17184:                 }
1.1092    raeburn  17185:             }
1.1287    raeburn  17186:             my ($types,$typename) = &course_types();
                   17187:             if (ref($types) eq 'ARRAY') {
                   17188:                 my @options = ('approval','validate','autolimit');
                   17189:                 my $optregex = join('|',@options);
                   17190:                 my (%willtrust,%trustchecked);
                   17191:                 foreach my $type (@{$types}) {
                   17192:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
                   17193:                     if ($dom_str ne '') {
                   17194:                         my $updatedstr = '';
                   17195:                         my @possdomains = split(',',$dom_str);
                   17196:                         foreach my $entry (@possdomains) {
                   17197:                             my ($extdom,$extopt) = split(':',$entry);
                   17198:                             unless ($trustchecked{$extdom}) {
                   17199:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
                   17200:                                 $trustchecked{$extdom} = 1;
                   17201:                             }
                   17202:                             if ($willtrust{$extdom}) {
                   17203:                                 $updatedstr .= $entry.',';
                   17204:                             }
                   17205:                         }
                   17206:                         $updatedstr =~ s/,$//;
                   17207:                         if ($updatedstr) {
                   17208:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
                   17209:                         } else {
                   17210:                             delete($userenv{'reqcrsotherdom.'.$type});
                   17211:                         }
                   17212:                     }
                   17213:                 }
                   17214:             }
1.1092    raeburn  17215:         }
1.462     albertel 17216: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  17217: 
1.462     albertel 17218: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   17219: 		 &GDBM_WRCREAT(),0640)) {
                   17220: 	    &_add_to_env(\%disk_env,\%initial_env);
                   17221: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   17222: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  17223:             if (ref($firstaccenv) eq 'HASH') {
                   17224:                 &_add_to_env(\%disk_env,$firstaccenv);
                   17225:             }
                   17226:             if (ref($timerintenv) eq 'HASH') {
                   17227:                 &_add_to_env(\%disk_env,$timerintenv);
                   17228:             }
1.463     albertel 17229: 	    if (ref($args->{'extra_env'})) {
                   17230: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   17231: 	    }
1.462     albertel 17232: 	    untie(%disk_env);
                   17233: 	} else {
1.705     tempelho 17234: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   17235: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 17236: 	    return 'error: '.$!;
                   17237: 	}
                   17238:     }
                   17239:     $env{'request.role'}='cm';
                   17240:     $env{'request.role.adv'}=$env{'user.adv'};
                   17241:     $env{'browser.type'}=$clientbrowser;
                   17242: 
                   17243:     return $cookie;
                   17244: 
                   17245: }
                   17246: 
                   17247: sub _add_to_env {
                   17248:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  17249:     if (ref($env_data) eq 'HASH') {
                   17250:         while (my ($key,$value) = each(%$env_data)) {
                   17251: 	    $idf->{$prefix.$key} = $value;
                   17252: 	    $env{$prefix.$key}   = $value;
                   17253:         }
1.462     albertel 17254:     }
                   17255: }
                   17256: 
1.685     tempelho 17257: # --- Get the symbolic name of a problem and the url
                   17258: sub get_symb {
                   17259:     my ($request,$silent) = @_;
1.726     raeburn  17260:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 17261:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   17262:     if ($symb eq '') {
                   17263:         if (!$silent) {
1.1071    raeburn  17264:             if (ref($request)) { 
                   17265:                 $request->print("Unable to handle ambiguous references:$url:.");
                   17266:             }
1.685     tempelho 17267:             return ();
                   17268:         }
                   17269:     }
                   17270:     &Apache::lonenc::check_decrypt(\$symb);
                   17271:     return ($symb);
                   17272: }
                   17273: 
                   17274: # --------------------------------------------------------------Get annotation
                   17275: 
                   17276: sub get_annotation {
                   17277:     my ($symb,$enc) = @_;
                   17278: 
                   17279:     my $key = $symb;
                   17280:     if (!$enc) {
                   17281:         $key =
                   17282:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   17283:     }
                   17284:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   17285:     return $annotation{$key};
                   17286: }
                   17287: 
                   17288: sub clean_symb {
1.731     raeburn  17289:     my ($symb,$delete_enc) = @_;
1.685     tempelho 17290: 
                   17291:     &Apache::lonenc::check_decrypt(\$symb);
                   17292:     my $enc = $env{'request.enc'};
1.731     raeburn  17293:     if ($delete_enc) {
1.730     raeburn  17294:         delete($env{'request.enc'});
                   17295:     }
1.685     tempelho 17296: 
                   17297:     return ($symb,$enc);
                   17298: }
1.462     albertel 17299: 
1.1181    raeburn  17300: ############################################################
                   17301: ############################################################
                   17302: 
                   17303: =pod
                   17304: 
                   17305: =head1 Routines for building display used to search for courses
                   17306: 
                   17307: 
                   17308: =over 4
                   17309: 
                   17310: =item * &build_filters()
                   17311: 
                   17312: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  17313: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   17314: and quotacheck.pl
                   17315: 
1.1181    raeburn  17316: 
                   17317: Inputs:
                   17318: 
                   17319: filterlist - anonymous array of fields to include as potential filters 
                   17320: 
                   17321: crstype - course type
                   17322: 
                   17323: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   17324:               to pop-open a course selector (will contain "extra element"). 
                   17325: 
                   17326: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   17327: 
                   17328: filter - anonymous hash of criteria and their values
                   17329: 
                   17330: action - form action
                   17331: 
                   17332: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   17333: 
1.1182    raeburn  17334: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  17335: 
                   17336: cloneruname - username of owner of new course who wants to clone
                   17337: 
                   17338: clonerudom - domain of owner of new course who wants to clone
                   17339: 
                   17340: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   17341: 
                   17342: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   17343: 
                   17344: codedom - domain
                   17345: 
                   17346: formname - value of form element named "form". 
                   17347: 
                   17348: fixeddom - domain, if fixed.
                   17349: 
                   17350: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   17351: 
                   17352: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   17353: 
                   17354: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   17355: 
                   17356: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   17357: 
                   17358: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   17359: 
                   17360: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   17361: 
                   17362: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   17363: 
1.1182    raeburn  17364: 
1.1181    raeburn  17365: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   17366: 
1.1182    raeburn  17367: 
1.1181    raeburn  17368: Side Effects: None
                   17369: 
                   17370: =cut
                   17371: 
                   17372: # ---------------------------------------------- search for courses based on last activity etc.
                   17373: 
                   17374: sub build_filters {
                   17375:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   17376:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   17377:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   17378:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   17379:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  17380:     my ($list,$jscript);
1.1181    raeburn  17381:     my $onchange = 'javascript:updateFilters(this)';
                   17382:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   17383:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   17384:         $typeselectform,$instcodetitle);
                   17385:     if ($formname eq '') {
                   17386:         $formname = $caller;
                   17387:     }
                   17388:     foreach my $item (@{$filterlist}) {
                   17389:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   17390:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   17391:             if ($item eq 'domainfilter') {
                   17392:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   17393:             } elsif ($item eq 'coursefilter') {
                   17394:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   17395:             } elsif ($item eq 'ownerfilter') {
                   17396:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17397:             } elsif ($item eq 'ownerdomfilter') {
                   17398:                 $filter->{'ownerdomfilter'} =
                   17399:                     &LONCAPA::clean_domain($filter->{$item});
                   17400:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   17401:                                                        'ownerdomfilter',1);
                   17402:             } elsif ($item eq 'personfilter') {
                   17403:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17404:             } elsif ($item eq 'persondomfilter') {
                   17405:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   17406:                                                         'persondomfilter',1);
                   17407:             } else {
                   17408:                 $filter->{$item} =~ s/\W//g;
                   17409:             }
                   17410:             if (!$filter->{$item}) {
                   17411:                 $filter->{$item} = '';
                   17412:             }
                   17413:         }
                   17414:         if ($item eq 'domainfilter') {
                   17415:             my $allow_blank = 1;
                   17416:             if ($formname eq 'portform') {
                   17417:                 $allow_blank=0;
                   17418:             } elsif ($formname eq 'studentform') {
                   17419:                 $allow_blank=0;
                   17420:             }
                   17421:             if ($fixeddom) {
                   17422:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   17423:                                     ' value="'.$codedom.'" />'.
                   17424:                                     &Apache::lonnet::domain($codedom,'description');
                   17425:             } else {
                   17426:                 $domainselectform = &select_dom_form($filter->{$item},
                   17427:                                                      'domainfilter',
                   17428:                                                       $allow_blank,'',$onchange);
                   17429:             }
                   17430:         } else {
                   17431:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   17432:         }
                   17433:     }
                   17434: 
                   17435:     # last course activity filter and selection
                   17436:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   17437: 
                   17438:     # course created filter and selection
                   17439:     if (exists($filter->{'createdfilter'})) {
                   17440:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   17441:     }
                   17442: 
1.1239    raeburn  17443:     my $prefix = $crstype;
                   17444:     if ($crstype eq 'Placement') {
                   17445:         $prefix = 'Placement Test'
                   17446:     }
1.1181    raeburn  17447:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  17448:                 'cac' => "$prefix Activity",
                   17449:                 'ccr' => "$prefix Created",
                   17450:                 'cde' => "$prefix Title",
                   17451:                 'cdo' => "$prefix Domain",
1.1181    raeburn  17452:                 'ins' => 'Institutional Code',
                   17453:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  17454:                 'cow' => "$prefix Owner/Co-owner",
                   17455:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  17456:                 'cog' => 'Type',
                   17457:              );
                   17458: 
                   17459:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17460:         my $typeval = 'Course';
                   17461:         if ($crstype eq 'Community') {
                   17462:             $typeval = 'Community';
1.1239    raeburn  17463:         } elsif ($crstype eq 'Placement') {
                   17464:             $typeval = 'Placement';
1.1181    raeburn  17465:         }
                   17466:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   17467:     } else {
                   17468:         $typeselectform =  '<select name="type" size="1"';
                   17469:         if ($onchange) {
                   17470:             $typeselectform .= ' onchange="'.$onchange.'"';
                   17471:         }
                   17472:         $typeselectform .= '>'."\n";
1.1237    raeburn  17473:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  17474:             my $shown;
                   17475:             if ($posstype eq 'Placement') {
                   17476:                 $shown = &mt('Placement Test');
                   17477:             } else {
                   17478:                 $shown = &mt($posstype);
                   17479:             }
1.1181    raeburn  17480:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  17481:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  17482:         }
                   17483:         $typeselectform.="</select>";
                   17484:     }
                   17485: 
                   17486:     my ($cloneableonlyform,$cloneabletitle);
                   17487:     if (exists($filter->{'cloneableonly'})) {
                   17488:         my $cloneableon = '';
                   17489:         my $cloneableoff = ' checked="checked"';
                   17490:         if ($filter->{'cloneableonly'}) {
                   17491:             $cloneableon = $cloneableoff;
                   17492:             $cloneableoff = '';
                   17493:         }
                   17494:         $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>';
                   17495:         if ($formname eq 'ccrs') {
1.1187    bisitz   17496:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  17497:         } else {
                   17498:             $cloneabletitle = &mt('Cloneable by you');
                   17499:         }
                   17500:     }
                   17501:     my $officialjs;
                   17502:     if ($crstype eq 'Course') {
                   17503:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  17504: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   17505: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   17506:             if ($codedom) { 
1.1181    raeburn  17507:                 $officialjs = 1;
                   17508:                 ($instcodeform,$jscript,$$numtitlesref) =
                   17509:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   17510:                                                                   $officialjs,$codetitlesref);
                   17511:                 if ($jscript) {
1.1182    raeburn  17512:                     $jscript = '<script type="text/javascript">'."\n".
                   17513:                                '// <![CDATA['."\n".
                   17514:                                $jscript."\n".
                   17515:                                '// ]]>'."\n".
                   17516:                                '</script>'."\n";
1.1181    raeburn  17517:                 }
                   17518:             }
                   17519:             if ($instcodeform eq '') {
                   17520:                 $instcodeform =
                   17521:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   17522:                     $list->{'instcodefilter'}.'" />';
                   17523:                 $instcodetitle = $lt{'ins'};
                   17524:             } else {
                   17525:                 $instcodetitle = $lt{'inc'};
                   17526:             }
                   17527:             if ($fixeddom) {
                   17528:                 $instcodetitle .= '<br />('.$codedom.')';
                   17529:             }
                   17530:         }
                   17531:     }
                   17532:     my $output = qq|
                   17533: <form method="post" name="filterpicker" action="$action">
                   17534: <input type="hidden" name="form" value="$formname" />
                   17535: |;
                   17536:     if ($formname eq 'modifycourse') {
                   17537:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   17538:                    '<input type="hidden" name="prevphase" value="'.
                   17539:                    $prevphase.'" />'."\n";
1.1198    musolffc 17540:     } elsif ($formname eq 'quotacheck') {
                   17541:         $output .= qq|
                   17542: <input type="hidden" name="sortby" value="" />
                   17543: <input type="hidden" name="sortorder" value="" />
                   17544: |;
                   17545:     } else {
1.1181    raeburn  17546:         my $name_input;
                   17547:         if ($cnameelement ne '') {
                   17548:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   17549:                           $cnameelement.'" />';
                   17550:         }
                   17551:         $output .= qq|
1.1182    raeburn  17552: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   17553: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  17554: $name_input
                   17555: $roleelement
                   17556: $multelement
                   17557: $typeelement
                   17558: |;
                   17559:         if ($formname eq 'portform') {
                   17560:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   17561:         }
                   17562:     }
                   17563:     if ($fixeddom) {
                   17564:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   17565:     }
                   17566:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   17567:     if ($sincefilterform) {
                   17568:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   17569:                   .$sincefilterform
                   17570:                   .&Apache::lonhtmlcommon::row_closure();
                   17571:     }
                   17572:     if ($createdfilterform) {
                   17573:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   17574:                   .$createdfilterform
                   17575:                   .&Apache::lonhtmlcommon::row_closure();
                   17576:     }
                   17577:     if ($domainselectform) {
                   17578:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   17579:                   .$domainselectform
                   17580:                   .&Apache::lonhtmlcommon::row_closure();
                   17581:     }
                   17582:     if ($typeselectform) {
                   17583:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17584:             $output .= $typeselectform;
                   17585:         } else {
                   17586:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   17587:                       .$typeselectform
                   17588:                       .&Apache::lonhtmlcommon::row_closure();
                   17589:         }
                   17590:     }
                   17591:     if ($instcodeform) {
                   17592:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   17593:                   .$instcodeform
                   17594:                   .&Apache::lonhtmlcommon::row_closure();
                   17595:     }
                   17596:     if (exists($filter->{'ownerfilter'})) {
                   17597:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   17598:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17599:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   17600:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17601:                    $ownerdomselectform.'</td></tr></table>'.
                   17602:                    &Apache::lonhtmlcommon::row_closure();
                   17603:     }
                   17604:     if (exists($filter->{'personfilter'})) {
                   17605:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   17606:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17607:                    '<input type="text" name="personfilter" size="20" value="'.
                   17608:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17609:                    $persondomselectform.'</td></tr></table>'.
                   17610:                    &Apache::lonhtmlcommon::row_closure();
                   17611:     }
                   17612:     if (exists($filter->{'coursefilter'})) {
                   17613:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   17614:                   .'<input type="text" name="coursefilter" size="25" value="'
                   17615:                   .$list->{'coursefilter'}.'" />'
                   17616:                   .&Apache::lonhtmlcommon::row_closure();
                   17617:     }
                   17618:     if ($cloneableonlyform) {
                   17619:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   17620:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   17621:     }
                   17622:     if (exists($filter->{'descriptfilter'})) {
                   17623:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   17624:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   17625:                   .$list->{'descriptfilter'}.'" />'
                   17626:                   .&Apache::lonhtmlcommon::row_closure(1);
                   17627:     }
                   17628:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   17629:                '<input type="hidden" name="updater" value="" />'."\n".
                   17630:                '<input type="submit" name="gosearch" value="'.
                   17631:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   17632:     return $jscript.$clonewarning.$output;
                   17633: }
                   17634: 
                   17635: =pod 
                   17636: 
                   17637: =item * &timebased_select_form()
                   17638: 
1.1182    raeburn  17639: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  17640: filter e.g., Course Activity, Course Created, when searching for courses
                   17641: or communities
                   17642: 
                   17643: Inputs:
                   17644: 
                   17645: item - name of form element (sincefilter or createdfilter)
                   17646: 
                   17647: filter - anonymous hash of criteria and their values
                   17648: 
                   17649: Returns: HTML for a select box contained a blank, then six time selections,
                   17650:          with value set in incoming form variables currently selected. 
                   17651: 
                   17652: Side Effects: None
                   17653: 
                   17654: =cut
                   17655: 
                   17656: sub timebased_select_form {
                   17657:     my ($item,$filter) = @_;
                   17658:     if (ref($filter) eq 'HASH') {
                   17659:         $filter->{$item} =~ s/[^\d-]//g;
                   17660:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   17661:         return &select_form(
                   17662:                             $filter->{$item},
                   17663:                             $item,
                   17664:                             {      '-1' => '',
                   17665:                                 '86400' => &mt('today'),
                   17666:                                '604800' => &mt('last week'),
                   17667:                               '2592000' => &mt('last month'),
                   17668:                               '7776000' => &mt('last three months'),
                   17669:                              '15552000' => &mt('last six months'),
                   17670:                              '31104000' => &mt('last year'),
                   17671:                     'select_form_order' =>
                   17672:                            ['-1','86400','604800','2592000','7776000',
                   17673:                             '15552000','31104000']});
                   17674:     }
                   17675: }
                   17676: 
                   17677: =pod
                   17678: 
                   17679: =item * &js_changer()
                   17680: 
                   17681: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  17682: when course type or domain is changed, and also to hide 'Searching ...' on
                   17683: page load completion for page showing search result.
1.1181    raeburn  17684: 
                   17685: Inputs: None
                   17686: 
1.1183    raeburn  17687: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  17688: 
                   17689: Side Effects: None
                   17690: 
                   17691: =cut
                   17692: 
                   17693: sub js_changer {
                   17694:     return <<ENDJS;
                   17695: <script type="text/javascript">
                   17696: // <![CDATA[
                   17697: function updateFilters(caller) {
                   17698:     if (typeof(caller) != "undefined") {
                   17699:         document.filterpicker.updater.value = caller.name;
                   17700:     }
                   17701:     document.filterpicker.submit();
                   17702: }
1.1183    raeburn  17703: 
                   17704: function hideSearching() {
                   17705:     if (document.getElementById('searching')) {
                   17706:         document.getElementById('searching').style.display = 'none';
                   17707:     }
                   17708:     return;
                   17709: }
                   17710: 
1.1181    raeburn  17711: // ]]>
                   17712: </script>
                   17713: 
                   17714: ENDJS
                   17715: }
                   17716: 
                   17717: =pod
                   17718: 
1.1182    raeburn  17719: =item * &search_courses()
                   17720: 
                   17721: Process selected filters form course search form and pass to lonnet::courseiddump
                   17722: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   17723: 
                   17724: Inputs:
                   17725: 
                   17726: dom - domain being searched 
                   17727: 
                   17728: type - course type ('Course' or 'Community' or '.' if any).
                   17729: 
                   17730: filter - anonymous hash of criteria and their values
                   17731: 
                   17732: numtitles - for institutional codes - number of categories
                   17733: 
                   17734: cloneruname - optional username of new course owner
                   17735: 
                   17736: clonerudom - optional domain of new course owner
                   17737: 
1.1221    raeburn  17738: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  17739:             (used when DC is using course creation form)
                   17740: 
                   17741: codetitles - reference to array of titles of components in institutional codes (official courses).
                   17742: 
1.1221    raeburn  17743: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   17744:            (and so can clone automatically)
                   17745: 
                   17746: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   17747: 
                   17748: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   17749:               courses to clone 
1.1182    raeburn  17750: 
                   17751: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   17752: 
                   17753: 
                   17754: Side Effects: None
                   17755: 
                   17756: =cut
                   17757: 
                   17758: 
                   17759: sub search_courses {
1.1221    raeburn  17760:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   17761:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  17762:     my (%courses,%showcourses,$cloner);
                   17763:     if (($filter->{'ownerfilter'} ne '') ||
                   17764:         ($filter->{'ownerdomfilter'} ne '')) {
                   17765:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   17766:                                        $filter->{'ownerdomfilter'};
                   17767:     }
                   17768:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   17769:         if (!$filter->{$item}) {
                   17770:             $filter->{$item}='.';
                   17771:         }
                   17772:     }
                   17773:     my $now = time;
                   17774:     my $timefilter =
                   17775:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   17776:     my ($createdbefore,$createdafter);
                   17777:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   17778:         $createdbefore = $now;
                   17779:         $createdafter = $now-$filter->{'createdfilter'};
                   17780:     }
                   17781:     my ($instcodefilter,$regexpok);
                   17782:     if ($numtitles) {
                   17783:         if ($env{'form.official'} eq 'on') {
                   17784:             $instcodefilter =
                   17785:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17786:             $regexpok = 1;
                   17787:         } elsif ($env{'form.official'} eq 'off') {
                   17788:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17789:             unless ($instcodefilter eq '') {
                   17790:                 $regexpok = -1;
                   17791:             }
                   17792:         }
                   17793:     } else {
                   17794:         $instcodefilter = $filter->{'instcodefilter'};
                   17795:     }
                   17796:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   17797:     if ($type eq '') { $type = '.'; }
                   17798: 
                   17799:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   17800:         $cloner = $cloneruname.':'.$clonerudom;
                   17801:     }
                   17802:     %courses = &Apache::lonnet::courseiddump($dom,
                   17803:                                              $filter->{'descriptfilter'},
                   17804:                                              $timefilter,
                   17805:                                              $instcodefilter,
                   17806:                                              $filter->{'combownerfilter'},
                   17807:                                              $filter->{'coursefilter'},
                   17808:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  17809:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  17810:                                              $filter->{'cloneableonly'},
                   17811:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  17812:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  17813:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   17814:         my $ccrole;
                   17815:         if ($type eq 'Community') {
                   17816:             $ccrole = 'co';
                   17817:         } else {
                   17818:             $ccrole = 'cc';
                   17819:         }
                   17820:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   17821:                                                      $filter->{'persondomfilter'},
                   17822:                                                      'userroles',undef,
                   17823:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   17824:                                                      $dom);
                   17825:         foreach my $role (keys(%rolehash)) {
                   17826:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   17827:             my $cid = $cdom.'_'.$cnum;
                   17828:             if (exists($courses{$cid})) {
                   17829:                 if (ref($courses{$cid}) eq 'HASH') {
                   17830:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   17831:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  17832:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  17833:                         }
                   17834:                     } else {
                   17835:                         $courses{$cid}{roles} = [$courserole];
                   17836:                     }
                   17837:                     $showcourses{$cid} = $courses{$cid};
                   17838:                 }
                   17839:             }
                   17840:         }
                   17841:         %courses = %showcourses;
                   17842:     }
                   17843:     return %courses;
                   17844: }
                   17845: 
                   17846: =pod
                   17847: 
1.1181    raeburn  17848: =back
                   17849: 
1.1207    raeburn  17850: =head1 Routines for version requirements for current course.
                   17851: 
                   17852: =over 4
                   17853: 
                   17854: =item * &check_release_required()
                   17855: 
                   17856: Compares required LON-CAPA version with version on server, and
                   17857: if required version is newer looks for a server with the required version.
                   17858: 
                   17859: Looks first at servers in user's owen domain; if none suitable, looks at
                   17860: servers in course's domain are permitted to host sessions for user's domain.
                   17861: 
                   17862: Inputs:
                   17863: 
                   17864: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17865: 
                   17866: $courseid - Course ID of current course
                   17867: 
                   17868: $rolecode - User's current role in course (for switchserver query string).
                   17869: 
                   17870: $required - LON-CAPA version needed by course (format: Major.Minor).
                   17871: 
                   17872: 
                   17873: Returns:
                   17874: 
                   17875: $switchserver - query string tp append to /adm/switchserver call (if 
                   17876:                 current server's LON-CAPA version is too old. 
                   17877: 
                   17878: $warning - Message is displayed if no suitable server could be found.
                   17879: 
                   17880: =cut
                   17881: 
                   17882: sub check_release_required {
                   17883:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   17884:     my ($switchserver,$warning);
                   17885:     if ($required ne '') {
                   17886:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   17887:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17888:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   17889:             my $otherserver;
                   17890:             if (($major eq '' && $minor eq '') ||
                   17891:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   17892:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   17893:                 my $switchlcrev =
                   17894:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   17895:                                                            $userdomserver);
                   17896:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17897:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   17898:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   17899:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   17900:                     if ($cdom ne $env{'user.domain'}) {
                   17901:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   17902:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   17903:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   17904:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   17905:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   17906:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   17907:                         my $canhost =
                   17908:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   17909:                                                               $coursedomserver,
                   17910:                                                               $remoterev,
                   17911:                                                               $udomdefaults{'remotesessions'},
                   17912:                                                               $defdomdefaults{'hostedsessions'});
                   17913: 
                   17914:                         if ($canhost) {
                   17915:                             $otherserver = $coursedomserver;
                   17916:                         } else {
                   17917:                             $warning = &mt('Requires LON-CAPA version [_1].',$env{'course.'.$courseid.'.internal.releaserequired'}).'<br />'. &mt("No suitable server could be found amongst servers in either your own domain or in the course's domain.");
                   17918:                         }
                   17919:                     } else {
                   17920:                         $warning = &mt('Requires LON-CAPA version [_1].',$env{'course.'.$courseid.'.internal.releaserequired'}).'<br />'.&mt("No suitable server could be found amongst servers in your own domain (which is also the course's domain).");
                   17921:                     }
                   17922:                 } else {
                   17923:                     $otherserver = $userdomserver;
                   17924:                 }
                   17925:             }
                   17926:             if ($otherserver ne '') {
                   17927:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   17928:             }
                   17929:         }
                   17930:     }
                   17931:     return ($switchserver,$warning);
                   17932: }
                   17933: 
                   17934: =pod
                   17935: 
                   17936: =item * &check_release_result()
                   17937: 
                   17938: Inputs:
                   17939: 
                   17940: $switchwarning - Warning message if no suitable server found to host session.
                   17941: 
                   17942: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17943:                 and current role.
                   17944: 
                   17945: Returns: HTML to display with information about requirement to switch server.
                   17946:          Either displaying warning with link to Roles/Courses screen or
                   17947:          display link to switchserver.
                   17948: 
1.1181    raeburn  17949: =cut
                   17950: 
1.1207    raeburn  17951: sub check_release_result {
                   17952:     my ($switchwarning,$switchserver) = @_;
                   17953:     my $output = &start_page('Selected course unavailable on this server').
                   17954:                  '<p class="LC_warning">';
                   17955:     if ($switchwarning) {
                   17956:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   17957:         if (&show_course()) {
                   17958:             $output .= &mt('Display courses');
                   17959:         } else {
                   17960:             $output .= &mt('Display roles');
                   17961:         }
                   17962:         $output .= '</a>';
                   17963:     } elsif ($switchserver) {
                   17964:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   17965:                    '<br />'.
                   17966:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   17967:                    &mt('Switch Server').
                   17968:                    '</a>';
                   17969:     }
                   17970:     $output .= '</p>'.&end_page();
                   17971:     return $output;
                   17972: }
                   17973: 
                   17974: =pod
                   17975: 
                   17976: =item * &needs_coursereinit()
                   17977: 
                   17978: Determine if course contents stored for user's session needs to be
                   17979: refreshed, because content has changed since "Big Hash" last tied.
                   17980: 
                   17981: Check for change is made if time last checked is more than 10 minutes ago
                   17982: (by default).
                   17983: 
                   17984: Inputs:
                   17985: 
                   17986: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17987: 
                   17988: $interval (optional) - Time which may elapse (in s) between last check for content
                   17989:                        change in current course. (default: 600 s).  
                   17990: 
                   17991: Returns: an array; first element is:
                   17992: 
                   17993: =over 4
                   17994: 
                   17995: 'switch' - if content updates mean user's session
                   17996:            needs to be switched to a server running a newer LON-CAPA version
                   17997:  
                   17998: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   17999:            on current server hosting user's session                
                   18000: 
                   18001: ''       - if no action required.
                   18002: 
                   18003: =back
                   18004: 
                   18005: If first item element is 'switch':
                   18006: 
                   18007: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   18008: 
                   18009: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18010:                               and current role. 
                   18011: 
                   18012: otherwise: no other elements returned.
                   18013: 
                   18014: =back
                   18015: 
                   18016: =cut
                   18017: 
                   18018: sub needs_coursereinit {
                   18019:     my ($loncaparev,$interval) = @_;
                   18020:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   18021:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18022:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   18023:     my $now = time;
                   18024:     if ($interval eq '') {
                   18025:         $interval = 600;
                   18026:     }
                   18027:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  18028:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1372  ! raeburn  18029:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  18030:         if ($blocked) {
                   18031:             return ();
                   18032:         }
1.1207    raeburn  18033:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   18034:         if ($lastchange > $env{'request.course.tied'}) {
                   18035:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   18036:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   18037:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   18038:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   18039:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   18040:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   18041:                     my ($switchserver,$switchwarning) =
                   18042:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   18043:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   18044:                     if ($switchwarning ne '' || $switchserver ne '') {
                   18045:                         return ('switch',$switchwarning,$switchserver);
                   18046:                     }
                   18047:                 }
                   18048:             }
                   18049:             return ('update');
                   18050:         }
                   18051:     }
                   18052:     return ();
                   18053: }
1.1181    raeburn  18054: 
1.1083    raeburn  18055: sub update_content_constraints {
1.1326    raeburn  18056:     my ($cdom,$cnum,$chome,$cid,$keeporder) = @_;
1.1083    raeburn  18057:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   18058:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
1.1307    raeburn  18059:     my (%checkresponsetypes,%checkcrsrestypes);
1.1083    raeburn  18060:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  18061:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  18062:         if ($item eq 'resourcetag') {
                   18063:             if ($name eq 'responsetype') {
                   18064:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   18065:             }
1.1307    raeburn  18066:         } elsif ($item eq 'course') {
                   18067:             if ($name eq 'courserestype') {
                   18068:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
                   18069:             }
1.1083    raeburn  18070:         }
                   18071:     }
                   18072:     my $navmap = Apache::lonnavmaps::navmap->new();
                   18073:     if (defined($navmap)) {
1.1307    raeburn  18074:         my (%allresponses,%allcrsrestypes);
                   18075:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
                   18076:             if ($res->is_tool()) {
                   18077:                 if ($allcrsrestypes{'exttool'}) {
                   18078:                     $allcrsrestypes{'exttool'} ++;
                   18079:                 } else {
                   18080:                     $allcrsrestypes{'exttool'} = 1;
                   18081:                 }
                   18082:                 next;
                   18083:             }
1.1083    raeburn  18084:             my %responses = $res->responseTypes();
                   18085:             foreach my $key (keys(%responses)) {
                   18086:                 next unless(exists($checkresponsetypes{$key}));
                   18087:                 $allresponses{$key} += $responses{$key};
                   18088:             }
                   18089:         }
                   18090:         foreach my $key (keys(%allresponses)) {
                   18091:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   18092:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18093:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   18094:             }
                   18095:         }
1.1307    raeburn  18096:         foreach my $key (keys(%allcrsrestypes)) {
1.1308    raeburn  18097:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
1.1307    raeburn  18098:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18099:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   18100:             }
                   18101:         }
1.1083    raeburn  18102:         undef($navmap);
                   18103:     }
1.1326    raeburn  18104:     my (@resources,@order,@resparms,@zombies);
                   18105:     if ($keeporder) {
                   18106:         use LONCAPA::map;
                   18107:         @resources = @LONCAPA::map::resources;
                   18108:         @order = @LONCAPA::map::order;
                   18109:         @resparms = @LONCAPA::map::resparms;
                   18110:         @zombies = @LONCAPA::map::zombies;
                   18111:     }
1.1308    raeburn  18112:     my $suppmap = 'supplemental.sequence';
                   18113:     my ($suppcount,$supptools,$errors) = (0,0,0);
                   18114:     ($suppcount,$supptools,$errors) = &recurse_supplemental($cnum,$cdom,$suppmap,
                   18115:                                                             $suppcount,$supptools,$errors);
1.1326    raeburn  18116:     if ($keeporder) {
                   18117:         @LONCAPA::map::resources = @resources;
                   18118:         @LONCAPA::map::order = @order;
                   18119:         @LONCAPA::map::resparms = @resparms;
                   18120:         @LONCAPA::map::zombies = @zombies;
                   18121:     }
1.1308    raeburn  18122:     if ($supptools) {
                   18123:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
                   18124:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18125:             ($reqdmajor,$reqdminor) = ($major,$minor);
                   18126:         }
                   18127:     }
1.1083    raeburn  18128:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   18129:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   18130:     }
                   18131:     return;
                   18132: }
                   18133: 
1.1110    raeburn  18134: sub allmaps_incourse {
                   18135:     my ($cdom,$cnum,$chome,$cid) = @_;
                   18136:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   18137:         $cid = $env{'request.course.id'};
                   18138:         $cdom = $env{'course.'.$cid.'.domain'};
                   18139:         $cnum = $env{'course.'.$cid.'.num'};
                   18140:         $chome = $env{'course.'.$cid.'.home'};
                   18141:     }
                   18142:     my %allmaps = ();
                   18143:     my $lastchange =
                   18144:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   18145:     if ($lastchange > $env{'request.course.tied'}) {
                   18146:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   18147:         unless ($ferr) {
1.1326    raeburn  18148:             &update_content_constraints($cdom,$cnum,$chome,$cid,1);
1.1110    raeburn  18149:         }
                   18150:     }
                   18151:     my $navmap = Apache::lonnavmaps::navmap->new();
                   18152:     if (defined($navmap)) {
                   18153:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   18154:             $allmaps{$res->src()} = 1;
                   18155:         }
                   18156:     }
                   18157:     return \%allmaps;
                   18158: }
                   18159: 
1.1083    raeburn  18160: sub parse_supplemental_title {
                   18161:     my ($title) = @_;
                   18162: 
                   18163:     my ($foldertitle,$renametitle);
                   18164:     if ($title =~ /&amp;&amp;&amp;/) {
                   18165:         $title = &HTML::Entites::decode($title);
                   18166:     }
                   18167:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   18168:         $renametitle=$4;
                   18169:         my ($time,$uname,$udom) = ($1,$2,$3);
                   18170:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   18171:         my $name =  &plainname($uname,$udom);
                   18172:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   18173:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   18174:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   18175:             $name.': <br />'.$foldertitle;
                   18176:     }
                   18177:     if (wantarray) {
                   18178:         return ($title,$foldertitle,$renametitle);
                   18179:     }
                   18180:     return $title;
                   18181: }
                   18182: 
1.1143    raeburn  18183: sub recurse_supplemental {
1.1308    raeburn  18184:     my ($cnum,$cdom,$suppmap,$numfiles,$numexttools,$errors) = @_;
1.1143    raeburn  18185:     if ($suppmap) {
                   18186:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   18187:         if ($fatal) {
                   18188:             $errors ++;
                   18189:         } else {
                   18190:             if ($#LONCAPA::map::resources > 0) {
                   18191:                 foreach my $res (@LONCAPA::map::resources) {
                   18192:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   18193:                     if (($src ne '') && ($status eq 'res')) {
1.1146    raeburn  18194:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1308    raeburn  18195:                             ($numfiles,$numexttools,$errors) = &recurse_supplemental($cnum,$cdom,$1,
                   18196:                                                                    $numfiles,$numexttools,$errors);
1.1143    raeburn  18197:                         } else {
1.1308    raeburn  18198:                             if ($src =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   18199:                                 $numexttools ++;
                   18200:                             }
1.1143    raeburn  18201:                             $numfiles ++;
                   18202:                         }
                   18203:                     }
                   18204:                 }
                   18205:             }
                   18206:         }
                   18207:     }
1.1308    raeburn  18208:     return ($numfiles,$numexttools,$errors);
1.1143    raeburn  18209: }
                   18210: 
1.1101    raeburn  18211: sub symb_to_docspath {
1.1267    raeburn  18212:     my ($symb,$navmapref) = @_;
                   18213:     return unless ($symb && ref($navmapref));
1.1101    raeburn  18214:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   18215:     if ($resurl=~/\.(sequence|page)$/) {
                   18216:         $mapurl=$resurl;
                   18217:     } elsif ($resurl eq 'adm/navmaps') {
                   18218:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   18219:     }
                   18220:     my $mapresobj;
1.1267    raeburn  18221:     unless (ref($$navmapref)) {
                   18222:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   18223:     }
                   18224:     if (ref($$navmapref)) {
                   18225:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  18226:     }
                   18227:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   18228:     my $type=$2;
                   18229:     my $path;
                   18230:     if (ref($mapresobj)) {
                   18231:         my $pcslist = $mapresobj->map_hierarchy();
                   18232:         if ($pcslist ne '') {
                   18233:             foreach my $pc (split(/,/,$pcslist)) {
                   18234:                 next if ($pc <= 1);
1.1267    raeburn  18235:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  18236:                 if (ref($res)) {
                   18237:                     my $thisurl = $res->src();
                   18238:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   18239:                     my $thistitle = $res->title();
                   18240:                     $path .= '&'.
                   18241:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  18242:                              &escape($thistitle).
1.1101    raeburn  18243:                              ':'.$res->randompick().
                   18244:                              ':'.$res->randomout().
                   18245:                              ':'.$res->encrypted().
                   18246:                              ':'.$res->randomorder().
                   18247:                              ':'.$res->is_page();
                   18248:                 }
                   18249:             }
                   18250:         }
                   18251:         $path =~ s/^\&//;
                   18252:         my $maptitle = $mapresobj->title();
                   18253:         if ($mapurl eq 'default') {
1.1129    raeburn  18254:             $maptitle = 'Main Content';
1.1101    raeburn  18255:         }
                   18256:         $path .= (($path ne '')? '&' : '').
                   18257:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  18258:                  &escape($maptitle).
1.1101    raeburn  18259:                  ':'.$mapresobj->randompick().
                   18260:                  ':'.$mapresobj->randomout().
                   18261:                  ':'.$mapresobj->encrypted().
                   18262:                  ':'.$mapresobj->randomorder().
                   18263:                  ':'.$mapresobj->is_page();
                   18264:     } else {
                   18265:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   18266:         my $ispage = (($type eq 'page')? 1 : '');
                   18267:         if ($mapurl eq 'default') {
1.1129    raeburn  18268:             $maptitle = 'Main Content';
1.1101    raeburn  18269:         }
                   18270:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  18271:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  18272:     }
                   18273:     unless ($mapurl eq 'default') {
                   18274:         $path = 'default&'.
1.1146    raeburn  18275:                 &escape('Main Content').
1.1101    raeburn  18276:                 ':::::&'.$path;
                   18277:     }
                   18278:     return $path;
                   18279: }
                   18280: 
1.1094    raeburn  18281: sub captcha_display {
1.1327    raeburn  18282:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  18283:     my ($output,$error);
1.1234    raeburn  18284:     my ($captcha,$pubkey,$privkey,$version) = 
1.1327    raeburn  18285:         &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  18286:     if ($captcha eq 'original') {
1.1094    raeburn  18287:         $output = &create_captcha();
                   18288:         unless ($output) {
1.1172    raeburn  18289:             $error = 'captcha';
1.1094    raeburn  18290:         }
                   18291:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  18292:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  18293:         unless ($output) {
1.1172    raeburn  18294:             $error = 'recaptcha';
1.1094    raeburn  18295:         }
                   18296:     }
1.1234    raeburn  18297:     return ($output,$error,$captcha,$version);
1.1094    raeburn  18298: }
                   18299: 
                   18300: sub captcha_response {
1.1327    raeburn  18301:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  18302:     my ($captcha_chk,$captcha_error);
1.1327    raeburn  18303:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  18304:     if ($captcha eq 'original') {
1.1094    raeburn  18305:         ($captcha_chk,$captcha_error) = &check_captcha();
                   18306:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  18307:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  18308:     } else {
                   18309:         $captcha_chk = 1;
                   18310:     }
                   18311:     return ($captcha_chk,$captcha_error);
                   18312: }
                   18313: 
                   18314: sub get_captcha_config {
1.1327    raeburn  18315:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1234    raeburn  18316:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  18317:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   18318:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   18319:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  18320:     if ($context eq 'usercreation') {
                   18321:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   18322:         if (ref($domconfig{$context}) eq 'HASH') {
                   18323:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   18324:             if (ref($hashtocheck) eq 'HASH') {
                   18325:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   18326:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   18327:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   18328:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   18329:                     }
                   18330:                     if ($privkey && $pubkey) {
                   18331:                         $captcha = 'recaptcha';
1.1234    raeburn  18332:                         $version = $hashtocheck->{'recaptchaversion'};
                   18333:                         if ($version ne '2') {
                   18334:                             $version = 1;
                   18335:                         }
1.1095    raeburn  18336:                     } else {
                   18337:                         $captcha = 'original';
                   18338:                     }
                   18339:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   18340:                     $captcha = 'original';
                   18341:                 }
1.1094    raeburn  18342:             }
1.1095    raeburn  18343:         } else {
                   18344:             $captcha = 'captcha';
                   18345:         }
                   18346:     } elsif ($context eq 'login') {
                   18347:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   18348:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   18349:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   18350:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  18351:             if ($privkey && $pubkey) {
                   18352:                 $captcha = 'recaptcha';
1.1234    raeburn  18353:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   18354:                 if ($version ne '2') {
                   18355:                     $version = 1; 
                   18356:                 }
1.1095    raeburn  18357:             } else {
                   18358:                 $captcha = 'original';
1.1094    raeburn  18359:             }
1.1095    raeburn  18360:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   18361:             $captcha = 'original';
1.1094    raeburn  18362:         }
1.1327    raeburn  18363:     } elsif ($context eq 'passwords') {
                   18364:         if ($dom_in_effect) {
                   18365:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   18366:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   18367:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   18368:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   18369:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   18370:                 }
                   18371:                 if ($privkey && $pubkey) {
                   18372:                     $captcha = 'recaptcha';
                   18373:                     $version = $passwdconf{'recaptchaversion'};
                   18374:                     if ($version ne '2') {
                   18375:                         $version = 1;
                   18376:                     }
                   18377:                 } else {
                   18378:                     $captcha = 'original';
                   18379:                 }
                   18380:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   18381:                 $captcha = 'original';
                   18382:             }
                   18383:         }
                   18384:     } 
1.1234    raeburn  18385:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  18386: }
                   18387: 
                   18388: sub create_captcha {
                   18389:     my %captcha_params = &captcha_settings();
                   18390:     my ($output,$maxtries,$tries) = ('',10,0);
                   18391:     while ($tries < $maxtries) {
                   18392:         $tries ++;
                   18393:         my $captcha = Authen::Captcha->new (
                   18394:                                            output_folder => $captcha_params{'output_dir'},
                   18395:                                            data_folder   => $captcha_params{'db_dir'},
                   18396:                                           );
                   18397:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   18398: 
                   18399:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   18400:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
1.1367    raeburn  18401:                       '<span class="LC_nobreak">'.
1.1094    raeburn  18402:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1176    raeburn  18403:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
1.1367    raeburn  18404:                       '</span><br />'.
1.1176    raeburn  18405:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  18406:             last;
                   18407:         }
                   18408:     }
1.1323    raeburn  18409:     if ($output eq '') {
                   18410:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   18411:     }
1.1094    raeburn  18412:     return $output;
                   18413: }
                   18414: 
                   18415: sub captcha_settings {
                   18416:     my %captcha_params = (
                   18417:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   18418:                            www_output_dir => "/captchaspool",
                   18419:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   18420:                            numchars       => '5',
                   18421:                          );
                   18422:     return %captcha_params;
                   18423: }
                   18424: 
                   18425: sub check_captcha {
                   18426:     my ($captcha_chk,$captcha_error);
                   18427:     my $code = $env{'form.code'};
                   18428:     my $md5sum = $env{'form.crypt'};
                   18429:     my %captcha_params = &captcha_settings();
                   18430:     my $captcha = Authen::Captcha->new(
                   18431:                       output_folder => $captcha_params{'output_dir'},
                   18432:                       data_folder   => $captcha_params{'db_dir'},
                   18433:                   );
1.1109    raeburn  18434:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  18435:     my %captcha_hash = (
                   18436:                         0       => 'Code not checked (file error)',
                   18437:                        -1      => 'Failed: code expired',
                   18438:                        -2      => 'Failed: invalid code (not in database)',
                   18439:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   18440:     );
                   18441:     if ($captcha_chk != 1) {
                   18442:         $captcha_error = $captcha_hash{$captcha_chk}
                   18443:     }
                   18444:     return ($captcha_chk,$captcha_error);
                   18445: }
                   18446: 
                   18447: sub create_recaptcha {
1.1234    raeburn  18448:     my ($pubkey,$version) = @_;
                   18449:     if ($version >= 2) {
1.1367    raeburn  18450:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
                   18451:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
1.1234    raeburn  18452:     } else {
                   18453:         my $use_ssl;
                   18454:         if ($ENV{'SERVER_PORT'} == 443) {
                   18455:             $use_ssl = 1;
                   18456:         }
                   18457:         my $captcha = Captcha::reCAPTCHA->new;
                   18458:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   18459:                $captcha->get_html($pubkey,undef,$use_ssl).
                   18460:                &mt('If the text is hard to read, [_1] will replace them.',
                   18461:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   18462:                '<br /><br />';
                   18463:     }
1.1094    raeburn  18464: }
                   18465: 
                   18466: sub check_recaptcha {
1.1234    raeburn  18467:     my ($privkey,$version) = @_;
1.1094    raeburn  18468:     my $captcha_chk;
1.1350    raeburn  18469:     my $ip = &Apache::lonnet::get_requestor_ip();
1.1234    raeburn  18470:     if ($version >= 2) {
                   18471:         my %info = (
                   18472:                      secret   => $privkey, 
                   18473:                      response => $env{'form.g-recaptcha-response'},
1.1350    raeburn  18474:                      remoteip => $ip,
1.1234    raeburn  18475:                    );
1.1280    raeburn  18476:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   18477:         $request->content(join('&',map {
                   18478:                          my $name = escape($_);
                   18479:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   18480:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   18481:                          : &escape($info{$_}) );
                   18482:         } keys(%info)));
                   18483:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  18484:         if ($response->is_success)  {
                   18485:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   18486:             if (ref($data) eq 'HASH') {
                   18487:                 if ($data->{'success'}) {
                   18488:                     $captcha_chk = 1;
                   18489:                 }
                   18490:             }
                   18491:         }
                   18492:     } else {
                   18493:         my $captcha = Captcha::reCAPTCHA->new;
                   18494:         my $captcha_result =
                   18495:             $captcha->check_answer(
                   18496:                                     $privkey,
1.1350    raeburn  18497:                                     $ip,
1.1234    raeburn  18498:                                     $env{'form.recaptcha_challenge_field'},
                   18499:                                     $env{'form.recaptcha_response_field'},
                   18500:                                   );
                   18501:         if ($captcha_result->{is_valid}) {
                   18502:             $captcha_chk = 1;
                   18503:         }
1.1094    raeburn  18504:     }
                   18505:     return $captcha_chk;
                   18506: }
                   18507: 
1.1174    raeburn  18508: sub emailusername_info {
1.1244    raeburn  18509:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  18510:     my %titles = &Apache::lonlocal::texthash (
                   18511:                      lastname      => 'Last Name',
                   18512:                      firstname     => 'First Name',
                   18513:                      institution   => 'School/college/university',
                   18514:                      location      => "School's city, state/province, country",
                   18515:                      web           => "School's web address",
                   18516:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  18517:                      id            => 'Student/Employee ID',
1.1174    raeburn  18518:                  );
                   18519:     return (\@fields,\%titles);
                   18520: }
                   18521: 
1.1161    raeburn  18522: sub cleanup_html {
                   18523:     my ($incoming) = @_;
                   18524:     my $outgoing;
                   18525:     if ($incoming ne '') {
                   18526:         $outgoing = $incoming;
                   18527:         $outgoing =~ s/;/&#059;/g;
                   18528:         $outgoing =~ s/\#/&#035;/g;
                   18529:         $outgoing =~ s/\&/&#038;/g;
                   18530:         $outgoing =~ s/</&#060;/g;
                   18531:         $outgoing =~ s/>/&#062;/g;
                   18532:         $outgoing =~ s/\(/&#040/g;
                   18533:         $outgoing =~ s/\)/&#041;/g;
                   18534:         $outgoing =~ s/"/&#034;/g;
                   18535:         $outgoing =~ s/'/&#039;/g;
                   18536:         $outgoing =~ s/\$/&#036;/g;
                   18537:         $outgoing =~ s{/}{&#047;}g;
                   18538:         $outgoing =~ s/=/&#061;/g;
                   18539:         $outgoing =~ s/\\/&#092;/g
                   18540:     }
                   18541:     return $outgoing;
                   18542: }
                   18543: 
1.1190    musolffc 18544: # Checks for critical messages and returns a redirect url if one exists.
                   18545: # $interval indicates how often to check for messages.
1.1282    raeburn  18546: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 18547: sub critical_redirect {
1.1282    raeburn  18548:     my ($interval,$context) = @_;
1.1356    raeburn  18549:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   18550:         return ();
                   18551:     }
1.1190    musolffc 18552:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  18553:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   18554:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18555:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372  ! raeburn  18556:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  18557:             if ($blocked) {
                   18558:                 my $checkrole = "cm./$cdom/$cnum";
                   18559:                 if ($env{'request.course.sec'} ne '') {
                   18560:                     $checkrole .= "/$env{'request.course.sec'}";
                   18561:                 }
                   18562:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   18563:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   18564:                     return;
                   18565:                 }
                   18566:             }
                   18567:         }
1.1190    musolffc 18568:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   18569:                                         $env{'user.name'});
                   18570:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  18571:         my $redirecturl;
1.1190    musolffc 18572:         if ($what[0]) {
1.1356    raeburn  18573: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1190    musolffc 18574: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  18575: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   18576:                 return (1, $url);
1.1190    musolffc 18577:             }
1.1191    raeburn  18578:         }
                   18579:     } 
                   18580:     return ();
1.1190    musolffc 18581: }
                   18582: 
1.1174    raeburn  18583: # Use:
                   18584: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   18585: #
                   18586: ##################################################
                   18587: #          password associated functions         #
                   18588: ##################################################
                   18589: sub des_keys {
                   18590:     # Make a new key for DES encryption.
                   18591:     # Each key has two parts which are returned separately.
                   18592:     # Please note:  Each key must be passed through the &hex function
                   18593:     # before it is output to the web browser.  The hex versions cannot
                   18594:     # be used to decrypt.
                   18595:     my @hexstr=('0','1','2','3','4','5','6','7',
                   18596:                 '8','9','a','b','c','d','e','f');
                   18597:     my $lkey='';
                   18598:     for (0..7) {
                   18599:         $lkey.=$hexstr[rand(15)];
                   18600:     }
                   18601:     my $ukey='';
                   18602:     for (0..7) {
                   18603:         $ukey.=$hexstr[rand(15)];
                   18604:     }
                   18605:     return ($lkey,$ukey);
                   18606: }
                   18607: 
                   18608: sub des_decrypt {
                   18609:     my ($key,$cyphertext) = @_;
                   18610:     my $keybin=pack("H16",$key);
                   18611:     my $cypher;
                   18612:     if ($Crypt::DES::VERSION>=2.03) {
                   18613:         $cypher=new Crypt::DES $keybin;
                   18614:     } else {
                   18615:         $cypher=new DES $keybin;
                   18616:     }
1.1233    raeburn  18617:     my $plaintext='';
                   18618:     my $cypherlength = length($cyphertext);
                   18619:     my $numchunks = int($cypherlength/32);
                   18620:     for (my $j=0; $j<$numchunks; $j++) {
                   18621:         my $start = $j*32;
                   18622:         my $cypherblock = substr($cyphertext,$start,32);
                   18623:         my $chunk =
                   18624:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   18625:         $chunk .=
                   18626:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   18627:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   18628:         $plaintext .= $chunk;
                   18629:     }
1.1174    raeburn  18630:     return $plaintext;
                   18631: }
                   18632: 
1.1344    raeburn  18633: sub get_requested_shorturls {
1.1309    raeburn  18634:     my ($cdom,$cnum,$navmap) = @_;
                   18635:     return unless (ref($navmap));
1.1344    raeburn  18636:     my ($numnew,$errors);
1.1309    raeburn  18637:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   18638:     if (@toshorten) {
                   18639:         my (%maps,%resources,%titles);
                   18640:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   18641:                                                                'shorturls',$cdom,$cnum);
                   18642:         if (keys(%resources)) {
1.1344    raeburn  18643:             my %tocreate;
1.1309    raeburn  18644:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   18645:                 my $symb = $resources{$item};
                   18646:                 if ($symb) {
                   18647:                     $tocreate{$cnum.'&'.$symb} = 1;
                   18648:                 }
                   18649:             }
1.1344    raeburn  18650:             if (keys(%tocreate)) {
                   18651:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   18652:                                                       \%tocreate);
                   18653:             }
1.1309    raeburn  18654:         }
1.1344    raeburn  18655:     }
                   18656:     return ($numnew,$errors);
                   18657: }
                   18658: 
                   18659: sub make_short_symbs {
                   18660:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   18661:     my ($numnew,@errors);
                   18662:     if (ref($tocreateref) eq 'HASH') {
                   18663:         my %tocreate = %{$tocreateref};
1.1309    raeburn  18664:         if (keys(%tocreate)) {
                   18665:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   18666:             my $su = Short::URL->new(no_vowels => 1);
                   18667:             my $init = '';
                   18668:             my (%newunique,%addcourse,%courseonly,%failed);
                   18669:             # get lock on tiny db
                   18670:             my $now = time;
1.1344    raeburn  18671:             if ($lockuser eq '') {
                   18672:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   18673:             }
1.1309    raeburn  18674:             my $lockhash = {
1.1344    raeburn  18675:                                 "lock\0$now" => $lockuser,
1.1309    raeburn  18676:                             };
                   18677:             my $tries = 0;
                   18678:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   18679:             my ($code,$error);
                   18680:             while (($gotlock ne 'ok') && ($tries<3)) {
                   18681:                 $tries ++;
                   18682:                 sleep 1;
1.1319    raeburn  18683:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
1.1309    raeburn  18684:             }
                   18685:             if ($gotlock eq 'ok') {
                   18686:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   18687:                                        \%addcourse,\%courseonly,\%failed);
                   18688:                 if (keys(%failed)) {
                   18689:                     my $numfailed = scalar(keys(%failed));
                   18690:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   18691:                 }
                   18692:                 if (keys(%newunique)) {
                   18693:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   18694:                     if ($putres eq 'ok') {
                   18695:                         $numnew = scalar(keys(%newunique));
                   18696:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   18697:                         unless ($newputres eq 'ok') {
                   18698:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   18699:                         }
                   18700:                     } else {
                   18701:                         push(@errors,&mt('error: could not store unique six character URLs'));
                   18702:                     }
                   18703:                 }
                   18704:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   18705:                 unless ($dellockres eq 'ok') {
                   18706:                     push(@errors,&mt('error: could not release lockfile'));
                   18707:                 }
                   18708:             } else {
                   18709:                 push(@errors,&mt('error: could not obtain lockfile'));
                   18710:             }
                   18711:             if (keys(%courseonly)) {
                   18712:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   18713:                 if ($result ne 'ok') {
                   18714:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   18715:                 }
                   18716:             }
                   18717:         }
                   18718:     }
                   18719:     return ($numnew,\@errors);
                   18720: }
                   18721: 
                   18722: sub shorten_symbs {
                   18723:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   18724:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   18725:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   18726:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   18727:     my (%possibles,%collisions);
                   18728:     foreach my $key (keys(%{$tocreate})) {
                   18729:         my $num = String::CRC32::crc32($key);
                   18730:         my $tiny = $su->encode($num,$init);
                   18731:         if ($tiny) {
                   18732:             $possibles{$tiny} = $key;
                   18733:         }
                   18734:     }
                   18735:     if (!$init) {
                   18736:         $init = 1;
                   18737:     } else {
                   18738:         $init ++;
                   18739:     }
                   18740:     if (keys(%possibles)) {
                   18741:         my @posstiny = keys(%possibles);
                   18742:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   18743:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   18744:         if (keys(%currtiny)) {
                   18745:             foreach my $key (keys(%currtiny)) {
                   18746:                 next if ($currtiny{$key} eq '');
                   18747:                 if ($currtiny{$key} eq $possibles{$key}) {
                   18748:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   18749:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18750:                         $courseonly->{$tsymb} = $key;
                   18751:                     }
                   18752:                 } else {
                   18753:                     $collisions{$possibles{$key}} = 1;
                   18754:                 }
                   18755:                 delete($possibles{$key});
                   18756:             }
                   18757:         }
                   18758:         foreach my $key (keys(%possibles)) {
                   18759:             $newunique->{$key} = $possibles{$key};
                   18760:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   18761:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18762:                 $addcourse->{$tsymb} = $key;
                   18763:             }
                   18764:         }
                   18765:     }
                   18766:     if (keys(%collisions)) {
                   18767:         if ($init <5) {
                   18768:             if (!$init) {
                   18769:                 $init = 1;
                   18770:             } else {
                   18771:                 $init ++;
                   18772:             }
                   18773:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   18774:                                    $newunique,$addcourse,$courseonly,$failed);
                   18775:         } else {
                   18776:             foreach my $key (keys(%collisions)) {
                   18777:                 $failed->{$key} = 1;
                   18778:             }
                   18779:         }
                   18780:     }
                   18781:     return $init;
                   18782: }
                   18783: 
1.1328    raeburn  18784: sub is_nonframeable {
1.1329    raeburn  18785:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   18786:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
1.1330    raeburn  18787:     return if (($remprotocol eq '') || ($remhost eq ''));
1.1329    raeburn  18788: 
                   18789:     $remprotocol = lc($remprotocol);
                   18790:     $remhost = lc($remhost);
                   18791:     my $remport = 80;
                   18792:     if ($remprotocol eq 'https') {
                   18793:         $remport = 443;
                   18794:     }
1.1330    raeburn  18795:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
1.1329    raeburn  18796:     if ($cached) {
                   18797:         unless ($nocache) {
                   18798:             if ($result) {
                   18799:                 return 1;
                   18800:             } else {
                   18801:                 return 0;
                   18802:             }
                   18803:         }
                   18804:     }
1.1328    raeburn  18805:     my $uselink;
                   18806:     my $request = new HTTP::Request('HEAD',$url);
                   18807:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
                   18808:     if ($response->is_success()) {
                   18809:         my $secpolicy = lc($response->header('content-security-policy'));
                   18810:         my $xframeop = lc($response->header('x-frame-options'));
                   18811:         $secpolicy =~ s/^\s+|\s+$//g;
                   18812:         $xframeop =~ s/^\s+|\s+$//g;
                   18813:         if (($secpolicy ne '') || ($xframeop ne '')) {
1.1329    raeburn  18814:             my $remotehost = $remprotocol.'://'.$remhost;
1.1328    raeburn  18815:             my ($origin,$protocol,$port);
                   18816:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   18817:                 $port = $ENV{'SERVER_PORT'};
                   18818:             } else {
                   18819:                 $port = 80;
                   18820:             }
                   18821:             if ($absolute eq '') {
                   18822:                 $protocol = 'http:';
                   18823:                 if ($port == 443) {
                   18824:                     $protocol = 'https:';
                   18825:                 }
                   18826:                 $origin = $protocol.'//'.lc($hostname);
                   18827:             } else {
                   18828:                 $origin = lc($absolute);
                   18829:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   18830:             }
                   18831:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   18832:                 my $framepolicy = $1;
                   18833:                 $framepolicy =~ s/^\s+|\s+$//g;
                   18834:                 my @policies = split(/\s+/,$framepolicy);
                   18835:                 if (@policies) {
                   18836:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   18837:                         $uselink = 1;
                   18838:                     } else {
                   18839:                         $uselink = 1;
                   18840:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   18841:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   18842:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   18843:                             undef($uselink);
                   18844:                         }
                   18845:                         if ($uselink) {
                   18846:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   18847:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   18848:                                     undef($uselink);
                   18849:                                 }
                   18850:                             }
                   18851:                         }
                   18852:                         if ($uselink) {
                   18853:                             my @possok;
                   18854:                             if ($ip ne '') {
                   18855:                                 push(@possok,$ip);
                   18856:                             }
                   18857:                             my $hoststr = '';
                   18858:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   18859:                                 if ($hoststr eq '') {
                   18860:                                     $hoststr = $part;
                   18861:                                 } else {
                   18862:                                     $hoststr = "$part.$hoststr";
                   18863:                                 }
                   18864:                                 if ($hoststr eq $hostname) {
                   18865:                                     push(@possok,$hostname);
                   18866:                                 } else {
                   18867:                                     push(@possok,"*.$hoststr");
                   18868:                                 }
                   18869:                             }
                   18870:                             if (@possok) {
                   18871:                                 foreach my $poss (@possok) {
                   18872:                                     last if (!$uselink);
                   18873:                                     foreach my $policy (@policies) {
                   18874:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   18875:                                             undef($uselink);
                   18876:                                             last;
                   18877:                                         }
                   18878:                                     }
                   18879:                                 }
                   18880:                             }
                   18881:                         }
                   18882:                     }
                   18883:                 }
                   18884:             } elsif ($xframeop ne '') {
                   18885:                 $uselink = 1;
                   18886:                 my @policies = split(/\s*,\s*/,$xframeop);
                   18887:                 if (@policies) {
                   18888:                     unless (grep(/^deny$/,@policies)) {
                   18889:                         if ($origin ne '') {
                   18890:                             if (grep(/^sameorigin$/,@policies)) {
                   18891:                                 if ($remotehost eq $origin) {
                   18892:                                     undef($uselink);
                   18893:                                 }
                   18894:                             }
                   18895:                             if ($uselink) {
                   18896:                                 foreach my $policy (@policies) {
                   18897:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   18898:                                         my $allowfrom = $1;
                   18899:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   18900:                                             undef($uselink);
                   18901:                                             last;
                   18902:                                         }
                   18903:                                     }
                   18904:                                 }
                   18905:                             }
                   18906:                         }
                   18907:                     }
                   18908:                 }
                   18909:             }
                   18910:         }
                   18911:     }
1.1329    raeburn  18912:     if ($nocache) {
                   18913:         if ($cached) {
                   18914:             my $devalidate;
                   18915:             if ($uselink && !$result) {
                   18916:                 $devalidate = 1;
                   18917:             } elsif (!$uselink && $result) {
                   18918:                 $devalidate = 1;
                   18919:             }
                   18920:             if ($devalidate) {
                   18921:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   18922:             }
                   18923:         }
                   18924:     } else {
                   18925:         if ($uselink) {
                   18926:             $result = 1;
                   18927:         } else {
                   18928:             $result = 0;
                   18929:         }
                   18930:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   18931:     }
1.1328    raeburn  18932:     return $uselink;
                   18933: }
                   18934: 
1.1359    raeburn  18935: sub page_menu {
                   18936:     my ($menucolls,$menunum) = @_;
                   18937:     my %menu;
                   18938:     foreach my $item (split(/;/,$menucolls)) {
                   18939:         my ($num,$value) = split(/\%/,$item);
                   18940:         if ($num eq $menunum) {
                   18941:             my @entries = split(/\&/,$value);
                   18942:             foreach my $entry (@entries) {
                   18943:                 my ($name,$fields) = split(/=/,$entry);
1.1368    raeburn  18944:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
1.1359    raeburn  18945:                     $menu{$name} = $fields;
                   18946:                 } else {
                   18947:                     my @shown;
                   18948:                     if ($fields =~ /,/) {
                   18949:                         @shown = split(/,/,$fields);
                   18950:                     } else {
                   18951:                         @shown = ($fields);
                   18952:                     }
                   18953:                     if (@shown) {
                   18954:                         foreach my $field (@shown) {
                   18955:                             next if ($field eq '');
                   18956:                             $menu{$field} = 1;
                   18957:                         }
                   18958:                     }
                   18959:                 }
                   18960:             }
                   18961:         }
                   18962:     }
                   18963:     return %menu;
                   18964: }
                   18965: 
1.112     bowersj2 18966: 1;
                   18967: __END__;
1.41      ng       18968: 

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